context stringlengths 2.52k 185k | gt stringclasses 1 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;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// SecurityFlags
//
////////////////////////////////////////////////////////////////
public enum SecurityFlags
{
None = 0,
FullTrust = 1,
}
////////////////////////////////////////////////////////////////
// TestAttr (attribute)
//
////////////////////////////////////////////////////////////////
public class CAttrBase : Attribute
{
//Data
private string _name;
private string _desc;
private object[] _params;
private int _id;
private bool _inheritance = true;
private CAttrBase _parent = null;
private string _filter;
//Allows Inheritance (i.e.: object to determine if ever been set)
private object _priority; //Allows Inheritance
private object _implemented; //Allows Inheritance
private object _skipped; //Allows Inheritance
private object _error; //Allows Inheritance
private object _security; //Allows Inheritance
private object _filtercriteria;//Allows Inheritance
private object[] _languages; //Allows Inheritance
private object _xml; //Allows Inheritance
//Constructors
public CAttrBase()
{
}
public CAttrBase(string desc)
{
Desc = desc;
}
//Accessors
public virtual string Name
{
get { return _name; }
set { _name = value; }
}
public virtual string Desc
{
get { return _desc; }
set { _desc = value; }
}
public virtual int id
{
get { return _id; }
set { _id = value; }
}
public virtual object Param
{
get
{
if (_params != null)
return _params[0];
return null;
}
set
{
if (_params == null)
_params = new object[1];
_params[0] = value;
}
}
public virtual object[] Params
{
get { return _params; }
set { _params = value; }
}
public virtual bool Inheritance
{
get { return _inheritance; }
set { _inheritance = value; }
}
public virtual CAttrBase Parent
{
get { return _parent; }
set { _parent = value; }
}
public virtual string Filter
{
get { return _filter; }
set { _filter = value; }
}
public virtual int Pri
{
get
{
if (_priority == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Pri;
//Default
return 2;
}
return (int)_priority;
}
set { _priority = value; }
}
public virtual int Priority //Alias for Pri
{
get { return this.Pri; }
set { this.Pri = value; }
}
public virtual bool Implemented
{
get
{
if (_implemented == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Implemented;
//Default
return true;
}
return (bool)_implemented;
}
set { _implemented = value; }
}
public virtual bool Skipped
{
get
{
if (_skipped == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Skipped;
//Default
return false;
}
return (bool)_skipped;
}
set { _skipped = value; }
}
public virtual bool Error
{
get
{
if (_error == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Error;
//Default
return false;
}
return (bool)_error;
}
set { _error = value; }
}
public virtual SecurityFlags Security
{
get
{
if (_security == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Security;
//Default
return SecurityFlags.None;
}
return (SecurityFlags)_security;
}
set { _security = value; }
}
public virtual string FilterCriteria
{
get
{
if (_filtercriteria == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.FilterCriteria;
//Default
return null;
}
return (string)_filtercriteria;
}
set { _filtercriteria = value; }
}
public virtual string Language
{
get
{
if (Languages != null)
return Languages[0];
return null;
}
set
{
if (Languages == null)
Languages = new string[1];
Languages[0] = value;
}
}
public virtual string[] Languages
{
get
{
if (_languages == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Languages;
//Default
return null;
}
return (string[])_languages;
}
set { _languages = value; }
}
public virtual string Xml
{
get
{
if (_xml == null)
{
//Inheritance
if (Inheritance && _parent != null)
return _parent.Xml;
//Default
return null;
}
return (string)_xml;
}
set { _xml = value; }
}
}
////////////////////////////////////////////////////////////////
// TestModule (attribute)
//
////////////////////////////////////////////////////////////////
public class TestModule : CAttrBase
{
//Data
private string[] _owners;
private int _version;
private string _created;
private string _modified;
//Constructors
public TestModule()
: base()
{
}
public TestModule(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[TestModule(Desc="desc", Version=1)]
}
//Accessors (named attributes)
public virtual string Owner
{
get
{
if (_owners != null)
return _owners[0];
return null;
}
set
{
if (_owners == null)
_owners = new string[1];
_owners[0] = value;
}
}
public virtual string[] Owners
{
get { return _owners; }
set { _owners = value; }
}
public virtual int Version
{
get { return _version; }
set { _version = value; }
}
public virtual string Created
{
get { return _created; }
set { _created = value; }
}
public virtual string Modified
{
get { return _modified; }
set { _modified = value; }
}
}
////////////////////////////////////////////////////////////////
// TestCase (attribute)
//
////////////////////////////////////////////////////////////////
public class TestCase : CAttrBase
{
//Constructors
public TestCase()
: base()
{
}
public TestCase(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[TestCase(Desc="desc", Name="name")]
}
}
////////////////////////////////////////////////////////////////
// Variation (attribute)
//
////////////////////////////////////////////////////////////////
public class Variation : CAttrBase
{
//Data
//Constructors
public Variation()
: base()
{
}
public Variation(string desc)
: base(desc)
{
//NOTE: For all other params, just simply use the named attributes:
//[Variation(Desc="desc", id=1)]
}
}
////////////////////////////////////////////////////////////////
// TestInclude (attribute)
//
////////////////////////////////////////////////////////////////
public class TestInclude : Attribute
{
//Data
private string _name;
private string _file;
private string _files;
private string _filter;
//Constructors
public TestInclude()
{
}
public virtual string Name
{
//Prefix for test case names
get { return _name; }
set { _name = value; }
}
public virtual string File
{
get { return _file; }
set { _file = value; }
}
public virtual string Files
{
//Search Pattern (i.e.: *.*)
get { return _files; }
set { _files = value; }
}
public virtual string Filter
{
get { return _filter; }
set { _filter = value; }
}
}
}
| |
namespace android.text.method
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.text.method.MetaKeyKeyListener_))]
public abstract partial class MetaKeyKeyListener : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected MetaKeyKeyListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual bool onKeyDown(android.view.View arg0, android.text.Editable arg1, int arg2, android.view.KeyEvent arg3)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.method.MetaKeyKeyListener.staticClass, "onKeyDown", "(Landroid/view/View;Landroid/text/Editable;ILandroid/view/KeyEvent;)Z", ref global::android.text.method.MetaKeyKeyListener._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual bool onKeyUp(android.view.View arg0, android.text.Editable arg1, int arg2, android.view.KeyEvent arg3)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.method.MetaKeyKeyListener.staticClass, "onKeyUp", "(Landroid/view/View;Landroid/text/Editable;ILandroid/view/KeyEvent;)Z", ref global::android.text.method.MetaKeyKeyListener._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m2;
public static int getMetaState(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m2.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m2 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(Ljava/lang/CharSequence;)I");
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static int getMetaState(string arg0)
{
return getMetaState((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m3;
public static int getMetaState(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m3.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m3 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(Ljava/lang/CharSequence;I)I");
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public static int getMetaState(string arg0, int arg1)
{
return getMetaState((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m4;
public static int getMetaState(long arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m4.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m4 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(JI)I");
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public static int getMetaState(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m5.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m5 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(J)I");
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual long clearMetaKeyState(long arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(JI)J", ref global::android.text.method.MetaKeyKeyListener._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void clearMetaKeyState(android.view.View arg0, android.text.Editable arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(Landroid/view/View;Landroid/text/Editable;I)V", ref global::android.text.method.MetaKeyKeyListener._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m8;
public static void clearMetaKeyState(android.text.Editable arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m8.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m8 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(Landroid/text/Editable;I)V");
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public static void resetMetaState(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m9.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m9 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetMetaState", "(Landroid/text/Spannable;)V");
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public static long adjustMetaAfterKeypress(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m10.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m10 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "adjustMetaAfterKeypress", "(J)J");
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public static void adjustMetaAfterKeypress(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m11.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m11 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "adjustMetaAfterKeypress", "(Landroid/text/Spannable;)V");
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public static bool isMetaTracker(java.lang.CharSequence arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m12.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m12 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "isMetaTracker", "(Ljava/lang/CharSequence;Ljava/lang/Object;)Z");
return @__env.CallStaticBooleanMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public static bool isMetaTracker(string arg0, java.lang.Object arg1)
{
return isMetaTracker((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m13;
public static bool isSelectingMetaTracker(java.lang.CharSequence arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m13.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m13 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "isSelectingMetaTracker", "(Ljava/lang/CharSequence;Ljava/lang/Object;)Z");
return @__env.CallStaticBooleanMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public static bool isSelectingMetaTracker(string arg0, java.lang.Object arg1)
{
return isSelectingMetaTracker((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m14;
protected static void resetLockedMeta(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m14.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m14 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetLockedMeta", "(Landroid/text/Spannable;)V");
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public static long resetLockedMeta(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m15.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m15 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetLockedMeta", "(J)J");
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public static long handleKeyDown(long arg0, int arg1, android.view.KeyEvent arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m16.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m16 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "handleKeyDown", "(JILandroid/view/KeyEvent;)J");
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m17;
public static long handleKeyUp(long arg0, int arg1, android.view.KeyEvent arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m17.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m17 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "handleKeyUp", "(JILandroid/view/KeyEvent;)J");
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m18;
public MetaKeyKeyListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.method.MetaKeyKeyListener._m18.native == global::System.IntPtr.Zero)
global::android.text.method.MetaKeyKeyListener._m18 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._m18);
Init(@__env, handle);
}
public static int META_SHIFT_ON
{
get
{
return 1;
}
}
public static int META_ALT_ON
{
get
{
return 2;
}
}
public static int META_SYM_ON
{
get
{
return 4;
}
}
public static int META_CAP_LOCKED
{
get
{
return 256;
}
}
public static int META_ALT_LOCKED
{
get
{
return 512;
}
}
public static int META_SYM_LOCKED
{
get
{
return 1024;
}
}
static MetaKeyKeyListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.method.MetaKeyKeyListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/method/MetaKeyKeyListener"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.method.MetaKeyKeyListener))]
internal sealed partial class MetaKeyKeyListener_ : android.text.method.MetaKeyKeyListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal MetaKeyKeyListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
static MetaKeyKeyListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.method.MetaKeyKeyListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/method/MetaKeyKeyListener"));
}
}
}
| |
/***************************************************************************
* DaapProxyWebServer.cs
*
* Copyright (C) 2005-2006 Novell, Inc.
* Copyright (C) 2009 Neil Loknath
* Written by Aaron Bockover <aaron@aaronbock.net>
* James Wilcox <snorp@snorp.net>
* Neil Loknath <neil.loknath@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.IO;
using System.Text;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using Banshee.Web;
using Hyena;
using DAAP = Daap;
namespace Banshee.Daap
{
internal class DaapProxyWebServer : BaseHttpServer
{
private ArrayList databases = new ArrayList();
public DaapProxyWebServer() : base (new IPEndPoint(IPAddress.Loopback, 8089), "DAAP Proxy")
{
}
protected override bool BindServerSocket ()
{
if (!base.BindServerSocket ()) {
EndPoint = new IPEndPoint(IPAddress.Loopback, 0);
try {
server.Bind (EndPoint);
} catch (System.Net.Sockets.SocketException e) {
Log.Warning (e);
return false;
}
}
return true;
}
public void RegisterDatabase(DAAP.Database database)
{
databases.Add(database);
}
public void UnregisterDatabase(DAAP.Database database)
{
databases.Remove(database);
}
protected override void HandleValidRequest(Socket client, string [] split_request, string [] body_request)
{
if(split_request[1].StartsWith("/")) {
split_request[1] = split_request[1].Substring(1);
}
string [] nodes = split_request[1].Split('/');
string body = String.Empty;
HttpStatusCode code = HttpStatusCode.OK;
if(nodes.Length == 1 && nodes[0] == String.Empty) {
body = GetHtmlHeader("Available Databases");
if(databases.Count == 0) {
body += "<blockquote><p><em>No databases found. Connect to a " +
"share in Banshee.</em></p></blockquote>";
} else {
body += "<ul>";
foreach(DAAP.Database database in (ArrayList)databases.Clone()) {
body += String.Format("<li><a href=\"/{0}\">{1} ({2} Tracks)</a></li>",
database.GetHashCode(), Escape (database.Name), database.TrackCount);
}
body += "</ul>";
}
} else if(nodes.Length == 1 && nodes[0] != String.Empty) {
bool db_found = false;
int id = 0;
try {
id = Convert.ToInt32(nodes[0]);
} catch {
}
foreach(DAAP.Database database in (ArrayList)databases.Clone()) {
if(database.GetHashCode() != id) {
continue;
}
body = GetHtmlHeader("Tracks in " + Escape (database.Name));
if(database.TrackCount == 0) {
body += "<blockquote><p><em>No songs in this database.</em></p></blockquote>";
} else {
body += "<p>Showing all " + database.TrackCount + " songs:</p><ul>";
foreach(DAAP.Track song in database.Tracks) {
body += String.Format("<li><a href=\"/{0}/{1}\">{2} - {3}</a> ({4}:{5})</li>",
database.GetHashCode(), song.Id, Escape (song.Artist), Escape (song.Title),
song.Duration.Minutes, song.Duration.Seconds.ToString("00"));
}
body += "</ul>";
}
db_found = true;
break;
}
if(!db_found) {
code = HttpStatusCode.BadRequest;
body = GetHtmlHeader("Invalid Request");
body += String.Format("<p>No database with id `{0}'</p>", id);
}
} else if(nodes.Length == 2) {
bool db_found = false;
int db_id = 0;
int song_id = 0;
try {
db_id = Convert.ToInt32(nodes[0]);
song_id = Convert.ToInt32(nodes[1]);
} catch {
}
foreach(DAAP.Database database in (ArrayList)databases.Clone()) {
if(database.GetHashCode() != db_id) {
continue;
}
try {
DAAP.Track song = database.LookupTrackById(song_id);
if(song != null) {
long offset = -1;
foreach (string line in body_request) {
if (line.ToLower ().Contains ("range:")) {
offset = ParseRangeRequest (line);
}
}
StreamTrack(client, database, song, offset);
return;
}
} catch (Exception e) {
Log.Error (e);
}
code = HttpStatusCode.BadRequest;
body = GetHtmlHeader("Invalid Request");
body += String.Format("<p>No song with id `{0}'</p>", song_id);
db_found = true;
break;
}
if(!db_found) {
code = HttpStatusCode.BadRequest;
body = GetHtmlHeader("Invalid Request");
body += String.Format("<p>No database with id `{0}'</p>", db_id);
}
} else {
code = HttpStatusCode.BadRequest;
body = GetHtmlHeader("Invalid Request");
body += String.Format("<p>The request '{0}' could not be processed by server.</p>",
Escape (split_request[1]));
}
WriteResponse(client, code, body + GetHtmlFooter());
}
protected void StreamTrack(Socket client, DAAP.Database database, DAAP.Track song)
{
StreamTrack (client, database, song, -1);
}
protected virtual void StreamTrack(Socket client, DAAP.Database database, DAAP.Track song, long offset)
{
long length;
Stream stream = database.StreamTrack(song, offset, out length);
WriteResponseStream(client, stream, length, song.FileName, offset < 0 ? 0 : offset);
stream.Close();
client.Close();
}
private static string GetHtmlHeader(string title)
{
return String.Format("<html><head><title>{0} - Banshee DAAP Browser</title></head><body><h1>{0}</h1>",
title);
}
private static string GetHtmlFooter()
{
return String.Format("<hr /><address>Generated on {0} by " +
"Banshee DAAP Extension (<a href=\"http://banshee.fm\">http://banshee.fm</a>)",
DateTime.Now.ToString());
}
private static IPAddress local_address = IPAddress.Parse("127.0.0.1");
public IPAddress IPAddress {
get {
return local_address;
}
}
public string HttpBaseAddress {
get {
return String.Format("http://{0}:{1}/", IPAddress, Port);
}
}
}
}
| |
// 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.ResourceManager
{
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>
/// ManagementGroupsOperations operations.
/// </summary>
internal partial class ManagementGroupsOperations : IServiceOperations<ManagementGroupsAPIClient>, IManagementGroupsOperations
{
/// <summary>
/// Initializes a new instance of the ManagementGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ManagementGroupsOperations(ManagementGroupsAPIClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ManagementGroupsAPIClient
/// </summary>
public ManagementGroupsAPIClient Client { get; private set; }
/// <summary>
/// List management groups for the authenticated user.
///
/// </summary>
/// <param name='skiptoken'>
/// Page continuation token is only used if a previous operation returned a
/// partial result.
/// If a previous response contains a nextLink element, the value of the
/// nextLink element will include a token parameter that specifies a starting
/// point to use for subsequent calls.
///
/// </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<ManagementGroupInfo>>> ListWithHttpMessagesAsync(string skiptoken = default(string), 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("skiptoken", skiptoken);
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.Management/managementGroups").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(skiptoken)));
}
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<ManagementGroupInfo>>();
_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<ManagementGroupInfo>>(_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>
/// Get the details of the management group.
///
/// </summary>
/// <param name='expand'>
/// The $expand=children query string parameter allows clients to request
/// inclusion of children in the response payload. Possible values include:
/// 'children'
/// </param>
/// <param name='recurse'>
/// The $recurse=true query string parameter allows clients to request
/// inclusion of entire hierarchy in the response payload.
/// </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<ManagementGroupWithHierarchy>> GetWithHttpMessagesAsync(string expand = default(string), bool? recurse = default(bool?), 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("expand", expand);
tracingParameters.Add("recurse", recurse);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Management/managementGroups/{groupId}").ToString();
_url = _url.Replace("{groupId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.GroupId, Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (recurse != null)
{
_queryParameters.Add(string.Format("$recurse={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(recurse, Client.SerializationSettings).Trim('"'))));
}
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<ManagementGroupWithHierarchy>();
_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<ManagementGroupWithHierarchy>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List management groups for the authenticated user.
///
/// </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<ManagementGroupInfo>>> 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<ManagementGroupInfo>>();
_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<ManagementGroupInfo>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
** Purpose: Provides some static methods to aid with the implementation
** of a Formatter for Serialization.
**
**
============================================================*/
namespace System.Runtime.Serialization {
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public static class FormatterServices {
#if FEATURE_SERIALIZATION
internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32);
[System.Security.SecurityCritical]
private static bool unsafeTypeForwardersIsEnabled = false;
[System.Security.SecurityCritical]
private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false;
private static Object s_FormatterServicesSyncObject = null;
private static Object formatterServicesSyncObject
{
get
{
if (s_FormatterServicesSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_FormatterServicesSyncObject, o, null);
}
return s_FormatterServicesSyncObject;
}
}
[SecuritySafeCritical]
static FormatterServices()
{
// Static initialization touches security critical types, so we need an
// explicit static constructor to allow us to mark it safe critical.
}
private static MemberInfo[] GetSerializableMembers(RuntimeType type) {
// get the list of all fields
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
int countProper = 0;
for (int i = 0; i < fields.Length; i++) {
if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
continue;
countProper++;
}
if (countProper != fields.Length) {
FieldInfo[] properFields = new FieldInfo[countProper];
countProper = 0;
for (int i = 0; i < fields.Length; i++) {
if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
continue;
properFields[countProper] = fields[i];
countProper++;
}
return properFields;
}
else
return fields;
}
private static bool CheckSerializable(RuntimeType type) {
if (type.IsSerializable) {
return true;
}
return false;
}
private static MemberInfo[] InternalGetSerializableMembers(RuntimeType type) {
List<SerializationFieldInfo> allMembers = null;
MemberInfo[] typeMembers;
FieldInfo [] typeFields;
RuntimeType parentType;
Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
if (type.IsInterface) {
return new MemberInfo[0];
}
if (!(CheckSerializable(type))) {
throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", type.FullName, type.Module.Assembly.FullName));
}
//Get all of the serializable members in the class to be serialized.
typeMembers = GetSerializableMembers(type);
//If this class doesn't extend directly from object, walk its hierarchy and
//get all of the private and assembly-access fields (e.g. all fields that aren't
//virtual) and include them in the list of things to be serialized.
parentType = (RuntimeType)(type.BaseType);
if (parentType != null && parentType != (RuntimeType)typeof(Object)) {
RuntimeType[] parentTypes = null;
int parentTypeCount = 0;
bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount);
if (parentTypeCount > 0){
allMembers = new List<SerializationFieldInfo>();
for (int i = 0; i < parentTypeCount;i++){
parentType = parentTypes[i];
if (!CheckSerializable(parentType)) {
throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", parentType.FullName, parentType.Module.Assembly.FullName));
}
typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
String typeName = classNamesUnique ? parentType.Name : parentType.FullName;
foreach (FieldInfo field in typeFields) {
// Family and Assembly fields will be gathered by the type itself.
if (!field.IsNotSerialized) {
allMembers.Add(new SerializationFieldInfo((RuntimeFieldInfo)field, typeName));
}
}
}
//If we actually found any new MemberInfo's, we need to create a new MemberInfo array and
//copy all of the members which we've found so far into that.
if (allMembers!=null && allMembers.Count>0) {
MemberInfo[] membersTemp = new MemberInfo[allMembers.Count + typeMembers.Length];
Array.Copy(typeMembers, membersTemp, typeMembers.Length);
((ICollection)allMembers).CopyTo(membersTemp, typeMembers.Length);
typeMembers = membersTemp;
}
}
}
return typeMembers;
}
private static bool GetParentTypes(RuntimeType parentType, out RuntimeType[] parentTypes, out int parentTypeCount){
//Check if there are any dup class names. Then we need to include as part of
//typeName to prefix the Field names in SerializationFieldInfo
/*out*/ parentTypes = null;
/*out*/ parentTypeCount = 0;
bool unique = true;
RuntimeType objectType = (RuntimeType)typeof(object);
for (RuntimeType t1 = parentType; t1 != objectType; t1 = (RuntimeType)t1.BaseType)
{
if (t1.IsInterface) continue;
string t1Name = t1.Name;
for(int i=0;unique && i<parentTypeCount;i++){
string t2Name = parentTypes[i].Name;
if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name){
unique = false;
break;
}
}
//expand array if needed
if (parentTypes == null || parentTypeCount == parentTypes.Length){
RuntimeType[] tempParentTypes = new RuntimeType[Math.Max(parentTypeCount*2, 12)];
if (parentTypes != null)
Array.Copy(parentTypes, 0, tempParentTypes, 0, parentTypeCount);
parentTypes = tempParentTypes;
}
parentTypes[parentTypeCount++] = t1;
}
return unique;
}
// Get all of the Serializable members for a particular class. For all practical intents and
// purposes, this is the non-transient, non-static members (fields and properties). In order to
// be included, properties must have both a getter and a setter. N.B.: A class
// which implements ISerializable or has a serialization surrogate may not use all of these members
// (or may have additional members).
[System.Security.SecurityCritical] // auto-generated_required
public static MemberInfo[] GetSerializableMembers(Type type) {
return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
}
// Get all of the Serializable Members for a particular class. If we're not cloning, this is all
// non-transient, non-static fields. If we are cloning, include the transient fields as well since
// we know that we're going to live inside of the same context.
[System.Security.SecurityCritical] // auto-generated_required
public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) {
MemberInfo[] members;
if ((object)type==null) {
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
if (!(type is RuntimeType)) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
}
MemberHolder mh = new MemberHolder(type, context);
//If we've already gathered the members for this type, just return them.
if (m_MemberInfoTable.ContainsKey(mh)) {
return m_MemberInfoTable[mh];
}
lock (formatterServicesSyncObject) {
//If we've already gathered the members for this type, just return them.
if (m_MemberInfoTable.ContainsKey(mh)) {
return m_MemberInfoTable[mh];
}
members = InternalGetSerializableMembers((RuntimeType)type);
m_MemberInfoTable[mh] = members;
}
return members;
}
static readonly Type[] advancedTypes = new Type[]{
typeof(System.DelegateSerializationHolder),
#if FEATURE_REMOTING
typeof(System.Runtime.Remoting.ObjRef),
typeof(System.Runtime.Remoting.IEnvoyInfo),
typeof(System.Runtime.Remoting.Lifetime.ISponsor),
#endif
};
public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) {
if (securityLevel == TypeFilterLevel.Low){
for(int i=0;i<advancedTypes.Length;i++){
if (advancedTypes[i].IsAssignableFrom(t))
throw new SecurityException(Environment.GetResourceString("Serialization_TypeSecurity", advancedTypes[i].FullName, t.FullName));
}
}
}
#endif // FEATURE_SERIALIZATION
// Gets a new instance of the object. The entire object is initalized to 0 and no
// constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE
// CONSISTENT WITH ITS INTERNAL REQUIREMENTS** This method should only be used for
// deserialization when the user intends to immediately populate all fields. This method
// will not create an unitialized string because it is non-sensical to create an empty
// instance of an immutable type.
//
[System.Security.SecurityCritical] // auto-generated_required
public static Object GetUninitializedObject(Type type) {
if ((object)type == null) {
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
if (!(type is RuntimeType)) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
}
return nativeGetUninitializedObject((RuntimeType)type);
}
[System.Security.SecurityCritical] // auto-generated_required
public static Object GetSafeUninitializedObject(Type type) {
if ((object)type == null) {
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
if (!(type is RuntimeType)) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
}
#if FEATURE_REMOTING
if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) ||
Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) ||
Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute)))
return nativeGetUninitializedObject((RuntimeType)type);
#endif
try {
return nativeGetSafeUninitializedObject((RuntimeType)type);
}
catch(SecurityException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e);
}
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetSafeUninitializedObject(RuntimeType type);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetUninitializedObject(RuntimeType type);
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool GetEnableUnsafeTypeForwarders();
[SecuritySafeCritical]
internal static bool UnsafeTypeForwardersIsEnabled()
{
if (!unsafeTypeForwardersIsEnabledInitialized)
{
unsafeTypeForwardersIsEnabled = GetEnableUnsafeTypeForwarders();
unsafeTypeForwardersIsEnabledInitialized = true;
}
return unsafeTypeForwardersIsEnabled;
}
#endif
private static Binder s_binder = Type.DefaultBinder;
[System.Security.SecurityCritical]
internal static void SerializationSetValue(MemberInfo fi, Object target, Object value)
{
Contract.Requires(fi != null);
RtFieldInfo rtField = fi as RtFieldInfo;
if (rtField != null)
{
rtField.CheckConsistency(target);
rtField.UnsafeSetValue(target, value, BindingFlags.Default, s_binder, null);
return;
}
SerializationFieldInfo serField = fi as SerializationFieldInfo;
if (serField != null)
{
serField.InternalSetValue(target, value, BindingFlags.Default, s_binder, null);
return;
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldInfo"));
}
// Fill in the members of obj with the data contained in data.
// Returns the number of members populated.
//
[System.Security.SecurityCritical] // auto-generated_required
public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) {
if (obj==null) {
throw new ArgumentNullException("obj");
}
if (members==null) {
throw new ArgumentNullException("members");
}
if (data==null) {
throw new ArgumentNullException("data");
}
if (members.Length!=data.Length) {
throw new ArgumentException(Environment.GetResourceString("Argument_DataLengthDifferent"));
}
Contract.EndContractBlock();
MemberInfo mi;
BCLDebug.Trace("SER", "[PopulateObjectMembers]Enter.");
for (int i=0; i<members.Length; i++) {
mi = members[i];
if (mi==null) {
throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
}
//If we find an empty, it means that the value was never set during deserialization.
//This is either a forward reference or a null. In either case, this may break some of the
//invariants mantained by the setter, so we'll do nothing with it for right now.
if (data[i]!=null) {
if (mi.MemberType==MemberTypes.Field) {
SerializationSetValue(mi, obj, data[i]);
} else {
throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
}
BCLDebug.Trace("SER", "[PopulateObjectMembers]\tType:", obj.GetType(), "\tMember:",
members[i].Name, " with member type: ", ((FieldInfo)members[i]).FieldType);
}
//Console.WriteLine("X");
}
BCLDebug.Trace("SER", "[PopulateObjectMembers]Leave.");
return obj;
}
// Extracts the data from obj. members is the array of members which we wish to
// extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and
// return it in a Object[] of the same size.
//
[System.Security.SecurityCritical] // auto-generated_required
public static Object[] GetObjectData(Object obj, MemberInfo[] members) {
if (obj==null) {
throw new ArgumentNullException("obj");
}
if (members==null) {
throw new ArgumentNullException("members");
}
Contract.EndContractBlock();
int numberOfMembers = members.Length;
Object[] data = new Object[numberOfMembers];
MemberInfo mi;
for (int i=0; i<numberOfMembers; i++) {
mi=members[i];
if (mi==null) {
throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
}
if (mi.MemberType==MemberTypes.Field) {
Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
"[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo.");
RtFieldInfo rfi = mi as RtFieldInfo;
if (rfi != null) {
rfi.CheckConsistency(obj);
data[i] = rfi.UnsafeGetValue(obj);
} else {
data[i] = ((SerializationFieldInfo)mi).InternalGetValue(obj);
}
} else {
throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
}
}
return data;
}
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
if (innerSurrogate == null)
throw new ArgumentNullException("innerSurrogate");
Contract.EndContractBlock();
return new SurrogateForCyclicalReference(innerSurrogate);
}
/*=============================GetTypeFromAssembly==============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
[System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromAssembly(Assembly assem, String name) {
if (assem==null)
throw new ArgumentNullException("assem");
Contract.EndContractBlock();
return assem.GetType(name, false, false);
}
/*============================LoadAssemblyFromString============================
**Action: Loads an assembly from a given string. The current assembly loading story
** is quite confusing. If the assembly is in the fusion cache, we can load it
** using the stringized-name which we transmitted over the wire. If that fails,
** we try for a lookup of the assembly using the simple name which is the first
** part of the assembly name. If we can't find it that way, we'll return null
** as our failure result.
**Returns: The loaded assembly or null if it can't be found.
**Arguments: assemblyName -- The stringized assembly name.
**Exceptions: None
==============================================================================*/
internal static Assembly LoadAssemblyFromString(String assemblyName) {
//
// Try using the stringized assembly name to load from the fusion cache.
//
BCLDebug.Trace("SER", "[LoadAssemblyFromString]Looking for assembly: ", assemblyName);
Assembly found = Assembly.Load(assemblyName);
return found;
}
internal static Assembly LoadAssemblyFromStringNoThrow(String assemblyName) {
try {
return LoadAssemblyFromString(assemblyName);
}
catch (Exception e){
BCLDebug.Trace("SER", "[LoadAssemblyFromString]", e.ToString());
}
return null;
}
internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) {
if ((object)type == null) {
throw new ArgumentNullException("type");
}
object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
if (typeAttributes != null && typeAttributes.Length > 0) {
hasTypeForwardedFrom = true;
TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0];
return typeForwardedFromAttribute.AssemblyFullName;
}
else {
hasTypeForwardedFrom = false;
return type.Assembly.FullName;
}
}
internal static string GetClrTypeFullName(Type type) {
if (type.IsArray) {
return GetClrTypeFullNameForArray(type);
}
else {
return GetClrTypeFullNameForNonArrayTypes(type);
}
}
static string GetClrTypeFullNameForArray(Type type) {
int rank = type.GetArrayRank();
if (rank == 1)
{
return String.Format(CultureInfo.InvariantCulture, "{0}{1}", GetClrTypeFullName(type.GetElementType()), "[]");
}
else
{
StringBuilder builder = new StringBuilder(GetClrTypeFullName(type.GetElementType())).Append("[");
for (int commaIndex = 1; commaIndex < rank; commaIndex++)
{
builder.Append(",");
}
builder.Append("]");
return builder.ToString();
}
}
static string GetClrTypeFullNameForNonArrayTypes(Type type) {
if (!type.IsGenericType) {
return type.FullName;
}
Type[] genericArguments = type.GetGenericArguments();
StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
bool hasTypeForwardedFrom;
foreach (Type genericArgument in genericArguments) {
builder.Append("[").Append(GetClrTypeFullName(genericArgument)).Append(", ");
builder.Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom)).Append("],");
}
//remove the last comma and close typename for generic with a close bracket
return builder.Remove(builder.Length - 1, 1).Append("]").ToString();
}
}
internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate
{
ISerializationSurrogate innerSurrogate;
internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
if (innerSurrogate == null)
throw new ArgumentNullException("innerSurrogate");
this.innerSurrogate = innerSurrogate;
}
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
{
innerSurrogate.GetObjectData(obj, info, context);
}
[System.Security.SecurityCritical] // auto-generated
public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return innerSurrogate.SetObjectData(obj, info, context, selector);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Globalization;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Net;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient.Clients;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Api;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.BlogClient
{
public struct PostResult
{
public string PostId;
public DateTime DatePublished;
public string ETag;
public XmlDocument AtomRemotePost;
}
/// <summary>
/// Facade class for programmatically interacting with a blog
/// </summary>
public class Blog : IEditorAccount
{
public Blog(string blogId)
{
_settings = BlogSettings.ForBlogId(blogId);
}
public Blog(IBlogSettingsAccessor accessor)
{
_settings = accessor;
}
public void Dispose()
{
if (_settings != null)
_settings.Dispose();
GC.SuppressFinalize(this);
}
~Blog()
{
Trace.Fail("Failed to dispose Blog object");
}
public string Id
{
get
{
return _settings.Id;
}
}
public string ProviderId
{
get
{
return _settings.ProviderId;
}
}
public string Name
{
get
{
return _settings.BlogName;
}
}
public Icon Icon
{
get
{
try
{
Icon favIcon = FavIcon;
if (favIcon != null)
return favIcon;
else
return ApplicationEnvironment.ProductIconSmall;
}
catch
{
return ApplicationEnvironment.ProductIconSmall;
}
}
}
public Icon FavIcon
{
get
{
try
{
// HACK: overcome WordPress icon transparency issues
if (_settings.ProviderId == "556A165F-DA11-463c-BB4A-C77CC9047F22" ||
_settings.ProviderId == "82E6C828-8764-4af1-B289-647FC84E7093")
{
return ResourceHelper.LoadAssemblyResourceIcon("Images.WordPressFav.ico");
}
else if (_settings.FavIcon != null)
{
return new Icon(new MemoryStream(_settings.FavIcon), 16, 16);
}
else
{
return null;
}
}
catch
{
return null;
}
}
}
public Image Image
{
get
{
try
{
if (_settings.Image != null)
{
return new Bitmap(new MemoryStream(_settings.Image));
}
else
{
return null;
}
}
catch
{
return null;
}
}
}
public Image WatermarkImage
{
get
{
try
{
if (_settings.WatermarkImage != null)
{
return new Bitmap(new MemoryStream(_settings.WatermarkImage));
}
else
{
return null;
}
}
catch
{
return null;
}
}
}
public string HostBlogId
{
get
{
return _settings.HostBlogId;
}
}
public string HomepageUrl
{
get
{
return _settings.HomepageUrl;
}
}
public string HomepageBaseUrl
{
get
{
string baseUrl = HomepageUrl;
Uri uri = new Uri(HomepageUrl);
string path = uri.PathAndQuery;
int queryIndex = path.IndexOf("?", StringComparison.OrdinalIgnoreCase);
if (queryIndex != -1)
path = path.Substring(0, queryIndex);
if (!path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
int lastPathIndex = path.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
string lastPathPart = path.Substring(lastPathIndex + 1);
if (lastPathPart.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1)
{
path = path.Substring(0, lastPathIndex);
string hostUrl = uri.GetLeftPart(UriPartial.Authority);
baseUrl = UrlHelper.UrlCombine(hostUrl, path);
}
}
return baseUrl;
}
}
public string PostApiUrl
{
get
{
return _settings.PostApiUrl;
}
}
public string AdminUrl
{
get
{
return FormatUrl(ClientOptions.AdminUrl);
}
}
public string GetPostEditingUrl(string postId)
{
string pattern = ClientOptions.PostEditingUrlPostIdPattern;
if (!string.IsNullOrEmpty(pattern))
{
Match m = Regex.Match(postId, pattern, RegexOptions.IgnoreCase);
if (m.Success && m.Groups[1].Success)
{
postId = m.Groups[1].Value;
}
else
{
Trace.Fail("Parsing failed: " + postId);
}
}
return FormatUrl(ClientOptions.PostEditingUrl, postId);
}
private string FormatUrl(string url)
{
return FormatUrl(url, null);
}
private string FormatUrl(string url, string postId)
{
return BlogClientHelper.FormatUrl(url, _settings.HomepageUrl, _settings.PostApiUrl, _settings.HostBlogId, postId);
}
public string ServiceName
{
get
{
return _settings.ServiceName;
}
}
public string ServiceDisplayName
{
get
{
// look for an option override
if (BlogClient.Options.ServiceName != String.Empty)
return BlogClient.Options.ServiceName;
else
return _settings.ServiceName;
}
}
public IBlogClientOptions ClientOptions
{
get
{
return BlogClient.Options;
}
}
IEditorOptions IEditorAccount.EditorOptions
{
get
{
return (IEditorOptions)BlogClient.Options;
}
}
public void DisplayException(IWin32Window owner, Exception ex)
{
// display a custom display message for exceptions that have one
// registered, otherwise display the generic error form
if (ex is BlogClientProviderException)
{
IBlogProvider provider = BlogProviderManager.FindProvider(_settings.ProviderId);
if (provider != null)
{
BlogClientProviderException pe = ex as BlogClientProviderException;
MessageId messageId = provider.DisplayMessageForProviderError(pe.ErrorCode, pe.ErrorString);
if (messageId != MessageId.None)
{
DisplayMessage.Show(messageId, owner);
return;
}
}
}
else if (ex is WebException)
{
WebException we = (WebException)ex;
HttpWebResponse resp = we.Response as HttpWebResponse;
if (resp != null)
{
string friendlyError = HttpRequestHelper.GetFriendlyErrorMessage(we);
Trace.WriteLine("Server response body:\r\n" + friendlyError);
ex = new BlogClientHttpErrorException(
UrlHelper.SafeToAbsoluteUri(resp.ResponseUri),
friendlyError,
we);
}
else
{
DisplayMessage msg = new DisplayMessage(MessageId.ErrorConnecting);
ex = new BlogClientException(msg.Title, msg.Text);
}
HttpRequestHelper.LogException(we);
}
// no custom message, use default UI
DisplayableExceptionDisplayForm.Show(owner, ex);
}
public bool IsSpacesBlog
{
get { return _settings.IsSpacesBlog; }
}
public SupportsFeature SupportsImageUpload
{
get
{
if (_settings.FileUploadSupport == FileUploadSupport.FTP || ClientOptions.SupportsFileUpload)
return SupportsFeature.Yes;
else
return SupportsFeature.No;
}
}
public string DefaultView
{
get { return ClientOptions.DefaultView; }
}
public FileUploadSupport FileUploadSupport
{
get { return _settings.FileUploadSupport; }
}
public IBlogFileUploadSettings FileUploadSettings
{
get { return _settings.FileUploadSettings; }
}
public bool VerifyCredentials()
{
return BlogClient.VerifyCredentials();
}
public BlogPostCategory[] Categories
{
get
{
return _settings.Categories;
}
}
public BlogPostKeyword[] Keywords
{
get
{
return _settings.Keywords;
}
set
{
_settings.Keywords = value;
}
}
public void RefreshKeywords()
{
try
{
_settings.Keywords = BlogClient.GetKeywords(_settings.HostBlogId);
}
catch (BlogClientOperationCancelledException)
{
}
}
public void RefreshCategories()
{
try
{
_settings.Categories = BlogClient.GetCategories(_settings.HostBlogId);
}
catch (BlogClientOperationCancelledException)
{
}
}
public BlogPost[] GetRecentPosts(int maxPosts, bool includeCategories)
{
BlogPost[] recentPosts = BlogClient.GetRecentPosts(_settings.HostBlogId, maxPosts, includeCategories, null);
foreach (BlogPost blogPost in recentPosts)
{
// apply content filters
blogPost.Contents = ContentFilterApplier.ApplyContentFilters(ClientOptions.ContentFilter, blogPost.Contents, ContentFilterMode.Open);
// if there is no permalink then attempt to construct one
EnsurePermalink(blogPost);
}
return recentPosts;
}
public AuthorInfo[] Authors
{
get
{
AuthorInfo[] authors = _settings.Authors;
if (authors != null)
Array.Sort(authors, new Comparison<AuthorInfo>(delegate(AuthorInfo a, AuthorInfo b)
{
if (a == null ^ b == null)
return (a == null) ? -1 : 1;
else if (a == null)
return 0;
else
return string.Compare(a.Name, b.Name, StringComparison.InvariantCulture);
}));
return authors;
}
}
public void RefreshAuthors()
{
_settings.Authors = BlogClient.GetAuthors(_settings.HostBlogId);
}
public PageInfo[] PageList
{
get
{
return _settings.Pages;
}
}
public void RefreshPageList()
{
_settings.Pages = BlogClient.GetPageList(_settings.HostBlogId);
}
public BlogPost[] GetPages(int maxPages)
{
// get the pages
BlogPost[] pages = BlogClient.GetPages(_settings.HostBlogId, maxPages);
// ensure they are marked with IsPage = true
foreach (BlogPost page in pages)
{
page.IsPage = true;
}
// narrow the array to the "max" if necessary
ArrayList pageList = new ArrayList();
for (int i = 0; i < Math.Min(pages.Length, maxPages); i++)
pageList.Add(pages[i]);
// return pages
return pageList.ToArray(typeof(BlogPost)) as BlogPost[];
}
public PostResult NewPost(BlogPost post, INewCategoryContext newCategoryContext, bool publish)
{
// initialize result
PostResult result = new PostResult();
try
{
using (new ContentFilterApplier(post, ClientOptions, ContentFilterMode.Publish))
{
// make the post
if (post.IsPage)
result.PostId = BlogClient.NewPage(_settings.HostBlogId, post, publish, out result.ETag, out result.AtomRemotePost);
else
result.PostId = BlogClient.NewPost(_settings.HostBlogId, post, newCategoryContext, publish, out result.ETag, out result.AtomRemotePost);
}
// note success
_settings.LastPublishFailed = false;
}
catch
{
_settings.LastPublishFailed = true;
throw;
}
// determine the date-published based on whether there was an override
if (post.HasDatePublishedOverride)
result.DatePublished = post.DatePublishedOverride;
else
result.DatePublished = DateTimeHelper.UtcNow;
// return result
return result;
}
public PostResult EditPost(BlogPost post, INewCategoryContext newCategoryContext, bool publish)
{
// initialize result (for edits the id never changes)
PostResult result = new PostResult();
result.PostId = post.Id;
try
{
//apply any publishing filters and make the post
using (new ContentFilterApplier(post, ClientOptions, ContentFilterMode.Publish))
{
// make the post
if (post.IsPage)
BlogClient.EditPage(_settings.HostBlogId, post, publish, out result.ETag, out result.AtomRemotePost);
else
BlogClient.EditPost(_settings.HostBlogId, post, newCategoryContext, publish, out result.ETag, out result.AtomRemotePost);
}
// note success
_settings.LastPublishFailed = false;
}
catch (BlogClientProviderException ex)
{
if (ErrorIsInvalidPostId(ex))
return NewPost(post, newCategoryContext, publish);
else
throw;
}
catch
{
_settings.LastPublishFailed = true;
throw;
}
// determine the date-published based on whether there was an override
if (post.HasDatePublishedOverride)
result.DatePublished = post.DatePublishedOverride;
else
result.DatePublished = DateTimeHelper.UtcNow;
// return result
return result;
}
/// <summary>
/// Get the version of the post currently residing on the server
/// </summary>
/// <param name="blogPost"></param>
/// <returns></returns>
public BlogPost GetPost(string postId, bool isPage)
{
BlogPost blogPost = null;
if (isPage)
{
// get the page
blogPost = BlogClient.GetPage(_settings.HostBlogId, postId);
// ensure it is marked as a page
blogPost.IsPage = true;
}
else
{
blogPost = BlogClient.GetPost(_settings.HostBlogId, postId);
// if there is no permalink then attempt to construct one
EnsurePermalink(blogPost);
}
// apply content filters
blogPost.Contents = ContentFilterApplier.ApplyContentFilters(ClientOptions.ContentFilter, blogPost.Contents, ContentFilterMode.Open);
// return the blog post
return blogPost;
}
public void DeletePost(string postId, bool isPage, bool publish)
{
if (isPage)
BlogClient.DeletePage(_settings.HostBlogId, postId);
else
BlogClient.DeletePost(_settings.HostBlogId, postId, publish);
}
/// <summary>
/// Force a refresh of ClientOptions by forcing the re-creation of the _blogClient
/// </summary>
public void InvalidateClient()
{
_blogClient = null;
}
public IBlogProviderButtonDescription[] ButtonDescriptions
{
get
{
return _settings.ButtonDescriptions;
}
}
public HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs)
{
return BlogClient.SendAuthenticatedHttpRequest(requestUri, timeoutMs, null);
}
public HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter)
{
return BlogClient.SendAuthenticatedHttpRequest(requestUri, timeoutMs, filter);
}
public override string ToString()
{
return _settings.BlogName;
}
private IBlogSettingsAccessor _settings;
private bool ErrorIsInvalidPostId(BlogClientProviderException ex)
{
string faultCodePattern = BlogClient.Options.InvalidPostIdFaultCodePattern;
string faultStringPattern = BlogClient.Options.InvalidPostIdFaultStringPattern;
if (faultCodePattern != String.Empty && faultStringPattern != String.Empty)
{
return FaultCodeMatchesInvalidPostId(ex.ErrorCode, faultCodePattern) &&
FaultStringMatchesInvalidPostId(ex.ErrorString, faultStringPattern);
}
else if (faultCodePattern != String.Empty)
{
return FaultCodeMatchesInvalidPostId(ex.ErrorCode, faultCodePattern);
}
else if (faultStringPattern != String.Empty)
{
return FaultStringMatchesInvalidPostId(ex.ErrorString, faultStringPattern);
}
else
{
return false;
}
}
private bool FaultCodeMatchesInvalidPostId(string faultCode, string pattern)
{
try // defend against invalid regex in provider or manifest file
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(faultCode);
}
catch (ArgumentException e)
{
Trace.Fail("Error processing regular expression: " + e.ToString());
return false;
}
}
private bool FaultStringMatchesInvalidPostId(string faultString, string pattern)
{
try // defend against invalid regex in provider or manifest file
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(faultString);
}
catch (ArgumentException e)
{
Trace.Fail("Error processing regular expression: " + e.ToString());
return false;
}
}
private void EnsurePermalink(BlogPost blogPost)
{
if (blogPost.Permalink == String.Empty)
{
if (ClientOptions.PermalinkFormat != String.Empty)
{
// construct the permalink from a pre-provided pattern
blogPost.Permalink = FormatUrl(ClientOptions.PermalinkFormat, blogPost.Id);
}
}
else if (!UrlHelper.IsUrl(blogPost.Permalink))
{
// if it is not a URL, then we may need to combine it with the homepage url
try
{
string permalink = UrlHelper.UrlCombine(_settings.HomepageUrl, blogPost.Permalink);
if (UrlHelper.IsUrl(permalink))
{
blogPost.Permalink = permalink;
}
}
catch
{
// url combine can throw exceptions, ignore these
}
}
}
/// <summary>
/// Weblog client
/// </summary>
private IBlogClient BlogClient
{
get
{
if (_blogClient == null)
_blogClient = BlogClientManager.CreateClient(_settings);
return _blogClient;
}
}
private IBlogClient _blogClient;
private enum ContentFilterMode { Open, Publish };
private class ContentFilterApplier : IDisposable
{
private BlogPost _blogPost;
private string _originalContents;
public ContentFilterApplier(BlogPost blogPost, IBlogClientOptions clientOptions, ContentFilterMode filterMode)
{
_blogPost = blogPost;
_originalContents = _blogPost.Contents;
if (_originalContents != null)
_blogPost.Contents = ApplyContentFilters(clientOptions.ContentFilter, _originalContents, filterMode);
}
internal static string ApplyContentFilters(string filters, string content, ContentFilterMode filterMode)
{
string[] contentFilters = filters.Split(',');
foreach (string filterString in contentFilters)
{
string contentFilter = filterString.Trim();
if (contentFilter != String.Empty)
{
IBlogPostContentFilter bpContentFilter = BlogPostContentFilters.CreateContentFilter(contentFilter);
if (filterMode == ContentFilterMode.Open)
content = bpContentFilter.OpenFilter(content);
else
content = bpContentFilter.PublishFilter(content);
}
}
return content;
}
public void Dispose()
{
_blogPost.Contents = _originalContents;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
using Aga.Controls.Tree.NodeControls;
using Aga.Controls.Threading;
namespace Aga.Controls.Tree
{
/// <summary>
/// Extensible advanced <see cref="TreeView"/> implemented in 100% managed C# code.
/// Features: Model/View architecture. Multiple column per node. Ability to select
/// multiple tree nodes. Different types of controls for each node column:
/// <see cref="CheckBox"/>, Icon, Label... Drag and Drop highlighting. Load on
/// demand of nodes. Incremental search of nodes.
/// </summary>
public partial class TreeViewAdv : Control
{
private const int LeftMargin = 7;
internal const int ItemDragSensivity = 4;
private const int DividerWidth = 9;
private const int DividerCorrectionGap = -2;
private Pen _linePen;
private Pen _markPen;
private bool _justGotFocus;
private bool _suspendUpdate;
private bool _needFullUpdate;
private bool _fireSelectionEvent;
private NodePlusMinus _plusMinus;
private ToolTip _toolTip;
private DrawContext _measureContext;
private TreeColumn _hotColumn;
private IncrementalSearch _search;
private List<TreeNodeAdv> _expandingNodes = new List<TreeNodeAdv>();
private AbortableThreadPool _threadPool = new AbortableThreadPool();
private Predicate<TreeNodeAdv> _viewNodeFilter = null;
#region Public Events
[Category("Action")]
public event ItemDragEventHandler ItemDrag;
private void OnItemDrag(MouseButtons buttons, object item)
{
if (ItemDrag != null)
ItemDrag(this, new ItemDragEventArgs(buttons, item));
}
[Category("Behavior")]
public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseClick;
private void OnNodeMouseClick(TreeNodeAdvMouseEventArgs args)
{
if (NodeMouseClick != null)
NodeMouseClick(this, args);
}
[Category("Behavior")]
public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseDoubleClick;
private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args)
{
if (NodeMouseDoubleClick != null)
NodeMouseDoubleClick(this, args);
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnWidthChanged;
internal void OnColumnWidthChanged(TreeColumn column)
{
if (ColumnWidthChanged != null)
ColumnWidthChanged(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnHeightChanged;
internal void OnColumnHeightChanged(TreeColumn column)
{
if (ColumnHeightChanged != null)
ColumnHeightChanged(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnReordered;
internal void OnColumnReordered(TreeColumn column)
{
if (ColumnReordered != null)
ColumnReordered(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnClicked;
internal void OnColumnClicked(TreeColumn column)
{
if (ColumnClicked != null)
ColumnClicked(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler SelectionChanged;
internal void OnSelectionChanged()
{
if (SuspendSelectionEvent)
_fireSelectionEvent = true;
else
{
_fireSelectionEvent = false;
if (SelectionChanged != null)
SelectionChanged(this, EventArgs.Empty);
}
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Collapsing;
private void OnCollapsing(TreeNodeAdv node)
{
if (Collapsing != null)
Collapsing(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Collapsed;
private void OnCollapsed(TreeNodeAdv node)
{
if (Collapsed != null)
Collapsed(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Expanding;
private void OnExpanding(TreeNodeAdv node)
{
if (Expanding != null)
Expanding(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Expanded;
private void OnExpanded(TreeNodeAdv node)
{
if (Expanded != null)
Expanded(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler GridLineStyleChanged;
private void OnGridLineStyleChanged()
{
if (GridLineStyleChanged != null)
GridLineStyleChanged(this, EventArgs.Empty);
}
[Category("Behavior")]
public event ScrollEventHandler Scroll;
protected virtual void OnScroll(ScrollEventArgs e)
{
if (Scroll != null)
Scroll(this, e);
}
[Category("Behavior")]
public event EventHandler<TreeViewRowDrawEventArgs> RowDraw;
protected virtual void OnRowDraw(PaintEventArgs e, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect)
{
if (RowDraw != null)
{
TreeViewRowDrawEventArgs args = new TreeViewRowDrawEventArgs(e.Graphics, e.ClipRectangle, node, context, row, rowRect);
RowDraw(this, args);
}
}
/// <summary>
/// Fires when control is going to draw. Can be used to change text or back color
/// </summary>
[Category("Behavior")]
public event EventHandler<DrawEventArgs> DrawControl;
internal bool DrawControlMustBeFired()
{
return DrawControl != null;
}
internal void FireDrawControl(DrawEventArgs args)
{
OnDrawControl(args);
}
protected virtual void OnDrawControl(DrawEventArgs args)
{
if (DrawControl != null)
DrawControl(this, args);
}
[Category("Drag Drop")]
public event EventHandler<DropNodeValidatingEventArgs> DropNodeValidating;
protected virtual void OnDropNodeValidating(Point point, ref TreeNodeAdv node)
{
if (DropNodeValidating != null)
{
DropNodeValidatingEventArgs args = new DropNodeValidatingEventArgs(point, node);
DropNodeValidating(this, args);
node = args.Node;
}
}
#endregion
public TreeViewAdv()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer
| ControlStyles.ResizeRedraw
| ControlStyles.Selectable
, true);
_headerLayout = new FixedHeaderHeightLayout(this, Application.RenderWithVisualStyles ? 20: 17);
//BorderStyle = BorderStyle.Fixed3D;
_hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight;
_vScrollBar.Width = SystemInformation.VerticalScrollBarWidth;
_rowLayout = new FixedRowHeightLayout(this, RowHeight);
_rowMap = new List<TreeNodeAdv>();
_selection = new List<TreeNodeAdv>();
_readonlySelection = new ReadOnlyCollection<TreeNodeAdv>(_selection);
_columns = new TreeColumnCollection(this);
_toolTip = new ToolTip();
_measureContext = new DrawContext();
_measureContext.Font = Font;
_measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1));
Input = new NormalInputState(this);
_search = new IncrementalSearch(this);
CreateNodes();
CreatePens();
ArrangeControls();
_plusMinus = new NodePlusMinus();
_controls = new NodeControlsCollection(this);
Font = _font;
ExpandingIcon.IconChanged += ExpandingIconChanged;
}
void ExpandingIconChanged(object sender, EventArgs e)
{
if (IsHandleCreated && !IsDisposed)
BeginInvoke(new MethodInvoker(DrawIcons));
}
private void DrawIcons()
{
using (Graphics gr = Graphics.FromHwnd(this.Handle))
{
//Apply the same Graphics Transform logic as used in OnPaint.
int y = 0;
if (UseColumns)
{
y += ColumnHeaderHeight;
if (Columns.Count == 0)
return;
}
int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y;
y -= firstRowY;
gr.ResetTransform();
gr.TranslateTransform(-OffsetX, y);
DrawContext context = new DrawContext();
context.Graphics = gr;
lock (_expandingNodes)
{
for (int i = 0; i < _expandingNodes.Count; i++)
{
foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i]))
{
if (item.Control is ExpandingIcon)
{
Rectangle bounds = item.Bounds;
if (item.Node.Parent == null && UseColumns)
bounds.Location = Point.Empty; // display root expanding icon at 0,0
context.Bounds = bounds;
item.Control.Draw(item.Node, context);
}
}
}
}
}
}
#region Public Methods
public TreePath GetPath(TreeNodeAdv node)
{
if (node == _root)
return TreePath.Empty;
else
{
Stack<object> stack = new Stack<object>();
while (node != _root && node != null)
{
stack.Push(node.Tag);
node = node.Parent;
}
return new TreePath(stack.ToArray());
}
}
public TreeNodeAdv GetNodeAt(Point point)
{
NodeControlInfo info = GetNodeControlInfoAt(point);
return info.Node;
}
public NodeControlInfo GetNodeControlInfoAt(Point point)
{
if (point.X < 0 || point.Y < 0)
return NodeControlInfo.Empty;
int row = _rowLayout.GetRowAt(point);
if (row < RowCount && row >= 0)
return GetNodeControlInfoAt(RowMap[row], point);
else
return NodeControlInfo.Empty;
}
private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point)
{
Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow);
point.Y += (rect.Y - ColumnHeaderHeight);
point.X += OffsetX;
foreach (NodeControlInfo info in GetNodeControls(node))
if (info.Bounds.Contains(point))
return info;
if (FullRowSelect)
return new NodeControlInfo(null, Rectangle.Empty, node);
else
return NodeControlInfo.Empty;
}
public void BeginUpdate()
{
_suspendUpdate = true;
SuspendSelectionEvent = true;
}
public void EndUpdate()
{
_suspendUpdate = false;
if (_needFullUpdate)
FullUpdate();
else
UpdateView();
SuspendSelectionEvent = false;
}
public void ExpandAll()
{
_root.ExpandAll();
}
public void CollapseAll()
{
_root.CollapseAll();
}
/// <summary>
/// Expand all parent nodes, andd scroll to the specified node
/// </summary>
public void EnsureVisible(TreeNodeAdv node)
{
if (node == null)
throw new ArgumentNullException("node");
if (!IsMyNode(node))
throw new ArgumentException();
TreeNodeAdv parent = node.Parent;
while (parent != _root)
{
parent.IsExpanded = true;
parent = parent.Parent;
}
ScrollTo(node);
}
/// <summary>
/// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded
/// </summary>
/// <param name="node"></param>
public void ScrollTo(TreeNodeAdv node)
{
if (node == null)
throw new ArgumentNullException("node");
if (!IsMyNode(node))
throw new ArgumentException();
if (node.Row < 0)
CreateRowMap();
int row = -1;
if (node.Row < FirstVisibleRow)
row = node.Row;
else
{
int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top;
int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom;
if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight)
row = _rowLayout.GetFirstRow(node.Row);
}
if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum)
_vScrollBar.Value = row;
}
public void ClearSelection()
{
BeginUpdate();
try
{
ClearSelectionInternal();
}
finally
{
EndUpdate();
}
}
internal void ClearSelectionInternal()
{
while (Selection.Count > 0)
{
var t = Selection[0];
t.IsSelected = false;
Selection.Remove(t); //hack
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (disposing)
{
AbortBackgroundExpandingThreads();
if (_model != null)
UnbindModelEvents();
ExpandingIcon.IconChanged -= ExpandingIconChanged;
if (components != null)
components.Dispose();
if (_dragBitmap != null) _dragBitmap.Dispose();
if (_dragTimer != null) _dragTimer.Dispose();
if (_linePen != null) _linePen.Dispose();
if (_markPen != null) _markPen.Dispose();
}
base.Dispose(disposing);
}
protected override void OnSizeChanged(EventArgs e)
{
ArrangeControls();
SafeUpdateScrollBars();
base.OnSizeChanged(e);
}
private void ArrangeControls()
{
int hBarSize = _hScrollBar.Height;
int vBarSize = _vScrollBar.Width;
Rectangle clientRect = ClientRectangle;
_hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize,
clientRect.Width - vBarSize, hBarSize);
_vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y,
vBarSize, clientRect.Height - hBarSize);
}
private void SafeUpdateScrollBars()
{
if (InvokeRequired)
BeginInvoke(new MethodInvoker(UpdateScrollBars));
else
UpdateScrollBars();
}
private void UpdateScrollBars()
{
UpdateVScrollBar();
UpdateHScrollBar();
UpdateVScrollBar();
UpdateHScrollBar();
_hScrollBar.Width = DisplayRectangle.Width;
_vScrollBar.Height = DisplayRectangle.Height;
}
private void UpdateHScrollBar()
{
_hScrollBar.Maximum = ContentWidth;
_hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0);
_hScrollBar.SmallChange = 5;
_hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum;
_hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1);
}
private void UpdateVScrollBar()
{
_vScrollBar.Maximum = Math.Max(RowCount - 1, 0);
_vScrollBar.LargeChange = _rowLayout.PageRowCount;
_vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum);
_vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1);
}
protected override CreateParams CreateParams
{
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
CreateParams res = base.CreateParams;
switch (BorderStyle)
{
case BorderStyle.FixedSingle:
res.Style |= 0x800000;
break;
case BorderStyle.Fixed3D:
res.ExStyle |= 0x200;
break;
}
return res;
}
}
protected override void OnGotFocus(EventArgs e)
{
this._justGotFocus = true;
UpdateView();
ChangeInput();
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
UpdateView();
base.OnLostFocus(e);
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
_measureContext.Font = Font;
FullUpdate();
}
internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node)
{
if (node == null)
yield break;
Rectangle rowRect = _rowLayout.GetRowBounds(node.Row);
foreach (NodeControlInfo n in GetNodeControls(node, rowRect))
yield return n;
}
internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node, Rectangle rowRect)
{
if (node == null)
yield break;
int y = rowRect.Y;
int x = (node.Level - 1) * _indent + LeftMargin;
int width = 0;
if (node.Row == 0 && ShiftFirstNode)
x -= _indent;
Rectangle rect = Rectangle.Empty;
if (ShowPlusMinus)
{
width = _plusMinus.GetActualSize(node, _measureContext).Width;
rect = new Rectangle(x, y, width, rowRect.Height);
if (UseColumns && Columns.Count > 0 && Columns[0].Width < rect.Right)
rect.Width = Columns[0].Width - x;
yield return new NodeControlInfo(_plusMinus, rect, node);
x += width;
}
if (!UseColumns)
{
foreach (NodeControl c in NodeControls)
{
Size s = c.GetActualSize(node, _measureContext);
if (!s.IsEmpty)
{
width = s.Width;
rect = new Rectangle(x, y, width, rowRect.Height);
x += rect.Width;
yield return new NodeControlInfo(c, rect, node);
}
}
}
else
{
int right = 0;
foreach (TreeColumn col in Columns)
{
if (col.IsVisible && col.Width > 0)
{
right += col.Width;
for (int i = 0; i < NodeControls.Count; i++)
{
NodeControl nc = NodeControls[i];
if (nc.ParentColumn == col)
{
Size s = nc.GetActualSize(node, _measureContext);
if (!s.IsEmpty)
{
bool isLastControl = true;
for (int k = i + 1; k < NodeControls.Count; k++)
if (NodeControls[k].ParentColumn == col)
{
isLastControl = false;
break;
}
width = right - x;
if (!isLastControl)
width = s.Width;
int maxWidth = Math.Max(0, right - x);
rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height);
x += width;
yield return new NodeControlInfo(nc, rect, node);
}
}
}
x = right;
}
}
}
}
internal static double Dist(Point p1, Point p2)
{
return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
}
public void FullUpdate()
{
HideEditor();
if (InvokeRequired)
BeginInvoke(new MethodInvoker(UnsafeFullUpdate));
else
UnsafeFullUpdate();
}
private void UnsafeFullUpdate()
{
_headerLayout.ClearCache();
_rowLayout.ClearCache();
CreateRowMap();
SafeUpdateScrollBars();
UpdateView();
_needFullUpdate = false;
}
internal void UpdateView()
{
if (!_suspendUpdate)
Invalidate(false);
}
internal void UpdateHeaders()
{
Invalidate(new Rectangle(0, 0, Width, ColumnHeaderHeight));
}
internal void UpdateColumns()
{
FullUpdate();
}
public void UpdateNodeFilter()
{
bool wasUpdating = _suspendUpdate;
if (!wasUpdating) BeginUpdate();
UpdateNodeFilter(_root);
if (!wasUpdating) EndUpdate();
}
private void UpdateNodeFilter(TreeNodeAdv node)
{
node.IsHidden = _viewNodeFilter != null ? !_viewNodeFilter(node) : false;
foreach (TreeNodeAdv child in node.Children)
this.UpdateNodeFilter(child);
}
private void CreateNodes()
{
Selection.Clear();
SelectionStart = null;
_root = new TreeNodeAdv(this, null);
_root.IsExpanded = true;
if (_root.Nodes.Count > 0)
CurrentNode = _root.Nodes[0];
else
CurrentNode = null;
}
internal void ReadChilds(TreeNodeAdv parentNode)
{
ReadChilds(parentNode, false);
}
internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate)
{
parentNode.Nodes.Clear();
if (!parentNode.IsLeaf)
{
parentNode.IsExpandedOnce = true;
if (Model != null)
{
IEnumerable items = Model.GetChildren(GetPath(parentNode));
if (items != null)
foreach (object obj in items)
{
AddNewNode(parentNode, obj, -1);
if (performFullUpdate)
FullUpdate();
}
}
if (parentNode.AutoExpandOnStructureChanged)
parentNode.ExpandAll();
}
}
private void AddNewNode(TreeNodeAdv parent, object tag, int index)
{
TreeNodeAdv node = new TreeNodeAdv(this, tag);
AddNode(parent, index, node);
if (_viewNodeFilter != null)
{
bool wasUpdating = _suspendUpdate;
if (!wasUpdating) BeginUpdate();
UpdateNodeFilter(node);
if (!wasUpdating) EndUpdate();
}
}
private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node)
{
if (index >= 0 && index < parent.Nodes.Count)
parent.Nodes.Insert(index, node);
else
parent.Nodes.Add(node);
node.IsLeaf = Model.IsLeaf(GetPath(node));
if (node.IsLeaf)
node.Nodes.Clear();
if (!LoadOnDemand || node.IsExpandedOnce)
ReadChilds(node);
}
private struct ExpandArgs
{
public TreeNodeAdv Node;
public bool Value;
public bool IgnoreChildren;
}
public void AbortBackgroundExpandingThreads()
{
lock (_expandingNodes)
{
_threadPool.CancelAll(true);
for (int i = 0; i < _expandingNodes.Count; i++)
_expandingNodes[i].IsExpandingNow = false;
_expandingNodes.Clear();
}
Invalidate();
}
internal void SetIsExpanded(TreeNodeAdv node, bool value, bool ignoreChildren)
{
ExpandArgs eargs = new ExpandArgs();
eargs.Node = node;
eargs.Value = value;
eargs.IgnoreChildren = ignoreChildren;
if (AsyncExpanding && LoadOnDemand && !_threadPool.IsMyThread(Thread.CurrentThread))
{
WaitCallback wc = delegate(object argument) { SetIsExpanded((ExpandArgs)argument); };
_threadPool.QueueUserWorkItem(wc, eargs);
}
else
SetIsExpanded(eargs);
}
private void SetIsExpanded(ExpandArgs eargs)
{
bool update = !eargs.IgnoreChildren && !AsyncExpanding;
if (update)
BeginUpdate();
try
{
if (IsMyNode(eargs.Node) && eargs.Node.IsExpanded != eargs.Value)
SetIsExpanded(eargs.Node, eargs.Value);
if (!eargs.IgnoreChildren)
SetIsExpandedRecursive(eargs.Node, eargs.Value);
}
finally
{
if (update)
EndUpdate();
}
}
internal void SetIsExpanded(TreeNodeAdv node, bool value)
{
if (Root == node && !value)
return; //Can't collapse root node
if (value)
{
OnExpanding(node);
node.OnExpanding();
}
else
{
OnCollapsing(node);
node.OnCollapsing();
}
if (value && !node.IsExpandedOnce)
{
if (AsyncExpanding && LoadOnDemand)
{
AddExpandingNode(node);
node.AssignIsExpanded(true);
Invalidate();
}
ReadChilds(node, AsyncExpanding);
RemoveExpandingNode(node);
}
node.AssignIsExpanded(value);
SmartFullUpdate();
if (value)
{
OnExpanded(node);
node.OnExpanded();
}
else
{
OnCollapsed(node);
node.OnCollapsed();
}
}
private void RemoveExpandingNode(TreeNodeAdv node)
{
lock (_expandingNodes)
{
node.IsExpandingNow = false;
_expandingNodes.Remove(node);
if (_expandingNodes.Count <= 0)
ExpandingIcon.Stop();
}
}
private void AddExpandingNode(TreeNodeAdv node)
{
lock (_expandingNodes)
{
node.IsExpandingNow = true;
_expandingNodes.Add(node);
ExpandingIcon.Start();
}
}
internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value)
{
for (int i = 0; i < root.Nodes.Count; i++)
{
TreeNodeAdv node = root.Nodes[i];
node.IsExpanded = value;
SetIsExpandedRecursive(node, value);
}
}
private void CreateRowMap()
{
RowMap.Clear();
int row = 0;
_contentWidth = 0;
foreach (TreeNodeAdv node in VisibleNodes)
{
node.Row = row;
RowMap.Add(node);
if (!UseColumns)
{
_contentWidth = Math.Max(_contentWidth, GetNodeWidth(node));
}
row++;
}
if (UseColumns)
{
_contentWidth = 0;
foreach (TreeColumn col in _columns)
if (col.IsVisible)
_contentWidth += col.Width;
}
}
private int GetNodeWidth(TreeNodeAdv node)
{
if (node.RightBounds == null)
{
Rectangle res = GetNodeBounds(GetNodeControls(node, Rectangle.Empty));
node.RightBounds = res.Right;
}
return node.RightBounds.Value;
}
internal Rectangle GetNodeBounds(TreeNodeAdv node)
{
return GetNodeBounds(GetNodeControls(node));
}
private Rectangle GetNodeBounds(IEnumerable<NodeControlInfo> nodeControls)
{
Rectangle res = Rectangle.Empty;
foreach (NodeControlInfo info in nodeControls)
{
if (res == Rectangle.Empty)
res = info.Bounds;
else
res = Rectangle.Union(res, info.Bounds);
}
return res;
}
private void _vScrollBar_ValueChanged(object sender, EventArgs e)
{
FirstVisibleRow = _vScrollBar.Value;
}
private void _hScrollBar_ValueChanged(object sender, EventArgs e)
{
OffsetX = _hScrollBar.Value;
}
private void _vScrollBar_Scroll(object sender, ScrollEventArgs e)
{
OnScroll(e);
}
private void _hScrollBar_Scroll(object sender, ScrollEventArgs e)
{
OnScroll(e);
}
internal void SmartFullUpdate()
{
if (_suspendUpdate)
_needFullUpdate = true;
else
FullUpdate();
}
internal bool IsMyNode(TreeNodeAdv node)
{
if (node == null)
return false;
if (node.Tree != this)
return false;
while (node.Parent != null)
node = node.Parent;
return node == _root;
}
internal void UpdateSelection()
{
bool flag = false;
if (!IsMyNode(CurrentNode))
CurrentNode = null;
if (!IsMyNode(_selectionStart))
_selectionStart = null;
for (int i = Selection.Count - 1; i >= 0; i--)
if (!IsMyNode(Selection[i]))
{
flag = true;
Selection.RemoveAt(i);
}
if (flag)
OnSelectionChanged();
}
internal void ChangeColumnWidth(TreeColumn column)
{
if (!(_input is ResizeColumnState))
{
FullUpdate();
OnColumnWidthChanged(column);
}
}
internal void ChangeColumnHeight(TreeColumn column)
{
if (!(_input is ResizeColumnState))
{
FullUpdate();
OnColumnHeightChanged(column);
}
}
public TreeNodeAdv FindNode(TreePath path)
{
return FindNode(path, false);
}
public TreeNodeAdv FindNode(TreePath path, bool readChilds)
{
if (path.IsEmpty())
return _root;
else
return FindNode(_root, path, 0, readChilds);
}
private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level, bool readChilds)
{
if (!root.IsExpandedOnce && readChilds)
ReadChilds(root);
for (int i = 0; i < root.Nodes.Count; i++)
{
TreeNodeAdv node = root.Nodes[i];
if (node.Tag == path.FullPath[level])
{
if (level == path.FullPath.Length - 1)
return node;
else
return FindNode(node, path, level + 1, readChilds);
}
}
return null;
}
public TreeNodeAdv FindNodeByTag(object tag)
{
return FindNodeByTag(_root, tag);
}
private TreeNodeAdv FindNodeByTag(TreeNodeAdv root, object tag)
{
foreach (TreeNodeAdv node in root.Nodes)
{
if (node.Tag == tag)
return node;
TreeNodeAdv res = FindNodeByTag(node, tag);
if (res != null)
return res;
}
return null;
}
public void SelectAllNodes()
{
SuspendSelectionEvent = true;
try
{
if (SelectionMode == TreeSelectionMode.MultiSameParent)
{
if (CurrentNode != null)
{
foreach (TreeNodeAdv n in CurrentNode.Parent.Nodes)
n.IsSelected = !n.IsHidden;
}
}
else if (SelectionMode == TreeSelectionMode.Multi)
{
SelectNodes(Root.Nodes);
}
}
finally
{
SuspendSelectionEvent = false;
}
}
private void SelectNodes(Collection<TreeNodeAdv> nodes)
{
foreach (TreeNodeAdv n in nodes)
{
if (n.IsHidden) continue;
n.IsSelected = true;
if (n.IsExpanded)
SelectNodes(n.Nodes);
}
}
#region ModelEvents
private void BindModelEvents()
{
_model.NodesChanged += new EventHandler<TreeModelEventArgs>(_model_NodesChanged);
_model.NodesInserted += new EventHandler<TreeModelEventArgs>(_model_NodesInserted);
_model.NodesRemoved += new EventHandler<TreeModelEventArgs>(_model_NodesRemoved);
_model.StructureChanged += new EventHandler<TreePathEventArgs>(_model_StructureChanged);
}
private void UnbindModelEvents()
{
_model.NodesChanged -= new EventHandler<TreeModelEventArgs>(_model_NodesChanged);
_model.NodesInserted -= new EventHandler<TreeModelEventArgs>(_model_NodesInserted);
_model.NodesRemoved -= new EventHandler<TreeModelEventArgs>(_model_NodesRemoved);
_model.StructureChanged -= new EventHandler<TreePathEventArgs>(_model_StructureChanged);
}
private static object[] GetRelativePath(TreeNodeAdv root, TreeNodeAdv node)
{
int level = 0;
TreeNodeAdv current = node;
while (current != root && current != null)
{
current = current.Parent;
level++;
}
if (current != null)
{
object[] result = new object[level];
current = node;
while (current != root && current != null)
{
level--;
result[level] = current.Tag;
current = current.Parent;
}
return result;
}
return null;
}
private TreeNodeAdv FindChildNode(TreeNodeAdv root, object[] relativePath, int level, bool readChilds)
{
if (relativePath == null)
return null;
if (level == relativePath.Length)
return root;
if (!root.IsExpandedOnce && readChilds)
ReadChilds(root);
for (int i = 0; i < root.Nodes.Count; i++)
{
TreeNodeAdv node = root.Nodes[i];
if (node.Tag == relativePath[level])
{
if (level == relativePath.Length - 1)
return node;
else
return FindChildNode(node, relativePath, level + 1, readChilds);
}
}
return null;
}
private void _model_StructureChanged(object sender, TreePathEventArgs e)
{
if (e.Path == null)
throw new ArgumentNullException();
TreeNodeAdv node = FindNode(e.Path);
if (node != null)
{
if (node != Root)
node.IsLeaf = Model.IsLeaf(GetPath(node));
object[] currentPath = GetRelativePath(node, _currentNode);
object[] selectionStartPath = GetRelativePath(node, _selectionStart);
List<object[]> selectionPaths = new List<object[]>();
List<TreeNodeAdv> preservedSelection = new List<TreeNodeAdv>();
foreach (var selectionNode in Selection)
{
object[] selectionPath = GetRelativePath(node, selectionNode);
if (selectionPath != null)
selectionPaths.Add(selectionPath);
else //preserve selection because this selectionNode is not a child of node
preservedSelection.Add(selectionNode);
}
var list = new Dictionary<object, object>();
SaveExpandedNodes(node, list);
ReadChilds(node);
bool suspendSelectionEventBefore = SuspendSelectionEvent;
bool suspendUpdateBefore = _suspendUpdate;
bool fireSelectionBefore = _fireSelectionEvent;
SuspendSelectionEvent = true;
_suspendUpdate = true;
RestoreExpandedNodes(node, list);
//Restore Selection:
_selection.Clear();
//restore preserved selection.
_selection.AddRange(preservedSelection);
//restore selection for child nodes.
foreach ( var selectionPath in selectionPaths)
{
TreeNodeAdv selectionNode = FindChildNode(node, selectionPath, 0, false);
if (selectionNode != null)
{
selectionNode.SetSelectedInternal(true);
_selection.Add(selectionNode);
}
else
fireSelectionBefore = true; // selection changed.
}
if (currentPath != null)
_currentNode = FindChildNode(node, currentPath, 0, false);
if (selectionStartPath != null)
_selectionStart = FindChildNode(node, selectionStartPath, 0, false);
_fireSelectionEvent = fireSelectionBefore;
_suspendUpdate = suspendUpdateBefore;
SuspendSelectionEvent = suspendSelectionEventBefore;
UpdateSelection();
SmartFullUpdate();
}
//else
// throw new ArgumentException("Path not found");
}
private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary<object, object> list)
{
if (node.Tag != null && list.ContainsKey(node.Tag))
{
node.IsExpanded = true;
foreach (var child in node.Children)
RestoreExpandedNodes(child, list);
}
}
private void SaveExpandedNodes(TreeNodeAdv node, Dictionary<object, object> list)
{
if (node.IsExpanded && node.Tag != null)
{
list.Add(node.Tag, null);
foreach (var child in node.Children)
SaveExpandedNodes(child, list);
}
}
private void _model_NodesRemoved(object sender, TreeModelEventArgs e)
{
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null)
{
if (parent.IsExpandedOnce)
{
if (e.Indices != null)
{
List<int> list = new List<int>(e.Indices);
list.Sort();
for (int n = list.Count - 1; n >= 0; n--)
{
int index = list[n];
if (index >= 0 && index <= parent.Nodes.Count)
parent.Nodes.RemoveAt(index);
else
throw new ArgumentOutOfRangeException("Index out of range");
}
}
else
{
for (int i = parent.Nodes.Count - 1; i >= 0; i--)
{
for (int n = 0; n < e.Children.Length; n++)
if (parent.Nodes[i].Tag == e.Children[n])
{
parent.Nodes.RemoveAt(i);
break;
}
}
}
if (parent.Nodes.Count == 0)
parent.IsLeaf = Model.IsLeaf(e.Path);
}
else
parent.IsLeaf = Model.IsLeaf(e.Path);
}
UpdateSelection();
SmartFullUpdate();
}
private void _model_NodesInserted(object sender, TreeModelEventArgs e)
{
if (e.Indices == null)
throw new ArgumentNullException("Indices");
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null)
{
if (parent.IsExpandedOnce)
{
for (int i = 0; i < e.Children.Length; i++)
AddNewNode(parent, e.Children[i], e.Indices[i]);
}
else if (parent.IsLeaf)
parent.IsLeaf = Model.IsLeaf(e.Path);
}
SmartFullUpdate();
}
private void _model_NodesChanged(object sender, TreeModelEventArgs e)
{
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null && parent.IsUnwrapped && parent.IsExpanded)
{
if (InvokeRequired)
BeginInvoke(new UpdateContentWidthDelegate(ClearNodesSize), e, parent);
else
ClearNodesSize(e, parent);
SmartFullUpdate();
}
}
private delegate void UpdateContentWidthDelegate(TreeModelEventArgs e, TreeNodeAdv parent);
private void ClearNodesSize(TreeModelEventArgs e, TreeNodeAdv parent)
{
if (e.Indices != null)
{
foreach (int index in e.Indices)
{
if (index >= 0 && index < parent.Nodes.Count)
{
TreeNodeAdv node = parent.Nodes[index];
node.Height = node.RightBounds = null;
}
else
throw new ArgumentOutOfRangeException("Index out of range");
}
}
else
{
foreach (TreeNodeAdv node in parent.Nodes)
{
foreach (object obj in e.Children)
if (node.Tag == obj)
{
node.Height = node.RightBounds = null;
}
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.NodejsTools.Debugger.Serialization;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Microsoft.NodejsTools.Debugger.DebugEngine
{
// Represents a logical stack frame on the thread stack.
// Also implements the IDebugExpressionContext interface, which allows expression evaluation and watch windows.
internal class AD7StackFrame : IDebugStackFrame2, IDebugExpressionContext2, IDebugProperty2
{
private readonly IComparer<string> _comparer = new NaturalSortComparer();
private readonly AD7Engine _engine;
private readonly NodeStackFrame _stackFrame;
private readonly AD7Thread _thread;
private AD7MemoryAddress _codeContext;
private AD7DocumentContext _documentContext;
public AD7StackFrame(AD7Engine engine, AD7Thread thread, NodeStackFrame stackFrame)
{
this._engine = engine;
this._thread = thread;
this._stackFrame = stackFrame;
}
public NodeStackFrame StackFrame => this._stackFrame;
public AD7Engine Engine => this._engine;
public AD7Thread Thread => this._thread;
private AD7MemoryAddress CodeContext
{
get
{
if (this._codeContext == null)
{
this._codeContext = new AD7MemoryAddress(this._engine, this._stackFrame);
}
return this._codeContext;
}
}
private AD7DocumentContext DocumentContext
{
get
{
if (this._documentContext == null)
{
this._documentContext = new AD7DocumentContext(this.CodeContext);
}
return this._documentContext;
}
}
#region Non-interface methods
// Construct a FRAMEINFO for this stack frame with the requested information.
public void SetFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, out FRAMEINFO frameInfo)
{
frameInfo = new FRAMEINFO();
// The debugger is asking for the formatted name of the function which is displayed in the callstack window.
// There are several optional parts to this name including the module, argument types and values, and line numbers.
// The optional information is requested by setting flags in the dwFieldSpec parameter.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME) != 0)
{
var funcName = this._stackFrame.FunctionName;
if (funcName == "<module>")
{
if (this._stackFrame.FileName.IndexOfAny(Path.GetInvalidPathChars()) == -1)
{
funcName = Path.GetFileName(this._stackFrame.FileName) + " module";
}
else if (this._stackFrame.FileName.EndsWith("<string>", StringComparison.Ordinal))
{
funcName = "<exec or eval>";
}
else
{
funcName = this._stackFrame.FileName + " unknown code";
}
}
else
{
if (this._stackFrame.FileName != "<unknown>")
{
funcName = string.Format(CultureInfo.InvariantCulture, "{0} [{1}]", funcName, Path.GetFileName(this._stackFrame.FileName));
}
else
{
funcName = funcName + " in <unknown>";
}
}
frameInfo.m_bstrFuncName = string.Format(CultureInfo.InvariantCulture, "{0} Line {1}", funcName, this._stackFrame.Line + 1);
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME;
}
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_LANGUAGE) != 0)
{
AD7Engine.MapLanguageInfo(this._stackFrame.FileName, out frameInfo.m_bstrLanguage, out var dummy);
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_LANGUAGE;
}
// The debugger is requesting the name of the module for this stack frame.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_MODULE) != 0)
{
if (this._stackFrame.FileName.IndexOfAny(Path.GetInvalidPathChars()) == -1)
{
frameInfo.m_bstrModule = Path.GetFileName(this._stackFrame.FileName);
}
else if (this._stackFrame.FileName.EndsWith("<string>", StringComparison.Ordinal))
{
frameInfo.m_bstrModule = "<exec/eval>";
}
else
{
frameInfo.m_bstrModule = "<unknown>";
}
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_MODULE;
}
// The debugger is requesting the IDebugStackFrame2 value for this frame info.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FRAME) != 0)
{
frameInfo.m_pFrame = this;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FRAME;
}
// Does this stack frame of symbols loaded?
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO) != 0)
{
frameInfo.m_fHasDebugInfo = 1;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO;
}
// Is this frame stale?
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_STALECODE) != 0)
{
frameInfo.m_fStaleCode = 0;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STALECODE;
}
// The debugger would like a pointer to the IDebugModule2 that contains this stack frame.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP) != 0)
{
// TODO: Module
/*
if (module != null)
{
AD7Module ad7Module = (AD7Module)module.Client;
Debug.Assert(ad7Module != null);
frameInfo.m_pModule = ad7Module;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP;
}*/
}
}
// Construct an instance of IEnumDebugPropertyInfo2 for the combined locals and parameters.
private List<DEBUG_PROPERTY_INFO> CreateLocalsPlusArgsProperties(uint radix)
{
return CreateLocalProperties(radix).Union(CreateParameterProperties(radix)).ToList();
}
// Construct an instance of IEnumDebugPropertyInfo2 for the locals collection only.
private List<DEBUG_PROPERTY_INFO> CreateLocalProperties(uint radix)
{
var properties = new List<DEBUG_PROPERTY_INFO>();
var locals = this._stackFrame.Locals;
for (var i = 0; i < locals.Count; i++)
{
var property = new AD7Property(this, locals[i]);
properties.Add(
property.ConstructDebugPropertyInfo(
radix,
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD | enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME
)
);
}
return properties;
}
// Construct an instance of IEnumDebugPropertyInfo2 for the parameters collection only.
private List<DEBUG_PROPERTY_INFO> CreateParameterProperties(uint radix)
{
var properties = new List<DEBUG_PROPERTY_INFO>();
var parameters = this._stackFrame.Parameters;
for (var i = 0; i < parameters.Count; i++)
{
var property = new AD7Property(this, parameters[i]);
properties.Add(
property.ConstructDebugPropertyInfo(
radix,
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD | enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME
)
);
}
return properties;
}
#endregion
#region IDebugStackFrame2 Members
// Creates an enumerator for properties associated with the stack frame, such as local variables.
// The sample engine only supports returning locals and parameters. Other possible values include
// class fields (this pointer), registers, exceptions...
int IDebugStackFrame2.EnumProperties(enum_DEBUGPROP_INFO_FLAGS dwFields, uint nRadix, ref Guid guidFilter, uint dwTimeout, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
List<DEBUG_PROPERTY_INFO> properties;
elementsReturned = 0;
enumObject = null;
if (guidFilter == DebuggerConstants.guidFilterLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocals)
{
properties = CreateLocalsPlusArgsProperties(nRadix);
}
else if (guidFilter == DebuggerConstants.guidFilterLocals)
{
properties = CreateLocalProperties(nRadix);
}
else if (guidFilter == DebuggerConstants.guidFilterArgs)
{
properties = CreateParameterProperties(nRadix);
}
else
{
return VSConstants.E_NOTIMPL;
}
// Select distinct values from arguments and local variables
properties = properties.GroupBy(p => p.bstrName).Select(p => p.First()).ToList();
elementsReturned = (uint)properties.Count;
enumObject = new AD7PropertyInfoEnum(properties.OrderBy(p => p.bstrName, this._comparer).ToArray());
return VSConstants.S_OK;
}
// Gets the code context for this stack frame. The code context represents the current instruction pointer in this stack frame.
int IDebugStackFrame2.GetCodeContext(out IDebugCodeContext2 memoryAddress)
{
memoryAddress = this.CodeContext;
return VSConstants.S_OK;
}
// Gets a description of the properties of a stack frame.
// Calling the IDebugProperty2::EnumChildren method with appropriate filters can retrieve the local variables, method parameters, registers, and "this"
// pointer associated with the stack frame. The debugger calls EnumProperties to obtain these values in the sample.
int IDebugStackFrame2.GetDebugProperty(out IDebugProperty2 property)
{
property = this;
return VSConstants.S_OK;
}
// Gets the document context for this stack frame. The debugger will call this when the current stack frame is changed
// and will use it to open the correct source document for this stack frame.
int IDebugStackFrame2.GetDocumentContext(out IDebugDocumentContext2 docContext)
{
docContext = this.DocumentContext;
return VSConstants.S_OK;
}
// Gets an evaluation context for expression evaluation within the current context of a stack frame and thread.
// Generally, an expression evaluation context can be thought of as a scope for performing expression evaluation.
// Call the IDebugExpressionContext2::ParseText method to parse an expression and then call the resulting IDebugExpression2::EvaluateSync
// or IDebugExpression2::EvaluateAsync methods to evaluate the parsed expression.
int IDebugStackFrame2.GetExpressionContext(out IDebugExpressionContext2 ppExprCxt)
{
ppExprCxt = this;
return VSConstants.S_OK;
}
// Gets a description of the stack frame.
int IDebugStackFrame2.GetInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, FRAMEINFO[] pFrameInfo)
{
SetFrameInfo(dwFieldSpec, out pFrameInfo[0]);
return VSConstants.S_OK;
}
// Gets the language associated with this stack frame.
// In this sample, all the supported stack frames are C++
int IDebugStackFrame2.GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage)
{
AD7Engine.MapLanguageInfo(this._stackFrame.FileName, out pbstrLanguage, out pguidLanguage);
return VSConstants.S_OK;
}
// Gets the name of the stack frame.
// The name of a stack frame is typically the name of the method being executed.
int IDebugStackFrame2.GetName(out string name)
{
name = this._stackFrame.FunctionName;
return 0;
}
// Gets a machine-dependent representation of the range of physical addresses associated with a stack frame.
int IDebugStackFrame2.GetPhysicalStackRange(out ulong addrMin, out ulong addrMax)
{
addrMin = 0;
addrMax = 0;
return VSConstants.S_OK;
}
// Gets the thread associated with a stack frame.
int IDebugStackFrame2.GetThread(out IDebugThread2 thread)
{
thread = this._thread;
return VSConstants.S_OK;
}
#endregion
#region IDebugExpressionContext2 Members
// Retrieves the name of the evaluation context.
// The name is the description of this evaluation context. It is typically something that can be parsed by an expression evaluator
// that refers to this exact evaluation context. For example, in C++ the name is as follows:
// "{ function-name, source-file-name, module-file-name }"
int IDebugExpressionContext2.GetName(out string pbstrName)
{
pbstrName = string.Format(CultureInfo.InvariantCulture, "{{ {0} {1} }}", this._stackFrame.FunctionName, this._stackFrame.FileName);
return VSConstants.S_OK;
}
// Parses a text-based expression for evaluation.
// The engine sample only supports locals and parameters so the only task here is to check the names in those collections.
int IDebugExpressionContext2.ParseText(string pszCode,
enum_PARSEFLAGS dwFlags,
uint nRadix,
out IDebugExpression2 ppExpr,
out string pbstrError,
out uint pichError)
{
pbstrError = string.Empty;
pichError = 0;
var evaluationResults = this._stackFrame.Locals.Union(this._stackFrame.Parameters);
foreach (var currVariable in evaluationResults)
{
if (StringComparer.Ordinal.Equals(currVariable.Expression, pszCode))
{
ppExpr = new UncalculatedAD7Expression(this, currVariable.Expression);
return VSConstants.S_OK;
}
}
if (!this._stackFrame.TryParseText(pszCode, out var errorMsg))
{
pbstrError = "Error: " + errorMsg;
pichError = (uint)pbstrError.Length;
}
ppExpr = new UncalculatedAD7Expression(this, pszCode);
return VSConstants.S_OK;
}
#endregion
#region IDebugProperty2 Members
int IDebugProperty2.GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo)
{
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout)
{
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout)
{
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum)
{
return ((IDebugStackFrame2)this).EnumProperties(dwFields, dwRadix, ref guidFilter, dwTimeout, out var pcelt, out ppEnum);
}
int IDebugProperty2.GetParent(out IDebugProperty2 ppParent)
{
ppParent = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost)
{
ppDerivedMost = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
ppMemoryBytes = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetMemoryContext(out IDebugMemoryContext2 ppMemory)
{
ppMemory = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetSize(out uint pdwSize)
{
pdwSize = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetReference(out IDebugReference2 ppReference)
{
ppReference = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetExtendedInfo(ref Guid guidExtendedInfo, out object pExtendedInfo)
{
pExtendedInfo = null;
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
#if UNIX
using System.Globalization;
using System.Management.Automation;
using System.Runtime.InteropServices;
#else
using System.Management.Automation;
using System.Management.Automation.Internal;
#endif
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>Removes the Zone.Identifier stream from a file.</summary>
[Cmdlet(VerbsSecurity.Unblock, "File", DefaultParameterSetName = "ByPath", SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097033")]
public sealed class UnblockFileCommand : PSCmdlet
{
#if UNIX
private const string MacBlockAttribute = "com.apple.quarantine";
private const int RemovexattrFollowSymLink = 0;
#endif
/// <summary>
/// The path of the file to unblock.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Path
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
/// <summary>
/// The literal path of the file to unblock.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)]
[Alias("PSPath", "LP")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
private string[] _paths;
/// <summary>
/// Generate the type(s)
/// </summary>
protected override void ProcessRecord()
{
List<string> pathsToProcess = new();
ProviderInfo provider = null;
if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
{
foreach (string path in _paths)
{
string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
if (IsValidFileForUnblocking(newPath))
{
pathsToProcess.Add(newPath);
}
}
}
else
{
// Resolve paths
foreach (string path in _paths)
{
try
{
Collection<string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
foreach (string currentFilepath in newPaths)
{
if (IsValidFileForUnblocking(currentFilepath))
{
pathsToProcess.Add(currentFilepath);
}
}
}
catch (ItemNotFoundException e)
{
if (!WildcardPattern.ContainsWildcardCharacters(path))
{
ErrorRecord errorRecord = new(e,
"FileNotFound",
ErrorCategory.ObjectNotFound,
path);
WriteError(errorRecord);
}
}
}
}
#if !UNIX
// Unblock files
foreach (string path in pathsToProcess)
{
if (ShouldProcess(path))
{
try
{
AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier");
}
catch (Exception e)
{
WriteError(new ErrorRecord(exception: e, errorId: "RemoveItemUnableToAccessFile", ErrorCategory.ResourceUnavailable, targetObject: path));
}
}
}
#else
if (Platform.IsLinux)
{
string errorMessage = UnblockFileStrings.LinuxNotSupported;
Exception e = new PlatformNotSupportedException(errorMessage);
ThrowTerminatingError(new ErrorRecord(exception: e, errorId: "LinuxNotSupported", ErrorCategory.NotImplemented, targetObject: null));
return;
}
foreach (string path in pathsToProcess)
{
if (IsBlocked(path))
{
UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink);
if (result != 0)
{
string errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path);
Exception e = new InvalidOperationException(errorMessage);
WriteError(new ErrorRecord(exception: e, errorId: "UnblockError", ErrorCategory.InvalidResult, targetObject: path));
}
}
}
#endif
}
/// <summary>
/// IsValidFileForUnblocking is a helper method used to validate if
/// the supplied file path has to be considered for unblocking.
/// </summary>
/// <param name="resolvedpath">File or directory path.</param>
/// <returns>True is the supplied path is a
/// valid file path or else false is returned.
/// If the supplied path is a directory path then false is returned.</returns>
private bool IsValidFileForUnblocking(string resolvedpath)
{
bool isValidUnblockableFile = false;
// Bug 501423 : silently ignore folders given that folders cannot have
// alternate data streams attached to them (i.e. they're already unblocked).
if (!System.IO.Directory.Exists(resolvedpath))
{
if (!System.IO.File.Exists(resolvedpath))
{
ErrorRecord errorRecord = new(
new System.IO.FileNotFoundException(resolvedpath),
"FileNotFound",
ErrorCategory.ObjectNotFound,
resolvedpath);
WriteError(errorRecord);
}
else
{
isValidUnblockableFile = true;
}
}
return isValidUnblockableFile;
}
#if UNIX
private static bool IsBlocked(string path)
{
const uint valueSize = 1024;
IntPtr value = Marshal.AllocHGlobal((int)valueSize);
try
{
var resultSize = GetXattr(path, MacBlockAttribute, value, valueSize, 0, RemovexattrFollowSymLink);
return resultSize != -1;
}
finally
{
Marshal.FreeHGlobal(value);
}
}
// Ansi means UTF8 on Unix
// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/RemoveXattr.2.html
[DllImport("libc", SetLastError = true, EntryPoint = "removexattr", CharSet = CharSet.Ansi)]
private static extern UInt32 RemoveXattr(string path, string name, int options);
[DllImport("libc", EntryPoint = "getxattr", CharSet = CharSet.Ansi)]
private static extern long GetXattr(
[MarshalAs(UnmanagedType.LPStr)] string path,
[MarshalAs(UnmanagedType.LPStr)] string name,
IntPtr value,
ulong size,
uint position,
int options);
#endif
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
using System.Threading;
namespace Microsoft.SPOT.Platform.Tests
{
public class SystemAppDomainTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
string szAssm = typeof(SystemAppDomainTests).Assembly.FullName;
m_appDomain = AppDomain.CreateDomain(this.GetType().FullName);
m_appDomain.Load(szAssm);
m_mbroProxy = (MyMarshalByRefObject)m_appDomain.CreateInstanceAndUnwrap(szAssm, typeof(MyMarshalByRefObject).FullName);
m_mbro = new MyMarshalByRefObject();
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
if (m_appDomain != null)
{
AppDomain.Unload(m_appDomain);
m_appDomain = null;
m_mbro = null;
m_mbroProxy = null;
Debug.GC(true);
}
}
[TestMethod]
public MFTestResults AppDomain_Test1()
{
/// <summary>
/// 1. Creates an AppDomain
/// 2. Calls SomeMethod in it
/// 3. Unloads that domain
/// 4. Calls SomeMethod again
/// 21291 Calling a method in an unloaded app domain should throw an exception.
/// </summary>
MFTestResults testResult = MFTestResults.Pass;
Log.Comment("Get and display the friendly name of the default AppDomain.");
string callingDomainName = Thread.GetDomain().FriendlyName;
if (callingDomainName != AppDomain.CurrentDomain.FriendlyName)
{
Log.Comment("Failure : Expected '" + AppDomain.CurrentDomain.FriendlyName +
"' but got '" + callingDomainName + "'");
testResult = MFTestResults.Fail;
}
Log.Comment(callingDomainName);
Type Type1 = this.GetType();
string exeAssembly = Assembly.GetAssembly(Type1).FullName;
Log.Comment("1. Creates an AppDomain");
AppDomain ad2 = AppDomain.CreateDomain("AppDomain #2");
TestMarshalByRefType mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap(
exeAssembly,
typeof(TestMarshalByRefType).FullName);
Assembly asm4 = ad2.Load(ad2.GetAssemblies()[0].FullName);
if (asm4.FullName != ad2.GetAssemblies()[0].FullName)
{
testResult = MFTestResults.Fail;
}
Log.Comment("2. Calls SomeMethod in it");
mbrt.SomeMethod(callingDomainName);
Log.Comment("3. Unloads that domain:");
AppDomain.Unload(ad2);
try
{
Log.Comment("4. calls SomeMethod again");
mbrt.SomeMethod(callingDomainName);
Log.Comment("Sucessful call.");
testResult = MFTestResults.Fail;
}
catch (AppDomainUnloadedException e)
{
Log.Comment("Specific Catch; this is expected. " + e.Message);
}
catch (Exception e)
{
Log.Comment("Generic Catch; this is bad. " + e.Message);
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults AppDomain_Test2()
{
MFTestResults testResult = MFTestResults.Pass;
try
{
Log.Comment("Get and display the friendly name of the default AppDomain.");
string callingDomainName = Thread.GetDomain().FriendlyName;
Type Type1 = this.GetType();
string exeAssembly = Assembly.GetAssembly(Type1).FullName;
Log.Comment("1. Creates an AppDomain");
AppDomain ad2 = AppDomain.CreateDomain("AppDomain #3");
TestMarshalByRefType mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap(
exeAssembly,
typeof(TestMarshalByRefType).FullName);
ad2.Load(ad2.GetAssemblies()[0].FullName);
Log.Comment("2. Calls SomeMethod in it");
mbrt.SomeMethod(callingDomainName);
Log.Comment("3. Unloads that domain:");
AppDomain.Unload(ad2);
Log.Comment("4. Reload AppDomain with same friendly name");
ad2 = AppDomain.CreateDomain("AppDomain #3");
mbrt = (TestMarshalByRefType)ad2.CreateInstanceAndUnwrap(
exeAssembly,
typeof(TestMarshalByRefType).FullName);
ad2.Load(ad2.GetAssemblies()[0].FullName);
Log.Comment("5. Calls SomeMethod in it");
mbrt.SomeMethod(callingDomainName);
Log.Comment("6. Unloads that domain:");
AppDomain.Unload(ad2);
}
catch (Exception e)
{
Log.Comment("Generic Catch; this is bad. " + e.Message);
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalInt_Test2()
{
MFTestResults testResult = MFTestResults.Pass;
int i = 123;
int result = m_mbroProxy.MarhsalInt(i);
if (result != i)
{
Log.Comment("Failure : Expected '" + i + "' but got '" + result + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalIntByRef_Test3()
{
MFTestResults testResult = MFTestResults.Pass;
int i = 123;
int i2 = 456;
m_mbroProxy.MarshalIntByRef(ref i, i2);
if (i != i2)
{
Log.Comment("Failure : Expected '" + i2 + "' but got '" + i + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalIntArrayByRef_Test4()
{
MFTestResults testResult = MFTestResults.Pass;
int[] i = new int[] { 123 };
int i2 = 456;
m_mbroProxy.MarshalIntByRef(ref i[0], i2);
if (i[0] != i2)
{
Log.Comment("Failure : Expected '" + i2 + "' but got '" + i[0] + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalDouble_Test5()
{
MFTestResults testResult = MFTestResults.Pass;
double d = 123.456;
double d2 = m_mbroProxy.MarhsalDouble(d);
if (d2 != d)
{
Log.Comment("Failure : Expected '" + d + "' but got '" + d2 + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalDoubleByRef_Test6()
{
MFTestResults testResult = MFTestResults.Pass;
double d = 123.0;
double d2 = 456.0;
m_mbroProxy.MarshalDoubleByRef(ref d, d2);
if (d != d2)
{
Log.Comment("Failure : Expected '" + d2 + "' but got '" + d + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalDateTime_Test7()
{
MFTestResults testResult = MFTestResults.Pass;
DateTime dt = new DateTime(1976, 3, 4);
DateTime dt2 = m_mbroProxy.MarshalDateTime(dt);
if (dt != dt2)
{
Log.Comment("Failure : Expected '" + dt2 + "' but got '" + dt + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalDateTimeByRef_Test8()
{
MFTestResults testResult = MFTestResults.Pass;
DateTime dt = new DateTime(1976, 3, 4);
DateTime dt2 = new DateTime(1976, 3, 10);
m_mbroProxy.MarshalDateTimeByRef(ref dt, dt2);
if (dt != dt2)
{
Log.Comment("Failure : Expected '" + dt2 + "' but got '" + dt + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalString_Test9()
{
MFTestResults testResult = MFTestResults.Pass;
string s = "hello";
string s2 = m_mbroProxy.MarshalString(s);
if (s != s2)
{
Log.Comment("Failure : Expected '" + s + "' but got '" + s2 + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalStringByRef_Test10()
{
MFTestResults testResult = MFTestResults.Pass;
string s = "hello";
string s2 = "goodbye";
m_mbroProxy.MarshalStringByRef(ref s, s2);
if (s != s2)
{
Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults TestNull_Test11()
{
MFTestResults testResult = MFTestResults.Pass;
if (!m_mbroProxy.MarshalNull(null))
{
Log.Comment("Failure : Marshalling a null obj. is not equal to null");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults TestThrow_Test12()
{
string message = "message";
MFTestResults testResult = MFTestResults.Fail;
try
{
m_mbroProxy.Throw(message);
Log.Comment("Failure to throw Exception");
}
catch (Exception e)
{
if (e.Message == message)
{
testResult = MFTestResults.Pass;
}
else
{
Log.Comment("Failure : Expected message '" + message + "' but got '" + e.Message + "'");
}
}
return testResult;
}
[TestMethod]
public MFTestResults TestNonSerializableClass_Test13()
{
MFTestResults testResult = MFTestResults.Fail;
try
{
m_mbroProxy.TestNonSerializableClass(new NonSerializableClass());
Log.Comment("Failure to throw Exception");
}
catch (Exception)
{
testResult = MFTestResults.Pass;
}
return testResult;
}
[TestMethod]
public MFTestResults TestProxyEquality_Test14()
{
MFTestResults testResult = MFTestResults.Pass;
if (!m_mbroProxy.ProxyEquality(m_mbro, m_mbro))
{
Log.Comment("Failure : Marshalling the same obj. and comparing failed");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults TestProxyDelegate_Test15()
{
MyMarshalByRefObject.PrintDelegate dlg = new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print);
dlg("Hello world");
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults TestProxyMulticastDelegate_Test16()
{
MyMarshalByRefObject.PrintDelegate dlg = null;
dlg = (MyMarshalByRefObject.PrintDelegate)Microsoft.SPOT.WeakDelegate.Combine(dlg, new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print));
dlg = (MyMarshalByRefObject.PrintDelegate)Microsoft.SPOT.WeakDelegate.Combine(dlg, new MyMarshalByRefObject.PrintDelegate(m_mbroProxy.Print));
dlg("Goodnight moon");
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults MarshalMBRO_Test17()
{
MFTestResults testResult = MFTestResults.Pass;
MyMarshalByRefObject mbro = m_mbroProxy.MarshalMBRO(m_mbro);
if (mbro != m_mbro)
{
Log.Comment("Failure : Expected '" + m_mbro + "' but got '" + mbro + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalMBROByRef_Test18()
{
MFTestResults testResult = MFTestResults.Pass;
MyMarshalByRefObject mbro = new MyMarshalByRefObject();
MyMarshalByRefObject mbro2 = new MyMarshalByRefObject();
m_mbroProxy.MarshalMBROByRef(ref mbro, mbro2);
if(!Object.ReferenceEquals(mbro, mbro2))
{
Log.Comment("Failure : Marshalling Obj. by Reference and comparing Object.ReferenceEquals(mbro, mbro2) failed");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalClass_Test19()
{
ClassToMarshal c = new ClassToMarshal(123, "hello");
return EqualsButNotSameInstance(c, m_mbroProxy.MarshalClass(c)) ? MFTestResults.Pass : MFTestResults.Fail;
}
[TestMethod]
public MFTestResults MarshalClassByRef_Test20()
{
ClassToMarshal c = new ClassToMarshal(123, "hello");
ClassToMarshal c2 = new ClassToMarshal(456, "goodbye");
m_mbroProxy.MarshalClassByRef(ref c, c2);
return this.EqualsButNotSameInstance(c, c2) ? MFTestResults.Pass : MFTestResults.Fail;
}
[TestMethod]
public MFTestResults MarshalClassArrayByRef_Test21()
{
ClassToMarshal[] c = new ClassToMarshal[] { new ClassToMarshal(123, "hello") };
ClassToMarshal c2 = new ClassToMarshal(456, "goodbye");
m_mbroProxy.MarshalClassByRef(ref c[0], c2);
return this.EqualsButNotSameInstance(c[0], c2) ? MFTestResults.Pass : MFTestResults.Fail;
}
[TestMethod]
public MFTestResults FieldAccess_Test22()
{
MFTestResults testResult = MFTestResults.Pass;
int i = 123;
string s = "hello";
m_mbroProxy.m_int = i;
m_mbroProxy.m_string = s;
if (m_mbroProxy.m_int != i)
{
Log.Comment("Failure : int acces, expected '" + i + "' but got '" + m_mbroProxy.m_int + "'");
testResult = MFTestResults.Fail;
}
if (m_mbroProxy.m_string != s)
{
Log.Comment("Failure : string acces, expected '" + s + "' but got '" + m_mbroProxy.m_string + "'");
testResult = MFTestResults.Fail;
}
i = 456;
s = "goodbye";
FieldInfo fi = m_mbroProxy.GetType().GetField("m_int", BindingFlags.Instance | BindingFlags.Public);
fi.SetValue(m_mbroProxy, i);
if ((int)fi.GetValue(m_mbroProxy) != i)
{
Log.Comment("Failure : Reflection int , expected '" + i + "' but got '" + (int)fi.GetValue(m_mbroProxy) + "'");
testResult = MFTestResults.Fail;
}
fi = m_mbroProxy.GetType().GetField("m_string", BindingFlags.Instance | BindingFlags.Public);
fi.SetValue(m_mbroProxy, s);
if ((string)fi.GetValue(m_mbroProxy) != s)
{
Log.Comment("Failure : Reflection string , expected '" + s + "' but got '" + (string)fi.GetValue(m_mbroProxy) + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults StartThread_Test23()
{
m_mbroProxy.StartThread();
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults MarshalType_Test24()
{
MFTestResults testResult = MFTestResults.Pass;
Type s = typeof(int);
Type s2 = typeof(bool);
s2 = m_mbroProxy.MarshalType(s);
if (s != s2)
{
Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalTypeByRef_Test25()
{
MFTestResults testResult = MFTestResults.Pass;
Type s = typeof(int);
Type s2 = typeof(bool);
m_mbroProxy.MarshalTypeByRef(ref s, s2);
if (s != s2)
{
Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalTypeArray_Test26()
{
MFTestResults testResult = MFTestResults.Pass;
Type[] s = new Type[] { typeof(int), typeof(bool) };
Type[] s2 = null;
s2 = m_mbroProxy.MarshalTypeArray(s);
if (s2 == null || s2[0] != s[0] || s2[1] != s[1])
{
Log.Comment("Failure : Expected '" + s2 + "' but got '" + s + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalAssembly_Test27()
{
MFTestResults testResult = MFTestResults.Pass;
Assembly s = typeof(int).Assembly;
Assembly s2 = typeof(MFTestResults).Assembly;
s2 = m_mbroProxy.MarshalAssembly(s);
if (s.FullName != s2.FullName)
{
Log.Comment("Failure : Expected '" + s2.FullName + "' but got '" + s.FullName + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalAssemblyByRef_Test28()
{
MFTestResults testResult = MFTestResults.Pass;
Assembly s = typeof(int).Assembly;
Assembly s2 = typeof(MFTestResults).Assembly;
m_mbroProxy.MarshalAssemblyByRef(ref s, s2);
if (s.FullName != s2.FullName)
{
Log.Comment("Failure : Expected '" + s2.FullName + "' but got '" + s.FullName + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalFieldInfo_Test29()
{
MFTestResults testResult = MFTestResults.Pass;
FieldInfo s = typeof(MyMarshalByRefObject).GetField("m_int");
FieldInfo s2 = typeof(MyMarshalByRefObject).GetFields()[1];
s2 = m_mbroProxy.MarshalFieldInfo(s);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalFieldInfoByRef_Test30()
{
MFTestResults testResult = MFTestResults.Pass;
FieldInfo s = typeof(MyMarshalByRefObject).GetField("m_int");
FieldInfo s2 = typeof(MyMarshalByRefObject).GetFields()[1];
m_mbroProxy.MarshalFieldInfoByRef(ref s, s2);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalMethodInfo_Test31()
{
MFTestResults testResult = MFTestResults.Pass;
MethodInfo s = typeof(MyMarshalByRefObject).GetMethod("Print");
MethodInfo s2 = typeof(Array).GetMethods()[0];
s2 = m_mbroProxy.MarshalMethodInfo(s);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalMethodInfoByRef_Test32()
{
MFTestResults testResult = MFTestResults.Pass;
MethodInfo s = typeof(MyMarshalByRefObject).GetMethod("Print");
MethodInfo s2 = typeof(Array).GetMethods()[0];
m_mbroProxy.MarshalMethodInfoByRef(ref s, s2);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalConstructorInfo_Test33()
{
MFTestResults testResult = MFTestResults.Pass;
ConstructorInfo s = typeof(MyMarshalByRefObject).GetConstructor(new Type[] {});
ConstructorInfo s2 = typeof(Array).GetConstructor(new Type[] { });
s2 = m_mbroProxy.MarshalConstructorInfo(s);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
[TestMethod]
public MFTestResults MarshalMethodInfoByRef_Test34()
{
MFTestResults testResult = MFTestResults.Pass;
ConstructorInfo s = typeof(MyMarshalByRefObject).GetConstructor(new Type[] { });
ConstructorInfo s2 = typeof(Array).GetConstructor(new Type[] { });
m_mbroProxy.MarshalConstructorInfoByRef(ref s, s2);
if (s.Name != s2.Name)
{
Log.Comment("Failure : Expected '" + s2.Name + "' but got '" + s.Name + "'");
testResult = MFTestResults.Fail;
}
return testResult;
}
#region Variables
protected AppDomain m_appDomain;
protected MyMarshalByRefObject m_mbroProxy;
protected MyMarshalByRefObject m_mbro;
#endregion Variables
#region HelperMethods
private bool EqualsButNotSameInstance(object obj1, object obj2)
{
bool bResult = true;
if (!Object.Equals(obj1, obj2))
{
Log.Comment("Failure : Object.Equals(obj1, obj2) returned false");
bResult = false;
}
else if (Object.ReferenceEquals(obj1, obj2))
{
Log.Comment("Failure : Object.ReferenceEquals(obj1, obj2) returned true");
bResult = false;
}
return bResult;
}
#endregion HelperMethods
#region HelperClasses
public class TestMarshalByRefType : MarshalByRefObject
{
/// <summary>
/// 1. This method is called via a proxy.
/// 2. Display the name of the calling AppDomain and the name of the second domain
/// </summary>
public void SomeMethod(string callingDomainName)
{
Log.Comment("Calling from " + callingDomainName + " to "
+ Thread.GetDomain().FriendlyName);
}
}
public class MyMarshalByRefObject : MarshalByRefObject
{
public int m_int;
public string m_string;
public delegate void PrintDelegate(string text);
public void Print(string text)
{
Debug.Print(text);
if (System.Runtime.Remoting.RemotingServices.IsTransparentProxy(this))
{
Debug.Print("FAILURE: METHOD CALL ON PROXY OBJECT ");
}
}
public int MarhsalInt(int i)
{
return i;
}
public void MarshalIntByRef(ref int i, int i2)
{
i = i2;
}
public double MarhsalDouble(double d)
{
return d;
}
public void MarshalDoubleByRef(ref double d, double d2)
{
d = d2;
}
public string MarshalString(string s)
{
return s;
}
public void MarshalStringByRef(ref string s, string s2)
{
s = s2;
}
public DateTime MarshalDateTime(DateTime dt)
{
return dt;
}
public void MarshalDateTimeByRef(ref DateTime dt, DateTime dt2)
{
dt = dt2;
}
public void Throw(string message)
{
throw new Exception(message);
}
public bool MarshalNull(object o)
{
return o == null;
}
public ClassToMarshal MarshalClass(ClassToMarshal c)
{
return c;
}
public void MarshalClassByRef(ref ClassToMarshal c, ClassToMarshal c2)
{
c = c2;
}
public void TestNonSerializableClass(NonSerializableClass c)
{
}
public bool ProxyEquality(MyMarshalByRefObject mbro1, MyMarshalByRefObject mbro2)
{
return mbro1 == mbro2;
}
public void MarshalDyingProxy(MyMarshalByRefObject mbro)
{
}
public void MarshalDeadProxy(MyMarshalByRefObject mbro)
{
}
public MyMarshalByRefObject MarshalMBRO(MyMarshalByRefObject mbro)
{
return mbro;
}
public void MarshalMBROByRef(ref MyMarshalByRefObject mbro, MyMarshalByRefObject mbro2)
{
mbro = mbro2;
}
public Type MarshalType(Type t1)
{
return t1;
}
public void MarshalTypeByRef(ref Type t1, Type t2)
{
t1 = t2;
}
public Type[] MarshalTypeArray(Type[] t1)
{
return t1;
}
public void MarshalTypeArrayByRef(ref Type[] t1, Type[] t2)
{
Array.Copy(t1, t2, t1.Length);
}
public Assembly MarshalAssembly(Assembly a1)
{
return a1;
}
public void MarshalAssemblyByRef(ref Assembly a1, Assembly a2)
{
a1 = a2;
}
public FieldInfo MarshalFieldInfo(FieldInfo a1)
{
return a1;
}
public void MarshalFieldInfoByRef(ref FieldInfo a1, FieldInfo a2)
{
a1 = a2;
}
public MethodInfo MarshalMethodInfo(MethodInfo a1)
{
return a1;
}
public void MarshalMethodInfoByRef(ref MethodInfo a1, MethodInfo a2)
{
a1 = a2;
}
public ConstructorInfo MarshalConstructorInfo(ConstructorInfo a1)
{
return a1;
}
public void MarshalConstructorInfoByRef(ref ConstructorInfo a1, ConstructorInfo a2)
{
a1 = a2;
}
public MyMarshalByRefObject CreateMBRO()
{
return new MyMarshalByRefObject();
}
public void StartThread()
{
Thread th = new Thread(new ThreadStart(ThreadWorker));
th.Start();
}
private void ThreadWorker()
{
try
{
while (true) ;
}
catch (Exception)
{
Debug.Print("ThreadWorker being aborted..");
}
}
}
[Serializable]
public class ClassToMarshal
{
public int m_int;
public string m_string;
public ClassToMarshal(int i, string s)
{
m_int = i;
m_string = s;
}
public override bool Equals(object obj)
{
ClassToMarshal cls = obj as ClassToMarshal;
if (cls == null) return false;
if (cls.m_int != m_int) return false;
if (cls.m_string != m_string) return false;
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class NonSerializableClass
{
}
#endregion HelperClasses
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the MamTratamiento class.
/// </summary>
[Serializable]
public partial class MamTratamientoCollection : ActiveList<MamTratamiento, MamTratamientoCollection>
{
public MamTratamientoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>MamTratamientoCollection</returns>
public MamTratamientoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
MamTratamiento o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the MAM_Tratamientos table.
/// </summary>
[Serializable]
public partial class MamTratamiento : ActiveRecord<MamTratamiento>, IActiveRecord
{
#region .ctors and Default Settings
public MamTratamiento()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MamTratamiento(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MamTratamiento(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MamTratamiento(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("MAM_Tratamientos", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTratamiento = new TableSchema.TableColumn(schema);
colvarIdTratamiento.ColumnName = "idTratamiento";
colvarIdTratamiento.DataType = DbType.Int32;
colvarIdTratamiento.MaxLength = 0;
colvarIdTratamiento.AutoIncrement = true;
colvarIdTratamiento.IsNullable = false;
colvarIdTratamiento.IsPrimaryKey = true;
colvarIdTratamiento.IsForeignKey = false;
colvarIdTratamiento.IsReadOnly = false;
colvarIdTratamiento.DefaultSetting = @"";
colvarIdTratamiento.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTratamiento);
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = false;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = false;
colvarIdPaciente.IsReadOnly = false;
colvarIdPaciente.DefaultSetting = @"((0))";
colvarIdPaciente.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = false;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"((0))";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarNeoadyuvancia = new TableSchema.TableColumn(schema);
colvarNeoadyuvancia.ColumnName = "neoadyuvancia";
colvarNeoadyuvancia.DataType = DbType.Int32;
colvarNeoadyuvancia.MaxLength = 0;
colvarNeoadyuvancia.AutoIncrement = false;
colvarNeoadyuvancia.IsNullable = false;
colvarNeoadyuvancia.IsPrimaryKey = false;
colvarNeoadyuvancia.IsForeignKey = false;
colvarNeoadyuvancia.IsReadOnly = false;
colvarNeoadyuvancia.DefaultSetting = @"((0))";
colvarNeoadyuvancia.ForeignKeyTableName = "";
schema.Columns.Add(colvarNeoadyuvancia);
TableSchema.TableColumn colvarFechaInicioNeoadyuvancia = new TableSchema.TableColumn(schema);
colvarFechaInicioNeoadyuvancia.ColumnName = "fechaInicioNeoadyuvancia";
colvarFechaInicioNeoadyuvancia.DataType = DbType.DateTime;
colvarFechaInicioNeoadyuvancia.MaxLength = 0;
colvarFechaInicioNeoadyuvancia.AutoIncrement = false;
colvarFechaInicioNeoadyuvancia.IsNullable = false;
colvarFechaInicioNeoadyuvancia.IsPrimaryKey = false;
colvarFechaInicioNeoadyuvancia.IsForeignKey = false;
colvarFechaInicioNeoadyuvancia.IsReadOnly = false;
colvarFechaInicioNeoadyuvancia.DefaultSetting = @"";
colvarFechaInicioNeoadyuvancia.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInicioNeoadyuvancia);
TableSchema.TableColumn colvarQuimioterapia = new TableSchema.TableColumn(schema);
colvarQuimioterapia.ColumnName = "quimioterapia";
colvarQuimioterapia.DataType = DbType.Int32;
colvarQuimioterapia.MaxLength = 0;
colvarQuimioterapia.AutoIncrement = false;
colvarQuimioterapia.IsNullable = false;
colvarQuimioterapia.IsPrimaryKey = false;
colvarQuimioterapia.IsForeignKey = false;
colvarQuimioterapia.IsReadOnly = false;
colvarQuimioterapia.DefaultSetting = @"((0))";
colvarQuimioterapia.ForeignKeyTableName = "";
schema.Columns.Add(colvarQuimioterapia);
TableSchema.TableColumn colvarFechaInicioQuimio = new TableSchema.TableColumn(schema);
colvarFechaInicioQuimio.ColumnName = "fechaInicioQuimio";
colvarFechaInicioQuimio.DataType = DbType.DateTime;
colvarFechaInicioQuimio.MaxLength = 0;
colvarFechaInicioQuimio.AutoIncrement = false;
colvarFechaInicioQuimio.IsNullable = false;
colvarFechaInicioQuimio.IsPrimaryKey = false;
colvarFechaInicioQuimio.IsForeignKey = false;
colvarFechaInicioQuimio.IsReadOnly = false;
colvarFechaInicioQuimio.DefaultSetting = @"";
colvarFechaInicioQuimio.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInicioQuimio);
TableSchema.TableColumn colvarRadioterapia = new TableSchema.TableColumn(schema);
colvarRadioterapia.ColumnName = "radioterapia";
colvarRadioterapia.DataType = DbType.Int32;
colvarRadioterapia.MaxLength = 0;
colvarRadioterapia.AutoIncrement = false;
colvarRadioterapia.IsNullable = false;
colvarRadioterapia.IsPrimaryKey = false;
colvarRadioterapia.IsForeignKey = false;
colvarRadioterapia.IsReadOnly = false;
colvarRadioterapia.DefaultSetting = @"((0))";
colvarRadioterapia.ForeignKeyTableName = "";
schema.Columns.Add(colvarRadioterapia);
TableSchema.TableColumn colvarFechaInicioRadioterapia = new TableSchema.TableColumn(schema);
colvarFechaInicioRadioterapia.ColumnName = "fechaInicioRadioterapia";
colvarFechaInicioRadioterapia.DataType = DbType.DateTime;
colvarFechaInicioRadioterapia.MaxLength = 0;
colvarFechaInicioRadioterapia.AutoIncrement = false;
colvarFechaInicioRadioterapia.IsNullable = false;
colvarFechaInicioRadioterapia.IsPrimaryKey = false;
colvarFechaInicioRadioterapia.IsForeignKey = false;
colvarFechaInicioRadioterapia.IsReadOnly = false;
colvarFechaInicioRadioterapia.DefaultSetting = @"";
colvarFechaInicioRadioterapia.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInicioRadioterapia);
TableSchema.TableColumn colvarTrastuzumab = new TableSchema.TableColumn(schema);
colvarTrastuzumab.ColumnName = "trastuzumab";
colvarTrastuzumab.DataType = DbType.Int32;
colvarTrastuzumab.MaxLength = 0;
colvarTrastuzumab.AutoIncrement = false;
colvarTrastuzumab.IsNullable = false;
colvarTrastuzumab.IsPrimaryKey = false;
colvarTrastuzumab.IsForeignKey = false;
colvarTrastuzumab.IsReadOnly = false;
colvarTrastuzumab.DefaultSetting = @"((0))";
colvarTrastuzumab.ForeignKeyTableName = "";
schema.Columns.Add(colvarTrastuzumab);
TableSchema.TableColumn colvarFechaInicioTrastuzumab = new TableSchema.TableColumn(schema);
colvarFechaInicioTrastuzumab.ColumnName = "fechaInicioTrastuzumab";
colvarFechaInicioTrastuzumab.DataType = DbType.DateTime;
colvarFechaInicioTrastuzumab.MaxLength = 0;
colvarFechaInicioTrastuzumab.AutoIncrement = false;
colvarFechaInicioTrastuzumab.IsNullable = false;
colvarFechaInicioTrastuzumab.IsPrimaryKey = false;
colvarFechaInicioTrastuzumab.IsForeignKey = false;
colvarFechaInicioTrastuzumab.IsReadOnly = false;
colvarFechaInicioTrastuzumab.DefaultSetting = @"";
colvarFechaInicioTrastuzumab.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInicioTrastuzumab);
TableSchema.TableColumn colvarHormonoterapia = new TableSchema.TableColumn(schema);
colvarHormonoterapia.ColumnName = "Hormonoterapia";
colvarHormonoterapia.DataType = DbType.AnsiString;
colvarHormonoterapia.MaxLength = 50;
colvarHormonoterapia.AutoIncrement = false;
colvarHormonoterapia.IsNullable = false;
colvarHormonoterapia.IsPrimaryKey = false;
colvarHormonoterapia.IsForeignKey = false;
colvarHormonoterapia.IsReadOnly = false;
colvarHormonoterapia.DefaultSetting = @"('')";
colvarHormonoterapia.ForeignKeyTableName = "";
schema.Columns.Add(colvarHormonoterapia);
TableSchema.TableColumn colvarFechaHormonoterapiaInicial = new TableSchema.TableColumn(schema);
colvarFechaHormonoterapiaInicial.ColumnName = "fechaHormonoterapiaInicial";
colvarFechaHormonoterapiaInicial.DataType = DbType.DateTime;
colvarFechaHormonoterapiaInicial.MaxLength = 0;
colvarFechaHormonoterapiaInicial.AutoIncrement = false;
colvarFechaHormonoterapiaInicial.IsNullable = false;
colvarFechaHormonoterapiaInicial.IsPrimaryKey = false;
colvarFechaHormonoterapiaInicial.IsForeignKey = false;
colvarFechaHormonoterapiaInicial.IsReadOnly = false;
colvarFechaHormonoterapiaInicial.DefaultSetting = @"";
colvarFechaHormonoterapiaInicial.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaHormonoterapiaInicial);
TableSchema.TableColumn colvarFechaHormonoterapia = new TableSchema.TableColumn(schema);
colvarFechaHormonoterapia.ColumnName = "fechaHormonoterapia";
colvarFechaHormonoterapia.DataType = DbType.DateTime;
colvarFechaHormonoterapia.MaxLength = 0;
colvarFechaHormonoterapia.AutoIncrement = false;
colvarFechaHormonoterapia.IsNullable = false;
colvarFechaHormonoterapia.IsPrimaryKey = false;
colvarFechaHormonoterapia.IsForeignKey = false;
colvarFechaHormonoterapia.IsReadOnly = false;
colvarFechaHormonoterapia.DefaultSetting = @"";
colvarFechaHormonoterapia.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaHormonoterapia);
TableSchema.TableColumn colvarObservacion = new TableSchema.TableColumn(schema);
colvarObservacion.ColumnName = "observacion";
colvarObservacion.DataType = DbType.AnsiString;
colvarObservacion.MaxLength = 200;
colvarObservacion.AutoIncrement = false;
colvarObservacion.IsNullable = false;
colvarObservacion.IsPrimaryKey = false;
colvarObservacion.IsForeignKey = false;
colvarObservacion.IsReadOnly = false;
colvarObservacion.DefaultSetting = @"('')";
colvarObservacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservacion);
TableSchema.TableColumn colvarIdResponsableExamen = new TableSchema.TableColumn(schema);
colvarIdResponsableExamen.ColumnName = "idResponsableExamen";
colvarIdResponsableExamen.DataType = DbType.Int32;
colvarIdResponsableExamen.MaxLength = 0;
colvarIdResponsableExamen.AutoIncrement = false;
colvarIdResponsableExamen.IsNullable = false;
colvarIdResponsableExamen.IsPrimaryKey = false;
colvarIdResponsableExamen.IsForeignKey = true;
colvarIdResponsableExamen.IsReadOnly = false;
colvarIdResponsableExamen.DefaultSetting = @"((0))";
colvarIdResponsableExamen.ForeignKeyTableName = "Sys_Profesional";
schema.Columns.Add(colvarIdResponsableExamen);
TableSchema.TableColumn colvarIdCentroSalud = new TableSchema.TableColumn(schema);
colvarIdCentroSalud.ColumnName = "idCentroSalud";
colvarIdCentroSalud.DataType = DbType.Int32;
colvarIdCentroSalud.MaxLength = 0;
colvarIdCentroSalud.AutoIncrement = false;
colvarIdCentroSalud.IsNullable = false;
colvarIdCentroSalud.IsPrimaryKey = false;
colvarIdCentroSalud.IsForeignKey = true;
colvarIdCentroSalud.IsReadOnly = false;
colvarIdCentroSalud.DefaultSetting = @"((0))";
colvarIdCentroSalud.ForeignKeyTableName = "Sys_Efector";
schema.Columns.Add(colvarIdCentroSalud);
TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema);
colvarActivo.ColumnName = "activo";
colvarActivo.DataType = DbType.Boolean;
colvarActivo.MaxLength = 0;
colvarActivo.AutoIncrement = false;
colvarActivo.IsNullable = false;
colvarActivo.IsPrimaryKey = false;
colvarActivo.IsForeignKey = false;
colvarActivo.IsReadOnly = false;
colvarActivo.DefaultSetting = @"((1))";
colvarActivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarActivo);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.String;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = false;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"('')";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = false;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"(((1)/(1))/(1900))";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.String;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = false;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"('')";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = false;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"(((1)/(1))/(1900))";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("MAM_Tratamientos",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTratamiento")]
[Bindable(true)]
public int IdTratamiento
{
get { return GetColumnValue<int>(Columns.IdTratamiento); }
set { SetColumnValue(Columns.IdTratamiento, value); }
}
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int IdPaciente
{
get { return GetColumnValue<int>(Columns.IdPaciente); }
set { SetColumnValue(Columns.IdPaciente, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int Edad
{
get { return GetColumnValue<int>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("Neoadyuvancia")]
[Bindable(true)]
public int Neoadyuvancia
{
get { return GetColumnValue<int>(Columns.Neoadyuvancia); }
set { SetColumnValue(Columns.Neoadyuvancia, value); }
}
[XmlAttribute("FechaInicioNeoadyuvancia")]
[Bindable(true)]
public DateTime FechaInicioNeoadyuvancia
{
get { return GetColumnValue<DateTime>(Columns.FechaInicioNeoadyuvancia); }
set { SetColumnValue(Columns.FechaInicioNeoadyuvancia, value); }
}
[XmlAttribute("Quimioterapia")]
[Bindable(true)]
public int Quimioterapia
{
get { return GetColumnValue<int>(Columns.Quimioterapia); }
set { SetColumnValue(Columns.Quimioterapia, value); }
}
[XmlAttribute("FechaInicioQuimio")]
[Bindable(true)]
public DateTime FechaInicioQuimio
{
get { return GetColumnValue<DateTime>(Columns.FechaInicioQuimio); }
set { SetColumnValue(Columns.FechaInicioQuimio, value); }
}
[XmlAttribute("Radioterapia")]
[Bindable(true)]
public int Radioterapia
{
get { return GetColumnValue<int>(Columns.Radioterapia); }
set { SetColumnValue(Columns.Radioterapia, value); }
}
[XmlAttribute("FechaInicioRadioterapia")]
[Bindable(true)]
public DateTime FechaInicioRadioterapia
{
get { return GetColumnValue<DateTime>(Columns.FechaInicioRadioterapia); }
set { SetColumnValue(Columns.FechaInicioRadioterapia, value); }
}
[XmlAttribute("Trastuzumab")]
[Bindable(true)]
public int Trastuzumab
{
get { return GetColumnValue<int>(Columns.Trastuzumab); }
set { SetColumnValue(Columns.Trastuzumab, value); }
}
[XmlAttribute("FechaInicioTrastuzumab")]
[Bindable(true)]
public DateTime FechaInicioTrastuzumab
{
get { return GetColumnValue<DateTime>(Columns.FechaInicioTrastuzumab); }
set { SetColumnValue(Columns.FechaInicioTrastuzumab, value); }
}
[XmlAttribute("Hormonoterapia")]
[Bindable(true)]
public string Hormonoterapia
{
get { return GetColumnValue<string>(Columns.Hormonoterapia); }
set { SetColumnValue(Columns.Hormonoterapia, value); }
}
[XmlAttribute("FechaHormonoterapiaInicial")]
[Bindable(true)]
public DateTime FechaHormonoterapiaInicial
{
get { return GetColumnValue<DateTime>(Columns.FechaHormonoterapiaInicial); }
set { SetColumnValue(Columns.FechaHormonoterapiaInicial, value); }
}
[XmlAttribute("FechaHormonoterapia")]
[Bindable(true)]
public DateTime FechaHormonoterapia
{
get { return GetColumnValue<DateTime>(Columns.FechaHormonoterapia); }
set { SetColumnValue(Columns.FechaHormonoterapia, value); }
}
[XmlAttribute("Observacion")]
[Bindable(true)]
public string Observacion
{
get { return GetColumnValue<string>(Columns.Observacion); }
set { SetColumnValue(Columns.Observacion, value); }
}
[XmlAttribute("IdResponsableExamen")]
[Bindable(true)]
public int IdResponsableExamen
{
get { return GetColumnValue<int>(Columns.IdResponsableExamen); }
set { SetColumnValue(Columns.IdResponsableExamen, value); }
}
[XmlAttribute("IdCentroSalud")]
[Bindable(true)]
public int IdCentroSalud
{
get { return GetColumnValue<int>(Columns.IdCentroSalud); }
set { SetColumnValue(Columns.IdCentroSalud, value); }
}
[XmlAttribute("Activo")]
[Bindable(true)]
public bool Activo
{
get { return GetColumnValue<bool>(Columns.Activo); }
set { SetColumnValue(Columns.Activo, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime CreatedOn
{
get { return GetColumnValue<DateTime>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime ModifiedOn
{
get { return GetColumnValue<DateTime>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysEfector ActiveRecord object related to this MamTratamiento
///
/// </summary>
public DalSic.SysEfector SysEfector
{
get { return DalSic.SysEfector.FetchByID(this.IdCentroSalud); }
set { SetColumnValue("idCentroSalud", value.IdEfector); }
}
/// <summary>
/// Returns a SysProfesional ActiveRecord object related to this MamTratamiento
///
/// </summary>
public DalSic.SysProfesional SysProfesional
{
get { return DalSic.SysProfesional.FetchByID(this.IdResponsableExamen); }
set { SetColumnValue("idResponsableExamen", value.IdProfesional); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdPaciente,DateTime varFecha,int varEdad,int varNeoadyuvancia,DateTime varFechaInicioNeoadyuvancia,int varQuimioterapia,DateTime varFechaInicioQuimio,int varRadioterapia,DateTime varFechaInicioRadioterapia,int varTrastuzumab,DateTime varFechaInicioTrastuzumab,string varHormonoterapia,DateTime varFechaHormonoterapiaInicial,DateTime varFechaHormonoterapia,string varObservacion,int varIdResponsableExamen,int varIdCentroSalud,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn)
{
MamTratamiento item = new MamTratamiento();
item.IdPaciente = varIdPaciente;
item.Fecha = varFecha;
item.Edad = varEdad;
item.Neoadyuvancia = varNeoadyuvancia;
item.FechaInicioNeoadyuvancia = varFechaInicioNeoadyuvancia;
item.Quimioterapia = varQuimioterapia;
item.FechaInicioQuimio = varFechaInicioQuimio;
item.Radioterapia = varRadioterapia;
item.FechaInicioRadioterapia = varFechaInicioRadioterapia;
item.Trastuzumab = varTrastuzumab;
item.FechaInicioTrastuzumab = varFechaInicioTrastuzumab;
item.Hormonoterapia = varHormonoterapia;
item.FechaHormonoterapiaInicial = varFechaHormonoterapiaInicial;
item.FechaHormonoterapia = varFechaHormonoterapia;
item.Observacion = varObservacion;
item.IdResponsableExamen = varIdResponsableExamen;
item.IdCentroSalud = varIdCentroSalud;
item.Activo = varActivo;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTratamiento,int varIdPaciente,DateTime varFecha,int varEdad,int varNeoadyuvancia,DateTime varFechaInicioNeoadyuvancia,int varQuimioterapia,DateTime varFechaInicioQuimio,int varRadioterapia,DateTime varFechaInicioRadioterapia,int varTrastuzumab,DateTime varFechaInicioTrastuzumab,string varHormonoterapia,DateTime varFechaHormonoterapiaInicial,DateTime varFechaHormonoterapia,string varObservacion,int varIdResponsableExamen,int varIdCentroSalud,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn)
{
MamTratamiento item = new MamTratamiento();
item.IdTratamiento = varIdTratamiento;
item.IdPaciente = varIdPaciente;
item.Fecha = varFecha;
item.Edad = varEdad;
item.Neoadyuvancia = varNeoadyuvancia;
item.FechaInicioNeoadyuvancia = varFechaInicioNeoadyuvancia;
item.Quimioterapia = varQuimioterapia;
item.FechaInicioQuimio = varFechaInicioQuimio;
item.Radioterapia = varRadioterapia;
item.FechaInicioRadioterapia = varFechaInicioRadioterapia;
item.Trastuzumab = varTrastuzumab;
item.FechaInicioTrastuzumab = varFechaInicioTrastuzumab;
item.Hormonoterapia = varHormonoterapia;
item.FechaHormonoterapiaInicial = varFechaHormonoterapiaInicial;
item.FechaHormonoterapia = varFechaHormonoterapia;
item.Observacion = varObservacion;
item.IdResponsableExamen = varIdResponsableExamen;
item.IdCentroSalud = varIdCentroSalud;
item.Activo = varActivo;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTratamientoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPacienteColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn NeoadyuvanciaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn FechaInicioNeoadyuvanciaColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn QuimioterapiaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FechaInicioQuimioColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn RadioterapiaColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn FechaInicioRadioterapiaColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn TrastuzumabColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn FechaInicioTrastuzumabColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn HormonoterapiaColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn FechaHormonoterapiaInicialColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn FechaHormonoterapiaColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn ObservacionColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn IdResponsableExamenColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn IdCentroSaludColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn ActivoColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[22]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTratamiento = @"idTratamiento";
public static string IdPaciente = @"idPaciente";
public static string Fecha = @"fecha";
public static string Edad = @"edad";
public static string Neoadyuvancia = @"neoadyuvancia";
public static string FechaInicioNeoadyuvancia = @"fechaInicioNeoadyuvancia";
public static string Quimioterapia = @"quimioterapia";
public static string FechaInicioQuimio = @"fechaInicioQuimio";
public static string Radioterapia = @"radioterapia";
public static string FechaInicioRadioterapia = @"fechaInicioRadioterapia";
public static string Trastuzumab = @"trastuzumab";
public static string FechaInicioTrastuzumab = @"fechaInicioTrastuzumab";
public static string Hormonoterapia = @"Hormonoterapia";
public static string FechaHormonoterapiaInicial = @"fechaHormonoterapiaInicial";
public static string FechaHormonoterapia = @"fechaHormonoterapia";
public static string Observacion = @"observacion";
public static string IdResponsableExamen = @"idResponsableExamen";
public static string IdCentroSalud = @"idCentroSalud";
public static string Activo = @"activo";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
namespace SlimMessageBus.Host.Memory.Test
{
using System;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using SlimMessageBus.Host.Config;
using SlimMessageBus.Host.DependencyResolver;
using SlimMessageBus.Host.Serialization;
using Xunit;
public class MemoryMessageBusTest
{
private readonly Lazy<MemoryMessageBus> _subject;
private readonly MessageBusSettings _settings = new MessageBusSettings();
private readonly MemoryMessageBusSettings _providerSettings = new MemoryMessageBusSettings();
private readonly Mock<IDependencyResolver> _dependencyResolverMock = new Mock<IDependencyResolver>();
private readonly Mock<IMessageSerializer> _messageSerializerMock = new Mock<IMessageSerializer>();
public MemoryMessageBusTest()
{
_settings.DependencyResolver = _dependencyResolverMock.Object;
_settings.Serializer = _messageSerializerMock.Object;
_messageSerializerMock
.Setup(x => x.Serialize(It.IsAny<Type>(), It.IsAny<object>()))
.Returns((Type type, object message) => Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)));
_messageSerializerMock
.Setup(x => x.Deserialize(It.IsAny<Type>(), It.IsAny<byte[]>()))
.Returns((Type type, byte[] payload) => JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload), type));
_subject = new Lazy<MemoryMessageBus>(() => new MemoryMessageBus(_settings, _providerSettings));
}
private static ProducerSettings Producer(Type messageType, string defaultTopic)
{
return new ProducerSettings
{
MessageType = messageType,
DefaultPath = defaultTopic
};
}
private static ConsumerSettings Consumer(Type messageType, string topic, Type consumerType)
{
return new ConsumerBuilder<object>(new MessageBusSettings(), messageType).Topic(topic).WithConsumer(consumerType).ConsumerSettings;
}
[Fact]
public void When_Create_Given_MessageSerializationDisabled_And_NoSerializerProvided_Then_NoException()
{
// arrange
_settings.Serializer = null;
_providerSettings.EnableMessageSerialization = false;
// act
Action act = () => { var _ = _subject.Value; };
// assert
act.Should().NotThrow<ConfigurationMessageBusException>();
}
[Fact]
public void When_Create_Given_MessageSerializationEnabled_And_NoSerializerProvided_Then_ThrowsException()
{
// arrange
_settings.Serializer = null;
_providerSettings.EnableMessageSerialization = true;
// act
Action act = () => { var _ = _subject.Value; };
// assert
act.Should().Throw<ConfigurationMessageBusException>();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void When_Publish_Given_MessageSerializationSetting_Then_DeliversMessageInstanceToRespectiveConsumers(bool enableMessageSerialization)
{
// arrange
const string topicA = "topic-a";
const string topicA2 = "topic-a-2";
const string topicB = "topic-b";
_settings.Producers.Add(Producer(typeof(SomeMessageA), topicA));
_settings.Producers.Add(Producer(typeof(SomeMessageB), topicB));
_settings.Consumers.Add(Consumer(typeof(SomeMessageA), topicA, typeof(SomeMessageAConsumer)));
_settings.Consumers.Add(Consumer(typeof(SomeMessageA), topicA2, typeof(SomeMessageAConsumer2)));
_settings.Consumers.Add(Consumer(typeof(SomeMessageB), topicB, typeof(SomeMessageBConsumer)));
var aConsumerMock = new Mock<SomeMessageAConsumer>();
var aConsumer2Mock = new Mock<SomeMessageAConsumer2>();
var bConsumerMock = new Mock<SomeMessageBConsumer>();
_dependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageAConsumer))).Returns(aConsumerMock.Object);
_dependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageAConsumer2))).Returns(aConsumer2Mock.Object);
_dependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageBConsumer))).Returns(bConsumerMock.Object);
_providerSettings.EnableMessageSerialization = enableMessageSerialization;
var m = new SomeMessageA();
// act
_subject.Value.Publish(m).Wait();
// assert
if (enableMessageSerialization)
{
aConsumerMock.Verify(x => x.OnHandle(It.Is<SomeMessageA>(a => a.Equals(m)), topicA), Times.Once);
}
else
{
aConsumerMock.Verify(x => x.OnHandle(m, topicA), Times.Once);
}
aConsumerMock.VerifyNoOtherCalls();
aConsumer2Mock.Verify(x => x.OnHandle(It.IsAny<SomeMessageA>(), topicA2), Times.Never);
aConsumer2Mock.VerifyNoOtherCalls();
bConsumerMock.Verify(x => x.OnHandle(It.IsAny<SomeMessageB>(), topicB), Times.Never);
bConsumerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task When_Publish_Given_PerMessageScopeEnabled_Then_TheScopeIsCreatedAndConsumerObtainedFromScope()
{
// arrange
var consumerMock = new Mock<SomeMessageAConsumer>();
var scope = new Mock<IChildDependencyResolver>();
scope.Setup(x => x.Resolve(typeof(SomeMessageAConsumer))).Returns(() => consumerMock.Object);
scope.Setup(x => x.Dispose()).Callback(() => { });
_dependencyResolverMock.Setup(x => x.CreateScope()).Returns(() => scope.Object);
const string topic = "topic-a";
_settings.Producers.Add(Producer(typeof(SomeMessageA), topic));
_settings.Consumers.Add(Consumer(typeof(SomeMessageA), topic, typeof(SomeMessageAConsumer)));
_settings.IsMessageScopeEnabled = true;
_providerSettings.EnableMessageSerialization = false;
var m = new SomeMessageA();
// act
await _subject.Value.Publish(m);
// assert
_dependencyResolverMock.Verify(x => x.Resolve(typeof(ILoggerFactory)), Times.Once);
_dependencyResolverMock.Verify(x => x.CreateScope(), Times.Once);
_dependencyResolverMock.VerifyNoOtherCalls();
scope.Verify(x => x.Resolve(typeof(SomeMessageAConsumer)), Times.Once);
scope.Verify(x => x.Dispose(), Times.Once);
scope.VerifyNoOtherCalls();
consumerMock.Verify(x => x.OnHandle(m, topic), Times.Once);
consumerMock.Verify(x => x.Dispose(), Times.Never);
consumerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task When_Publish_Given_PerMessageScopeDisabled_Then_TheScopeIsNotCreatedAndConsumerObtainedFromRoot()
{
// arrange
var consumerMock = new Mock<SomeMessageAConsumer>();
_dependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageAConsumer))).Returns(() => consumerMock.Object);
const string topic = "topic-a";
_settings.Producers.Add(Producer(typeof(SomeMessageA), topic));
var consumerSettings = Consumer(typeof(SomeMessageA), topic, typeof(SomeMessageAConsumer));
consumerSettings.IsDisposeConsumerEnabled = true;
_settings.Consumers.Add(consumerSettings);
_settings.IsMessageScopeEnabled = false;
_providerSettings.EnableMessageSerialization = false;
var m = new SomeMessageA();
// act
await _subject.Value.Publish(m);
// assert
_dependencyResolverMock.Verify(x => x.Resolve(typeof(ILoggerFactory)), Times.Once);
_dependencyResolverMock.Verify(x => x.CreateScope(), Times.Never);
_dependencyResolverMock.Verify(x => x.Resolve(typeof(SomeMessageAConsumer)), Times.Once);
_dependencyResolverMock.VerifyNoOtherCalls();
consumerMock.Verify(x => x.OnHandle(m, topic), Times.Once);
consumerMock.Verify(x => x.Dispose(), Times.Once);
consumerMock.VerifyNoOtherCalls();
}
[Theory]
[InlineData(new object[] { true })]
[InlineData(new object[] { false })]
public async Task When_Publish_Given_PerMessageScopeDisabledOrEnabled_And_OutterBusCreatedMesssageScope_Then_TheScopeIsNotCreated_And_ConsumerObtainedFromCurrentMessageScope(bool isMessageScopeEnabled)
{
// arrange
var consumerMock = new Mock<SomeMessageAConsumer>();
_dependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageAConsumer))).Returns(() => consumerMock.Object);
var currentScopeDependencyResolverMock = new Mock<IDependencyResolver>();
currentScopeDependencyResolverMock.Setup(x => x.Resolve(typeof(SomeMessageAConsumer))).Returns(() => consumerMock.Object);
const string topic = "topic-a";
_settings.Producers.Add(Producer(typeof(SomeMessageA), topic));
var consumerSettings = Consumer(typeof(SomeMessageA), topic, typeof(SomeMessageAConsumer));
consumerSettings.IsDisposeConsumerEnabled = true;
_settings.Consumers.Add(consumerSettings);
_settings.IsMessageScopeEnabled = isMessageScopeEnabled;
_providerSettings.EnableMessageSerialization = false;
var m = new SomeMessageA();
// set current scope
MessageScope.Current = currentScopeDependencyResolverMock.Object;
// act
await _subject.Value.Publish(m);
// assert
// current scope is not changed
MessageScope.Current.Should().BeSameAs(currentScopeDependencyResolverMock.Object);
_dependencyResolverMock.Verify(x => x.Resolve(typeof(ILoggerFactory)), Times.Once);
_dependencyResolverMock.Verify(x => x.CreateScope(), Times.Never);
_dependencyResolverMock.Verify(x => x.Resolve(typeof(SomeMessageAConsumer)), Times.Never);
_dependencyResolverMock.VerifyNoOtherCalls();
currentScopeDependencyResolverMock.Verify(x => x.CreateScope(), Times.Never);
currentScopeDependencyResolverMock.Verify(x => x.Resolve(typeof(SomeMessageAConsumer)), Times.Once);
currentScopeDependencyResolverMock.VerifyNoOtherCalls();
consumerMock.Verify(x => x.OnHandle(m, topic), Times.Once);
consumerMock.Verify(x => x.Dispose(), Times.Once);
consumerMock.VerifyNoOtherCalls();
}
}
public class SomeMessageA
{
public Guid Value { get; set; }
#region Equality members
protected bool Equals(SomeMessageA other)
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((SomeMessageA)obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
#endregion
}
public class SomeMessageB
{
public Guid Value { get; set; }
#region Equality members
protected bool Equals(SomeMessageB other)
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((SomeMessageB)obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
#endregion
}
public class SomeMessageAConsumer : IConsumer<SomeMessageA>, IDisposable
{
public virtual void Dispose()
{
// Needed to check disposing
}
#region Implementation of IConsumer<in SomeMessageA>
public virtual Task OnHandle(SomeMessageA messageA, string name)
{
return Task.CompletedTask;
}
#endregion
}
public class SomeMessageAConsumer2 : IConsumer<SomeMessageA>
{
#region Implementation of IConsumer<in SomeMessageA>
public virtual Task OnHandle(SomeMessageA messageA, string name)
{
return Task.CompletedTask;
}
#endregion
}
public class SomeMessageBConsumer : IConsumer<SomeMessageB>
{
#region Implementation of IConsumer<in SomeMessageB>
public virtual Task OnHandle(SomeMessageB message, string name)
{
return Task.CompletedTask;
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace SoftLogik.Win.Data
{
/// <summary>
/// Strongly-typed collection for the MasterGroup class.
/// </summary>
[Serializable]
public partial class MasterGroupCollection : ActiveList<MasterGroup, MasterGroupCollection>
{
public MasterGroupCollection() {}
}
/// <summary>
/// This is an ActiveRecord class which wraps the SLMasterGroup table.
/// </summary>
[Serializable]
public partial class MasterGroup : ActiveRecord<MasterGroup>
{
#region .ctors and Default Settings
public MasterGroup()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MasterGroup(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MasterGroup(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MasterGroup(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("SLMasterGroup", TableType.Table, DataService.GetInstance("WinSubSonicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarGroupID = new TableSchema.TableColumn(schema);
colvarGroupID.ColumnName = "GroupID";
colvarGroupID.DataType = DbType.String;
colvarGroupID.MaxLength = 5;
colvarGroupID.AutoIncrement = false;
colvarGroupID.IsNullable = false;
colvarGroupID.IsPrimaryKey = true;
colvarGroupID.IsForeignKey = false;
colvarGroupID.IsReadOnly = false;
colvarGroupID.DefaultSetting = @"";
colvarGroupID.ForeignKeyTableName = "";
schema.Columns.Add(colvarGroupID);
TableSchema.TableColumn colvarGroupName = new TableSchema.TableColumn(schema);
colvarGroupName.ColumnName = "GroupName";
colvarGroupName.DataType = DbType.String;
colvarGroupName.MaxLength = 100;
colvarGroupName.AutoIncrement = false;
colvarGroupName.IsNullable = true;
colvarGroupName.IsPrimaryKey = false;
colvarGroupName.IsForeignKey = false;
colvarGroupName.IsReadOnly = false;
colvarGroupName.DefaultSetting = @"";
colvarGroupName.ForeignKeyTableName = "";
schema.Columns.Add(colvarGroupName);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.String;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["WinSubSonicProvider"].AddSchema("SLMasterGroup",schema);
}
}
#endregion
#region Props
[XmlAttribute("GroupID")]
public string GroupID
{
get { return GetColumnValue<string>("GroupID"); }
set { SetColumnValue("GroupID", value); }
}
[XmlAttribute("GroupName")]
public string GroupName
{
get { return GetColumnValue<string>("GroupName"); }
set { SetColumnValue("GroupName", value); }
}
[XmlAttribute("CreatedOn")]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>("CreatedOn"); }
set { SetColumnValue("CreatedOn", value); }
}
[XmlAttribute("ModifiedOn")]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>("ModifiedOn"); }
set { SetColumnValue("ModifiedOn", value); }
}
[XmlAttribute("ModifiedBy")]
public string ModifiedBy
{
get { return GetColumnValue<string>("ModifiedBy"); }
set { SetColumnValue("ModifiedBy", value); }
}
#endregion
#region PrimaryKey Methods
public SoftLogik.Win.Data.MasterCollection MasterRecords()
{
return new SoftLogik.Win.Data.MasterCollection().Where(Master.Columns.GroupID, GroupID).Load();
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varGroupID,string varGroupName,DateTime? varCreatedOn,DateTime? varModifiedOn,string varModifiedBy)
{
MasterGroup item = new MasterGroup();
item.GroupID = varGroupID;
item.GroupName = varGroupName;
item.CreatedOn = varCreatedOn;
item.ModifiedOn = varModifiedOn;
item.ModifiedBy = varModifiedBy;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varGroupID,string varGroupName,DateTime? varCreatedOn,DateTime? varModifiedOn,string varModifiedBy)
{
MasterGroup item = new MasterGroup();
item.GroupID = varGroupID;
item.GroupName = varGroupName;
item.CreatedOn = varCreatedOn;
item.ModifiedOn = varModifiedOn;
item.ModifiedBy = varModifiedBy;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Columns Struct
public struct Columns
{
public static string GroupID = @"GroupID";
public static string GroupName = @"GroupName";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedOn = @"ModifiedOn";
public static string ModifiedBy = @"ModifiedBy";
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetGore.Db.ClassCreator
{
/// <summary>
/// A <see cref="CodeFormatter"/> for CSharp.
/// </summary>
public class CSharpCodeFormatter : CodeFormatter
{
/// <summary>
/// Gets the closing char for a brace.
/// </summary>
public override string CloseBrace
{
get { return "}"; }
}
/// <summary>
/// Gets the closing char for an indexer.
/// </summary>
public override string CloseIndexer
{
get { return "]"; }
}
/// <summary>
/// Gets the char for an end of a line.
/// </summary>
public override string EndOfLine
{
get { return ";"; }
}
/// <summary>
/// Gets the file name suffix.
/// </summary>
public override string FilenameSuffix
{
get { return "cs"; }
}
/// <summary>
/// Gets the opening char for a brace.
/// </summary>
public override string OpenBrace
{
get { return "{"; }
}
/// <summary>
/// Gets the opening char for an indexer.
/// </summary>
public override string OpenIndexer
{
get { return "["; }
}
/// <summary>
/// Gets the char to use to separate parameters.
/// </summary>
public override string ParameterSpacer
{
get { return ", "; }
}
/// <summary>
/// Gets the code for an attribute.
/// </summary>
/// <param name="attributeType">The attribute type</param>
/// <param name="args">The attribute arguments.</param>
/// <returns>The code.</returns>
public override string GetAttribute(string attributeType, params string[] args)
{
var sb = new StringBuilder();
sb.Append(OpenIndexer);
sb.Append(attributeType);
sb.Append(OpenParameterString);
if (args != null && args.Length > 0)
{
for (var i = 0; i < args.Length - 1; i++)
{
sb.Append(args[i]);
sb.Append(ParameterSpacer);
}
sb.Append(args[args.Length - 1]);
}
sb.Append(CloseParameterString);
sb.Append(CloseIndexer);
return sb.ToString();
}
/// <summary>
/// Gets the code for a class.
/// </summary>
/// <param name="className">Name of the class.</param>
/// <param name="visibility">The visibility.</param>
/// <param name="isStatic">Whether or not it is a static class.</param>
/// <param name="interfaces">The interfaces.</param>
/// <returns>The code.</returns>
public override string GetClass(string className, MemberVisibilityLevel visibility, bool isStatic, IEnumerable<string> interfaces)
{
var sb = new StringBuilder();
sb.Append(GetVisibilityLevel(visibility));
if (isStatic)
sb.Append(" static ");
sb.Append(" class ");
sb.Append(className);
if (interfaces != null && !interfaces.IsEmpty())
{
sb.Append(" : ");
foreach (var i in interfaces)
{
sb.Append(i);
sb.Append(ParameterSpacer);
}
sb.Length -= ParameterSpacer.Length;
}
return sb.ToString();
}
/// <summary>
/// Gets the code for a constant field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="type">The type.</param>
/// <param name="visibility">The visibility.</param>
/// <param name="value">The value.</param>
/// <returns>The code.</returns>
public override string GetConstField(string fieldName, Type type, MemberVisibilityLevel visibility, string value)
{
var sb = new StringBuilder();
sb.Append(GetVisibilityLevel(visibility));
sb.Append(" const ");
sb.Append(GetTypeString(type));
sb.Append(" ");
sb.Append(fieldName);
sb.Append(" = ");
sb.Append(value);
sb.Append(EndOfLine);
return sb.ToString();
}
/// <summary>
/// Gets the code for a field.
/// </summary>
/// <param name="memberName">Name of the member.</param>
/// <param name="type">The type.</param>
/// <param name="visibility">The visibility.</param>
/// <param name="code">The code.</param>
/// <param name="isReadonly">If this field is readonly.</param>
/// <param name="isStatic">If this field is static.</param>
/// <returns>The code.</returns>
public override string GetField(string memberName, string type, MemberVisibilityLevel visibility, string code,
bool isReadonly, bool isStatic)
{
var sb = new StringBuilder();
if (visibility != MemberVisibilityLevel.Private)
{
sb.Append(GetVisibilityLevel(visibility));
sb.Append(" ");
}
if (isStatic)
sb.Append(" static ");
if (isReadonly)
sb.Append(" readonly ");
sb.Append(type);
sb.Append(" ");
sb.Append(memberName);
if (!string.IsNullOrEmpty(code))
{
sb.Append(" = ");
sb.Append(code);
}
sb.Append(EndOfLine);
return sb.ToString();
}
/// <summary>
/// Gets the code for an interface.
/// </summary>
/// <param name="interfaceName">The interface name.</param>
/// <param name="visibility">The visibility.</param>
/// <returns>The code.</returns>
public override string GetInterface(string interfaceName, MemberVisibilityLevel visibility)
{
return GetVisibilityLevel(visibility) + " interface " + interfaceName;
}
/// <summary>
/// Gets the code for a local field.
/// </summary>
/// <param name="memberName">Name of the member.</param>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
/// <returns>The code.</returns>
public override string GetLocalField(string memberName, string type, string value)
{
var sb = new StringBuilder();
sb.Append(type);
sb.Append(" ");
sb.Append(memberName);
if (!string.IsNullOrEmpty(value))
{
sb.Append(" = ");
sb.Append(value);
}
sb.Append(EndOfLine);
return sb.ToString();
}
/// <summary>
/// Gets the code for a namespace.
/// </summary>
/// <param name="namespaceName">Name of the namespace.</param>
/// <returns>The code.</returns>
public override string GetNamespace(string namespaceName)
{
return "namespace " + namespaceName;
}
/// <summary>
/// When overridden in the derived class, generates the code for an array of string literals.
/// </summary>
/// <param name="strings">The string literals to include.</param>
/// <returns>The code for an array of string literals.</returns>
public override string GetStringArrayCode(IEnumerable<string> strings)
{
var sb = new StringBuilder();
sb.Append("new string[] ");
sb.Append(OpenBrace);
foreach (var s in strings)
{
sb.Append("\"");
sb.Append(s);
sb.Append("\"");
sb.Append(ParameterSpacer);
}
if (!strings.IsEmpty())
sb.Length -= ParameterSpacer.Length;
sb.Append(" ");
sb.Append(CloseBrace);
return sb.ToString();
}
/// <summary>
/// When overridden in the derived class, generates the code for a switch.
/// </summary>
/// <param name="switchOn">The code to switch on.</param>
/// <param name="switches">The switches to use, where the key is the switch's value, and the value is the
/// code used for the switch.</param>
/// <param name="defaultCode">The code to use on a default. If null, no default switch will be made.</param>
/// <returns>The code for a switch.</returns>
public override string GetSwitch(string switchOn, IEnumerable<KeyValuePair<string, string>> switches, string defaultCode)
{
var sb = new StringBuilder(512);
sb.Append("switch ");
sb.Append(OpenParameterString);
sb.Append(switchOn);
sb.AppendLine(CloseParameterString);
sb.AppendLine(OpenBrace);
foreach (var item in switches)
{
sb.Append("case ");
sb.Append(item.Key);
sb.AppendLine(":");
sb.AppendLine(item.Value);
sb.AppendLine();
}
if (defaultCode != null)
{
sb.AppendLine("default:");
sb.AppendLine(defaultCode);
}
sb.AppendLine(CloseBrace);
return sb.ToString();
}
/// <summary>
/// Gets the code for a using namespace directive.
/// </summary>
/// <param name="namespaceName">Name of the namespace.</param>
/// <returns>The code.</returns>
public override string GetUsing(string namespaceName)
{
return "using " + namespaceName + EndOfLine;
}
/// <summary>
/// Gets the code to represent a visibility level.
/// </summary>
/// <param name="visibility">The visibility level.</param>
/// <returns>The code.</returns>
/// <exception cref="ArgumentOutOfRangeException"><c>visibility</c> contains an undefined
/// <see cref="MemberVisibilityLevel"/> value.</exception>
public override string GetVisibilityLevel(MemberVisibilityLevel visibility)
{
switch (visibility)
{
case MemberVisibilityLevel.Private:
return "private";
case MemberVisibilityLevel.Public:
return "public";
case MemberVisibilityLevel.Internal:
return "internal";
case MemberVisibilityLevel.Protected:
return "protected";
case MemberVisibilityLevel.ProtectedInternal:
return "protected internal";
default:
throw new ArgumentOutOfRangeException("visibility");
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Tests.Common;
using System.Text;
using System.Xml;
using Xunit;
using Xunit.Extensions;
public static class BasicHttpBindingTest
{
[Fact]
public static void Default_Ctor_Initializes_Properties()
{
var binding = new BasicHttpBinding();
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("http", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[Fact]
public static void Ctor_With_BasicHttpSecurityMode_Transport_Initializes_Properties()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("https", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[Fact]
public static void Ctor_With_BasicHttpSecurityMode_TransportCredentialOnly_Initializes_Properties()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("http", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[Fact(Skip = "SecurityBindingElement Not Supported Yet")]
public static void Ctor_With_BasicHttpSecurityMode_TransportWithMessageCredential_Initializes_Properties()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("https", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void AllowCookies_Property_Sets(bool value)
{
var binding = new BasicHttpBinding();
binding.AllowCookies = value;
Assert.Equal<bool>(value, binding.AllowCookies);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxBufferPoolSize_Property_Sets(long value)
{
var binding = new BasicHttpBinding();
binding.MaxBufferPoolSize = value;
Assert.Equal<long>(value, binding.MaxBufferPoolSize);
}
[Theory]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxBufferPoolSize_Property_Set_Invalid_Value_Throws(long value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferPoolSize = value);
}
[Theory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxBufferSize_Property_Sets(int value)
{
var binding = new BasicHttpBinding();
binding.MaxBufferSize = value;
Assert.Equal<long>(value, binding.MaxBufferSize);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxBufferSize_Property_Set_Invalid_Value_Throws(int value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferSize = value);
}
[Theory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxReceivedMessageSize_Property_Sets(long value)
{
var binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = value;
Assert.Equal<long>(value, binding.MaxReceivedMessageSize);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxReceivedMessageSize_Property_Set_Invalid_Value_Throws(int value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxReceivedMessageSize = value);
}
[Theory]
[InlineData("testName")]
public static void Name_Property_Sets(string value)
{
var binding = new BasicHttpBinding();
binding.Name = value;
Assert.Equal<string>(value, binding.Name);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public static void Name_Property_Set_Invalid_Value_Throws(string value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentException>(() => binding.Name = value);
}
[Theory]
[InlineData("")]
[InlineData("http://hello")]
[InlineData("testNamespace")]
public static void Namespace_Property_Sets(string value)
{
var binding = new BasicHttpBinding();
binding.Namespace = value;
Assert.Equal<string>(value, binding.Namespace);
}
[Theory]
[InlineData(null)]
public static void Namespace_Property_Set_Invalid_Value_Throws(string value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentNullException>(() => binding.Namespace = value);
}
public static MemberDataSet<Encoding> ValidEncodings
{
get
{
return new MemberDataSet<Encoding>
{
{ Encoding.BigEndianUnicode },
{ Encoding.Unicode },
{ Encoding.UTF8 },
};
}
}
public static MemberDataSet<Encoding> InvalidEncodings
{
get
{
MemberDataSet<Encoding> data = new MemberDataSet<Encoding>();
foreach (string encodingName in new string[] { "utf-7", "Windows-1252", "us-ascii", "iso-8859-1", "x-Chinese-CNS", "IBM273" })
{
try
{
Encoding encoding = Encoding.GetEncoding(encodingName);
data.Add(encoding);
}
catch
{
// not all encodings are supported on all frameworks
}
}
return data;
}
}
[Fact]
public static void ReaderQuotas_Property_Sets()
{
var binding = new BasicHttpBinding();
XmlDictionaryReaderQuotas maxQuota = XmlDictionaryReaderQuotas.Max;
XmlDictionaryReaderQuotas defaultQuota = new XmlDictionaryReaderQuotas();
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, defaultQuota));
binding.ReaderQuotas = maxQuota;
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, maxQuota), "Setting Max ReaderQuota failed");
}
[Fact]
public static void ReaderQuotas_Property_Set_Null_Throws()
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentNullException>(() => binding.ReaderQuotas = null);
}
[Theory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void CloseTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.CloseTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.CloseTimeout);
}
[Theory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void CloseTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.CloseTimeout = timeSpan);
}
[Theory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void OpenTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.OpenTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.OpenTimeout);
}
[Theory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void OpenTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.OpenTimeout = timeSpan);
}
[Theory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void SendTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.SendTimeout);
}
[Theory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void SendTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan);
}
[Theory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void ReceiveTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.ReceiveTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.ReceiveTimeout);
}
[Theory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void ReceiveTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan);
}
[Theory]
[MemberData("ValidEncodings", MemberType = typeof(TestData))]
public static void TextEncoding_Property_Sets(Encoding encoding)
{
var binding = new BasicHttpBinding();
binding.TextEncoding = encoding;
Assert.Equal<Encoding>(encoding, binding.TextEncoding);
}
[Theory]
[MemberData("InvalidEncodings", MemberType = typeof(TestData))]
public static void TextEncoding_Property_Set_Invalid_Value_Throws(Encoding encoding)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentException>(() => binding.TextEncoding = encoding);
}
[Theory]
[InlineData(TransferMode.Buffered)]
[InlineData(TransferMode.Streamed)]
[InlineData(TransferMode.StreamedRequest)]
[InlineData(TransferMode.StreamedResponse)]
public static void TransferMode_Property_Sets(TransferMode transferMode)
{
var binding = new BasicHttpBinding();
binding.TransferMode = transferMode;
Assert.Equal<TransferMode>(transferMode, binding.TransferMode);
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An image, video, or audio object embedded in a web page. Note that a creative work may have many media objects associated with it on the same web page. For example, a page about a single song (MusicRecording) may have a music video (VideoObject), and a high and low bandwidth audio stream (2 AudioObject's).
/// </summary>
public class MediaObject_Core : TypeCore, ICreativeWork
{
public MediaObject_Core()
{
this._TypeId = 161;
this._Id = "MediaObject";
this._Schema_Org_Url = "http://schema.org/MediaObject";
string label = "";
GetLabel(out label, "MediaObject", typeof(MediaObject_Core));
this._Label = label;
this._Ancestors = new int[]{266,78};
this._SubTypes = new int[]{22,136,181,285};
this._SuperTypes = new int[]{78};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,17,31,52,53,71,76,79,80,88,101,160,188,192,228,234};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// A NewsArticle associated with the Media Object.
/// </summary>
private AssociatedArticle_Core associatedArticle;
public AssociatedArticle_Core AssociatedArticle
{
get
{
return associatedArticle;
}
set
{
associatedArticle = value;
SetPropertyInstance(associatedArticle);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// The bitrate of the media object.
/// </summary>
private Bitrate_Core bitrate;
public Bitrate_Core Bitrate
{
get
{
return bitrate;
}
set
{
bitrate = value;
SetPropertyInstance(bitrate);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// File size in (mega/kilo) bytes.
/// </summary>
private ContentSize_Core contentSize;
public ContentSize_Core ContentSize
{
get
{
return contentSize;
}
set
{
contentSize = value;
SetPropertyInstance(contentSize);
}
}
/// <summary>
/// Actual bytes of the media object, for example the image file or video file.
/// </summary>
private ContentURL_Core contentURL;
public ContentURL_Core ContentURL
{
get
{
return contentURL;
}
set
{
contentURL = value;
SetPropertyInstance(contentURL);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// A URL pointing to a player for a specific video. In general, this is the information in the <code>src</code> element of an <code>embed</code> tag and should not be the same as the content of the <code>loc</code> tag.
/// </summary>
private EmbedURL_Core embedURL;
public EmbedURL_Core EmbedURL
{
get
{
return embedURL;
}
set
{
embedURL = value;
SetPropertyInstance(embedURL);
}
}
/// <summary>
/// The creative work encoded by this media object
/// </summary>
private EncodesCreativeWork_Core encodesCreativeWork;
public EncodesCreativeWork_Core EncodesCreativeWork
{
get
{
return encodesCreativeWork;
}
set
{
encodesCreativeWork = value;
SetPropertyInstance(encodesCreativeWork);
}
}
/// <summary>
/// mp3, mpeg4, etc.
/// </summary>
private EncodingFormat_Core encodingFormat;
public EncodingFormat_Core EncodingFormat
{
get
{
return encodingFormat;
}
set
{
encodingFormat = value;
SetPropertyInstance(encodingFormat);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Date the content expires and is no longer useful or available. Useful for videos.
/// </summary>
private Expires_Core expires;
public Expires_Core Expires
{
get
{
return expires;
}
set
{
expires = value;
SetPropertyInstance(expires);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// The height of the media object.
/// </summary>
private Height_Core height;
public Height_Core Height
{
get
{
return height;
}
set
{
height = value;
SetPropertyInstance(height);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Player type required\u2014for example, Flash or Silverlight.
/// </summary>
private PlayerType_Core playerType;
public PlayerType_Core PlayerType
{
get
{
return playerType;
}
set
{
playerType = value;
SetPropertyInstance(playerType);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// The regions where the media is allowed. If not specified, then it's assumed to be allowed everywhere. Specify the countries in <a href=\http://en.wikipedia.org/wiki/ISO_3166\ target=\new\>ISO 3166 format</a>.
/// </summary>
private RegionsAllowed_Core regionsAllowed;
public RegionsAllowed_Core RegionsAllowed
{
get
{
return regionsAllowed;
}
set
{
regionsAllowed = value;
SetPropertyInstance(regionsAllowed);
}
}
/// <summary>
/// Indicates if use of the media require a subscription (either paid or free). Allowed values are <code>yes</code> or <code>no</code>.
/// </summary>
private RequiresSubscription_Core requiresSubscription;
public RequiresSubscription_Core RequiresSubscription
{
get
{
return requiresSubscription;
}
set
{
requiresSubscription = value;
SetPropertyInstance(requiresSubscription);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// Date when this media object was uploaded to this site.
/// </summary>
private UploadDate_Core uploadDate;
public UploadDate_Core UploadDate
{
get
{
return uploadDate;
}
set
{
uploadDate = value;
SetPropertyInstance(uploadDate);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
/// <summary>
/// The width of the media object.
/// </summary>
private Width_Core width;
public Width_Core Width
{
get
{
return width;
}
set
{
width = value;
SetPropertyInstance(width);
}
}
}
}
| |
namespace android.view.animation
{
[global::MonoJavaBridge.JavaClass()]
public partial class GridLayoutAnimationController : android.view.animation.LayoutAnimationController
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected GridLayoutAnimationController(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public new partial class AnimationParameters : android.view.animation.LayoutAnimationController.AnimationParameters
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AnimationParameters(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public AnimationParameters() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.GridLayoutAnimationController.AnimationParameters._m0.native == global::System.IntPtr.Zero)
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._m0 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, global::android.view.animation.GridLayoutAnimationController.AnimationParameters._m0);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _column5888;
public int column
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _column5888);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _row5889;
public int row
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _row5889);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _columnsCount5890;
public int columnsCount
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _columnsCount5890);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _rowsCount5891;
public int rowsCount
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _rowsCount5891);
}
set
{
}
}
static AnimationParameters()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/GridLayoutAnimationController$AnimationParameters"));
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._column5888 = @__env.GetFieldIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "column", "I");
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._row5889 = @__env.GetFieldIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "row", "I");
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._columnsCount5890 = @__env.GetFieldIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "columnsCount", "I");
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._rowsCount5891 = @__env.GetFieldIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "rowsCount", "I");
}
}
private static global::MonoJavaBridge.MethodId _m0;
public override bool willOverlap()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "willOverlap", "()Z", ref global::android.view.animation.GridLayoutAnimationController._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
protected override long getDelayForView(android.view.View arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "getDelayForView", "(Landroid/view/View;)J", ref global::android.view.animation.GridLayoutAnimationController._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float ColumnDelay
{
get
{
return getColumnDelay();
}
set
{
setColumnDelay(value);
}
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual float getColumnDelay()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "getColumnDelay", "()F", ref global::android.view.animation.GridLayoutAnimationController._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void setColumnDelay(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "setColumnDelay", "(F)V", ref global::android.view.animation.GridLayoutAnimationController._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float RowDelay
{
get
{
return getRowDelay();
}
set
{
setRowDelay(value);
}
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual float getRowDelay()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "getRowDelay", "()F", ref global::android.view.animation.GridLayoutAnimationController._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void setRowDelay(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "setRowDelay", "(F)V", ref global::android.view.animation.GridLayoutAnimationController._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Direction
{
get
{
return getDirection();
}
set
{
setDirection(value);
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int getDirection()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "getDirection", "()I", ref global::android.view.animation.GridLayoutAnimationController._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setDirection(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "setDirection", "(I)V", ref global::android.view.animation.GridLayoutAnimationController._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int DirectionPriority
{
get
{
return getDirectionPriority();
}
set
{
setDirectionPriority(value);
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual int getDirectionPriority()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "getDirectionPriority", "()I", ref global::android.view.animation.GridLayoutAnimationController._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setDirectionPriority(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.GridLayoutAnimationController.staticClass, "setDirectionPriority", "(I)V", ref global::android.view.animation.GridLayoutAnimationController._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public GridLayoutAnimationController(android.view.animation.Animation arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.GridLayoutAnimationController._m10.native == global::System.IntPtr.Zero)
global::android.view.animation.GridLayoutAnimationController._m10 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m11;
public GridLayoutAnimationController(android.view.animation.Animation arg0, float arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.GridLayoutAnimationController._m11.native == global::System.IntPtr.Zero)
global::android.view.animation.GridLayoutAnimationController._m11 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;FF)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m12;
public GridLayoutAnimationController(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.GridLayoutAnimationController._m12.native == global::System.IntPtr.Zero)
global::android.view.animation.GridLayoutAnimationController._m12 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
public static int DIRECTION_LEFT_TO_RIGHT
{
get
{
return 0;
}
}
public static int DIRECTION_RIGHT_TO_LEFT
{
get
{
return 1;
}
}
public static int DIRECTION_TOP_TO_BOTTOM
{
get
{
return 0;
}
}
public static int DIRECTION_BOTTOM_TO_TOP
{
get
{
return 2;
}
}
public static int DIRECTION_HORIZONTAL_MASK
{
get
{
return 1;
}
}
public static int DIRECTION_VERTICAL_MASK
{
get
{
return 2;
}
}
public static int PRIORITY_NONE
{
get
{
return 0;
}
}
public static int PRIORITY_COLUMN
{
get
{
return 1;
}
}
public static int PRIORITY_ROW
{
get
{
return 2;
}
}
static GridLayoutAnimationController()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.GridLayoutAnimationController.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/GridLayoutAnimationController"));
}
}
}
| |
/*
*
* (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.Linq;
using System.Threading;
using ASC.Common.Logging;
namespace ASC.Common.Threading.Workers
{
public class WorkerQueue<T>
{
private static readonly ILog log = LogManager.GetLogger("ASC.WorkerQueue");
private readonly ICollection<WorkItem<T>> items = new List<WorkItem<T>>();
private readonly List<Thread> threads = new List<Thread>();
private readonly AutoResetEvent waitEvent = new AutoResetEvent(false);
private readonly ManualResetEvent stopEvent = new ManualResetEvent(false);
private readonly int workerCount;
private readonly bool stopAfterFinsih;
private readonly int errorCount;
private readonly int waitInterval;
private Action<T> action;
private volatile bool started;
public object SynchRoot { get { return Items; } }
protected virtual ICollection<WorkItem<T>> Items { get { return items; } }
public bool IsStarted { get { return started; } }
public WorkerQueue(int workerCount, TimeSpan waitInterval)
: this(workerCount, waitInterval, 1, false)
{
}
public WorkerQueue(int workerCount, TimeSpan waitInterval, int errorCount, bool stopAfterFinsih)
{
this.workerCount = workerCount;
this.errorCount = errorCount;
this.stopAfterFinsih = stopAfterFinsih;
this.waitInterval = (int)waitInterval.TotalMilliseconds;
}
public void Start(Action<T> starter)
{
Start(starter, true);
}
public IEnumerable<T> GetItems()
{
lock (Items)
{
return Items.Select(x => x.Item).ToList();
}
}
public virtual void AddRange(IEnumerable<T> items)
{
lock (Items)
{
foreach (var item in items)
{
Items.Add(new WorkItem<T>(item));
}
}
waitEvent.Set();
ReviveThreads();
}
public virtual void Add(T item)
{
lock (Items)
{
Items.Add(new WorkItem<T>(item));
}
waitEvent.Set();
ReviveThreads();
}
public void Remove(T item)
{
lock (Items)
{
var existing = Items.Where(x => Equals(x.Item, item)).SingleOrDefault();
RemoveInternal(existing);
}
}
public void Clear()
{
lock (Items)
{
foreach (var workItem in Items)
{
workItem.Dispose();
}
Items.Clear();
}
}
public void Stop()
{
if (started)
{
started = false;
stopEvent.Set();
waitEvent.Set();
log.Debug("Stoping queue. Joining threads");
foreach (var workerThread in threads)
{
workerThread.Join();
}
threads.Clear();
log.Debug("Queue stoped. Threads cleared");
}
}
public void Terminate()
{
if (started)
{
started = false;
stopEvent.Set();
waitEvent.Set();
log.Debug("Stoping queue. Terminating threads");
foreach (var worker in threads.Where(t => t != Thread.CurrentThread))
{
worker.Abort();
}
if (threads.Contains(Thread.CurrentThread))
{
threads.Clear();
log.Debug("Terminate called from current worker thread. Terminating");
Thread.CurrentThread.Abort();
}
threads.Clear();
log.Debug("Queue stoped. Threads cleared");
}
}
protected virtual WorkItem<T> Selector()
{
return Items.Where(x => !x.IsProcessed).OrderBy(x => x.Added).FirstOrDefault();
}
protected virtual void PostComplete(WorkItem<T> item)
{
RemoveInternal(item);
}
protected void RemoveInternal(WorkItem<T> item)
{
if (item != null)
{
Items.Remove(item);
item.Dispose();
}
}
protected virtual void ErrorLimit(WorkItem<T> item)
{
RemoveInternal(item);
}
protected virtual void Error(WorkItem<T> item, Exception exception)
{
LogManager.GetLogger("ASC.Common.Threading.Workers").Error(item, exception);
item.IsProcessed = false;
item.Added = DateTime.Now;
}
private WaitHandle[] WaitObjects()
{
return new WaitHandle[] { stopEvent, waitEvent };
}
private void ReviveThreads()
{
if (threads.Count != 0)
{
var haveLiveThread = threads.Count(x => x.IsAlive) > 0;
if (!haveLiveThread)
{
Stop();
Start(action);
}
}
}
private void Start(Action<T> starter, bool backgroundThreads)
{
if (!started)
{
started = true;
action = starter;
stopEvent.Reset();
waitEvent.Reset();
log.Debug("Creating threads");
for (var i = 0; i < workerCount; i++)
{
threads.Add(new Thread(DoWork) { IsBackground = backgroundThreads });
}
log.Debug("Starting threads");
foreach (var thread in threads)
{
thread.Start(stopAfterFinsih);
}
}
}
private void DoWork(object state)
{
try
{
bool stopAfterFinsih = false;
if (state != null && state is bool)
{
stopAfterFinsih = (bool)state;
}
do
{
WorkItem<T> item;
Action<T> localAction;
lock (Items)
{
localAction = action;
item = Selector();
if (item != null)
{
item.IsProcessed = true;
}
}
if (localAction == null)
break;//Exit if action is null
if (item != null)
{
try
{
localAction(item.Item);
bool fallSleep = false;
lock (Items)
{
PostComplete(item);
if (Items.Count == 0)
{
fallSleep = true;
}
}
if (fallSleep)
{
if (stopAfterFinsih || WaitHandle.WaitAny(WaitObjects(), Timeout.Infinite, false) == 0)
{
break;
}
}
}
catch (ThreadAbortException)
{
return;
}
catch (Exception e)
{
lock (Items)
{
Error(item, e);
item.ErrorCount++;
if (item.ErrorCount > errorCount)
{
ErrorLimit(item);
}
}
}
}
else
{
if (stopAfterFinsih || WaitHandle.WaitAny(WaitObjects(), waitInterval, false) == 0)
{
break;
}
}
} while (true);
}
catch (ThreadAbortException)
{
return;
}
catch (Exception err)
{
log.Error(err);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing
{
using System.Diagnostics;
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes"]/*' />
/// <devdoc>
/// Brushes for select Windows system-wide colors. Whenever possible, try to use
/// SystemPens and SystemBrushes rather than SystemColors.
/// </devdoc>
public sealed class SystemBrushes
{
private static readonly object s_systemBrushesKey = new object();
private SystemBrushes()
{
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ActiveBorder"]/*' />
/// <devdoc>
/// Brush is the color of the active window border.
/// </devdoc>
public static Brush ActiveBorder
{
get
{
return FromSystemColor(SystemColors.ActiveBorder);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ActiveCaption"]/*' />
/// <devdoc>
/// Brush is the color of the active caption bar.
/// </devdoc>
public static Brush ActiveCaption
{
get
{
return FromSystemColor(SystemColors.ActiveCaption);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ActiveCaptionText"]/*' />
/// <devdoc>
/// Brush is the color of the active caption bar.
/// </devdoc>
public static Brush ActiveCaptionText
{
get
{
return FromSystemColor(SystemColors.ActiveCaptionText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.AppWorkspace"]/*' />
/// <devdoc>
/// Brush is the color of the app workspace window.
/// </devdoc>
public static Brush AppWorkspace
{
get
{
return FromSystemColor(SystemColors.AppWorkspace);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ButtonFace"]/*' />
/// <devdoc>
/// Brush for the ButtonFace system color.
/// </devdoc>
public static Brush ButtonFace
{
get
{
return FromSystemColor(SystemColors.ButtonFace);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ButtonHighlight"]/*' />
/// <devdoc>
/// Brush for the ButtonHighlight system color.
/// </devdoc>
public static Brush ButtonHighlight
{
get
{
return FromSystemColor(SystemColors.ButtonHighlight);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ButtonShadow"]/*' />
/// <devdoc>
/// Brush for the ButtonShadow system color.
/// </devdoc>
public static Brush ButtonShadow
{
get
{
return FromSystemColor(SystemColors.ButtonShadow);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Control"]/*' />
/// <devdoc>
/// Brush is the control color, which is the surface color for 3D elements.
/// </devdoc>
public static Brush Control
{
get
{
return FromSystemColor(SystemColors.Control);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ControlLightLight"]/*' />
/// <devdoc>
/// Brush is the lighest part of a 3D element.
/// </devdoc>
public static Brush ControlLightLight
{
get
{
return FromSystemColor(SystemColors.ControlLightLight);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ControlLight"]/*' />
/// <devdoc>
/// Brush is the highlight part of a 3D element.
/// </devdoc>
public static Brush ControlLight
{
get
{
return FromSystemColor(SystemColors.ControlLight);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ControlDark"]/*' />
/// <devdoc>
/// Brush is the shadow part of a 3D element.
/// </devdoc>
public static Brush ControlDark
{
get
{
return FromSystemColor(SystemColors.ControlDark);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ControlDarkDark"]/*' />
/// <devdoc>
/// Brush is the darkest part of a 3D element.
/// </devdoc>
public static Brush ControlDarkDark
{
get
{
return FromSystemColor(SystemColors.ControlDarkDark);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ControlText"]/*' />
/// <devdoc>
/// Brush is the color of text on controls.
/// </devdoc>
public static Brush ControlText
{
get
{
return FromSystemColor(SystemColors.ControlText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Desktop"]/*' />
/// <devdoc>
/// Brush is the color of the desktop.
/// </devdoc>
public static Brush Desktop
{
get
{
return FromSystemColor(SystemColors.Desktop);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.GradientActiveCaption"]/*' />
/// <devdoc>
/// Brush for the GradientActiveCaption system color.
/// </devdoc>
public static Brush GradientActiveCaption
{
get
{
return FromSystemColor(SystemColors.GradientActiveCaption);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.GradientInactiveCaption"]/*' />
/// <devdoc>
/// Brush for the GradientInactiveCaption system color.
/// </devdoc>
public static Brush GradientInactiveCaption
{
get
{
return FromSystemColor(SystemColors.GradientInactiveCaption);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.GrayText"]/*' />
/// <devdoc>
/// Brush for the GrayText system color.
/// </devdoc>
public static Brush GrayText
{
get
{
return FromSystemColor(SystemColors.GrayText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Highlight"]/*' />
/// <devdoc>
/// Brush is the color of the background of highlighted elements.
/// </devdoc>
public static Brush Highlight
{
get
{
return FromSystemColor(SystemColors.Highlight);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.HighlightText"]/*' />
/// <devdoc>
/// Brush is the color of the foreground of highlighted elements.
/// </devdoc>
public static Brush HighlightText
{
get
{
return FromSystemColor(SystemColors.HighlightText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.HotTrack"]/*' />
/// <devdoc>
/// Brush is the color used to represent hot tracking.
/// </devdoc>
public static Brush HotTrack
{
get
{
return FromSystemColor(SystemColors.HotTrack);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.InactiveCaption"]/*' />
/// <devdoc>
/// Brush is the color of an inactive caption bar.
/// </devdoc>
public static Brush InactiveCaption
{
get
{
return FromSystemColor(SystemColors.InactiveCaption);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.InactiveBorder"]/*' />
/// <devdoc>
/// Brush is the color if an inactive window border.
/// </devdoc>
public static Brush InactiveBorder
{
get
{
return FromSystemColor(SystemColors.InactiveBorder);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.InactiveCaptionText"]/*' />
/// <devdoc>
/// Brush is the color of an inactive caption text.
/// </devdoc>
public static Brush InactiveCaptionText
{
get
{
return FromSystemColor(SystemColors.InactiveCaptionText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Info"]/*' />
/// <devdoc>
/// Brush is the color of the background of the info tooltip.
/// </devdoc>
public static Brush Info
{
get
{
return FromSystemColor(SystemColors.Info);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.InfoText"]/*' />
/// <devdoc>
/// Brush is the color of the info tooltip's text.
/// </devdoc>
public static Brush InfoText
{
get
{
return FromSystemColor(SystemColors.InfoText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Menu"]/*' />
/// <devdoc>
/// Brush is the color of the menu background.
/// </devdoc>
public static Brush Menu
{
get
{
return FromSystemColor(SystemColors.Menu);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.MenuBar"]/*' />
/// <devdoc>
/// Brush is the color of the menu background.
/// </devdoc>
public static Brush MenuBar
{
get
{
return FromSystemColor(SystemColors.MenuBar);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.MenuHighlight"]/*' />
/// <devdoc>
/// Brush for the MenuHighlight system color.
/// </devdoc>
public static Brush MenuHighlight
{
get
{
return FromSystemColor(SystemColors.MenuHighlight);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.MenuText"]/*' />
/// <devdoc>
/// Brush is the color of the menu text.
/// </devdoc>
public static Brush MenuText
{
get
{
return FromSystemColor(SystemColors.MenuText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.ScrollBar"]/*' />
/// <devdoc>
/// Brush is the color of the scroll bar area that is not being used by the
/// thumb button.
/// </devdoc>
public static Brush ScrollBar
{
get
{
return FromSystemColor(SystemColors.ScrollBar);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.Window"]/*' />
/// <devdoc>
/// Brush is the color of the window background.
/// </devdoc>
public static Brush Window
{
get
{
return FromSystemColor(SystemColors.Window);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.WindowFrame"]/*' />
/// <devdoc>
/// Brush is the color of the thin frame drawn around a window.
/// </devdoc>
public static Brush WindowFrame
{
get
{
return FromSystemColor(SystemColors.WindowFrame);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.WindowText"]/*' />
/// <devdoc>
/// Brush is the color of text on controls.
/// </devdoc>
public static Brush WindowText
{
get
{
return FromSystemColor(SystemColors.WindowText);
}
}
/// <include file='doc\SystemBrushes.uex' path='docs/doc[@for="SystemBrushes.FromSystemColor"]/*' />
/// <devdoc>
/// Retrieves a brush given a system color. An error will be raised
/// if the color provide is not a system color.
/// </devdoc>
public static Brush FromSystemColor(Color c)
{
if (!c.IsSystemColor)
{
throw new ArgumentException(SR.Format(SR.ColorNotSystemColor, c.ToString()));
}
Brush[] systemBrushes = (Brush[])SafeNativeMethods.Gdip.ThreadData[s_systemBrushesKey];
if (systemBrushes == null)
{
systemBrushes = new Brush[(int)KnownColor.WindowText + (int)KnownColor.MenuHighlight - (int)KnownColor.YellowGreen];
SafeNativeMethods.Gdip.ThreadData[s_systemBrushesKey] = systemBrushes;
}
int idx = (int)c.ToKnownColor();
if (idx > (int)KnownColor.YellowGreen)
{
idx -= (int)KnownColor.YellowGreen - (int)KnownColor.WindowText;
}
idx--;
Debug.Assert(idx >= 0 && idx < systemBrushes.Length, "System colors have been added but our system color array has not been expanded.");
if (systemBrushes[idx] == null)
{
systemBrushes[idx] = new SolidBrush(c, true);
}
return systemBrushes[idx];
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Asn1;
namespace Internal.Cryptography.Pal
{
internal abstract class ManagedCertificateFinder : IFindPal
{
private readonly X509Certificate2Collection _findFrom;
private readonly X509Certificate2Collection _copyTo;
private readonly bool _validOnly;
internal ManagedCertificateFinder(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly)
{
_findFrom = findFrom;
_copyTo = copyTo;
_validOnly = validOnly;
}
public string NormalizeOid(string maybeOid, OidGroup expectedGroup)
{
Oid oid = new Oid(maybeOid);
// If maybeOid is interpreted to be a FriendlyName, return the OID.
if (!StringComparer.OrdinalIgnoreCase.Equals(oid.Value, maybeOid))
{
return oid.Value;
}
FindPal.ValidateOidValue(maybeOid);
return maybeOid;
}
public void FindByThumbprint(byte[] thumbprint)
{
FindCore(cert => cert.GetCertHash().ContentsEqual(thumbprint));
}
public void FindBySubjectName(string subjectName)
{
FindCore(
cert =>
{
string formedSubject = X500NameEncoder.X500DistinguishedNameDecode(cert.SubjectName.RawData, false, X500DistinguishedNameFlags.None);
return formedSubject.IndexOf(subjectName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindBySubjectDistinguishedName(string subjectDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(subjectDistinguishedName, cert.Subject));
}
public void FindByIssuerName(string issuerName)
{
FindCore(
cert =>
{
string formedIssuer = X500NameEncoder.X500DistinguishedNameDecode(cert.IssuerName.RawData, false, X500DistinguishedNameFlags.None);
return formedIssuer.IndexOf(issuerName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindByIssuerDistinguishedName(string issuerDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(issuerDistinguishedName, cert.Issuer));
}
public void FindBySerialNumber(BigInteger hexValue, BigInteger decimalValue)
{
FindCore(
cert =>
{
byte[] serialBytes = cert.GetSerialNumber();
BigInteger serialNumber = FindPal.PositiveBigIntegerFromByteArray(serialBytes);
bool match = hexValue.Equals(serialNumber) || decimalValue.Equals(serialNumber);
return match;
});
}
private static DateTime NormalizeDateTime(DateTime dateTime)
{
// If it's explicitly UTC, convert it to local before a comparison, since the
// NotBefore and NotAfter are in Local time.
//
// If it was Unknown, assume it was Local.
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime.ToLocalTime();
}
return dateTime;
}
public void FindByTimeValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore <= normalized && normalized <= cert.NotAfter);
}
public void FindByTimeNotYetValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore > normalized);
}
public void FindByTimeExpired(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotAfter < normalized);
}
public void FindByTemplateName(string templateName)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnrollCertTypeExtension);
if (ext != null)
{
// Try a V1 template structure, just a string:
AsnReader reader = new AsnReader(ext.RawData, AsnEncodingRules.DER);
string decodedName = reader.ReadDirectoryOrIA5String();
reader.ThrowIfNotEmpty();
// If this doesn't match, maybe a V2 template will
if (StringComparer.OrdinalIgnoreCase.Equals(templateName, decodedName))
{
return true;
}
}
ext = FindExtension(cert, Oids.CertificateTemplate);
if (ext != null)
{
CertificateTemplateAsn template = CertificateTemplateAsn.Decode(ext.RawData, AsnEncodingRules.DER);
if (StringComparer.Ordinal.Equals(templateName, template.TemplateID))
{
return true;
}
}
return false;
});
}
public void FindByApplicationPolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnhancedKeyUsage);
if (ext == null)
{
// A certificate with no EKU is valid for all extended purposes.
return true;
}
var ekuExt = (X509EnhancedKeyUsageExtension)ext;
foreach (Oid usageOid in ekuExt.EnhancedKeyUsages)
{
if (StringComparer.Ordinal.Equals(oidValue, usageOid.Value))
{
return true;
}
}
// If the certificate had an EKU extension, and the value we wanted was
// not present, then it is not valid for that usage.
return false;
});
}
public void FindByCertificatePolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.CertPolicies);
if (ext == null)
{
// Unlike Application Policy, Certificate Policy is "assume false".
return false;
}
ISet<string> policyOids = CertificatePolicyChain.ReadCertPolicyExtension(ext);
return policyOids.Contains(oidValue);
});
}
public void FindByExtension(string oidValue)
{
FindCore(cert => FindExtension(cert, oidValue) != null);
}
public void FindByKeyUsage(X509KeyUsageFlags keyUsage)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.KeyUsage);
if (ext == null)
{
// A certificate with no key usage extension is considered valid for all key usages.
return true;
}
var kuExt = (X509KeyUsageExtension)ext;
return (kuExt.KeyUsages & keyUsage) == keyUsage;
});
}
protected abstract byte[] GetSubjectPublicKeyInfo(X509Certificate2 cert);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required for Compat")]
public void FindBySubjectKeyIdentifier(byte[] keyIdentifier)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.SubjectKeyIdentifier);
byte[] certKeyId;
if (ext != null)
{
// The extension exposes the value as a hexadecimal string, or we can decode here.
// Enough parsing has gone on, let's decode.
certKeyId = ManagedX509ExtensionProcessor.DecodeX509SubjectKeyIdentifierExtension(ext.RawData);
}
else
{
// The Desktop/Windows version of this method use CertGetCertificateContextProperty
// with a property ID of CERT_KEY_IDENTIFIER_PROP_ID.
//
// MSDN says that when there's no extension, this method takes the SHA-1 of the
// SubjectPublicKeyInfo block, and returns that.
//
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079%28v=vs.85%29.aspx
using (HashAlgorithm hash = SHA1.Create())
{
byte[] publicKeyInfoBytes = GetSubjectPublicKeyInfo(cert);
certKeyId = hash.ComputeHash(publicKeyInfoBytes);
}
}
return keyIdentifier.ContentsEqual(certKeyId);
});
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
}
private static X509Extension FindExtension(X509Certificate2 cert, string extensionOid)
{
if (cert.Extensions == null || cert.Extensions.Count == 0)
{
return null;
}
foreach (X509Extension ext in cert.Extensions)
{
if (ext != null &&
ext.Oid != null &&
StringComparer.Ordinal.Equals(extensionOid, ext.Oid.Value))
{
return ext;
}
}
return null;
}
protected abstract X509Certificate2 CloneCertificate(X509Certificate2 cert);
private void FindCore(Predicate<X509Certificate2> predicate)
{
foreach (X509Certificate2 cert in _findFrom)
{
if (predicate(cert))
{
if (!_validOnly || IsCertValid(cert))
{
X509Certificate2 clone = CloneCertificate(cert);
Debug.Assert(!ReferenceEquals(cert, clone));
_copyTo.Add(clone);
}
}
}
}
private static bool IsCertValid(X509Certificate2 cert)
{
try
{
// This needs to be kept in sync with VerifyCertificateIgnoringErrors in the
// Windows PAL version (and potentially any other PALs that come about)
using (X509Chain chain = new X509Chain
{
ChainPolicy =
{
RevocationMode = X509RevocationMode.NoCheck,
RevocationFlag = X509RevocationFlag.ExcludeRoot
}
})
{
bool valid = chain.Build(cert);
int elementCount = chain.ChainElements.Count;
for (int i = 0; i < elementCount; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
return valid;
}
}
catch (CryptographicException)
{
return false;
}
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Threading;
using ServiceStack.Text.Json;
namespace ServiceStack.Text.Common
{
internal static class DeserializeListWithElements<TSerializer>
where TSerializer : ITypeSerializer
{
internal static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
private static Dictionary<Type, ParseListDelegate> ParseDelegateCache
= new Dictionary<Type, ParseListDelegate>();
private delegate object ParseListDelegate(string value, Type createListType, ParseStringDelegate parseFn);
public static Func<string, Type, ParseStringDelegate, object> GetListTypeParseFn(
Type createListType, Type elementType, ParseStringDelegate parseFn)
{
ParseListDelegate parseDelegate;
if (ParseDelegateCache.TryGetValue(elementType, out parseDelegate))
return parseDelegate.Invoke;
var genericType = typeof(DeserializeListWithElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetMethod("ParseGenericList", BindingFlags.Static | BindingFlags.Public);
parseDelegate = (ParseListDelegate)Delegate.CreateDelegate(typeof(ParseListDelegate), mi);
Dictionary<Type, ParseListDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseListDelegate>(ParseDelegateCache);
newCache[elementType] = parseDelegate;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseDelegate.Invoke;
}
internal static string StripList(string value)
{
if (string.IsNullOrEmpty(value))
return null;
const int startQuotePos = 1;
const int endQuotePos = 2;
var ret = value[0] == JsWriter.ListStartChar
? value.Substring(startQuotePos, value.Length - endQuotePos)
: value;
var pos = 0;
Serializer.EatWhitespace(ret, ref pos);
return ret.Substring(pos, ret.Length - pos);
}
public static List<string> ParseStringList(string value)
{
if ((value = StripList(value)) == null) return null;
if (value == string.Empty) return new List<string>();
var to = new List<string>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
var listValue = Serializer.UnescapeString(elementValue);
to.Add(listValue);
Serializer.EatItemSeperatorOrMapEndChar(value, ref i);
}
return to;
}
public static List<int> ParseIntList(string value)
{
if ((value = StripList(value)) == null) return null;
if (value == string.Empty) return new List<int>();
var intParts = value.Split(JsWriter.ItemSeperator);
var intValues = new List<int>(intParts.Length);
foreach (var intPart in intParts)
{
intValues.Add(int.Parse(intPart));
}
return intValues;
}
}
internal static class DeserializeListWithElements<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
public static ICollection<T> ParseGenericList(string value, Type createListType, ParseStringDelegate parseFn)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null;
var isReadOnly = createListType != null
&& (createListType.IsGenericType && createListType.GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>));
var to = (createListType == null || isReadOnly)
? new List<T>()
: (ICollection<T>)createListType.CreateInstance();
if (value == string.Empty) return to;
var tryToParseItemsAsPrimitiveTypes =
JsConfig.TryToParsePrimitiveTypeValues && typeof(T) == typeof(object);
if (!string.IsNullOrEmpty(value))
{
var valueLength = value.Length;
var i = 0;
Serializer.EatWhitespace(value, ref i);
if (i < valueLength && value[i] == JsWriter.MapStartChar)
{
do
{
var itemValue = Serializer.EatTypeValue(value, ref i);
to.Add((T)parseFn(itemValue));
Serializer.EatWhitespace(value, ref i);
} while (++i < value.Length);
}
else
{
while (i < valueLength)
{
var startIndex = i;
var elementValue = Serializer.EatValue(value, ref i);
var listValue = elementValue;
if (listValue != null) {
if (tryToParseItemsAsPrimitiveTypes) {
Serializer.EatWhitespace(value, ref startIndex);
to.Add((T) DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[startIndex]));
} else {
to.Add((T) parseFn(elementValue));
}
}
if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i)
&& i == valueLength)
{
// If we ate a separator and we are at the end of the value,
// it means the last element is empty => add default
to.Add(default(T));
}
}
}
}
//TODO: 8-10-2011 -- this CreateInstance call should probably be moved over to ReflectionExtensions,
//but not sure how you'd like to go about caching constructors with parameters -- I would probably build a NewExpression, .Compile to a LambdaExpression and cache
return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to;
}
}
internal static class DeserializeList<T, TSerializer>
where TSerializer : ITypeSerializer
{
private readonly static ParseStringDelegate CacheFn;
static DeserializeList()
{
CacheFn = GetParseFn();
}
public static ParseStringDelegate Parse
{
get { return CacheFn; }
}
public static ParseStringDelegate GetParseFn()
{
var listInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IList<>));
if (listInterface == null)
throw new ArgumentException(string.Format("Type {0} is not of type IList<>", typeof(T).FullName));
//optimized access for regularly used types
if (typeof(T) == typeof(List<string>))
return DeserializeListWithElements<TSerializer>.ParseStringList;
if (typeof(T) == typeof(List<int>))
return DeserializeListWithElements<TSerializer>.ParseIntList;
var elementType = listInterface.GetGenericArguments()[0];
var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType);
if (supportedTypeParseMethod != null)
{
var createListType = typeof(T).HasAnyTypeDefinitionsOf(typeof(List<>), typeof(IList<>))
? null : typeof(T);
var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn(createListType, elementType, supportedTypeParseMethod);
return value => parseFn(value, createListType, supportedTypeParseMethod);
}
return null;
}
}
internal static class DeserializeEnumerable<T, TSerializer>
where TSerializer : ITypeSerializer
{
private readonly static ParseStringDelegate CacheFn;
static DeserializeEnumerable()
{
CacheFn = GetParseFn();
}
public static ParseStringDelegate Parse
{
get { return CacheFn; }
}
public static ParseStringDelegate GetParseFn()
{
var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>));
if (enumerableInterface == null)
throw new ArgumentException(string.Format("Type {0} is not of type IEnumerable<>", typeof(T).FullName));
//optimized access for regularly used types
if (typeof(T) == typeof(IEnumerable<string>))
return DeserializeListWithElements<TSerializer>.ParseStringList;
if (typeof(T) == typeof(IEnumerable<int>))
return DeserializeListWithElements<TSerializer>.ParseIntList;
var elementType = enumerableInterface.GetGenericArguments()[0];
var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType);
if (supportedTypeParseMethod != null)
{
const Type createListTypeWithNull = null; //Use conversions outside this class. see: Queue
var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn(
createListTypeWithNull, elementType, supportedTypeParseMethod);
return value => parseFn(value, createListTypeWithNull, supportedTypeParseMethod);
}
return null;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Grpc.Core.Interceptors;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Generic base class for client-side stubs.
/// </summary>
public abstract class ClientBase<T> : ClientBase
where T : ClientBase<T>
{
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : base()
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(ChannelBase channel) : base(channel)
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>
/// Creates a new client that sets host field for calls explicitly.
/// gRPC supports multiple "hosts" being served by a single server.
/// By default (if a client was not created by calling this method),
/// host <c>null</c> with the meaning "use default host" is used.
/// </summary>
public T WithHost(string host)
{
var newConfiguration = this.Configuration.WithHost(host);
return NewInstance(newConfiguration);
}
/// <summary>
/// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
/// </summary>
protected abstract T NewInstance(ClientBaseConfiguration configuration);
}
/// <summary>
/// Base class for client-side stubs.
/// </summary>
public abstract class ClientBase
{
readonly ClientBaseConfiguration configuration;
readonly CallInvoker callInvoker;
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class that
/// throws <c>NotImplementedException</c> upon invocation of any RPC.
/// This constructor is only provided to allow creation of test doubles
/// for client classes (e.g. mocking requires a parameterless constructor).
/// </summary>
protected ClientBase() : this(new UnimplementedCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
protected ClientBase(ClientBaseConfiguration configuration)
{
this.configuration = GrpcPreconditions.CheckNotNull(configuration, "configuration");
this.callInvoker = configuration.CreateDecoratedCallInvoker();
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="channel">The channel to use for remote call invocation.</param>
public ClientBase(ChannelBase channel) : this(channel.CreateCallInvoker())
{
}
/// <summary>
/// Initializes a new instance of <c>ClientBase</c> class.
/// </summary>
/// <param name="callInvoker">The <c>CallInvoker</c> for remote call invocation.</param>
public ClientBase(CallInvoker callInvoker) : this(new ClientBaseConfiguration(callInvoker, null))
{
}
/// <summary>
/// Gets the call invoker.
/// </summary>
protected CallInvoker CallInvoker
{
get { return this.callInvoker; }
}
/// <summary>
/// Gets the configuration.
/// </summary>
internal ClientBaseConfiguration Configuration
{
get { return this.configuration; }
}
/// <summary>
/// Represents configuration of ClientBase. The class itself is visible to
/// subclasses, but contents are marked as internal to make the instances opaque.
/// The verbose name of this class was chosen to make name clash in generated code
/// less likely.
/// </summary>
protected internal class ClientBaseConfiguration
{
private class ClientBaseConfigurationInterceptor : Interceptor
{
readonly Func<IMethod, string?, CallOptions, ClientBaseConfigurationInfo> interceptor;
/// <summary>
/// Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function.
/// </summary>
public ClientBaseConfigurationInterceptor(Func<IMethod, string?, CallOptions, ClientBaseConfigurationInfo> interceptor)
{
this.interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor));
}
private ClientInterceptorContext<TRequest, TResponse> GetNewContext<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context)
where TRequest : class
where TResponse : class
{
var newHostAndCallOptions = interceptor(context.Method, context.Host, context.Options);
return new ClientInterceptorContext<TRequest, TResponse>(context.Method, newHostAndCallOptions.Host, newHostAndCallOptions.CallOptions);
}
public override TResponse BlockingUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, BlockingUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(request, GetNewContext(context));
}
public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation)
{
return continuation(GetNewContext(context));
}
}
internal struct ClientBaseConfigurationInfo
{
internal readonly string? Host;
internal readonly CallOptions CallOptions;
internal ClientBaseConfigurationInfo(string? host, CallOptions callOptions)
{
Host = host;
CallOptions = callOptions;
}
}
readonly CallInvoker undecoratedCallInvoker;
readonly string? host;
internal ClientBaseConfiguration(CallInvoker undecoratedCallInvoker, string? host)
{
this.undecoratedCallInvoker = GrpcPreconditions.CheckNotNull(undecoratedCallInvoker);
this.host = host;
}
internal CallInvoker CreateDecoratedCallInvoker()
{
return undecoratedCallInvoker.Intercept(new ClientBaseConfigurationInterceptor((method, host, options) => new ClientBaseConfigurationInfo(this.host, options)));
}
internal ClientBaseConfiguration WithHost(string host)
{
GrpcPreconditions.CheckNotNull(host, nameof(host));
return new ClientBaseConfiguration(this.undecoratedCallInvoker, host);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WindowsStatusBar.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Windows Status Proxy
//
// History:
// 07/01/2003 : a-jeanp Created for WCP
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Text;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.ComponentModel;
using System.Windows;
using System.Globalization;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
class WindowsStatusBar : ProxyHwnd, IGridProvider, IRawElementProviderHwndOverride
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
internal WindowsStatusBar(IntPtr hwnd, ProxyFragment parent, int item, Accessible acc)
: base(hwnd, parent, item)
{
_acc = acc;
_cControlType = ControlType.StatusBar;
_fHasGrip = StatusBarGrip.HasGrip(hwnd);
_sAutomationId = "StatusBar"; // This string is a non-localizable string
// support for events
_createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents);
}
#endregion
#region Proxy Create
// Static Create method called by UIAutomation to create this proxy.
// returns null if unsuccessful
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject)
{
return Create(hwnd, idChild);
}
private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
{
// Something is wrong if idChild is not zero
if (idChild != 0)
{
System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0");
throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero));
}
return new WindowsStatusBar(hwnd, null, idChild, null);
}
// Static Create method called by the event tracker system
internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
if (idObject != NativeMethods.OBJID_VSCROLL && idObject != NativeMethods.OBJID_HSCROLL)
{
bool isWinforms = WindowsFormsHelper.IsWindowsFormsControl(hwnd);
ProxySimple el = isWinforms ? (ProxySimple)WindowsFormsHelper.Create(hwnd, 0, idObject) : (ProxySimple)Create(hwnd, 0);
if (el == null)
{
// WindowsFormsHelper may return null if the MSAA Role for this hwnd isn't handled
return;
}
if (idChild > 0)
{
if (eventId == NativeMethods.EventObjectNameChange && idChild == 1)
{
// Need to let the overall control process this event also.
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
el = ((WindowsStatusBar)el).CreateStatusBarPane(idChild - 1);
}
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
internal ProxySimple CreateStatusBarPane (int index)
{
// Use the Accessible object if this is a [....] control. Only [....] StatusBars
// can have children.
Accessible accChild = null;
if (_acc != null)
{
// OLEACC's Win32 proxy does use a 1, 2, 3... scheme, but the [....]
// controls in some cases supply their own children, using a different scheme.
// Using the "ByIndex" approach avoids having to know what the underlying
// object's idChild scheme is.
accChild = Accessible.GetFullAccessibleChildByIndex(_acc, index);
if (accChild != null && accChild.Role != AccessibleRole.PushButton)
{
// [....] toolbars have full IAccessibles for their children, but
// return the overall hwnd; treat those same as regular items.
// We only want to special-case actual child hwnds for overriding.
IntPtr hwndChild = accChild.Window;
if (hwndChild == IntPtr.Zero || hwndChild == _hwnd)
{
hwndChild = GetChildHwnd(_hwnd, accChild.Location);
}
if(hwndChild != IntPtr.Zero && hwndChild != _hwnd)
{
// We have an actual child hwnd.
return new WindowsStatusBarPaneChildOverrideProxy(hwndChild, this, index);
}
}
}
return new WindowsStatusBarPane(_hwnd, this, index, accChild);
}
#endregion Proxy Create
// ------------------------------------------------------
//
// Patterns Implementation
//
// ------------------------------------------------------
#region ProxySimple Interface
// Returns a pattern interface if supported.
internal override object GetPatternProvider (AutomationPattern iid)
{
return iid == GridPattern.Pattern ? this : null;
}
//Gets the localized name
internal override string LocalizedName
{
get
{
return Misc.ProxyGetText(_hwnd);
}
}
#endregion ElementProvider
#region ProxyFragment Interface
// Returns the next sibling element in the raw hierarchy.
// Peripheral controls have always negative values.
// Returns null if no next child
internal override ProxySimple GetNextSibling (ProxySimple child)
{
int item = child._item;
int count = Count;
// Next for an item that does not exist in the list
if (item >= count)
{
throw new ElementNotAvailableException ();
}
// The grip is the last item. Exit when we see it.
if (item == GripItemID)
{
return null;
}
// Eventually add the Grip as the last element in the list
return item + 1 < count ? CreateStatusBarPane(item + 1) : (_fHasGrip ? StatusBarGrip.Create(_hwnd, this, -1) : null);
}
// Returns the previous sibling element in the raw hierarchy.
// Peripheral controls have always negative values.
// Returns null is no previous
internal override ProxySimple GetPreviousSibling (ProxySimple child)
{
int item = child._item;
int count = Count;
// Next for an item that does not exist in the list
if (item >= count)
{
throw new ElementNotAvailableException ();
}
// Grip is the last in the list but has a negative number
// Fake a new item number that is last in the list
if (item == GripItemID)
{
item = count;
}
return item > 0 && (item - 1) < Count ? CreateStatusBarPane (item - 1) : null;
}
// Returns the first child element in the raw hierarchy.
internal override ProxySimple GetFirstChild ()
{
// Grip is the last Element
return Count > 0 ? CreateStatusBarPane(0) : (_fHasGrip ? StatusBarGrip.Create(_hwnd, this, GripItemID) : null);
}
// Returns the last child element in the raw hierarchy.
internal override ProxySimple GetLastChild ()
{
// Grip is the last Element
if (_fHasGrip)
{
return StatusBarGrip.Create(_hwnd, this, GripItemID);
}
int count = Count;
return count > 0 ? CreateStatusBarPane (count - 1): null;
}
// Returns a Proxy element corresponding to the specified screen coordinates.
internal override ProxySimple ElementProviderFromPoint (int x, int y)
{
// Loop through all the panes
for (int item = 0, count = Count; item < count; item++)
{
NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect (WindowsStatusBarPane.GetBoundingRectangle (_hwnd, item));
if (Misc.PtInRect(ref rc, x, y))
{
return CreateStatusBarPane(item);
}
}
// Try the Grip
if (_fHasGrip)
{
NativeMethods.Win32Rect rc = StatusBarGrip.GetBoundingRectangle (_hwnd);
if (Misc.PtInRect(ref rc, x, y))
{
ProxySimple grip = StatusBarGrip.Create(_hwnd, this, -1);
return (ProxySimple)(grip != null ? grip : this);
}
}
return this;
}
#endregion
#region Grid Pattern
// Obtain the AutomationElement at an zero based absolute position in the grid.
// Where 0,0 is top left
IRawElementProviderSimple IGridProvider.GetItem(int row, int column)
{
// NOTE: Status bar has only 1 row
if (row != 0)
{
throw new ArgumentOutOfRangeException("row", row, SR.Get(SRID.GridRowOutOfRange));
}
if (column < 0 || column >= Count)
{
throw new ArgumentOutOfRangeException("column", column, SR.Get(SRID.GridColumnOutOfRange));
}
return CreateStatusBarPane(column);
}
int IGridProvider.RowCount
{
get
{
return 1;
}
}
int IGridProvider.ColumnCount
{
get
{
return Count;
}
}
#endregion Grid Pattern
#region IRawElementProviderHwndOverride Interface
//------------------------------------------------------
//
// Interface IRawElementProviderHwndOverride
//
//------------------------------------------------------
IRawElementProviderSimple IRawElementProviderHwndOverride.GetOverrideProviderForHwnd(IntPtr hwnd)
{
// return the appropriate placeholder for the given hwnd...
// loop over all the band to find it.
// Only [....] StatusBars can have children.
if (_acc != null)
{
Accessible accChild = _acc.FirstChild;
IntPtr hwndChild = IntPtr.Zero;
for (int i = 0; accChild != null; i++, accChild = accChild.NextSibling(_acc))
{
hwndChild = accChild.Window;
if (hwndChild == IntPtr.Zero)
{
hwndChild = GetChildHwnd(_hwnd, accChild.Location);
}
if (hwndChild == hwnd)
{
return new WindowsStatusBarPaneChildOverrideProxy(hwnd, this, i);
}
}
}
return null;
}
#endregion IRawElementProviderHwndOverride Interface
// ------------------------------------------------------
//
// Private Methods
//
// ------------------------------------------------------
#region Private Methods
// Returns the number of Status Bar Panes
private int Count
{
get
{
if (_acc == null)
{
return Misc.ProxySendMessageInt(_hwnd, NativeMethods.SB_GETPARTS, IntPtr.Zero, IntPtr.Zero);
}
else
{
return _acc.ChildCount;
}
}
}
unsafe static private IntPtr GetChildHwnd(IntPtr hwnd, Rect rc)
{
UnsafeNativeMethods.ENUMCHILDWINDOWFROMRECT info = new UnsafeNativeMethods.ENUMCHILDWINDOWFROMRECT();
info.hwnd = IntPtr.Zero;
info.rc.left = (int)rc.Left;
info.rc.top = (int)rc.Top;
info.rc.right = (int)rc.Right;
info.rc.bottom = (int)rc.Bottom;
Misc.EnumChildWindows(hwnd, new NativeMethods.EnumChildrenCallbackVoid(FindChildFromRect), (void*)&info);
return info.hwnd;
}
unsafe static private bool FindChildFromRect(IntPtr hwnd, void* lParam)
{
NativeMethods.Win32Rect rc = NativeMethods.Win32Rect.Empty;
if (!Misc.GetClientRectInScreenCoordinates(hwnd, ref rc))
{
return true;
}
UnsafeNativeMethods.ENUMCHILDWINDOWFROMRECT * info = (UnsafeNativeMethods.ENUMCHILDWINDOWFROMRECT *)lParam;
if (rc.left == info->rc.left && rc.top == info->rc.top && rc.right == info->rc.right && rc.bottom == info->rc.bottom)
{
info->hwnd = hwnd;
return false;
}
return true;
}
#endregion
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
// Status bar with a Grip Style
private bool _fHasGrip;
private Accessible _acc; // Accessible is used for [....] controls.
// Item ID for the grip. Must be negative as it is a peripheral element
private const int GripItemID = -1;
private const int SBARS_SIZEGRIP = 0x0100;
#endregion
// ------------------------------------------------------
//
// WindowsStatusBarPane Private Class
//
// ------------------------------------------------------
#region WindowsStatusBarPane
class WindowsStatusBarPane : ProxySimple, IGridItemProvider, IValueProvider
{
// ------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal WindowsStatusBarPane (IntPtr hwnd, ProxyFragment parent, int item, Accessible acc)
: base (hwnd, parent, item)
{
_acc = acc;
_cControlType = ControlType.Edit;
_sAutomationId = "StatusBar.Pane" + item.ToString(CultureInfo.CurrentCulture); // This string is a non-localizable string
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
// Returns a pattern interface if supported.
internal override object GetPatternProvider (AutomationPattern iid)
{
if (iid == GridItemPattern.Pattern)
{
return this;
}
else if (iid == ValuePattern.Pattern)
{
return this;
}
return null;
}
// Gets the bounding rectangle for this element
internal override Rect BoundingRectangle
{
get
{
return GetBoundingRectangle (_hwnd, _item);
}
}
// Gets the localized name
internal override string LocalizedName
{
get
{
return Text;
}
}
#endregion ProxySimple Interface
#region Grid Pattern
int IGridItemProvider.Row
{
get
{
return 0;
}
}
int IGridItemProvider.Column
{
get
{
return _item;
}
}
int IGridItemProvider.RowSpan
{
get
{
return 1;
}
}
int IGridItemProvider.ColumnSpan
{
get
{
return 1;
}
}
IRawElementProviderSimple IGridItemProvider.ContainingGrid
{
get
{
return _parent;
}
}
#endregion Grid Pattern
#region Value Pattern
// Sets the text of the edit.
void IValueProvider.SetValue(string str)
{
// This is a read only element.
throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed));
}
// Request to get the value that this UI element is representing as a string
string IValueProvider.Value
{
get
{
return Text;
}
}
// Read only status
bool IValueProvider.IsReadOnly
{
get
{
return true;
}
}
#endregion
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Retrieves the bounding rectangle of the Status Bar Pane.
static internal Rect GetBoundingRectangle (IntPtr hwnd, int item)
{
if( !WindowsFormsHelper.IsWindowsFormsControl(hwnd))
{
return XSendMessage.GetItemRect(hwnd, NativeMethods.SB_GETRECT, item);
}
else
{
Accessible acc = null;
if (Accessible.AccessibleObjectFromWindow(hwnd, NativeMethods.OBJID_CLIENT, ref acc) != NativeMethods.S_OK || acc == null)
{
return Rect.Empty;
}
else
{
// OLEACC's Win32 proxy does use a 1, 2, 3... scheme, but the [....]
// controls in some cases supply their own children, using a different scheme.
// Using the "ByIndex" approach avoids having to know what the underlying
// object's idChild scheme is.
acc = Accessible.GetFullAccessibleChildByIndex(acc, item);
if (acc == null)
{
return Rect.Empty;
}
else
{
return acc.Location;
}
}
}
}
//Gets the localized name
internal string Text
{
get
{
if (_acc == null)
{
// Get the length of the string
int retValue = Misc.ProxySendMessageInt(_hwnd, NativeMethods.SB_GETTEXTLENGTHW, new IntPtr(_item), IntPtr.Zero);
// The low word specifies the length, in characters, of the text.
// The high word specifies the type of operation used to draw the text.
int len = NativeMethods.Util.LOWORD(retValue);
return XSendMessage.GetItemText(_hwnd, NativeMethods.SB_GETTEXTW, _item, len);
}
else
{
return _acc.Name;
}
}
}
#endregion
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
private Accessible _acc; // Accessible is used for [....] controls.
#endregion
}
#endregion
// ------------------------------------------------------
//
// WindowsStatusBarPaneChildOverrideProxy Private Class
//
//------------------------------------------------------
#region WindowsStatusBarPaneChildOverrideProxy
class WindowsStatusBarPaneChildOverrideProxy : ProxyHwnd, IGridItemProvider
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
internal WindowsStatusBarPaneChildOverrideProxy(IntPtr hwnd, ProxyFragment parent, int item)
: base(hwnd, parent, item)
{
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
internal override ProviderOptions ProviderOptions
{
get
{
return base.ProviderOptions | ProviderOptions.OverrideProvider;
}
}
// Returns a pattern interface if supported.
internal override object GetPatternProvider(AutomationPattern iid)
{
if (iid == GridItemPattern.Pattern)
{
return this;
}
return null;
}
internal override object GetElementProperty(AutomationProperty idProp)
{
// No property should be handled by the override proxy
// Overrides the ProxySimple implementation.
return null;
}
#endregion
#region Grid Pattern
int IGridItemProvider.Row
{
get
{
return 0;
}
}
int IGridItemProvider.Column
{
get
{
return _item;
}
}
int IGridItemProvider.RowSpan
{
get
{
return 1;
}
}
int IGridItemProvider.ColumnSpan
{
get
{
return 1;
}
}
IRawElementProviderSimple IGridItemProvider.ContainingGrid
{
get
{
return _parent;
}
}
#endregion Grid Pattern
}
#endregion
// ------------------------------------------------------
//
// StatusBarGrip Private Class
//
// ------------------------------------------------------
#region StatusBarGrip
class StatusBarGrip: ProxyFragment
{
// ------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
public StatusBarGrip (IntPtr hwnd, ProxyHwnd parent, int item)
: base( hwnd, parent, item)
{
_sType = ST.Get(STID.LocalizedControlTypeGrip);
_sAutomationId = "StatusBar.Grip"; // This string is a non-localizable string
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
// Gets the bounding rectangle for this element
internal override Rect BoundingRectangle
{
get
{
// Don't need to normalize, GetBoundingRectangle returns absolute coordinates.
return GetBoundingRectangle(_hwnd).ToRect(false);
}
}
#endregion
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Gets the bounding rectangle for this element
internal static NativeMethods.Win32Rect GetBoundingRectangle (IntPtr hwnd)
{
if (!HasGrip(hwnd))
{
return NativeMethods.Win32Rect.Empty;
}
NativeMethods.Win32Rect client = new NativeMethods.Win32Rect();
if (!Misc.GetClientRectInScreenCoordinates(hwnd, ref client))
{
return NativeMethods.Win32Rect.Empty;
}
// Get the Size for the Gripper
// The size can change at any time so the value cannot be cached
NativeMethods.SIZE sizeGrip = WindowsGrip.GetGripSize(hwnd, true);
if (Misc.IsLayoutRTL(hwnd))
{
// Right to left mirroring style
return new NativeMethods.Win32Rect(client.left, client.bottom - sizeGrip.cy, client.left + sizeGrip.cx, client.bottom);
}
else
{
return new NativeMethods.Win32Rect(client.right - sizeGrip.cx, client.bottom - sizeGrip.cy, client.right, client.bottom);
}
}
internal static StatusBarGrip Create(IntPtr hwnd, ProxyHwnd parent, int item)
{
if(HasGrip(hwnd))
{
return new StatusBarGrip(hwnd, parent, item);
}
return null;
}
#endregion
#region Private Methods
internal static bool HasGrip(IntPtr hwnd)
{
int style = Misc.GetWindowStyle(hwnd);
return Misc.IsBitSet(style, SBARS_SIZEGRIP) || WindowsGrip.IsGripPresent(hwnd, true);
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using Microsoft.Tools.Transformer.CodeModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
// TODO: let entry point be removable?
namespace TrimBin
{
public class Trimmer : MetadataRewriter
{
public Trimmer(IncludeSet includeSet, bool changeVisibility, bool applyAnnotations, bool removeDesktopSecurity, HostEnvironment hostEnvironment, bool removeSerializabilityInfo)
: this(includeSet, changeVisibility, applyAnnotations, removeDesktopSecurity, hostEnvironment, removeSerializabilityInfo, false, false)
{ }
public Trimmer(IncludeSet includeSet, bool changeVisibility, bool applyAnnotations, bool removeDesktopSecurity, HostEnvironment hostEnvironment, bool removeSerializabilityInfo, bool ensureConstructorsPresent)
: this(includeSet, changeVisibility, applyAnnotations, removeDesktopSecurity, hostEnvironment, removeSerializabilityInfo, false, false)
{ }
public Trimmer(IncludeSet includeSet, bool changeVisibility, bool applyAnnotations, bool removeDesktopSecurity, HostEnvironment hostEnvironment, bool removeSerializabilityInfo, bool ensureConstructorsPresent, bool removeManifestResources)
: base(hostEnvironment)
{
_includeSet = includeSet;
_changeVisibility = changeVisibility;
_applyAnnotations = applyAnnotations;
_removeDesktopSecurity = removeDesktopSecurity;
_removeSerializabilityInfo = removeSerializabilityInfo;
_ensureConstructorsPresent = ensureConstructorsPresent;
_removeManifestResources = removeManifestResources;
_trimElements = new Stack<Element>();
_systemTypes = new List<string>{
"<Module>",
}; // No need to include build-related types like AssemblyRef, FXAssembly, nor ThisAssembly
}
protected List<INamedTypeDefinition> _allTypesList = new List<INamedTypeDefinition>();
public bool TrimBinaries(string sourceDir, string outputDir)
{
bool fSuccess = true;
foreach (TrimAssembly trimAssembly in _includeSet.GetAllAssemblies())
{
_currentTrimAssembly = trimAssembly;
try
{
string sourceFile = Path.Combine(sourceDir, trimAssembly.Name + ".dll");
string outputFile = Path.Combine(outputDir, trimAssembly.Name + ".dll");
Console.WriteLine("loading assembly '" + sourceFile + "'");
IModule module = host.LoadUnitFrom(sourceFile) as IModule;
if (module == null || module == Dummy.Module || module == Dummy.Assembly)
{
throw new Exception(sourceFile + " is not a PE file containing a CLR module or assembly, or an error occurred when loading it.");
}
// Working around bug
DummyTraverser dummyTraverser = new DummyTraverser();
PdbReader pdbReader = null;
PdbWriter pdbWriter = null;
string pdbSourceFile = Path.ChangeExtension(sourceFile, "pdb");
string pdbOutputFile = Path.ChangeExtension(outputFile, "pdb");
if (File.Exists(pdbSourceFile))
{
Stream pdbStream = File.OpenRead(pdbSourceFile);
pdbReader = new PdbReader(pdbStream, host);
pdbWriter = new PdbWriter(Path.GetFullPath(pdbOutputFile), pdbReader);
}
IAssembly/*?*/ assembly = module as IAssembly;
if (assembly != null)
{
dummyTraverser.Visit(assembly);
module = this.Rewrite(assembly);
}
else
{
dummyTraverser.Visit(module);
module = this.Rewrite(module);
}
PeWriter.WritePeToStream(module, host, File.Create(outputFile), pdbReader, pdbReader, pdbWriter);
}
catch (Exception e)
{
Console.WriteLine(trimAssembly.Key + ": " + e.Message);
throw;
}
}
if (!fSuccess)
Console.Error.WriteLine(String.Format("At least one of the assemblies could not be processed!"));
return fSuccess;
}
/// <summary>
/// Update references to the given assembly identity to reference the new identity.
/// </summary>
/// <param name="assemblyIdentity"></param>
/// <param name="newAssemblyIdentity"></param>
public void UpdateAssemblyReferences(AssemblyIdentity assemblyIdentity, AssemblyIdentity newAssemblyIdentity)
{
foreach (object reference in referenceRewrites)
{
if (reference is Microsoft.Cci.MutableCodeModel.AssemblyReference)
{
var assemblyRef = reference as Microsoft.Cci.MutableCodeModel.AssemblyReference;
if (assemblyRef.AssemblyIdentity.Equals(assemblyIdentity))
{
// Set the reference identity. This updates related properties like name and culture as well.
assemblyRef.AssemblyIdentity = newAssemblyIdentity;
}
}
}
}
public override List<ICustomAttribute> Rewrite(List<ICustomAttribute> customAttributes)
{
List<ICustomAttribute> newList = new List<ICustomAttribute>();
if (customAttributes == null)
{
return newList;
}
foreach (ICustomAttribute attribute in customAttributes)
{
if ((_removeSerializabilityInfo && Util.FullyQualifiedTypeNameFromType(attribute.Type) == "System.Runtime.Serialization.OptionalFieldAttribute") ||
(_removeSerializabilityInfo && Util.FullyQualifiedTypeNameFromType(attribute.Type) == "System.NonSerializedAttribute") ||
(_removeDesktopSecurity && Util.FullyQualifiedTypeNameFromType(attribute.Type) == "System.Security.SuppressUnmanagedCodeSecurityAttribute"))
continue;
newList.Add(Rewrite(attribute));
}
return newList;
}
public override List<ISecurityAttribute> Rewrite(List<ISecurityAttribute> securityAttributes)
{
if (!_removeDesktopSecurity)
return securityAttributes;
List<ISecurityAttribute> newList = new List<ISecurityAttribute>();
if (securityAttributes == null)
{
return newList;
}
foreach (ISecurityAttribute sa in securityAttributes)
{
bool removeSA = false;
if (sa.Action == SecurityAction.LinkDemand || sa.Action == SecurityAction.InheritanceDemand)
{
removeSA = true;
foreach (ICustomAttribute attribute in sa.Attributes)
{
if (Util.GetTypeName(attribute.Type) == "System.Security.Permissions.HostProtectionAttribute")
{
removeSA = false;
}
}
}
if (!removeSA)
{
ISecurityAttribute newSA = sa;
newList.Add(Rewrite(newSA));
}
}
return newList;
}
public override void RewriteChildren(Assembly assembly)
{
_currentTrimAssembly = (TrimAssembly)_includeSet.Assemblies[assembly.Name.Value];
// This should never happen.
if (assembly.Name.Value != _currentTrimAssembly.Name)
throw new Exception("Assembly name mismatch.");
_trimElements.Push(_currentTrimAssembly);
base.RewriteChildren(assembly);
assembly.AllTypes = _allTypesList;
_trimElements.Pop();
}
public override void RewriteChildren(Module module)
{
// Special case of calling the type <Module> since that one won't get called as part of the traversal and is required.
// This was done before in CCI, but it's not anymore, which is why we are adding that special case here.
if (module.AllTypes.Count > 0)
this.Rewrite((INamespaceTypeDefinition)module.AllTypes[0]);
base.RewriteChildren(module);
// Cci doesn't trim any module references or user strings if they were read in from an assembly.
// Clear them so that trimmed versions are built during PE writing.
if (module.ModuleReferences != null)
module.ModuleReferences.Clear();
if (module.Strings != null)
module.Strings.Clear();
}
public override void RewriteChildren(NamespaceTypeDefinition namespaceTypeDefinition)
{
string typeName = Util.FullyQualifiedTypeNameFromType(namespaceTypeDefinition);
Element currentElement = null;
// Unlike all other types that visited from either a namespace or a parent,
// the module type is visited from the containing module
if (_systemTypes.Contains(typeName))
{
currentElement = new SpecialTrimType(typeName);
_trimElements.Push(currentElement);
}
this.RewriteChildren((NamedTypeDefinition)namespaceTypeDefinition);
//namespaceTypeDefinition.ContainingUnitNamespace = this.GetCurrentNamespace();
if (!_systemTypes.Contains(typeName))
{
TypeElement type = _currentTrimAssembly.GetTypeElement(typeName);
MutateType(namespaceTypeDefinition, type);
}
if (currentElement != null)
{
_trimElements.Pop();
}
}
public override List<INamespaceMember> Rewrite(List<INamespaceMember> namespaceMembers)
{
List<INamespaceMember> newList = new List<INamespaceMember>();
if (namespaceMembers == null)
{
return newList;
}
foreach (INamespaceMember member in namespaceMembers)
{
Element currentElement = null;
MemberTypes memberType = Util.GetMemberTypeFromMember(member);
if (memberType == MemberTypes.Type)
{
INamedTypeDefinition typeDef = member as INamedTypeDefinition;
string typeName = Util.FullyQualifiedTypeNameFromType(typeDef);
currentElement = _currentTrimAssembly.GetTypeElement(typeName);
// special case for the module class. In mscorlib we don't have any global functions, etc.
// TODO: process its members too.
if (currentElement == null && IsSpecialType(typeName))
{
currentElement = new SpecialTrimType(typeName);
if (!_systemTypes.Contains(typeName))
{
_systemTypes.Add(typeName);
}
}
}
else
{
currentElement = new SpecialTrimMember(null, member.Name.Value, null, memberType);
}
if (currentElement != null)
{
_trimElements.Push(currentElement);
// Visit(INamespaceMember) will create the Mutable copy
INamespaceMember newMember = this.Rewrite(member);
newList.Add(newMember);
_trimElements.Pop();
}
}
return newList;
}
public override List<IAliasForType> Rewrite(List<IAliasForType> aliasesForTypes)
{
List<IAliasForType> newList = new List<IAliasForType>();
if (aliasesForTypes == null)
{
return newList;
}
foreach (IAliasForType alias in aliasesForTypes)
{
ITypeReference aliasedType = alias.AliasedType;
String forwardedToAssemblyName = Util.GetDefiningAssembly(aliasedType).Name.Value;
String forwardedToTypeName = Util.GetTypeName(aliasedType);
Element currentElement = _currentTrimAssembly.GetTypeForwarderElement(forwardedToAssemblyName, forwardedToTypeName);
if (currentElement != null)
{
newList.Add(alias);
}
}
return base.Rewrite(newList);
}
public override List<INestedTypeDefinition> Rewrite(List<INestedTypeDefinition> nestedTypeDefinitions)
{
List<INestedTypeDefinition> newList = new List<INestedTypeDefinition>();
bool inParentSpecialType = CurrentTrimElement is SpecialTrimType;
if (nestedTypeDefinitions == null)
{
return newList;
}
foreach (INestedTypeDefinition nestedType in nestedTypeDefinitions)
{
string typeName = Util.FullyQualifiedTypeNameFromType(nestedType);
Element currentElement = null;
if (inParentSpecialType)
{
currentElement = new SpecialTrimType(typeName);
}
else
{
currentElement = _currentTrimAssembly.GetTypeElement(typeName);
}
// special case for the module class. In mscorlib we don't have any global functions, etc.
// TODO: process its members too.
if (currentElement != null)
{
_trimElements.Push(currentElement);
// Need to create the Mutable copy here
INestedTypeDefinition newType = Rewrite(nestedType);
newList.Add(newType);
MutateType(newType, currentElement);
_trimElements.Pop();
}
}
return newList;
}
public override List<IEventDefinition> Rewrite(List<IEventDefinition> eventDefinitions)
{
TrimType currentType = CurrentTrimElement as TrimType;
List<IEventDefinition> newList = new List<IEventDefinition>();
if (eventDefinitions == null)
{
return newList;
}
foreach (IEventDefinition evnt in eventDefinitions)
{
MemberElement currentElement = currentType.GetMemberElementFromMember(evnt);
if (currentElement != null)
{
_trimElements.Push(currentElement);
IEventDefinition newEvnt = Rewrite(evnt);
newList.Add(newEvnt);
_trimElements.Pop();
}
}
return newList;
}
public override List<IFieldDefinition> Rewrite(List<IFieldDefinition> fieldDefinitions)
{
TrimType currentType = CurrentTrimElement as TrimType;
List<IFieldDefinition> newList = new List<IFieldDefinition>();
if (fieldDefinitions == null)
{
return newList;
}
foreach (IFieldDefinition field in fieldDefinitions)
{
MemberElement currentElement = currentType.GetMemberElementFromMember(field);
if (currentElement != null)
{
_trimElements.Push(currentElement);
IFieldDefinition newField = Rewrite(field);
newList.Add(newField);
_trimElements.Pop();
}
}
return newList;
}
public override List<IMethodDefinition> Rewrite(List<IMethodDefinition> methodDefinitions)
{
TrimType currentType = CurrentTrimElement as TrimType;
List<IMethodDefinition> newList = new List<IMethodDefinition>();
if (methodDefinitions == null)
{
return newList;
}
foreach (IMethodDefinition method in methodDefinitions)
{
MemberElement currentElement = currentType.GetMemberElementFromMember(method);
if (currentElement != null)
{
_trimElements.Push(currentElement);
IMethodDefinition newMethod = Rewrite(method);
newList.Add(newMethod);
_trimElements.Pop();
}
}
return newList;
}
public override List<IPropertyDefinition> Rewrite(List<IPropertyDefinition> propertyDefinitions)
{
TrimType currentType = CurrentTrimElement as TrimType;
List<IPropertyDefinition> newList = new List<IPropertyDefinition>();
if (propertyDefinitions == null)
{
return newList;
}
foreach (IPropertyDefinition property in propertyDefinitions)
{
MemberElement currentElement = currentType.GetMemberElementFromMember(property);
if (currentElement != null)
{
_trimElements.Push(currentElement);
IPropertyDefinition newProperty = Rewrite(property);
newList.Add(newProperty);
_trimElements.Pop();
}
}
return newList;
}
public override List<IMethodImplementation> Rewrite(List<IMethodImplementation> methodImplementations)
{
TrimType currentType = CurrentTrimElement as TrimType;
List<IMethodImplementation> newList = new List<IMethodImplementation>();
if (methodImplementations == null)
{
return newList;
}
foreach (IMethodImplementation methodImpl in methodImplementations)
{
IMethodReference implementingMethod = methodImpl.ImplementingMethod;
IMethodReference implementedMethod = methodImpl.ImplementedMethod;
TrimMember implementingMemberElement = currentType.GetMemberElementFromMember(implementingMethod);
TrimMember implementedMemberElement = null;
if (implementingMemberElement != null)
{
ITypeReference implementedType = Util.CanonicalizeTypeReference(implementedMethod.ContainingType);
TrimType implementedTypeElement = (TrimType)_currentTrimAssembly.GetTypeElement(Util.GetTypeName(implementedType));
if (implementedTypeElement != null)
implementedMemberElement = implementedTypeElement.GetMemberElementFromMember(Util.CanonicalizeMethodReference(implementedMethod));
}
else
{ }
if (implementingMemberElement != null && (implementedMemberElement != null ||
!_includeSet.Assemblies.ContainsKey(Util.GetDefiningAssembly(implementedMethod.ContainingType).Name.Value)))
{
IMethodImplementation newMethodImpl = Rewrite(methodImpl);
newList.Add(newMethodImpl);
}
//else
//{ Console.WriteLine("Removing {0}'s impl of {1}", implementingMethod.ToString(), implementedMethod.ToString()); }
}
return newList;
}
public override void RewriteChildren(NamedTypeDefinition typeDefinition)
{
// Remove interfaces
List<ITypeReference> newList = new List<ITypeReference>();
if (typeDefinition.Interfaces != null)
{
foreach (ITypeReference iface in typeDefinition.Interfaces)
{
INamedTypeDefinition canonicalInterface = Util.CanonicalizeType(iface);
// TODO: m_currentTrimAssembly is bad if we want to trim more than one assembly in one pass.
// Keep implemented interfaces that are present in the include set, or defined in a different assembly.
TypeElement element = _currentTrimAssembly.GetTypeElement(Util.FullyQualifiedTypeNameFromType(canonicalInterface));
if (element != null ||
!_includeSet.Assemblies.ContainsKey(Util.GetDefiningAssembly(canonicalInterface).Name.Value))
{
// No need to visit iface here because base.Visit will do that
newList.Add(iface);
}
}
}
typeDefinition.Interfaces = newList;
// Remove SerializableAttribute
if (_removeSerializabilityInfo)
{
typeDefinition.IsSerializable = false;
}
// Ensure we visit all children
base.RewriteChildren(typeDefinition);
// Adding this type to the flat list of types for this assembly. This is required because the MetadataRewriter doesn't update the AllTypes property of the assembly.
if (_currentTrimAssembly.GetTypeElement(Util.GetTypeName(typeDefinition)) != null || _systemTypes.Contains(Util.GetTypeName(typeDefinition)))
_allTypesList.Add(typeDefinition);
if (typeDefinition.HasDeclarativeSecurity && typeDefinition.SecurityAttributes.Count == 0)
{
typeDefinition.HasDeclarativeSecurity = false;
}
// Add an empty constructor to constructor-less types
if (_ensureConstructorsPresent)
{
bool hasConstructors = false;
foreach (IMethodDefinition method in typeDefinition.Methods)
{
if (method.IsConstructor && !method.IsStatic)
{
hasConstructors = true;
}
}
if (!hasConstructors && !_systemTypes.Contains(typeDefinition.Name.Value) && typeDefinition.IsClass && !typeDefinition.IsStatic)
{
MethodDefinition method = new MethodDefinition();
method.IsSpecialName = true;
method.Name = this.host.NameTable.Ctor;
method.CallingConvention = CallingConvention.HasThis;
method.ContainingTypeDefinition = typeDefinition;
method.Parameters = new List<IParameterDefinition>();
MethodBody methodBody = new MethodBody();
method.Body = methodBody;
method.Type = typeDefinition.PlatformType.SystemVoid;
method.Visibility = TypeMemberVisibility.Private;
// To avoid warnings when round-tripping these through ildasm & ilasm, put 1 return instruction
// in the method body. Unfortunately this doesn't seem to work.
List<IOperation> instrs = new List<IOperation>(1);
Operation o = new Operation();
o.OperationCode = OperationCode.Ret;
o.Offset = 0;
instrs.Add(o);
methodBody.Operations = instrs;
methodBody.MethodDefinition = method;
//this.path.Push(typeDefinition);
typeDefinition.Methods.Add(this.Rewrite(method));
//this.path.Pop();
}
}
}
public override void RewriteChildren(EventDefinition eventDefinition)
{
base.RewriteChildren(eventDefinition);
MutateMember(eventDefinition, CurrentTrimElement);
}
public override void RewriteChildren(FieldDefinition fieldDefinition)
{
base.RewriteChildren(fieldDefinition);
MutateMember(fieldDefinition, CurrentTrimElement);
if (_removeSerializabilityInfo)
{
(fieldDefinition).IsNotSerialized = false;
}
}
public override void RewriteChildren(MethodDefinition methodDefinition)
{
base.RewriteChildren(methodDefinition);
MutateMember(methodDefinition, CurrentTrimElement);
if (methodDefinition.HasDeclarativeSecurity && methodDefinition.SecurityAttributes.Count == 0)
{
methodDefinition.HasDeclarativeSecurity = false;
}
}
public override IFieldReference Rewrite(IFieldReference fieldReference)
{
IFieldDefinition fieldDefinition = fieldReference as IFieldDefinition;
if (fieldDefinition != null)
return fieldDefinition; // If the reference already is a definition, then we don't need to traverse again.
return base.Rewrite(fieldReference);
}
public override void RewriteChildren(PropertyDefinition propertyDefinition)
{
base.RewriteChildren(propertyDefinition);
MutateMember(propertyDefinition, CurrentTrimElement);
}
private void MutateMember(TypeDefinitionMember member, Element element)
{
// Set transparency attributes.
if (_applyAnnotations)
{
SecurityTransparencyStatus currentStatus = GetMarkedSecurityAnnotation(member.Attributes, member.ContainingTypeDefinition);
if (element.SecurityTransparencyStatus != SecurityTransparencyStatus.Undefined && currentStatus != element.SecurityTransparencyStatus)
{
RemoveSecurityTransparencyAttributes(member.Attributes, member.ContainingTypeDefinition);
AddSecurityTransparencyAttribute(member.Attributes, element.SecurityTransparencyStatus, member.ContainingTypeDefinition);
}
}
// Add FriendAccessAllowed attribute.
if (!(member is PropertyDefinition)) // FAA isn't needed on properties; it's only needed on getters and setters
{
List<ICustomAttribute> attributes = member.Attributes;
AddFaaAttributeIfNeeded(element, attributes, member.ContainingTypeDefinition);
}
// Make internal if needed.
if (_changeVisibility && element.ShouldMakeInternal && !Util.IsInternal(member.ResolvedTypeDefinitionMember.Visibility))
{
// Make the member internal
MakeInternal(member);
// Interface method implementations don't need Explicit Interface Method Implementations (EIMI's) if the implementing
// method is public and has the same signature as the interface method. Since we're making the method internal,
// we need to add the EIMI's.
CreateExplicitInterfaceImplementations(member);
}
}
private void AddFaaAttributeIfNeeded(Element element, List<ICustomAttribute> attributes, ITypeReference containingType)
{
if (element != null && element.IsFriendAccessAllowed)//typeHasFaaAttribute(attributes, containingType))
{
List<INamedTypeDefinition> types = new List<INamedTypeDefinition>(this.host.FindAssembly(this.host.CoreAssemblySymbolicIdentity).GetAllTypes());
if (types == null || !types.Any())
return; //Couldn't find any type on the assembly
IEnumerable<INamedTypeDefinition> faaAttributeType = types.Where(t => t.Name.Value == "FriendAccessAllowedAttribute");
if (!faaAttributeType.Any())
return; //Unable to find the FriendAccessAllowedAttribute
var faaAttributeResult = faaAttributeType.FirstOrDefault();
if (!Util.HasAttribute(attributes, faaAttributeResult))
{
Microsoft.Cci.MethodReference faaCtor = new Microsoft.Cci.MethodReference(this.host, faaAttributeResult,
CallingConvention.HasThis, this.host.PlatformType.SystemVoid, this.host.NameTable.Ctor, 0);
CustomAttribute faaAttribute = new CustomAttribute();
faaAttribute.Constructor = faaCtor;
attributes.Add(Rewrite(faaAttribute));
}
}
}
private void CreateExplicitInterfaceImplementations(TypeDefinitionMember member)
{
List<ITypeDefinitionMember> interfaceMembers = Util.FindRelatedInterfaceMembers(member);
foreach (ITypeDefinitionMember interfaceMember in interfaceMembers)
{
IMethodDefinition methodDef = interfaceMember.ResolvedTypeDefinitionMember as IMethodDefinition;
if (methodDef != null)
{
List<IMethodImplementation> methodImpls = null;
methodImpls = GetExplicitImplementationOverrides(member, methodImpls);
if (methodImpls != null)
{
// Make sure implementedmethod is in the closure
TrimType trimType = (TrimType)_currentTrimAssembly.GetTypeElement(Util.GetTypeName(Util.ContainingTypeDefinition(interfaceMember)));
if (trimType != null)
{
TrimMember trimMember = trimType.GetMemberElementFromMember(interfaceMember);
if (trimMember != null)
{
MethodImplementation methodImpl = new MethodImplementation();
methodImpl.ImplementedMethod = interfaceMember.ResolvedTypeDefinitionMember as IMethodReference;
methodImpl.ImplementingMethod = member as IMethodReference;
methodImpl.ContainingType = member.ContainingTypeDefinition;
methodImpls.Add(Rewrite(methodImpl));
}
}
}
}
}
}
private void MutateType(INamedTypeDefinition iTypeDef, Element element)
{
NamedTypeDefinition typeDef = iTypeDef as NamedTypeDefinition;
if (typeDef == null)
throw new Exception("Invalid namedType definition.");
if (_applyAnnotations)
{
SecurityTransparencyStatus currentStatus = GetMarkedSecurityAnnotation(typeDef.Attributes, typeDef);
if (element.SecurityTransparencyStatus != SecurityTransparencyStatus.Undefined && element.SecurityTransparencyStatus != SecurityTransparencyStatus.Transparent && currentStatus != element.SecurityTransparencyStatus)
{
RemoveSecurityTransparencyAttributes(typeDef.Attributes, typeDef);
AddSecurityTransparencyAttribute(typeDef.Attributes, element.SecurityTransparencyStatus, typeDef);
}
}
AddFaaAttributeIfNeeded(element, typeDef.Attributes, typeDef);
if (_changeVisibility && element.ShouldMakeInternal)
{
MakeInternal(typeDef);
}
}
private void MakeInternal(TypeDefinitionMember member)
{
member.Visibility = GetInternalVisibility(member.Visibility);
}
private TypeMemberVisibility GetInternalVisibility(TypeMemberVisibility vis)
{
if (vis == TypeMemberVisibility.Public || vis == TypeMemberVisibility.FamilyOrAssembly)
return TypeMemberVisibility.Assembly;
else if (vis == TypeMemberVisibility.Family)
return TypeMemberVisibility.FamilyAndAssembly;
else { return vis; }
}
private void MakeInternal(NamedTypeDefinition nsType)
{
NestedTypeDefinition nestedTypeDef = nsType as NestedTypeDefinition;
NamespaceTypeDefinition namespaceTypeDef = nsType as NamespaceTypeDefinition;
if (namespaceTypeDef != null)
{
namespaceTypeDef.IsPublic = false;
}
else if (nestedTypeDef != null)
{
nestedTypeDef.Visibility = GetInternalVisibility(nestedTypeDef.Visibility);
}
}
private bool _changeVisibility = true;
private bool _applyAnnotations = false;
private bool _removeDesktopSecurity = false;
private bool _removeSerializabilityInfo = false;
private bool _ensureConstructorsPresent = false;
private bool _removeManifestResources = false;
private bool IsCurrentElementFAA
{
get
{
Element element = CurrentTrimElement;
if (element != null && element.IsFriendAccessAllowed)
return true;
else
return false;
}
}
// TODO: Find a better (traversal order-agnostic) mapping between trim elements and cci elements
private Element CurrentTrimElement
{
get
{
//if (m_trimElements.Count == 0)
// return null;
return _trimElements.Peek();
}
}
private bool IsSpecialType(string typeName)
{
if (_systemTypes.Contains(typeName) ||
typeName.StartsWith("<PrivateImplementationDetails>"))
{
return true;
}
return false;
}
private IncludeSet _includeSet;
private IList<string> _systemTypes;
private Stack<Element> _trimElements;
//// We need this because types are organized in a flat tructure instead of hierarchically in model.xml
// so type lookups are always done at the assembly level, even for nested types.
private TrimAssembly _currentTrimAssembly;
private Dictionary<String, INamedTypeDefinition> _typeCache = new Dictionary<string, INamedTypeDefinition>();
private String _securityTreatAsSafeAttributeName = "System.Security.SecurityTreatAsSafe";
internal SecurityTransparencyStatus GetMarkedSecurityAnnotation(List<ICustomAttribute> list, ITypeReference containingType)
{
ITypeReference securityCriticalAttributeType = containingType.PlatformType.SystemSecuritySecurityCriticalAttribute;
ITypeReference securitySafeCriticalAttributeType = containingType.PlatformType.SystemSecuritySecuritySafeCriticalAttribute;
bool containsSecurityCriticalAttribute = false;
bool containsSecuritySafeCriticalAttribute = false;
bool containsSecurityTreatAsSafeAttribute = false;
// TODO: Handle SecurityTreatAsSafe?
foreach (ICustomAttribute attribute in list)
{
if (TypeHelper.TypesAreEquivalent(attribute.Type, securityCriticalAttributeType))
{
containsSecurityCriticalAttribute = true;
}
else if (Util.GetTypeName(attribute.Type).Equals(_securityTreatAsSafeAttributeName))
{
containsSecurityTreatAsSafeAttribute = true;
}
else if (TypeHelper.TypesAreEquivalent(attribute.Type, securitySafeCriticalAttributeType))
{
containsSecuritySafeCriticalAttribute = true;
}
}
if (containsSecuritySafeCriticalAttribute)
{
return SecurityTransparencyStatus.SafeCritical;
}
else if (containsSecurityCriticalAttribute)
{
if (containsSecurityTreatAsSafeAttribute) // Critical + TreatAsSafe == SafeCritical
{
return SecurityTransparencyStatus.SafeCritical;
}
else
{
return SecurityTransparencyStatus.Critical;
}
}
else // No annotation
{
return SecurityTransparencyStatus.Transparent;
}
}
internal void RemoveSecurityTransparencyAttributes(List<ICustomAttribute> list, ITypeReference containingType)
{
ITypeReference securityCriticalAttributeType = containingType.PlatformType.SystemSecuritySecurityCriticalAttribute;
ITypeReference securitySafeCriticalAttributeType = containingType.PlatformType.SystemSecuritySecuritySafeCriticalAttribute;
for (int i = list.Count - 1; i >= 0; i--)
{
ICustomAttribute attribute = list[i];
if (TypeHelper.TypesAreEquivalent(attribute.Type, securityCriticalAttributeType) || TypeHelper.TypesAreEquivalent(attribute.Type, securitySafeCriticalAttributeType) || Util.GetTypeName(attribute.Type).Equals(_securityTreatAsSafeAttributeName))
{
list.RemoveAt(i);
}
}
}
internal void AddSecurityTransparencyAttribute(List<ICustomAttribute> list, SecurityTransparencyStatus securityTransparencyStatus, ITypeReference containingType)
{
Microsoft.Cci.MethodReference ctor = null;
switch (securityTransparencyStatus)
{
case SecurityTransparencyStatus.Critical:
ctor = new Microsoft.Cci.MethodReference(this.host, containingType.PlatformType.SystemSecuritySecurityCriticalAttribute,//FindType("System.Security.SecurityCriticalAttribute"),
CallingConvention.HasThis, this.host.PlatformType.SystemVoid, this.host.NameTable.Ctor, 0);
break;
case SecurityTransparencyStatus.SafeCritical:
ctor = new Microsoft.Cci.MethodReference(this.host, containingType.PlatformType.SystemSecuritySecuritySafeCriticalAttribute,//FindType("System.Security.SecuritySafeCriticalAttribute"),
CallingConvention.HasThis, this.host.PlatformType.SystemVoid, this.host.NameTable.Ctor, 0);
break;
case SecurityTransparencyStatus.Transparent:
break;
}
if (ctor != null)
{
CustomAttribute securityAttribute = new CustomAttribute();
securityAttribute.Constructor = ctor;
list.Add(Rewrite(securityAttribute));
}
}
private List<IMethodImplementation> GetExplicitImplementationOverrides(TypeDefinitionMember member, List<IMethodImplementation> methodImpls)
{
INamespaceTypeDefinition namespaceTypeDef = member.ContainingTypeDefinition as INamespaceTypeDefinition;
INestedTypeDefinition nestedTypeDef = member.ContainingTypeDefinition as INestedTypeDefinition;
if (namespaceTypeDef != null)
{
methodImpls = ((NamespaceTypeDefinition)namespaceTypeDef).ExplicitImplementationOverrides;
}
else if (nestedTypeDef != null)
{
methodImpls = ((NamespaceTypeDefinition)namespaceTypeDef).ExplicitImplementationOverrides;
}
else
{
throw new InvalidOperationException("ExplicitImplementationOverrides can only be accessed on a NamespaceTypeDefinition or a NestedTypeDefinition object");
}
return methodImpls;
}
public override List<IResourceReference> Rewrite(List<IResourceReference> resourceReferences)
{
if (_removeManifestResources)
{
if (resourceReferences.Count > 0)
{
return new List<IResourceReference>();
}
}
return resourceReferences;
}
}
#pragma warning disable 618
// Warning is displayed that we should use MetadataTraverser instead of BaseMetadataTraverser, but due to breaking changes, we supressed the warning.
// This class exists to work around a bug in Cci.
internal class DummyTraverser : BaseMetadataTraverser
#pragma warning restore 618
{
public DummyTraverser()
: base()
{ }
public override void Visit(ITypeReference typeReference)
{
return;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.Rules.Models;
using Orchard.Rules.Services;
using Orchard.Rules.ViewModels;
using Orchard.ContentManagement;
using Orchard.Core.Contents.Controllers;
using Orchard.Data;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Notify;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
namespace Orchard.Rules.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly ISiteService _siteService;
private readonly IRulesManager _rulesManager;
private readonly IRulesServices _rulesServices;
public AdminController(
IOrchardServices services,
IShapeFactory shapeFactory,
ISiteService siteService,
IRulesManager rulesManager,
IRulesServices rulesServices,
IRepository<RuleRecord> repository) {
_siteService = siteService;
_rulesManager = rulesManager;
_rulesServices = rulesServices;
Services = services;
T = NullLocalizer.Instance;
Shape = shapeFactory;
}
dynamic Shape { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(RulesIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list rules")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new RulesIndexOptions();
var rules = _rulesServices.GetRules();
switch (options.Filter) {
case RulesFilter.Disabled:
rules = rules.Where(r => r.Enabled == false);
break;
case RulesFilter.Enabled:
rules = rules.Where(u => u.Enabled);
break;
}
if (!String.IsNullOrWhiteSpace(options.Search)) {
rules = rules.Where(r => r.Name.Contains(options.Search));
}
var pagerShape = Shape.Pager(pager).TotalItemCount(rules.Count());
switch (options.Order) {
case RulesOrder.Name:
rules = rules.OrderBy(u => u.Name);
break;
}
var results = rules
.Skip(pager.GetStartIndex())
.Take(pager.PageSize)
.ToList();
var model = new RulesIndexViewModel {
Rules = results.Select(x => new RulesEntry {
Rule = x,
IsChecked = false,
RuleId = x.Id
}).ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
[HttpPost]
[FormValueRequired("submit.BulkEdit")]
public ActionResult Index(FormCollection input) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
var viewModel = new RulesIndexViewModel { Rules = new List<RulesEntry>(), Options = new RulesIndexOptions() };
UpdateModel(viewModel);
var checkedEntries = viewModel.Rules.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case RulesBulkAction.None:
break;
case RulesBulkAction.Enable:
foreach (var entry in checkedEntries) {
_rulesServices.GetRule(entry.RuleId).Enabled = true;
}
break;
case RulesBulkAction.Disable:
foreach (var entry in checkedEntries) {
_rulesServices.GetRule(entry.RuleId).Enabled = false;
}
break;
case RulesBulkAction.Delete:
foreach (var entry in checkedEntries) {
_rulesServices.DeleteRule(entry.RuleId);
}
break;
}
return RedirectToAction("Index");
}
public ActionResult Move(string direction, int id, int actionId) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
switch(direction) {
case "up" : _rulesServices.MoveUp(actionId);
break;
case "down": _rulesServices.MoveDown(actionId);
break;
default:
throw new ArgumentException("direction");
}
return RedirectToAction("Edit", new { id });
}
public ActionResult Create() {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
return View(new CreateRuleViewModel());
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePost(CreateRuleViewModel viewModel) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
}
else {
var rule = _rulesServices.CreateRule(viewModel.Name);
return RedirectToAction("Edit", new { id = rule.Id });
}
return View(viewModel);
}
public ActionResult Edit(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit rules")))
return new HttpUnauthorizedResult();
var rule = _rulesServices.GetRule(id);
var viewModel = new EditRuleViewModel {
Id = rule.Id,
Enabled = rule.Enabled,
Name = rule.Name
};
#region Load events
var eventEntries = new List<EventEntry>();
var allEvents = _rulesManager.DescribeEvents().SelectMany(x => x.Descriptors);
foreach (var eventRecord in rule.Events) {
var category = eventRecord.Category;
var type = eventRecord.Type;
var ev = allEvents.Where(x => category == x.Category && type == x.Type).FirstOrDefault();
if (ev != null) {
var eventParameters = FormParametersHelper.FromString(eventRecord.Parameters);
eventEntries.Add(
new EventEntry {
Category = ev.Category,
Type = ev.Type,
EventRecordId = eventRecord.Id,
DisplayText = ev.Display(new EventContext { Properties = eventParameters })
});
}
}
viewModel.Events = eventEntries;
#endregion
#region Load actions
var actionEntries = new List<ActionEntry>();
var allActions = _rulesManager.DescribeActions().SelectMany(x => x.Descriptors);
foreach (var actionRecord in rule.Actions.OrderBy(x => x.Position)) {
var category = actionRecord.Category;
var type = actionRecord.Type;
var action = allActions.Where(x => category == x.Category && type == x.Type).FirstOrDefault();
if (action != null) {
var actionParameters = FormParametersHelper.FromString(actionRecord.Parameters);
actionEntries.Add(
new ActionEntry {
Category = action.Category,
Type = action.Type,
ActionRecordId = actionRecord.Id,
DisplayText = action.Display(new ActionContext { Properties = actionParameters })
});
}
}
viewModel.Actions = actionEntries;
#endregion
return View(viewModel);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public ActionResult EditPost(EditRuleViewModel viewModel) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
}
else {
var rule = _rulesServices.GetRule(viewModel.Id);
rule.Name = viewModel.Name;
rule.Enabled = viewModel.Enabled;
Services.Notifier.Information(T("Rule Saved"));
return RedirectToAction("Edit", new { id = rule.Id });
}
return View(viewModel);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.SaveAndEnable")]
public ActionResult EditAndEnablePost(EditRuleViewModel viewModel) {
viewModel.Enabled = true;
return EditPost(viewModel);
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
var rule = _rulesServices.GetRule(id);
if (rule != null) {
_rulesServices.DeleteRule(id);
Services.Notifier.Information(T("Rule {0} deleted", rule.Name));
}
return RedirectToAction("Index");
}
public ActionResult Enable(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
var rule = _rulesServices.GetRule(id);
if (rule != null) {
rule.Enabled = true;
Services.Notifier.Information(T("Rule enabled"));
}
return RedirectToAction("Index");
}
public ActionResult Disable(int id) {
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage rules")))
return new HttpUnauthorizedResult();
var rule = _rulesServices.GetRule(id);
if (rule != null) {
rule.Enabled = false;
Services.Notifier.Information(T("Rule disabled"));
}
return RedirectToAction("Index");
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using System.Linq;
namespace RefactoringEssentials.CSharp.Diagnostics
{
//[DiagnosticAnalyzer(LanguageNames.CSharp)]
[NotPortedYet]
public class InconsistentNamingAnalyzer : DiagnosticAnalyzer
{
internal const string DiagnosticId = "InconsistentNaming";
const string Description = "Inconsistent Naming";
const string MessageFormat = "";
const string Category = DiagnosticAnalyzerCategories.ConstraintViolations;
static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Name doesn't match the defined style for this entity.");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
//context.RegisterSyntaxNodeAction(
// (nodeContext) => {
// Diagnostic diagnostic;
// if (TryGetDiagnostic (nodeContext, out diagnostic)) {
// nodeContext.ReportDiagnostic(diagnostic);
// }
// },
// new SyntaxKind[] { SyntaxKind.None }
//);
}
static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
{
diagnostic = default(Diagnostic);
//var node = nodeContext.Node as ;
//diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
//return true;
return false;
}
// class GatherVisitor : GatherVisitorBase<InconsistentNamingAnalyzer>
// {
// //readonly NamingConventionService service;
// public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
// : base (semanticModel, addDiagnostic, cancellationToken)
// {
// // service = (NamingConventionService)ctx.GetService (typeof (NamingConventionService));
// }
//// void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult;
//// if (resolveResult == null)
//// return;
//// var type = resolveResult.Type;
//// if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) {
//// return;
//// }
//// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) {
//// return;
//// }
//// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) {
//// return;
//// }
//// }
////
//// var typeDef = type.GetDefinition();
//// if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) {
//// return;
//// }
//// }
////
//// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
//// }
////
//// void CheckName(MethodDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// ResolveResult resolveResult = null;
//// if (node != null && node.Attributes.Any ())
//// resolveResult = ctx.Resolve(node);
////
//// if (resolveResult is MemberResolveResult) {
//// var member = ((MemberResolveResult)resolveResult).Member;
//// if (member.SymbolKind == SymbolKind.Method && member.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestAttribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestMethod, identifier, accessibilty)) {
//// return;
//// }
//// }
//// }
////
//// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
//// }
////
//// void CheckName(AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// CheckNamedResolveResult(null, node, entity, identifier, accessibilty);
//// }
////
//// bool CheckNamedResolveResult(ResolveResult resolveResult, AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// bool wasHandled = false;
//// foreach (var rule in service.Rules) {
//// if (!rule.AffectedEntity.HasFlag(entity)) {
//// continue;
//// }
//// if (!rule.VisibilityMask.HasFlag(accessibilty)) {
//// continue;
//// }
//// if (!rule.IncludeInstanceMembers || !rule.IncludeStaticEntities) {
//// EntityDeclaration typeSystemEntity;
//// if (node is VariableInitializer) {
//// typeSystemEntity = node.Parent as EntityDeclaration;
//// } else {
//// typeSystemEntity = node as EntityDeclaration;
//// }
//// if (!rule.IncludeInstanceMembers) {
//// if (typeSystemEntity == null || !typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) {
//// continue;
//// }
//// }
//// if (!rule.IncludeStaticEntities) {
//// if (typeSystemEntity == null || typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) {
//// continue;
//// }
//// }
//// }
////
//// wasHandled = true;
//// if (!rule.IsValid(identifier.Name)) {
//// IList<string> suggestedNames;
//// var msg = rule.GetErrorMessage(ctx, identifier.Name, out suggestedNames);
//// var actions = new List<CodeAction>(suggestedNames.Select(n => new CodeAction(string.Format(ctx.TranslateString("Rename to '{0}'"), n), (Script script) => {
//// if (resolveResult == null)
//// resolveResult = ctx.Resolve (node);
//// if (resolveResult is MemberResolveResult) {
//// script.Rename(((MemberResolveResult)resolveResult).Member, n);
//// } else if (resolveResult is TypeResolveResult) {
//// var def = resolveResult.Type.GetDefinition();
//// if (def != null) {
//// script.Rename(def, n);
//// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) {
//// script.Rename((ITypeParameter)resolveResult.Type, n);
//// }
//// } else if (resolveResult is LocalResolveResult) {
//// script.Rename(((LocalResolveResult)resolveResult).Variable, n);
//// } else if (resolveResult is NamespaceResolveResult) {
//// script.Rename(((NamespaceResolveResult)resolveResult).Namespace, n);
//// } else {
//// script.Replace(identifier, Identifier.Create(n));
//// }
//// }, identifier)));
////
//// if (entity != AffectedEntity.Label) {
//// actions.Add(new CodeAction(string.Format(ctx.TranslateString("Rename '{0}'..."), identifier.Name), (Script script) => {
//// if (resolveResult == null)
//// resolveResult = ctx.Resolve (node);
//// if (resolveResult is MemberResolveResult) {
//// script.Rename(((MemberResolveResult)resolveResult).Member);
//// } else if (resolveResult is TypeResolveResult) {
//// var def = resolveResult.Type.GetDefinition();
//// if (def != null) {
//// script.Rename(def);
//// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) {
//// script.Rename((ITypeParameter)resolveResult.Type);
//// }
//// } else if (resolveResult is LocalResolveResult) {
//// script.Rename(((LocalResolveResult)resolveResult).Variable);
//// } else if (resolveResult is NamespaceResolveResult) {
//// script.Rename(((NamespaceResolveResult)resolveResult).Namespace);
//// }
//// }, identifier));
//// }
////
//// AddDiagnosticAnalyzer(new CodeIssue(identifier, msg, actions));
//// }
//// }
//// return wasHandled;
//// }
////
//// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
//// {
//// base.VisitNamespaceDeclaration(namespaceDeclaration);
//// var type = namespaceDeclaration.NamespaceName;
//// while (type is MemberType) {
//// var mt = (MemberType)type;
//// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, mt.MemberNameToken, Modifiers.None);
//// type = mt.Target;
//// }
//// if (type is SimpleType)
//// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, ((SimpleType)type).IdentifierToken, Modifiers.None);
//// }
////
//// Modifiers GetAccessibiltiy(EntityDeclaration decl, Modifiers defaultModifier)
//// {
//// var accessibility = (decl.Modifiers & Modifiers.VisibilityMask);
//// if (accessibility == Modifiers.None) {
//// return defaultModifier;
//// }
//// return accessibility;
//// }
////
//// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
//// {
//// base.VisitTypeDeclaration(typeDeclaration);
//// AffectedEntity entity;
//// switch (typeDeclaration.ClassType) {
//// case ClassType.Class:
//// entity = AffectedEntity.Class;
//// break;
//// case ClassType.Struct:
//// entity = AffectedEntity.Struct;
//// break;
//// case ClassType.Interface:
//// entity = AffectedEntity.Interface;
//// break;
//// case ClassType.Enum:
//// entity = AffectedEntity.Enum;
//// break;
//// default:
//// throw new System.ArgumentOutOfRangeException();
//// }
//// CheckName(typeDeclaration, entity, typeDeclaration.NameToken, GetAccessibiltiy(typeDeclaration, typeDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal));
//// }
////
//// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
//// {
//// base.VisitDelegateDeclaration(delegateDeclaration);
//// CheckName(delegateDeclaration, AffectedEntity.Delegate, delegateDeclaration.NameToken, GetAccessibiltiy(delegateDeclaration, delegateDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal));
//// }
////
//// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
//// {
//// if (propertyDeclaration.Modifiers.HasFlag (Modifiers.Override))
//// return;
//// base.VisitPropertyDeclaration(propertyDeclaration);
//// CheckName(propertyDeclaration, AffectedEntity.Property, propertyDeclaration.NameToken, GetAccessibiltiy(propertyDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
//// {
//// if (indexerDeclaration.Modifiers.HasFlag(Modifiers.Override)) {
//// var rr = ctx.Resolve (indexerDeclaration) as MemberResolveResult;
//// if (rr == null)
//// return;
//// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface);
//// var method = baseType != null ? baseType.GetProperties (m => m.IsIndexer && m.IsOverridable && m.Parameters.Count == indexerDeclaration.Parameters.Count).FirstOrDefault () : null;
//// if (method == null)
//// return;
//// int i = 0;
//// foreach (var par in indexerDeclaration.Parameters) {
//// if (method.Parameters[i++].Name != par.Name) {
//// par.AcceptVisitor (this);
//// }
//// }
//// return;
//// }
//// base.VisitIndexerDeclaration(indexerDeclaration);
//// }
////
//// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
//// {
//// if (methodDeclaration.Modifiers.HasFlag(Modifiers.Override)) {
//// var rr = ctx.Resolve (methodDeclaration) as MemberResolveResult;
//// if (rr == null)
//// return;
//// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface);
//// var method = baseType != null ? baseType.GetMethods (m => m.Name == rr.Member.Name && m.IsOverridable && m.Parameters.Count == methodDeclaration.Parameters.Count).FirstOrDefault () : null;
//// if (method == null)
//// return;
//// int i = 0;
//// foreach (var par in methodDeclaration.Parameters) {
//// if (method.Parameters[i++].Name != par.Name) {
//// par.AcceptVisitor (this);
//// }
//// }
////
//// return;
//// }
//// base.VisitMethodDeclaration(methodDeclaration);
////
//// CheckName(methodDeclaration, methodDeclaration.Modifiers.HasFlag(Modifiers.Async) ? AffectedEntity.AsyncMethod : AffectedEntity.Method, methodDeclaration.NameToken, GetAccessibiltiy(methodDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
//// {
//// base.VisitFieldDeclaration(fieldDeclaration);
//// var entity = AffectedEntity.Field;
//// if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) {
//// entity = AffectedEntity.ConstantField;
//// } else if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) {
//// entity = AffectedEntity.ReadonlyField;
//// }
//// foreach (var init in fieldDeclaration.Variables) {
//// CheckName(init, entity, init.NameToken, GetAccessibiltiy(fieldDeclaration, Modifiers.Private));
//// }
//// }
////
//// public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
//// {
//// base.VisitFixedFieldDeclaration(fixedFieldDeclaration);
//// var entity = AffectedEntity.Field;
//// if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) {
//// entity = AffectedEntity.ConstantField;
//// } else if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) {
//// entity = AffectedEntity.ReadonlyField;
//// }
//// CheckName(fixedFieldDeclaration, entity, fixedFieldDeclaration.NameToken, GetAccessibiltiy(fixedFieldDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
//// {
//// base.VisitEventDeclaration(eventDeclaration);
//// foreach (var init in eventDeclaration.Variables) {
//// CheckName(init, AffectedEntity.Event, init.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private));
//// }
//// }
////
//// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
//// {
//// if (eventDeclaration.Modifiers.HasFlag (Modifiers.Override))
//// return;
//// base.VisitCustomEventDeclaration(eventDeclaration);
//// CheckName(eventDeclaration, AffectedEntity.Event, eventDeclaration.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
//// {
//// base.VisitEnumMemberDeclaration(enumMemberDeclaration);
//// CheckName(enumMemberDeclaration, AffectedEntity.EnumMember, enumMemberDeclaration.NameToken, GetAccessibiltiy(enumMemberDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
//// {
//// base.VisitParameterDeclaration(parameterDeclaration);
//// CheckNamedResolveResult(null, parameterDeclaration, parameterDeclaration.Parent is LambdaExpression ? AffectedEntity.LambdaParameter : AffectedEntity.Parameter, parameterDeclaration.NameToken, Modifiers.None);
//// }
////
//// public override void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
//// {
//// base.VisitTypeParameterDeclaration(typeParameterDeclaration);
//// CheckNamedResolveResult(null, typeParameterDeclaration, AffectedEntity.TypeParameter, typeParameterDeclaration.NameToken, Modifiers.None);
//// }
////
//// public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
//// {
//// base.VisitVariableDeclarationStatement(variableDeclarationStatement);
//// var entity = variableDeclarationStatement.Modifiers.HasFlag(Modifiers.Const) ? AffectedEntity.LocalConstant : AffectedEntity.LocalVariable;
//// foreach (var init in variableDeclarationStatement.Variables) {
//// CheckNamedResolveResult(null, init, entity, init.NameToken, Modifiers.None);
//// }
//// }
////
//// public override void VisitLabelStatement(LabelStatement labelStatement)
//// {
//// base.VisitLabelStatement(labelStatement);
//// CheckNamedResolveResult(null, labelStatement, AffectedEntity.Label, labelStatement.LabelToken, Modifiers.None);
//// }
// }
}
[ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
public class InconsistentNamingIssueFixProvider : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(InconsistentNamingAnalyzer.DiagnosticId);
}
}
public override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var span = context.Span;
var diagnostics = context.Diagnostics;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var diagnostic = diagnostics.First();
var node = root.FindNode(context.Span);
//if (!node.IsKind(SyntaxKind.BaseList))
// continue;
var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic);
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.ActivationsLifeCycleTests
{
public class GrainActivateDeactivateTests : HostedTestClusterEnsureDefaultStarted, IDisposable
{
private IActivateDeactivateWatcherGrain watcher;
public GrainActivateDeactivateTests(DefaultClusterFixture fixture) : base(fixture)
{
watcher = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
watcher.Clear().Wait();
}
public virtual void Dispose()
{
watcher.Clear().Wait();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public async Task WatcherGrain_GetGrain()
{
IActivateDeactivateWatcherGrain grain = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(1);
await grain.Clear();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Activate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Activate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("Reentrancy")]
public async Task LongRunning_Deactivate()
{
int id = random.Next();
ILongRunningActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ILongRunningActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "Before deactivation");
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate;
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
await grain.ThrowSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_GetValue()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
long key = await grain.GetKey();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain, but returned " + key);
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await_ViaOtherGrain()
{
try
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = this.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
await grain.ForwardCall(this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id));
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Constructor_Bad_Await()
{
try
{
int id = random.Next();
IBadConstructorTestGrain grain = this.GrainFactory.GetGrain<IBadConstructorTestGrain>(id);
await grain.DoSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (TimeoutException te)
{
Console.WriteLine("Received timeout: " + te);
throw; // Fail test
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Constructor");
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Constructor_CreateGrainReference()
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = this.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
string activation = await grain.DoSomething();
Assert.NotNull(activation);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task TaskAction_Deactivate()
{
int id = random.Next();
ITaskActionActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITaskActionActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation.ToString());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task DeactivateOnIdleWhileActivate()
{
int id = random.Next();
IDeactivatingWhileActivatingTestGrain grain = this.GrainFactory.GetGrain<IDeactivatingWhileActivatingTestGrain>(id);
try
{
string activation = await grain.DoSomething();
Assert.True(false, "Should have thrown.");
}
catch(InvalidOperationException exc)
{
this.Logger.Info("Thrown as expected:", exc);
Assert.True(
exc.Message.Contains("DeactivateOnIdle from within OnActivateAsync"),
"Did not get expected exception message returned: " + exc.Message);
}
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string forActivation,
string when = null)
{
await CheckNumActivateDeactivateCalls(
expectedActivateCalls,
expectedDeactivateCalls,
new string[] { forActivation },
when )
;
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string[] forActivations,
string when = null)
{
string[] activateCalls = await watcher.GetActivateCalls();
Assert.Equal(expectedActivateCalls, activateCalls.Length);
string[] deactivateCalls = await watcher.GetDeactivateCalls();
Assert.Equal(expectedDeactivateCalls, deactivateCalls.Length);
for (int i = 0; i < expectedActivateCalls; i++)
{
Assert.Equal(forActivations[i], activateCalls[i]);
}
for (int i = 0; i < expectedDeactivateCalls; i++)
{
Assert.Equal(forActivations[i], deactivateCalls[i]);
}
}
private static void AssertIsNotInvalidOperationException(Exception thrownException, string expectedMessageSubstring)
{
Console.WriteLine("Received exception: " + thrownException);
Exception e = thrownException.GetBaseException();
Console.WriteLine("Nested exception type: " + e.GetType().FullName);
Console.WriteLine("Nested exception message: " + e.Message);
Assert.IsAssignableFrom<Exception>(e);
Assert.False(e is InvalidOperationException);
Assert.True(e.Message.Contains(expectedMessageSubstring), "Did not get expected exception message returned: " + e.Message);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataTableMapping.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
[
System.ComponentModel.TypeConverterAttribute(typeof(System.Data.Common.DataTableMapping.DataTableMappingConverter))
]
public sealed class DataTableMapping : MarshalByRefObject, ITableMapping, ICloneable {
private DataTableMappingCollection parent;
private DataColumnMappingCollection _columnMappings;
private string _dataSetTableName;
private string _sourceTableName;
public DataTableMapping() {
}
public DataTableMapping(string sourceTable, string dataSetTable) {
SourceTable = sourceTable;
DataSetTable = dataSetTable;
}
public DataTableMapping(string sourceTable, string dataSetTable, DataColumnMapping[] columnMappings) {
SourceTable = sourceTable;
DataSetTable = dataSetTable;
if ((null != columnMappings) && (0 < columnMappings.Length)) {
ColumnMappings.AddRange(columnMappings);
}
}
// explict ITableMapping implementation
IColumnMappingCollection ITableMapping.ColumnMappings {
get { return ColumnMappings; }
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataTableMapping_ColumnMappings),
]
public DataColumnMappingCollection ColumnMappings {
get {
DataColumnMappingCollection columnMappings = _columnMappings;
if (null == columnMappings) {
columnMappings = new DataColumnMappingCollection();
_columnMappings = columnMappings;
}
return columnMappings;
}
}
[
DefaultValue(""),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataTableMapping_DataSetTable),
]
public string DataSetTable {
get {
string dataSetTableName = _dataSetTableName;
return ((null != dataSetTableName) ? dataSetTableName : ADP.StrEmpty);
}
set {
_dataSetTableName = value;
}
}
internal DataTableMappingCollection Parent {
get {
return parent;
}
set {
parent = value;
}
}
[
DefaultValue(""),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataTableMapping_SourceTable),
]
public string SourceTable {
get {
string sourceTableName = _sourceTableName;
return ((null != sourceTableName) ? sourceTableName : ADP.StrEmpty);
}
set {
if ((null != Parent) && (0 != ADP.SrcCompare(_sourceTableName, value))) {
Parent.ValidateSourceTable(-1, value);
}
_sourceTableName = value;
}
}
object ICloneable.Clone() {
DataTableMapping clone = new DataTableMapping(); // MDAC 81448
clone._dataSetTableName = _dataSetTableName;
clone._sourceTableName = _sourceTableName;
if ((null != _columnMappings) && (0 < ColumnMappings.Count)) {
DataColumnMappingCollection parameters = clone.ColumnMappings;
foreach(ICloneable parameter in ColumnMappings) {
parameters.Add(parameter.Clone());
}
}
return clone;
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
public DataColumn GetDataColumn(string sourceColumn, Type dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) {
return DataColumnMappingCollection.GetDataColumn(_columnMappings, sourceColumn, dataType, dataTable, mappingAction, schemaAction);
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
public DataColumnMapping GetColumnMappingBySchemaAction(string sourceColumn, MissingMappingAction mappingAction) {
return DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMappings, sourceColumn, mappingAction);
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
public DataTable GetDataTableBySchemaAction(DataSet dataSet, MissingSchemaAction schemaAction) {
if (null == dataSet) {
throw ADP.ArgumentNull("dataSet");
}
string dataSetTable = DataSetTable;
if (ADP.IsEmpty(dataSetTable)) {
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning) {
Debug.WriteLine("explicit filtering of SourceTable \"" + SourceTable + "\"");
}
#endif
return null;
}
DataTableCollection tables = dataSet.Tables;
int index = tables.IndexOf(dataSetTable);
if ((0 <= index) && (index < tables.Count)) {
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo) {
Debug.WriteLine("schema match on DataTable \"" + dataSetTable);
}
#endif
return tables[index];
}
switch (schemaAction) {
case MissingSchemaAction.Add:
case MissingSchemaAction.AddWithKey:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo) {
Debug.WriteLine("schema add of DataTable \"" + dataSetTable + "\"");
}
#endif
return new DataTable(dataSetTable);
case MissingSchemaAction.Ignore:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning) {
Debug.WriteLine("schema filter of DataTable \"" + dataSetTable + "\"");
}
#endif
return null;
case MissingSchemaAction.Error:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceError) {
Debug.WriteLine("schema error on DataTable \"" + dataSetTable + "\"");
}
#endif
throw ADP.MissingTableSchema(dataSetTable, SourceTable);
}
throw ADP.InvalidMissingSchemaAction(schemaAction);
}
public override String ToString() {
return SourceTable;
}
sealed internal class DataTableMappingConverter : System.ComponentModel.ExpandableObjectConverter {
// converter classes should have public ctor
public DataTableMappingConverter() {
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (typeof(InstanceDescriptor) == destinationType) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (null == destinationType) {
throw ADP.ArgumentNull("destinationType");
}
if ((typeof(InstanceDescriptor) == destinationType) && (value is DataTableMapping)) {
DataTableMapping mapping = (DataTableMapping)value;
DataColumnMapping[] columnMappings = new DataColumnMapping[mapping.ColumnMappings.Count];
mapping.ColumnMappings.CopyTo(columnMappings, 0);
object[] values = new object[] { mapping.SourceTable, mapping.DataSetTable, columnMappings};
Type[] types = new Type[] { typeof(string), typeof(string), typeof(DataColumnMapping[]) };
ConstructorInfo ctor = typeof(DataTableMapping).GetConstructor(types);
return new InstanceDescriptor(ctor, values);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.
// ***********************************************************************
#if !PORTABLE
using System;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using System.IO;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft .NET Compact Framework</summary>
NetCF,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>Silverlight</summary>
Silverlight,
/// <summary>MonoTouch</summary>
MonoTouch
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static RuntimeFramework currentFramework;
private RuntimeType runtime;
private Version frameworkVersion;
private Version clrVersion;
private string displayName;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
this.runtime = runtime;
this.frameworkVersion = runtime == RuntimeType.Mono && version.Major == 1
? new Version(1, 0)
: new Version(version.Major, version.Minor);
this.clrVersion = version;
if (version.Build < 0)
this.clrVersion = GetClrVersion(runtime, version);
this.displayName = GetDefaultDisplayName(runtime, version);
}
private static Version GetClrVersion(RuntimeType runtime, Version version)
{
switch (runtime)
{
case RuntimeType.Silverlight:
return version.Major >= 4
? new Version(4, 0, 60310)
: new Version(2, 0, 50727);
default:
switch (version.Major)
{
case 4:
return new Version(4, 0, 30319);
case 2:
case 3:
return new Version(2, 0, 50727);
case 1:
return version.Minor == 0 && runtime != RuntimeType.Mono
? new Version(1, 0, 3705)
: new Version(1, 1, 4322);
default:
return version;
}
}
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
#if SILVERLIGHT
currentFramework = new RuntimeFramework(
RuntimeType.Silverlight,
new Version(Environment.Version.Major, Environment.Version.Minor));
#else
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate, monotouch");
bool isMonoTouch = monoTouchType != null;
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMonoTouch
? RuntimeType.MonoTouch
: isMono
? RuntimeType.Mono
: Environment.OSVersion.Platform == PlatformID.WinCE
? RuntimeType.NetCF
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
}
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.clrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.displayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
#endif
}
return currentFramework;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime
{
get { return runtime; }
}
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion
{
get { return frameworkVersion; }
}
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion
{
get { return clrVersion; }
}
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.clrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName
{
get { return displayName; }
}
#if !NUNITLITE
private static RuntimeFramework[] availableFrameworks;
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
// TODO: Special handling for netcf
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
FrameworkList frameworks = new FrameworkList();
AppendDotNetFrameworks(frameworks);
AppendDefaultMonoFramework(frameworks);
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (this.Supports(framework))
return true;
return false;
}
}
#endif
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphentated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
#if !NUNITLITE
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
#endif
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return runtime.ToString().ToLower();
}
else
{
string vstring = frameworkVersion.ToString();
if (runtime == RuntimeType.Any)
return "v" + vstring;
else
return runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (this.Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& this.Runtime != target.Runtime)
return false;
if (this.AllowAnyVersion || target.AllowAnyVersion)
return true;
if (!VersionsMatch(this.ClrVersion, target.ClrVersion))
return false;
return Runtime == RuntimeType.Silverlight
? this.frameworkVersion.Major == target.FrameworkVersion.Major && this.frameworkVersion.Minor == target.FrameworkVersion.Minor
: this.FrameworkVersion.Major >= target.FrameworkVersion.Major && this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
foreach (string item in TypeHelper.GetEnumNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version.ToString();
else
return runtime.ToString() + " " + version.ToString();
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#if !NUNITLITE
private static void AppendMonoFrameworks(FrameworkList frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(FrameworkList frameworks)
{
// TODO: Find multiple installed Mono versions under Linux
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Use registry to find alternate versions
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key == null) return;
foreach (string version in key.GetSubKeyNames())
{
RegistryKey subKey = key.OpenSubKey(version);
string monoPrefix = subKey.GetValue("SdkInstallRoot") as string;
AppendMonoFramework(frameworks, monoPrefix, version);
}
}
else
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(FrameworkList frameworks)
{
string monoPrefix = null;
string version = null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key != null)
{
version = key.GetValue("DefaultCLR") as string;
if (version != null && version != "")
{
key = key.OpenSubKey(version);
if (key != null)
monoPrefix = key.GetValue("SdkInstallRoot") as string;
}
}
}
else // Assuming we're currently running Mono - change if more runtimes are added
{
string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
}
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(FrameworkList frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.displayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.displayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.displayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
}
}
private static void AppendDotNetFrameworks(FrameworkList frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy");
if (key != null)
{
foreach (string name in key.GetSubKeyNames())
{
if (name.StartsWith("v"))
{
RegistryKey key2 = key.OpenSubKey(name);
foreach (string build in key2.GetValueNames())
frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version(name.Substring(1) + "." + build)));
}
}
}
}
}
#endif
#if CLR_2_0 || CLR_4_0
class FrameworkList : System.Collections.Generic.List<RuntimeFramework> { }
#else
class FrameworkList : System.Collections.ArrayList
{
public new RuntimeFramework[] ToArray()
{
return (RuntimeFramework[])base.ToArray(typeof(RuntimeFramework));
}
}
#endif
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using WaterOneFlow.Schema.v1;
using WaterOneFlowImpl;
//using Microsoft.Web.Services3;
//using Microsoft.Web.Services3.Addressing;
//using Microsoft.Web.Services3.Messaging;
using log4net;
namespace WaterOneFlow.odws
{
using WaterOneFlow.odm.v1_0;
public class ODService : IDisposable
{
private Cache appCache;
private HttpContext appContext;
private VariablesDataset vds;
/* This is now done in the global.asax file
// this got cached, which cause the name to be localhost
*/
private string serviceUrl;
private string serviceName;
private static readonly ILog log = LogManager.GetLogger(typeof(ODService));
private static readonly ILog queryLog = LogManager.GetLogger("QueryLog");
private static readonly Logging queryLog2 = new Logging();
public ODService(HttpContext aContext)
{
log.Debug("Starting " + System.Configuration.ConfigurationManager.AppSettings["network"]);
appContext = aContext;
// This is now done in the global.asax file
// this got cached, which cause the name to be localhost
serviceName = ConfigurationManager.AppSettings["GetValuesName"];
Boolean odValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]);
if (odValues)
{
string Port = aContext.Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
string Protocol = aContext.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
// *** Figure out the base Url which points at the application's root
serviceUrl = Protocol + aContext.Request.ServerVariables["SERVER_NAME"] +
Port +
aContext.Request.ApplicationPath
+ "/" + ConfigurationManager.AppSettings["asmxPage"];
}
else
{
serviceUrl = ConfigurationManager.AppSettings["externalGetValuesService"];
}
}
#region Site Information
public SiteInfoResponseType GetSiteInfo(string locationParameter)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
queryLog2.LogStart(Logging.Methods.GetSiteInfo, locationParameter,
appContext.Request.UserHostName);
locationParam lp = null;
try
{
lp = new locationParam(locationParameter);
if (lp.isGeometry)
{
String error = "Location by Geometry not accepted: " + locationParameter;
log.Debug(error);
throw new WaterOneFlowException(error);
}
}
catch (WaterOneFlowException we)
{
//waterLog.WriteEntry("Bad SiteID:" + siteId, EventLogEntryType.Information);
log.Error(we.Message);
throw;
}
catch (Exception e)
{
// waterLog.WriteEntry("Uncaught exception:" + e.Message, EventLogEntryType.Error);
String error =
"Sorry. Your submitted site ID for this getSiteInfo request caused an problem that we failed to catch programmatically: " +
e.Message;
log.Error(error);
throw new WaterOneFlowException(error);
}
GetSiteInfoOD getSiteInfo = new GetSiteInfoOD();
SiteInfoResponseType resp = getSiteInfo.GetSiteInfo(lp);
// add service location using the app context
// for ODM, we one only seriesCatalog
// String serviceName = (String) appContext.Session["serviceName"];
// String serviceUrl = (String) appContext.Session["serviceUrl"];
if (resp.site[0].seriesCatalog.Length > 0)
{
resp.site[0].seriesCatalog[0].menuGroupName = serviceName;
resp.site[0].seriesCatalog[0].serviceWsdl = serviceUrl;
}
queryLog2.LogEnd(Logging.Methods.GetSiteInfo,
locationParameter,
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
public SiteInfoResponseType GetSites(string[] locationIDs)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
GetSitesOD obj = new GetSitesOD();
string location = null;
if (locationIDs != null)
{
location = locationIDs.ToString();
}
queryLog2.LogStart(Logging.Methods.GetSites, location,
appContext.Request.UserHostName);
SiteInfoResponseType resp = obj.GetSites(locationIDs);
queryLog2.LogEnd(Logging.Methods.GetSites,
locationIDs.ToString(),
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
#endregion
#region variable
public VariablesResponseType GetVariableInfo(String VariableParameter)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
GetVariablesOD obj = new GetVariablesOD();
//queryLog.InfoFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
// System.Configuration.ConfigurationManager.AppSettings["network"], // network
// "GetVariableInfo", // method
// null, //locaiton
// VariableParameter, //variable
// null, // startdate
// null, //enddate
// String.Empty, // processing time
// String.Empty // count
// );
queryLog2.LogStart(Logging.Methods.GetVariables, VariableParameter,
appContext.Request.UserHostName);
VariablesResponseType resp = obj.GetVariableInfo(VariableParameter);
queryLog2.LogEnd(Logging.Methods.GetVariables,
VariableParameter,
timer.ElapsedMilliseconds.ToString(),
resp.variables.Length.ToString(),
appContext.Request.UserHostName);
// queryLog.InfoFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
//System.Configuration.ConfigurationManager.AppSettings["network"], // network
//"GetValues", // method
//null, //locaiton
//VariableParameter, //variable
//null, // startdate
//null, //enddate
//timer.ElapsedMilliseconds, // processing time
//resp.variables.Length // count
//);
return resp;
}
#endregion
#region values
public TimeSeriesResponseType GetValues(string SiteNumber,
string Variable,
string StartDate,
string EndDate)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
GetValuesOD obj = new GetValuesOD();
queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
StartDate, //enddate
appContext.Request.UserHostName
);
TimeSeriesResponseType resp = obj.getValues(SiteNumber, Variable, StartDate, EndDate);
queryLog2.LogValuesEnd(Logging.Methods.GetValues,
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
StartDate, //enddate
timer.ElapsedMilliseconds, // processing time
resp.timeSeries.values.value.Length, // count
appContext.Request.UserHostName
);
return resp;
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposeOf)
{
// waterLog.Dispose();
}
#endregion
}
}
| |
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using ClientDependency.Core;
using umbraco.cms.businesslogic;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.propertytype;
namespace umbraco.controls.GenericProperties
{
/// <summary>
/// Summary description for GenericProperty.
/// </summary>
[ClientDependency(ClientDependencyType.Css, "GenericProperty/genericproperty.css", "UmbracoClient")]
[ClientDependency(ClientDependencyType.Javascript, "GenericProperty/genericproperty.js", "UmbracoClient")]
public partial class GenericProperty : System.Web.UI.UserControl
{
/// <summary>
/// Constructor
/// </summary>
public GenericProperty()
{
FullId = "";
AllowPropertyEdit = true;
}
private cms.businesslogic.datatype.DataTypeDefinition[] _dataTypeDefinitions;
private int _tabId = 0;
public event EventHandler Delete;
/// <summary>
/// Defines whether the property can be edited in the UI
/// </summary>
public bool AllowPropertyEdit { get; set; }
public cms.businesslogic.datatype.DataTypeDefinition[] DataTypeDefinitions
{
set { _dataTypeDefinitions = value; }
}
public int TabId
{
set { _tabId = value; }
}
public PropertyType PropertyType { get; set; }
public ContentType.TabI[] Tabs { get; set; }
public string Name
{
get { return tbName.Text; }
}
public string Alias
{
get {return tbAlias.Text;} // FIXME so we blindly trust the UI for safe aliases?!
}
public string Description
{
get {return tbDescription.Text;}
}
public string Validation
{
get {return tbValidation.Text;}
}
public bool Mandatory
{
get {return checkMandatory.Checked;}
}
public int Tab
{
get {return int.Parse(ddlTab.SelectedValue);}
}
public string FullId { get; set; }
public int Id { get; set; }
public int Type
{
get {return int.Parse(ddlTypes.SelectedValue);}
}
public void Clear()
{
tbName.Text = "";
tbAlias.Text = "";
tbValidation.Text = "";
tbDescription.Text = "";
ddlTab.SelectedIndex = 0;
SetDefaultDocumentTypeProperty();
checkMandatory.Checked = false;
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
UpdateInterface();
}
}
//SD: this is temporary in v4, in v6 we have a proper user control hierarchy
//containing this property.
//this is required due to this issue: http://issues.umbraco.org/issue/u4-493
//because we need to execute some code in async but due to the localization
//framework requiring an httpcontext.current, it will not work.
//http://issues.umbraco.org/issue/u4-2143
//so, we are going to make a property here and ensure that the basepage has
//resolved the user before we execute the async task so that in this method
//our calls to ui.text will include the current user and not rely on the
//httpcontext.current. This also makes it perform better:
// http://issues.umbraco.org/issue/U4-2142
private User CurrentUser
{
get { return ((BasePage) Page).getUser(); }
}
public void UpdateInterface()
{
// Name and alias
if (PropertyType != null)
{
Id = PropertyType.Id;
//form.Attributes.Add("style", "display: none;");
tbName.Text = PropertyType.GetRawName();
tbAlias.Text = PropertyType.Alias;
FullHeader.Text = PropertyType.GetRawName() + " (" + PropertyType.Alias + "), Type: " + PropertyType.DataTypeDefinition.Text;;
Header.Text = PropertyType.GetRawName();
DeleteButton.CssClass = "delete-button";
DeleteButton.Attributes.Add("onclick", "return confirm('" + ui.Text("areyousure", CurrentUser) + "');");
DeleteButton2.CssClass = "delete-button";
DeleteButton2.Attributes.Add("onclick", "return confirm('" + ui.Text("areyousure", CurrentUser) + "');");
DeleteButton.Visible = AllowPropertyEdit;
DeleteButton2.Visible = AllowPropertyEdit;
tbAlias.Visible = AllowPropertyEdit;
PropertyPanel5.Visible = AllowPropertyEdit;
PropertyPanel6.Visible = AllowPropertyEdit;
PropertyPanel3.Visible = AllowPropertyEdit;
}
else
{
// Add new header
FullHeader.Text = "Click here to add a new property";
Header.Text = "Create new property";
// Hide image button
DeleteButton.Visible = false;
DeleteButton2.Visible = false;
}
validationLink.NavigateUrl = "#";
validationLink.Attributes["onclick"] = ClientTools.Scripts.OpenModalWindow("dialogs/regexWs.aspx?target=" + tbValidation.ClientID, "Search for regular expression", 600, 500) + ";return false;";
// Data type definitions
if (_dataTypeDefinitions != null)
{
ddlTypes.Items.Clear();
var itemSelected = false;
foreach(cms.businesslogic.datatype.DataTypeDefinition dt in _dataTypeDefinitions)
{
var li = new ListItem(dt.Text, dt.Id.ToString());
if ((PropertyType != null && PropertyType.DataTypeDefinition.Id == dt.Id))
{
li.Selected = true;
itemSelected = true;
}
ddlTypes.Items.Add(li);
}
// If item not selected from previous edit or load, set to default according to settings
if (!itemSelected)
{
SetDefaultDocumentTypeProperty();
}
}
// tabs
if (Tabs != null)
{
ddlTab.Items.Clear();
for (int i=0;i<Tabs.Length;i++)
{
ListItem li = new ListItem(Tabs[i].Caption, Tabs[i].Id.ToString());
if (Tabs[i].Id == _tabId)
li.Selected = true;
ddlTab.Items.Add(li);
}
}
ListItem liGeneral = new ListItem("Generic Properties", "0");
if (_tabId == 0)
liGeneral.Selected = true;
ddlTab.Items.Add(liGeneral);
// mandatory
if (PropertyType != null && PropertyType.Mandatory)
checkMandatory.Checked = true;
// validation
if (PropertyType != null && string.IsNullOrEmpty(PropertyType.ValidationRegExp) == false)
tbValidation.Text = PropertyType.ValidationRegExp;
// description
if (PropertyType != null && PropertyType.Description != "")
tbDescription.Text = PropertyType.GetRawDescription();
}
private void SetDefaultDocumentTypeProperty()
{
var itemToSelect = ddlTypes.Items.Cast<ListItem>()
.FirstOrDefault(item => item.Text.ToLowerInvariant() == UmbracoConfig.For.UmbracoSettings().Content.DefaultDocumentTypeProperty.ToLowerInvariant());
if (itemToSelect != null)
{
itemToSelect.Selected = true;
}
else
{
ddlTypes.SelectedIndex = -1;
}
}
protected void defaultDeleteHandler(object sender, EventArgs e)
{
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
DeleteButton.Click += DeleteButton_Click;
DeleteButton2.Click += DeleteButton2_Click;
Delete += defaultDeleteHandler;
// [ClientDependency(ClientDependencyType.Javascript, "js/UmbracoCasingRules.aspx", "UmbracoRoot")]
var loader = ClientDependency.Core.Controls.ClientDependencyLoader.GetInstance(new HttpContextWrapper(Context));
var helper = new UrlHelper(new RequestContext(new HttpContextWrapper(Context), new RouteData()));
loader.RegisterDependency(helper.GetCoreStringsControllerPath() + "ServicesJavaScript", ClientDependencyType.Javascript);
}
void DeleteButton2_Click(object sender, EventArgs e)
{
Delete(this,new EventArgs());
}
void DeleteButton_Click(object sender, EventArgs e)
{
Delete(this,new EventArgs());
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Scripting.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for C# scripts.
/// </summary>
internal class ScriptBuilder
{
/// <summary>
/// Unique prefix for generated uncollectible assemblies.
/// </summary>
/// <remarks>
/// The full names of uncollectible assemblies generated by this context must be unique,
/// so that we can resolve references among them. Note that CLR can load two different assemblies of the very
/// identity into the same load context.
///
/// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number).
/// If we allowed the compiled code to add references that match this exact pattern it migth happen that
/// the user supplied reference identity conflicts with the identity we use for our generated assemblies and
/// the AppDomain assembly resolve event won't be able to correctly identify the target assembly.
///
/// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references.
/// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name").
/// </remarks>
private static readonly string s_globalAssemblyNamePrefix;
private static int s_engineIdDispenser;
private int _submissionIdDispenser = -1;
private readonly string _assemblyNamePrefix;
// dynamic code storage
//
// TODO (tomat): Dynamic assembly allocation strategy. A dynamic assembly is a unit of
// collection. We need to find a balance between creating a new assembly per execution
// (potentially shorter code lifetime) and reusing a single assembly for all executions
// (less overhead per execution).
private readonly UncollectibleCodeManager _uncollectibleCodeManager;
private readonly CollectibleCodeManager _collectibleCodeManager;
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
#region Testing and Debugging
private const string CollectibleModuleFileName = "CollectibleModule.dll";
private const string UncollectibleModuleFileName = "UncollectibleModule.dll";
// Setting this flag will add DebuggableAttribute on the emitted code that disables JIT optimizations.
// With optimizations disabled JIT will verify the method before it compiles it so we can easily
// discover incorrect code.
internal static bool DisableJitOptimizations;
#if DEBUG
// Flags to make debugging of emitted code easier.
// Enables saving the dynamic assemblies to disk. Must be called before any code is compiled.
internal static bool EnableAssemblySave;
// Helps debugging issues in emitted code. If set the next call to Execute/Compile will save the dynamic assemblies to disk.
internal static bool SaveCompiledAssemblies;
#endif
#endregion
static ScriptBuilder()
{
s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString() + "-";
}
public ScriptBuilder(AssemblyLoader assemblyLoader = null)
{
if (assemblyLoader == null)
{
assemblyLoader = new InteractiveAssemblyLoader();
}
_assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
_collectibleCodeManager = new CollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
_uncollectibleCodeManager = new UncollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
}
public AssemblyLoader AssemblyLoader
{
get { return _collectibleCodeManager.assemblyLoader; }
}
internal string AssemblyNamePrefix
{
get { return _assemblyNamePrefix; }
}
internal static bool IsReservedAssemblyName(AssemblyIdentity identity)
{
return identity.Name.StartsWith(s_globalAssemblyNamePrefix, StringComparison.Ordinal);
}
public int GenerateSubmissionId(out string assemblyName, out string typeName)
{
int id = Interlocked.Increment(ref _submissionIdDispenser);
string idAsString = id.ToString();
assemblyName = _assemblyNamePrefix + idAsString;
typeName = "Submission#" + idAsString;
return id;
}
/// <summary>
/// Builds a delegate that will execute just this scripts code.
/// </summary>
public Func<object[], object> Build(
Script script,
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var compilation = script.GetCompilation();
var options = script.Options;
DiagnosticBag emitDiagnostics = DiagnosticBag.GetInstance();
byte[] compiledAssemblyImage;
MethodInfo entryPoint;
bool success = compilation.Emit(
GetOrCreateDynamicModule(options.IsCollectible),
assemblyLoader: GetAssemblyLoader(options.IsCollectible),
assemblySymbolMapper: symbol => MapAssemblySymbol(symbol, options.IsCollectible),
recoverOnError: true,
diagnostics: emitDiagnostics,
cancellationToken: cancellationToken,
entryPoint: out entryPoint,
compiledAssemblyImage: out compiledAssemblyImage
);
if (diagnostics != null)
{
diagnostics.AddRange(emitDiagnostics);
}
bool hadEmitErrors = emitDiagnostics.HasAnyErrors();
emitDiagnostics.Free();
// emit can fail due to compilation errors or because there is nothing to emit:
if (!success)
{
return null;
}
Debug.Assert(entryPoint != null);
if (compiledAssemblyImage != null)
{
// Ref.Emit wasn't able to emit the assembly
_uncollectibleCodeManager.AddFallBackAssembly(entryPoint.DeclaringType.Assembly);
}
#if DEBUG
if (SaveCompiledAssemblies)
{
_uncollectibleCodeManager.Save(UncollectibleModuleFileName);
_collectibleCodeManager.Save(CollectibleModuleFileName);
}
#endif
return (Func<object[], object>)Delegate.CreateDelegate(typeof(Func<object[], object>), entryPoint);
}
internal ModuleBuilder GetOrCreateDynamicModule(bool collectible)
{
if (collectible)
{
return _collectibleCodeManager.GetOrCreateDynamicModule();
}
else
{
return _uncollectibleCodeManager.GetOrCreateDynamicModule();
}
}
private static ModuleBuilder CreateDynamicModule(AssemblyBuilderAccess access, AssemblyIdentity name, string fileName)
{
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name.ToAssemblyName(), access);
if (DisableJitOptimizations)
{
assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(
typeof(DebuggableAttribute).GetConstructor(new[] { typeof(DebuggableAttribute.DebuggingModes) }),
new object[] { DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations }));
}
const string moduleName = "InteractiveModule";
if (access == AssemblyBuilderAccess.RunAndSave)
{
return assemblyBuilder.DefineDynamicModule(moduleName, fileName, emitSymbolInfo: false);
}
else
{
return assemblyBuilder.DefineDynamicModule(moduleName, emitSymbolInfo: false);
}
}
/// <summary>
/// Maps given assembly symbol to an assembly ref.
/// </summary>
/// <remarks>
/// The compiler represents every submission by a compilation instance for which it creates a distinct source assembly symbol.
/// However multiple submissions might compile into a single dynamic assembly and so we need to map the corresponding assembly symbols to
/// the name of the dynamic assembly.
/// </remarks>
internal AssemblyIdentity MapAssemblySymbol(IAssemblySymbol symbol, bool collectible)
{
if (symbol.IsInteractive)
{
if (collectible)
{
// collectible assemblies can't reference other generated assemblies
throw ExceptionUtilities.Unreachable;
}
else if (!_uncollectibleCodeManager.ContainsAssembly(symbol.Identity.Name))
{
// uncollectible assemblies can reference uncollectible dynamic or uncollectible CCI generated assemblies:
return _uncollectibleCodeManager.dynamicAssemblyName;
}
}
return symbol.Identity;
}
internal AssemblyLoader GetAssemblyLoader(bool collectible)
{
return collectible ? (AssemblyLoader)_collectibleCodeManager : _uncollectibleCodeManager;
}
// TODO (tomat): the code managers can be improved - common base class, less locking, etc.
private sealed class CollectibleCodeManager : AssemblyLoader
{
internal readonly AssemblyLoader assemblyLoader;
private readonly AssemblyIdentity _dynamicAssemblyName;
/// <summary>
/// lock(_gate) on access.
/// </summary>
private readonly object _gate = new object();
/// <summary>
/// lock(_gate) on access.
/// </summary>
internal ModuleBuilder dynamicModule;
public CollectibleCodeManager(AssemblyLoader assemblyLoader, string assemblyNamePrefix)
{
this.assemblyLoader = assemblyLoader;
_dynamicAssemblyName = new AssemblyIdentity(name: assemblyNamePrefix + "CD");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
}
internal ModuleBuilder GetOrCreateDynamicModule()
{
if (dynamicModule == null)
{
lock (_gate)
{
if (dynamicModule == null)
{
dynamicModule = CreateDynamicModule(
#if DEBUG
EnableAssemblySave ? AssemblyBuilderAccess.RunAndSave :
#endif
AssemblyBuilderAccess.RunAndCollect, _dynamicAssemblyName, CollectibleModuleFileName);
}
}
}
return dynamicModule;
}
internal void Save(string fileName)
{
if (dynamicModule != null)
{
((AssemblyBuilder)dynamicModule.Assembly).Save(fileName);
}
}
private Assembly Resolve(object sender, ResolveEventArgs args)
{
if (args.Name != _dynamicAssemblyName.GetDisplayName())
{
return null;
}
lock (_gate)
{
return (dynamicModule != null) ? dynamicModule.Assembly : null;
}
}
public override Assembly Load(AssemblyIdentity identity, string location = null)
{
if (dynamicModule != null && identity.Name == _dynamicAssemblyName.Name)
{
return dynamicModule.Assembly;
}
return assemblyLoader.Load(identity, location);
}
}
/// <summary>
/// Manages uncollectible assemblies and resolves assembly references baked into CCI generated metadata.
/// The resolution is triggered by the CLR Type Loader.
/// </summary>
private sealed class UncollectibleCodeManager : AssemblyLoader
{
private readonly AssemblyLoader _assemblyLoader;
private readonly string _assemblyNamePrefix;
internal readonly AssemblyIdentity dynamicAssemblyName;
// lock(_gate) on access
private ModuleBuilder _dynamicModule; // primary uncollectible assembly
private HashSet<Assembly> _fallBackAssemblies; // additional uncollectible assemblies created due to a Ref.Emit falling back to CCI
private Dictionary<string, Assembly> _mapping; // { simple name -> fall-back assembly }
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
internal UncollectibleCodeManager(AssemblyLoader assemblyLoader, string assemblyNamePrefix)
{
_assemblyLoader = assemblyLoader;
_assemblyNamePrefix = assemblyNamePrefix;
this.dynamicAssemblyName = new AssemblyIdentity(name: assemblyNamePrefix + "UD");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
}
internal ModuleBuilder GetOrCreateDynamicModule()
{
if (_dynamicModule == null)
{
lock (_gate)
{
if (_dynamicModule == null)
{
_dynamicModule = CreateDynamicModule(
#if DEBUG
EnableAssemblySave ? AssemblyBuilderAccess.RunAndSave :
#endif
AssemblyBuilderAccess.Run, dynamicAssemblyName, UncollectibleModuleFileName);
}
}
}
return _dynamicModule;
}
internal void Save(string fileName)
{
if (_dynamicModule != null)
{
((AssemblyBuilder)_dynamicModule.Assembly).Save(fileName);
}
}
internal void AddFallBackAssembly(Assembly assembly)
{
lock (_gate)
{
if (_fallBackAssemblies == null)
{
Debug.Assert(_mapping == null);
_fallBackAssemblies = new HashSet<Assembly>();
_mapping = new Dictionary<string, Assembly>();
}
_fallBackAssemblies.Add(assembly);
_mapping[assembly.GetName().Name] = assembly;
}
}
internal bool ContainsAssembly(string simpleName)
{
if (_mapping == null)
{
return false;
}
lock (_gate)
{
return _mapping.ContainsKey(simpleName);
}
}
private Assembly Resolve(object sender, ResolveEventArgs args)
{
if (!args.Name.StartsWith(_assemblyNamePrefix, StringComparison.Ordinal))
{
return null;
}
lock (_gate)
{
if (args.Name == dynamicAssemblyName.GetDisplayName())
{
return _dynamicModule != null ? _dynamicModule.Assembly : null;
}
if (_dynamicModule != null && _dynamicModule.Assembly == args.RequestingAssembly ||
_fallBackAssemblies != null && _fallBackAssemblies.Contains(args.RequestingAssembly))
{
int comma = args.Name.IndexOf(',');
return ResolveNoLock(args.Name.Substring(0, (comma != -1) ? comma : args.Name.Length));
}
}
return null;
}
private Assembly Resolve(string simpleName)
{
lock (_gate)
{
return ResolveNoLock(simpleName);
}
}
private Assembly ResolveNoLock(string simpleName)
{
if (_dynamicModule != null && simpleName == dynamicAssemblyName.Name)
{
return _dynamicModule.Assembly;
}
Assembly assembly;
if (_mapping != null && _mapping.TryGetValue(simpleName, out assembly))
{
return assembly;
}
return null;
}
public override Assembly Load(AssemblyIdentity identity, string location = null)
{
return Resolve(identity.Name) ?? _assemblyLoader.Load(identity, location);
}
}
}
}
| |
/*
* Copyright (c) 2015, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 BadgerJaus.Util;
namespace BadgerJaus.Messages.LocalPoseSensor
{
public class ReportLocalPose : QueryLocalPose
{
JausUnsignedInteger x;
JausUnsignedInteger y;
JausUnsignedInteger z;
JausUnsignedInteger positionRMS;
JausUnsignedShort roll;
JausUnsignedShort pitch;
JausUnsignedShort yaw;
JausUnsignedShort attitudeRMS;
JausTimeStamp timeStamp;
public const int X_BIT = 0;
public const int Y_BIT = 1;
public const int Z_BIT = 2;
public const int P_RMS = 3;
public const int ROLL_BIT = 4;
public const int PITCH_BIT = 5;
public const int YAW_BIT = 6;
public const int A_RMS = 7;
public const int TS_BIT = 8;
private const int POSE_MIN = -100000;
private const int POSE_MAX = 100000;
private const double ORIENT_MIN = -System.Math.PI;
private const double ORIENT_MAX = System.Math.PI;
protected override int CommandCode
{
get { return JausCommandCode.REPORT_LOCAL_POSE; }
}
protected override void InitFieldData()
{
base.InitFieldData();
x = new JausUnsignedInteger();
y = new JausUnsignedInteger();
z = new JausUnsignedInteger();
positionRMS = new JausUnsignedInteger();
roll = new JausUnsignedShort();
pitch = new JausUnsignedShort();
yaw = new JausUnsignedShort();
attitudeRMS = new JausUnsignedShort();
timeStamp = new JausTimeStamp();
}
public void SetX(double xValue)
{
x.SetValueFromDouble(xValue, POSE_MIN, POSE_MAX);
presence.setBit(X_BIT);
}
public void SetY(double yValue)
{
y.SetValueFromDouble(yValue, POSE_MIN, POSE_MAX);
presence.setBit(Y_BIT);
}
public void SetZ(double zValue)
{
z.SetValueFromDouble(zValue, POSE_MIN, POSE_MAX);
presence.setBit(Z_BIT);
}
public void SetRoll(double rollValue)
{
roll.SetValueFromDouble(rollValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(ROLL_BIT);
}
public void SetPitch(double pitchValue)
{
pitch.SetValueFromDouble(pitchValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(PITCH_BIT);
}
public void SetYaw(double yawValue)
{
yaw.SetValueFromDouble(yawValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(YAW_BIT);
}
public void SetTimestamp(int timeValue)
{
//timeStamp.setValue(timeValue);
presence.setBit(TS_BIT);
}
public double GetX()
{
return x.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetY()
{
return y.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetZ()
{
return z.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetRoll()
{
return roll.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public double GetPitch()
{
return pitch.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public double GetYaw()
{
return yaw.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public override int GetPayloadSize()
{
int payloadSize = 0;
payloadSize += base.GetPayloadSize();
if (presence.IsBitSet(X_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(Y_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(Z_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(YAW_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(TS_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
return payloadSize;
}
protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
{
bool status;
status = base.PayloadToJausBuffer(buffer, index, out indexOffset);
if (!status)
return false;
if (presence.IsBitSet(X_BIT))
{
if (!x.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(Y_BIT))
{
if (!y.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(Z_BIT))
{
if (!z.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(YAW_BIT))
{
if (!y.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(TS_BIT))
{
if (!timeStamp.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
return true;
}
protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
{
base.SetPayloadFromJausBuffer(buffer, index, out indexOffset);
if (presence.IsBitSet(X_BIT))
{
x.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(Y_BIT))
{
y.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(Z_BIT))
{
z.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(YAW_BIT))
{
yaw.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(TS_BIT))
{
timeStamp.Deserialize(buffer, indexOffset, out indexOffset);
}
return true;
}
public void SetToCurrentTime()
{
presence.setBit(TS_BIT);
timeStamp.setToCurrentTime();
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="D09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class D09_Region_Child : BusinessBase<D09_Region_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D09_Region_Child"/> object.</returns>
internal static D09_Region_Child NewD09_Region_Child()
{
return DataPortal.CreateChild<D09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="D09_Region_Child"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID1">The Region_ID1 parameter of the D09_Region_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="D09_Region_Child"/> object.</returns>
internal static D09_Region_Child GetD09_Region_Child(int region_ID1)
{
return DataPortal.FetchChild<D09_Region_Child>(region_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D09_Region_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D09_Region_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D09_Region_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D09_Region_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID1">The Region ID1.</param>
protected void Child_Fetch(int region_ID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD09_Region_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID1", region_ID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, region_ID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D09_Region_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD09_Region_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D08_Region parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD09_Region_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD09_Region_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID1", parent.Region_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.Runtime.InteropServices;
namespace MonoMac.OpenGL
{
/// <summary>Represents a 2D vector using two single-precision floating-point numbers.</summary>
/// <remarks>
/// The Vector2 structure is suitable for interoperation with unmanaged code requiring two consecutive floats.
/// </remarks>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
#region Fields
/// <summary>
/// The X component of the Vector2.
/// </summary>
public float X;
/// <summary>
/// The Y component of the Vector2.
/// </summary>
public float Y;
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector2(float value)
{
X = value;
Y = value;
}
/// <summary>
/// Constructs a new Vector2.
/// </summary>
/// <param name="x">The x coordinate of the net Vector2.</param>
/// <param name="y">The y coordinate of the net Vector2.</param>
public Vector2(float x, float y)
{
X = x;
Y = y;
}
/// <summary>
/// Constructs a new Vector2 from the given Vector2.
/// </summary>
/// <param name="v">The Vector2 to copy components from.</param>
[Obsolete]
public Vector2(Vector2 v)
{
X = v.X;
Y = v.Y;
}
/// <summary>
/// Constructs a new Vector2 from the given Vector3.
/// </summary>
/// <param name="v">The Vector3 to copy components from. Z is discarded.</param>
[Obsolete]
public Vector2(Vector3 v)
{
X = v.X;
Y = v.Y;
}
/// <summary>
/// Constructs a new Vector2 from the given Vector4.
/// </summary>
/// <param name="v">The Vector4 to copy components from. Z and W are discarded.</param>
[Obsolete]
public Vector2(Vector4 v)
{
X = v.X;
Y = v.Y;
}
#endregion
#region Public Members
#region Instance
#region public void Add()
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[Obsolete("Use static Add() method instead.")]
public void Add(Vector2 right)
{
this.X += right.X;
this.Y += right.Y;
}
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
[Obsolete("Use static Add() method instead.")]
public void Add(ref Vector2 right)
{
this.X += right.X;
this.Y += right.Y;
}
#endregion public void Add()
#region public void Sub()
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[Obsolete("Use static Subtract() method instead.")]
public void Sub(Vector2 right)
{
this.X -= right.X;
this.Y -= right.Y;
}
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
[Obsolete("Use static Subtract() method instead.")]
public void Sub(ref Vector2 right)
{
this.X -= right.X;
this.Y -= right.Y;
}
#endregion public void Sub()
#region public void Mult()
/// <summary>Multiply this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Mult(float f)
{
this.X *= f;
this.Y *= f;
}
#endregion public void Mult()
#region public void Div()
/// <summary>Divide this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
[Obsolete("Use static Divide() method instead.")]
public void Div(float f)
{
float mult = 1.0f / f;
this.X *= mult;
this.Y *= mult;
}
#endregion public void Div()
#region public float Length
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
public float Length
{
get
{
return (float)System.Math.Sqrt(X * X + Y * Y);
}
}
#endregion
#region public float LengthFast
/// <summary>
/// Gets an approximation of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property uses an approximation of the square root function to calculate vector magnitude, with
/// an upper error bound of 0.001.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthSquared"/>
public float LengthFast
{
get
{
return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y);
}
}
#endregion
#region public float LengthSquared
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthFast"/>
public float LengthSquared
{
get
{
return X * X + Y * Y;
}
}
#endregion
#region public Vector2 PerpendicularRight
/// <summary>
/// Gets the perpendicular vector on the right side of this vector.
/// </summary>
public Vector2 PerpendicularRight
{
get
{
return new Vector2(Y, -X);
}
}
#endregion
#region public Vector2 PerpendicularLeft
/// <summary>
/// Gets the perpendicular vector on the left side of this vector.
/// </summary>
public Vector2 PerpendicularLeft
{
get
{
return new Vector2(-Y, X);
}
}
#endregion
#region public void Normalize()
/// <summary>
/// Scales the Vector2 to unit length.
/// </summary>
public void Normalize()
{
float scale = 1.0f / this.Length;
X *= scale;
Y *= scale;
}
#endregion
#region public void NormalizeFast()
/// <summary>
/// Scales the Vector2 to approximately unit length.
/// </summary>
public void NormalizeFast()
{
float scale = MathHelper.InverseSqrtFast(X * X + Y * Y);
X *= scale;
Y *= scale;
}
#endregion
#region public void Scale()
/// <summary>
/// Scales the current Vector2 by the given amounts.
/// </summary>
/// <param name="sx">The scale of the X component.</param>
/// <param name="sy">The scale of the Y component.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Scale(float sx, float sy)
{
this.X = X * sx;
this.Y = Y * sy;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Scale(Vector2 scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[CLSCompliant(false)]
[Obsolete("Use static Multiply() method instead.")]
public void Scale(ref Vector2 scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
}
#endregion public void Scale()
#endregion
#region Static
#region Fields
/// <summary>
/// Defines a unit-length Vector2 that points towards the X-axis.
/// </summary>
public static readonly Vector2 UnitX = new Vector2(1, 0);
/// <summary>
/// Defines a unit-length Vector2 that points towards the Y-axis.
/// </summary>
public static readonly Vector2 UnitY = new Vector2(0, 1);
/// <summary>
/// Defines a zero-length Vector2.
/// </summary>
public static readonly Vector2 Zero = new Vector2(0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector2 One = new Vector2(1, 1);
/// <summary>
/// Defines the size of the Vector2 struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector2());
#endregion
#region Obsolete
#region Sub
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
[Obsolete("Use static Subtract() method instead.")]
public static Vector2 Sub(Vector2 a, Vector2 b)
{
a.X -= b.X;
a.Y -= b.Y;
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
[Obsolete("Use static Subtract() method instead.")]
public static void Sub(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result.X = a.X - b.X;
result.Y = a.Y - b.Y;
}
#endregion
#region Mult
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the multiplication</returns>
[Obsolete("Use static Multiply() method instead.")]
public static Vector2 Mult(Vector2 a, float f)
{
a.X *= f;
a.Y *= f;
return a;
}
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the multiplication</param>
[Obsolete("Use static Multiply() method instead.")]
public static void Mult(ref Vector2 a, float f, out Vector2 result)
{
result.X = a.X * f;
result.Y = a.Y * f;
}
#endregion
#region Div
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the division</returns>
[Obsolete("Use static Divide() method instead.")]
public static Vector2 Div(Vector2 a, float f)
{
float mult = 1.0f / f;
a.X *= mult;
a.Y *= mult;
return a;
}
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the division</param>
[Obsolete("Use static Divide() method instead.")]
public static void Div(ref Vector2 a, float f, out Vector2 result)
{
float mult = 1.0f / f;
result.X = a.X * mult;
result.Y = a.Y * mult;
}
#endregion
#endregion
#region Add
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <returns>Result of operation.</returns>
public static Vector2 Add(Vector2 a, Vector2 b)
{
Add(ref a, ref b, out a);
return a;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <param name="result">Result of operation.</param>
public static void Add(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result = new Vector2(a.X + b.X, a.Y + b.Y);
}
#endregion
#region Subtract
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector2 Subtract(Vector2 a, Vector2 b)
{
Subtract(ref a, ref b, out a);
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Subtract(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result = new Vector2(a.X - b.X, a.Y - b.Y);
}
#endregion
#region Multiply
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector2 Multiply(Vector2 vector, float scale)
{
Multiply(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector2 vector, float scale, out Vector2 result)
{
result = new Vector2(vector.X * scale, vector.Y * scale);
}
/// <summary>
/// Multiplies a vector by the components a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector2 Multiply(Vector2 vector, Vector2 scale)
{
Multiply(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector2 vector, ref Vector2 scale, out Vector2 result)
{
result = new Vector2(vector.X * scale.X, vector.Y * scale.Y);
}
#endregion
#region Divide
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector2 Divide(Vector2 vector, float scale)
{
Divide(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector2 vector, float scale, out Vector2 result)
{
Multiply(ref vector, 1 / scale, out result);
}
/// <summary>
/// Divides a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector2 Divide(Vector2 vector, Vector2 scale)
{
Divide(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Divide a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector2 vector, ref Vector2 scale, out Vector2 result)
{
result = new Vector2(vector.X / scale.X, vector.Y / scale.Y);
}
#endregion
#region ComponentMin
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector2 ComponentMin(Vector2 a, Vector2 b)
{
a.X = a.X < b.X ? a.X : b.X;
a.Y = a.Y < b.Y ? a.Y : b.Y;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void ComponentMin(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result.X = a.X < b.X ? a.X : b.X;
result.Y = a.Y < b.Y ? a.Y : b.Y;
}
#endregion
#region ComponentMax
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector2 ComponentMax(Vector2 a, Vector2 b)
{
a.X = a.X > b.X ? a.X : b.X;
a.Y = a.Y > b.Y ? a.Y : b.Y;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void ComponentMax(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result.X = a.X > b.X ? a.X : b.X;
result.Y = a.Y > b.Y ? a.Y : b.Y;
}
#endregion
#region Min
/// <summary>
/// Returns the Vector3 with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector2 Min(Vector2 left, Vector2 right)
{
return left.LengthSquared < right.LengthSquared ? left : right;
}
#endregion
#region Max
/// <summary>
/// Returns the Vector3 with the minimum magnitude
/// </summary>
/// <param name="left">Left operand</param>
/// <param name="right">Right operand</param>
/// <returns>The minimum Vector3</returns>
public static Vector2 Max(Vector2 left, Vector2 right)
{
return left.LengthSquared >= right.LengthSquared ? left : right;
}
#endregion
#region Clamp
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector2 Clamp(Vector2 vec, Vector2 min, Vector2 max)
{
vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector2 vec, ref Vector2 min, ref Vector2 max, out Vector2 result)
{
result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
}
#endregion
#region Normalize
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector2 Normalize(Vector2 vec)
{
float scale = 1.0f / vec.Length;
vec.X *= scale;
vec.Y *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector2 vec, out Vector2 result)
{
float scale = 1.0f / vec.Length;
result.X = vec.X * scale;
result.Y = vec.Y * scale;
}
#endregion
#region NormalizeFast
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector2 NormalizeFast(Vector2 vec)
{
float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y);
vec.X *= scale;
vec.Y *= scale;
return vec;
}
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void NormalizeFast(ref Vector2 vec, out Vector2 result)
{
float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y);
result.X = vec.X * scale;
result.Y = vec.Y * scale;
}
#endregion
#region Dot
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static float Dot(Vector2 left, Vector2 right)
{
return left.X * right.X + left.Y * right.Y;
}
/// <summary>
/// Calculate the dot (scalar) product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector2 left, ref Vector2 right, out float result)
{
result = left.X * right.X + left.Y * right.Y;
}
#endregion
#region Lerp
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector2 Lerp(Vector2 a, Vector2 b, float blend)
{
a.X = blend * (b.X - a.X) + a.X;
a.Y = blend * (b.Y - a.Y) + a.Y;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector2 a, ref Vector2 b, float blend, out Vector2 result)
{
result.X = blend * (b.X - a.X) + a.X;
result.Y = blend * (b.Y - a.Y) + a.Y;
}
#endregion
#region Barycentric
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector2 BaryCentric(Vector2 a, Vector2 b, Vector2 c, float u, float v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector2 a, ref Vector2 b, ref Vector2 c, float u, float v, out Vector2 result)
{
result = a; // copy
Vector2 temp = b; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, u, out temp);
Add(ref result, ref temp, out result);
temp = c; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, v, out temp);
Add(ref result, ref temp, out result);
}
#endregion
#region Transform
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <returns>The result of the operation.</returns>
public static Vector2 Transform(Vector2 vec, Quaternion quat)
{
Vector2 result;
Transform(ref vec, ref quat, out result);
return result;
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <param name="result">The result of the operation.</param>
public static void Transform(ref Vector2 vec, ref Quaternion quat, out Vector2 result)
{
Quaternion v = new Quaternion(vec.X, vec.Y, 0, 0), i, t;
Quaternion.Invert(ref quat, out i);
Quaternion.Multiply(ref quat, ref v, out t);
Quaternion.Multiply(ref t, ref i, out v);
result = new Vector2(v.X, v.Y);
}
#endregion
#endregion
#region Operators
/// <summary>
/// Adds the specified instances.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>Result of addition.</returns>
public static Vector2 operator +(Vector2 left, Vector2 right)
{
left.X += right.X;
left.Y += right.Y;
return left;
}
/// <summary>
/// Subtracts the specified instances.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>Result of subtraction.</returns>
public static Vector2 operator -(Vector2 left, Vector2 right)
{
left.X -= right.X;
left.Y -= right.Y;
return left;
}
/// <summary>
/// Negates the specified instance.
/// </summary>
/// <param name="vec">Operand.</param>
/// <returns>Result of negation.</returns>
public static Vector2 operator -(Vector2 vec)
{
vec.X = -vec.X;
vec.Y = -vec.Y;
return vec;
}
/// <summary>
/// Multiplies the specified instance by a scalar.
/// </summary>
/// <param name="vec">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of multiplication.</returns>
public static Vector2 operator *(Vector2 vec, float scale)
{
vec.X *= scale;
vec.Y *= scale;
return vec;
}
/// <summary>
/// Multiplies the specified instance by a scalar.
/// </summary>
/// <param name="scale">Left operand.</param>
/// <param name="vec">Right operand.</param>
/// <returns>Result of multiplication.</returns>
public static Vector2 operator *(float scale, Vector2 vec)
{
vec.X *= scale;
vec.Y *= scale;
return vec;
}
/// <summary>
/// Divides the specified instance by a scalar.
/// </summary>
/// <param name="vec">Left operand</param>
/// <param name="scale">Right operand</param>
/// <returns>Result of the division.</returns>
public static Vector2 operator /(Vector2 vec, float scale)
{
float mult = 1.0f / scale;
vec.X *= mult;
vec.Y *= mult;
return vec;
}
/// <summary>
/// Compares the specified instances for equality.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>True if both instances are equal; false otherwise.</returns>
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
/// <summary>
/// Compares the specified instances for inequality.
/// </summary>
/// <param name="left">Left operand.</param>
/// <param name="right">Right operand.</param>
/// <returns>True if both instances are not equal; false otherwise.</returns>
public static bool operator !=(Vector2 left, Vector2 right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Vector2.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("({0}, {1})", X, Y);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector2))
return false;
return this.Equals((Vector2)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Vector2> Members
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector2 other)
{
return
X == other.X &&
Y == other.Y;
}
#endregion
}
}
| |
/*
* 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.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenSim.Services.Connectors.Hypergrid;
namespace OpenSim.Services.LLLoginService
{
public class LLLoginService : ILoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[LLOGIN SERVICE]";
private static bool Initialized = false;
protected IUserAccountService m_UserAccountService;
protected IGridUserService m_GridUserService;
protected IAuthenticationService m_AuthenticationService;
protected IInventoryService m_InventoryService;
protected IInventoryService m_HGInventoryService;
protected IGridService m_GridService;
protected IPresenceService m_PresenceService;
protected ISimulationService m_LocalSimulationService;
protected ISimulationService m_RemoteSimulationService;
protected ILibraryService m_LibraryService;
protected IFriendsService m_FriendsService;
protected IAvatarService m_AvatarService;
protected IUserAgentService m_UserAgentService;
protected GatekeeperServiceConnector m_GatekeeperConnector;
protected string m_DefaultRegionName;
protected string m_WelcomeMessage;
protected bool m_RequireInventory;
protected int m_MinLoginLevel;
protected string m_GatekeeperURL;
protected bool m_AllowRemoteSetLoginLevel;
protected string m_MapTileURL;
protected string m_SearchURL;
protected string m_Currency;
protected string m_ClassifiedFee;
protected int m_MaxAgentGroups;
protected string m_DestinationGuide;
protected string m_AvatarPicker;
protected string m_AllowedClients;
protected string m_DeniedClients;
protected string m_MessageUrl;
protected string m_DSTZone;
IConfig m_LoginServerConfig;
// IConfig m_ClientsConfig;
public LLLoginService(IConfigSource config, ISimulationService simService, ILibraryService libraryService)
{
m_LoginServerConfig = config.Configs["LoginService"];
if (m_LoginServerConfig == null)
throw new Exception(String.Format("No section LoginService in config file"));
string accountService = m_LoginServerConfig.GetString("UserAccountService", String.Empty);
string gridUserService = m_LoginServerConfig.GetString("GridUserService", String.Empty);
string agentService = m_LoginServerConfig.GetString("UserAgentService", String.Empty);
string authService = m_LoginServerConfig.GetString("AuthenticationService", String.Empty);
string invService = m_LoginServerConfig.GetString("InventoryService", String.Empty);
string gridService = m_LoginServerConfig.GetString("GridService", String.Empty);
string presenceService = m_LoginServerConfig.GetString("PresenceService", String.Empty);
string libService = m_LoginServerConfig.GetString("LibraryService", String.Empty);
string friendsService = m_LoginServerConfig.GetString("FriendsService", String.Empty);
string avatarService = m_LoginServerConfig.GetString("AvatarService", String.Empty);
string simulationService = m_LoginServerConfig.GetString("SimulationService", String.Empty);
m_DefaultRegionName = m_LoginServerConfig.GetString("DefaultRegion", String.Empty);
m_WelcomeMessage = m_LoginServerConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
m_RequireInventory = m_LoginServerConfig.GetBoolean("RequireInventory", true);
m_AllowRemoteSetLoginLevel = m_LoginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false);
m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0);
m_GatekeeperURL = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "LoginService" }, String.Empty);
m_MapTileURL = m_LoginServerConfig.GetString("MapTileURL", string.Empty);
m_SearchURL = m_LoginServerConfig.GetString("SearchURL", string.Empty);
m_Currency = m_LoginServerConfig.GetString("Currency", string.Empty);
m_ClassifiedFee = m_LoginServerConfig.GetString("ClassifiedFee", string.Empty);
m_DestinationGuide = m_LoginServerConfig.GetString ("DestinationGuide", string.Empty);
m_AvatarPicker = m_LoginServerConfig.GetString ("AvatarPicker", string.Empty);
string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "LoginService" };
m_AllowedClients = Util.GetConfigVarFromSections<string>(
config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
m_DeniedClients = Util.GetConfigVarFromSections<string>(
config, "DeniedClients", possibleAccessControlConfigSections, string.Empty);
m_MessageUrl = m_LoginServerConfig.GetString("MessageUrl", string.Empty);
m_DSTZone = m_LoginServerConfig.GetString("DSTZone", "America/Los_Angeles;Pacific Standard Time");
IConfig groupConfig = config.Configs["Groups"];
if (groupConfig != null)
m_MaxAgentGroups = groupConfig.GetInt("MaxAgentGroups", 42);
// Clean up some of these vars
if (m_MapTileURL != String.Empty)
{
m_MapTileURL = m_MapTileURL.Trim();
if (!m_MapTileURL.EndsWith("/"))
m_MapTileURL = m_MapTileURL + "/";
}
// These are required; the others aren't
if (accountService == string.Empty || authService == string.Empty)
throw new Exception("LoginService is missing service specifications");
// replace newlines in welcome message
m_WelcomeMessage = m_WelcomeMessage.Replace("\\n", "\n");
Object[] args = new Object[] { config };
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(invService, args);
if (gridService != string.Empty)
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
if (presenceService != string.Empty)
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
if (avatarService != string.Empty)
m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args);
if (friendsService != string.Empty)
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
if (simulationService != string.Empty)
m_RemoteSimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
if (agentService != string.Empty)
m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(agentService, args);
// Get the Hypergrid inventory service (exists only if Hypergrid is enabled)
string hgInvServicePlugin = m_LoginServerConfig.GetString("HGInventoryServicePlugin", String.Empty);
if (hgInvServicePlugin != string.Empty)
{
string hgInvServiceArg = m_LoginServerConfig.GetString("HGInventoryServiceConstructorArg", String.Empty);
Object[] args2 = new Object[] { config, hgInvServiceArg };
m_HGInventoryService = ServerUtils.LoadPlugin<IInventoryService>(hgInvServicePlugin, args2);
}
//
// deal with the services given as argument
//
m_LocalSimulationService = simService;
if (libraryService != null)
{
m_log.DebugFormat("[LLOGIN SERVICE]: Using LibraryService given as argument");
m_LibraryService = libraryService;
}
else if (libService != string.Empty)
{
m_log.DebugFormat("[LLOGIN SERVICE]: Using instantiated LibraryService");
m_LibraryService = ServerUtils.LoadPlugin<ILibraryService>(libService, args);
}
m_GatekeeperConnector = new GatekeeperServiceConnector();
if (!Initialized)
{
Initialized = true;
RegisterCommands();
}
m_log.DebugFormat("[LLOGIN SERVICE]: Starting...");
}
public LLLoginService(IConfigSource config) : this(config, null, null)
{
}
public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP)
{
Hashtable response = new Hashtable();
response["success"] = "false";
if (!m_AllowRemoteSetLoginLevel)
return response;
try
{
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName);
return response;
}
if (account.UserLevel < 200)
{
m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low");
return response;
}
//
// Authenticate this user
//
// We don't support clear passwords here
//
string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
UUID secureSession = UUID.Zero;
if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
{
m_log.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed");
return response;
}
}
catch (Exception e)
{
m_log.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e.ToString());
return response;
}
m_MinLoginLevel = level;
m_log.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName);
response["success"] = true;
return response;
}
public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
{
bool success = false;
UUID session = UUID.Random();
string processedMessage;
m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} at {2} using viewer {3}, channel {4}, IP {5}, Mac {6}, Id0 {7}",
firstName, lastName, startLocation, clientVersion, channel, clientIP.Address.ToString(), mac, id0);
try
{
//
// Check client
//
if (m_AllowedClients != string.Empty)
{
Regex arx = new Regex(m_AllowedClients);
Match am = arx.Match(clientVersion);
if (!am.Success)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is not allowed",
firstName, lastName, clientVersion);
return LLFailedLoginResponse.LoginBlockedProblem;
}
}
if (m_DeniedClients != string.Empty)
{
Regex drx = new Regex(m_DeniedClients);
Match dm = drx.Match(clientVersion);
if (dm.Success)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: client {2} is denied",
firstName, lastName, clientVersion);
return LLFailedLoginResponse.LoginBlockedProblem;
}
}
//
// Get the account and check that it exists
//
UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
if (account == null)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user not found", firstName, lastName);
return LLFailedLoginResponse.UserProblem;
}
if (account.UserLevel < m_MinLoginLevel)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: user level is {2} but minimum login level is {3}",
firstName, lastName, account.UserLevel, m_MinLoginLevel);
return LLFailedLoginResponse.LoginBlockedProblem;
}
// If a scope id is requested, check that the account is in
// that scope, or unscoped.
//
if (scopeID != UUID.Zero)
{
if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed, reason: user {0} {1} not found", firstName, lastName);
return LLFailedLoginResponse.UserProblem;
}
}
else
{
scopeID = account.ScopeID;
}
//
// Authenticate this user
//
if (!passwd.StartsWith("$1$"))
passwd = "$1$" + Util.Md5Hash(passwd);
passwd = passwd.Remove(0, 3); //remove $1$
string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
UUID secureSession = UUID.Zero;
if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: authentication failed",
firstName, lastName);
return LLFailedLoginResponse.UserProblem;
}
//
// Get the user's inventory
//
if (m_RequireInventory && m_InventoryService == null)
{
m_log.WarnFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: inventory service not set up",
firstName, lastName);
return LLFailedLoginResponse.InventoryProblem;
}
if (m_HGInventoryService != null)
{
// Give the Suitcase service a chance to create the suitcase folder.
// (If we're not using the Suitcase inventory service then this won't do anything.)
m_HGInventoryService.GetRootFolder(account.PrincipalID);
}
List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed, for {0} {1}, reason: unable to retrieve user inventory",
firstName, lastName);
return LLFailedLoginResponse.InventoryProblem;
}
// Get active gestures
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
// m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);
//
// Login the presence
//
if (m_PresenceService != null)
{
success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);
if (!success)
{
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: could not login presence",
firstName, lastName);
return LLFailedLoginResponse.GridProblem;
}
}
//
// Change Online status and get the home region
//
GridRegion home = null;
GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());
// We are only going to complain about no home if the user actually tries to login there, to avoid
// spamming the console.
if (guinfo != null)
{
if (guinfo.HomeRegionID == UUID.Zero && startLocation == "home")
{
m_log.WarnFormat(
"[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location but they have none set",
account.Name);
}
else if (m_GridService != null)
{
home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);
if (home == null && startLocation == "home")
{
m_log.WarnFormat(
"[LLOGIN SERVICE]: User {0} tried to login to a 'home' start location with ID {1} but this was not found.",
account.Name, guinfo.HomeRegionID);
}
}
}
else
{
// something went wrong, make something up, so that we don't have to test this anywhere else
m_log.DebugFormat("{0} Failed to fetch GridUserInfo. Creating empty GridUserInfo as home", LogHeader);
guinfo = new GridUserInfo();
guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
}
//
// Find the destination region/grid
//
string where = string.Empty;
Vector3 position = Vector3.Zero;
Vector3 lookAt = Vector3.Zero;
GridRegion gatekeeper = null;
TeleportFlags flags;
GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
if (destination == null)
{
m_PresenceService.LogoutAgent(session);
m_log.InfoFormat(
"[LLOGIN SERVICE]: Login failed for {0} {1}, reason: destination not found",
firstName, lastName);
return LLFailedLoginResponse.GridProblem;
}
else
{
m_log.DebugFormat(
"[LLOGIN SERVICE]: Found destination {0}, endpoint {1} for {2} {3}",
destination.RegionName, destination.ExternalEndPoint, firstName, lastName);
}
if (account.UserLevel >= 200)
flags |= TeleportFlags.Godlike;
//
// Get the avatar
//
AvatarAppearance avatar = null;
if (m_AvatarService != null)
{
avatar = m_AvatarService.GetAppearance(account.PrincipalID);
}
//
// Instantiate/get the simulation interface and launch an agent at the destination
//
string reason = string.Empty;
GridRegion dest;
AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);
destination = dest;
if (aCircuit == null)
{
m_PresenceService.LogoutAgent(session);
m_log.InfoFormat("[LLOGIN SERVICE]: Login failed for {0} {1}, reason: {2}", firstName, lastName, reason);
return new LLFailedLoginResponse("key", reason, "false");
}
// Get Friends list
FriendInfo[] friendsList = new FriendInfo[0];
if (m_FriendsService != null)
{
friendsList = m_FriendsService.GetFriends(account.PrincipalID);
// m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
}
//
// Finally, fill out the response and return it
//
if (m_MessageUrl != String.Empty)
{
WebClient client = new WebClient();
processedMessage = client.DownloadString(m_MessageUrl);
}
else
{
processedMessage = m_WelcomeMessage;
}
processedMessage = processedMessage.Replace("\\n", "\n").Replace("<USERNAME>", firstName + " " + lastName);
LLLoginResponse response
= new LLLoginResponse(
account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
where, startLocation, position, lookAt, gestures, processedMessage, home, clientIP,
m_MapTileURL, m_SearchURL, m_Currency, m_DSTZone,
m_DestinationGuide, m_AvatarPicker, m_ClassifiedFee, m_MaxAgentGroups);
m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to {0} {1}", firstName, lastName);
return response;
}
catch (Exception e)
{
m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
if (m_PresenceService != null)
m_PresenceService.LogoutAgent(session);
return LLFailedLoginResponse.InternalError;
}
}
protected GridRegion FindDestination(
UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation,
GridRegion home, out GridRegion gatekeeper,
out string where, out Vector3 position, out Vector3 lookAt, out TeleportFlags flags)
{
flags = TeleportFlags.ViaLogin;
m_log.DebugFormat(
"[LLOGIN SERVICE]: Finding destination matching start location {0} for {1}",
startLocation, account.Name);
gatekeeper = null;
where = "home";
position = new Vector3(128, 128, 0);
lookAt = new Vector3(0, 1, 0);
if (m_GridService == null)
return null;
if (startLocation.Equals("home"))
{
// logging into home region
if (pinfo == null)
return null;
GridRegion region = null;
bool tryDefaults = false;
if (home == null)
{
tryDefaults = true;
}
else
{
region = home;
position = pinfo.HomePosition;
lookAt = pinfo.HomeLookAt;
flags |= TeleportFlags.ViaHome;
}
if (tryDefaults)
{
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
else
{
m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region",
account.FirstName, account.LastName);
region = FindAlternativeRegion(scopeID);
if (region != null)
where = "safe";
}
}
return region;
}
else if (startLocation.Equals("last"))
{
// logging into last visited region
where = "last";
if (pinfo == null)
return null;
GridRegion region = null;
if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null)
{
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
else
{
m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
region = FindAlternativeRegion(scopeID);
if (region != null)
where = "safe";
}
}
else
{
position = pinfo.LastPosition;
lookAt = pinfo.LastLookAt;
}
return region;
}
else
{
flags |= TeleportFlags.ViaRegionID;
// free uri form
// e.g. New Moon&135&46 New Moon@osgrid.org:8002&153&34
where = "url";
GridRegion region = null;
Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+[.]?\d*)&(?<y>\d+[.]?\d*)&(?<z>\d+[.]?\d*)$");
Match uriMatch = reURI.Match(startLocation);
if (uriMatch == null)
{
m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation);
return null;
}
else
{
position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));
string regionName = uriMatch.Groups["region"].ToString();
if (regionName != null)
{
if (!regionName.Contains("@"))
{
List<GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1);
if ((regions == null) || (regions != null && regions.Count == 0))
{
m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName);
regions = m_GridService.GetDefaultRegions(scopeID);
if (regions != null && regions.Count > 0)
{
where = "safe";
return regions[0];
}
else
{
m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
region = FindAlternativeRegion(scopeID);
if (region != null)
{
where = "safe";
return region;
}
else
{
m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions and no alternative found.", startLocation);
return null;
}
}
}
return regions[0];
}
else
{
if (m_UserAgentService == null)
{
m_log.WarnFormat("[LLLOGIN SERVICE]: This llogin service is not running a user agent service, as such it can't lauch agents at foreign grids");
return null;
}
string[] parts = regionName.Split(new char[] { '@' });
if (parts.Length < 2)
{
m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName);
return null;
}
// Valid specification of a remote grid
regionName = parts[0];
string domainLocator = parts[1];
parts = domainLocator.Split(new char[] {':'});
string domainName = parts[0];
uint port = 0;
if (parts.Length > 1)
UInt32.TryParse(parts[1], out port);
region = FindForeignRegion(domainName, port, regionName, account, out gatekeeper);
return region;
}
}
else
{
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
where = "safe";
return defaults[0];
}
else
return null;
}
}
//response.LookAt = "[r0,r1,r0]";
//// can be: last, home, safe, url
//response.StartLocation = "url";
}
}
private GridRegion FindAlternativeRegion(UUID scopeID)
{
List<GridRegion> hyperlinks = null;
List<GridRegion> regions = m_GridService.GetFallbackRegions(scopeID, (int)Util.RegionToWorldLoc(1000), (int)Util.RegionToWorldLoc(1000));
if (regions != null && regions.Count > 0)
{
hyperlinks = m_GridService.GetHyperlinks(scopeID);
IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
if (availableRegions.Count() > 0)
return availableRegions.ElementAt(0);
}
// No fallbacks, try to find an arbitrary region that is not a hyperlink
// maxNumber is fixed for now; maybe use some search pattern with increasing maxSize here?
regions = m_GridService.GetRegionsByName(scopeID, "", 10);
if (regions != null && regions.Count > 0)
{
if (hyperlinks == null)
hyperlinks = m_GridService.GetHyperlinks(scopeID);
IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
if (availableRegions.Count() > 0)
return availableRegions.ElementAt(0);
}
return null;
}
private GridRegion FindForeignRegion(string domainName, uint port, string regionName, UserAccount account, out GridRegion gatekeeper)
{
m_log.Debug("[LLLOGIN SERVICE]: attempting to findforeignregion " + domainName + ":" + port.ToString() + ":" + regionName);
gatekeeper = new GridRegion();
gatekeeper.ExternalHostName = domainName;
gatekeeper.HttpPort = port;
gatekeeper.RegionName = regionName;
gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);
UUID regionID;
ulong handle;
string imageURL = string.Empty, reason = string.Empty;
string message;
if (m_GatekeeperConnector.LinkRegion(gatekeeper, out regionID, out handle, out domainName, out imageURL, out reason))
{
string homeURI = null;
if (account.ServiceURLs != null && account.ServiceURLs.ContainsKey("HomeURI"))
homeURI = (string)account.ServiceURLs["HomeURI"];
GridRegion destination = m_GatekeeperConnector.GetHyperlinkRegion(gatekeeper, regionID, account.PrincipalID, homeURI, out message);
return destination;
}
return null;
}
private string hostName = string.Empty;
private int port = 0;
private void SetHostAndPort(string url)
{
try
{
Uri uri = new Uri(url);
hostName = uri.Host;
port = uri.Port;
}
catch
{
m_log.WarnFormat("[LLLogin SERVICE]: Unable to parse GatekeeperURL {0}", url);
}
}
protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarAppearance avatar,
UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, string channel, string mac, string id0,
IPEndPoint clientIP, TeleportFlags flags, out string where, out string reason, out GridRegion dest)
{
where = currentWhere;
ISimulationService simConnector = null;
reason = string.Empty;
uint circuitCode = 0;
AgentCircuitData aCircuit = null;
if (m_UserAgentService == null)
{
// HG standalones have both a localSimulatonDll and a remoteSimulationDll
// non-HG standalones have just a localSimulationDll
// independent login servers have just a remoteSimulationDll
if (m_LocalSimulationService != null)
simConnector = m_LocalSimulationService;
else if (m_RemoteSimulationService != null)
simConnector = m_RemoteSimulationService;
}
else // User Agent Service is on
{
if (gatekeeper == null) // login to local grid
{
if (hostName == string.Empty)
SetHostAndPort(m_GatekeeperURL);
gatekeeper = new GridRegion(destination);
gatekeeper.ExternalHostName = hostName;
gatekeeper.HttpPort = (uint)port;
gatekeeper.ServerURI = m_GatekeeperURL;
}
m_log.Debug("[LLLOGIN SERVICE]: no gatekeeper detected..... using " + m_GatekeeperURL);
}
bool success = false;
if (m_UserAgentService == null && simConnector != null)
{
circuitCode = (uint)Util.RandomClass.Next(); ;
aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
success = LaunchAgentDirectly(simConnector, destination, aCircuit, flags, out reason);
if (!success && m_GridService != null)
{
// Try the fallback regions
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
if (fallbacks != null)
{
foreach (GridRegion r in fallbacks)
{
success = LaunchAgentDirectly(simConnector, r, aCircuit, flags | TeleportFlags.ViaRegionID, out reason);
if (success)
{
where = "safe";
destination = r;
break;
}
}
}
}
}
if (m_UserAgentService != null)
{
circuitCode = (uint)Util.RandomClass.Next(); ;
aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
aCircuit.teleportFlags |= (uint)flags;
success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason);
if (!success && m_GridService != null)
{
// Try the fallback regions
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
if (fallbacks != null)
{
foreach (GridRegion r in fallbacks)
{
success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason);
if (success)
{
where = "safe";
destination = r;
break;
}
}
}
}
}
dest = destination;
if (success)
return aCircuit;
else
return null;
}
private AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
AvatarAppearance avatar, UUID session, UUID secureSession, uint circuit, Vector3 position,
string ipaddress, string viewer, string channel, string mac, string id0)
{
AgentCircuitData aCircuit = new AgentCircuitData();
aCircuit.AgentID = account.PrincipalID;
if (avatar != null)
aCircuit.Appearance = new AvatarAppearance(avatar);
else
aCircuit.Appearance = new AvatarAppearance();
//aCircuit.BaseFolder = irrelevant
aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
aCircuit.child = false; // the first login agent is root
aCircuit.ChildrenCapSeeds = new Dictionary<ulong, string>();
aCircuit.circuitcode = circuit;
aCircuit.firstname = account.FirstName;
//aCircuit.InventoryFolder = irrelevant
aCircuit.lastname = account.LastName;
aCircuit.SecureSessionID = secureSession;
aCircuit.SessionID = session;
aCircuit.startpos = position;
aCircuit.IPAddress = ipaddress;
aCircuit.Viewer = viewer;
aCircuit.Channel = channel;
aCircuit.Mac = mac;
aCircuit.Id0 = id0;
SetServiceURLs(aCircuit, account);
return aCircuit;
}
private void SetServiceURLs(AgentCircuitData aCircuit, UserAccount account)
{
aCircuit.ServiceURLs = new Dictionary<string, object>();
if (account.ServiceURLs == null)
return;
// Old style: get the service keys from the DB
foreach (KeyValuePair<string, object> kvp in account.ServiceURLs)
{
if (kvp.Value != null)
{
aCircuit.ServiceURLs[kvp.Key] = kvp.Value;
if (!aCircuit.ServiceURLs[kvp.Key].ToString().EndsWith("/"))
aCircuit.ServiceURLs[kvp.Key] = aCircuit.ServiceURLs[kvp.Key] + "/";
}
}
// New style: service keys start with SRV_; override the previous
string[] keys = m_LoginServerConfig.GetKeys();
if (keys.Length > 0)
{
bool newUrls = false;
IEnumerable<string> serviceKeys = keys.Where(value => value.StartsWith("SRV_"));
foreach (string serviceKey in serviceKeys)
{
string keyName = serviceKey.Replace("SRV_", "");
string keyValue = m_LoginServerConfig.GetString(serviceKey, string.Empty);
if (!keyValue.EndsWith("/"))
keyValue = keyValue + "/";
if (!account.ServiceURLs.ContainsKey(keyName) || (account.ServiceURLs.ContainsKey(keyName) && (string)account.ServiceURLs[keyName] != keyValue))
{
account.ServiceURLs[keyName] = keyValue;
newUrls = true;
}
aCircuit.ServiceURLs[keyName] = keyValue;
m_log.DebugFormat("[LLLOGIN SERVICE]: found new key {0} {1}", keyName, aCircuit.ServiceURLs[keyName]);
}
if (!account.ServiceURLs.ContainsKey("GatekeeperURI") && !string.IsNullOrEmpty(m_GatekeeperURL))
{
m_log.DebugFormat("[LLLOGIN SERVICE]: adding gatekeeper uri {0}", m_GatekeeperURL);
account.ServiceURLs["GatekeeperURI"] = m_GatekeeperURL;
newUrls = true;
}
// The grid operator decided to override the defaults in the
// [LoginService] configuration. Let's store the correct ones.
if (newUrls)
m_UserAccountService.StoreUserAccount(account);
}
}
private bool LaunchAgentDirectly(ISimulationService simConnector, GridRegion region, AgentCircuitData aCircuit, TeleportFlags flags, out string reason)
{
string version;
if (
!simConnector.QueryAccess(
region, aCircuit.AgentID, null, true, aCircuit.startpos, "SIMULATION/0.3", new List<UUID>(), out version, out reason))
return false;
return simConnector.CreateAgent(null, region, aCircuit, (uint)flags, out reason);
}
private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason)
{
m_log.Debug("[LLOGIN SERVICE]: Launching agent at " + destination.RegionName);
if (m_UserAgentService.LoginAgentToGrid(null, aCircuit, gatekeeper, destination, true, out reason))
return true;
return false;
}
#region Console Commands
private void RegisterCommands()
{
//MainConsole.Instance.Commands.AddCommand
MainConsole.Instance.Commands.AddCommand("Users", false, "login level",
"login level <level>",
"Set the minimum user level to log in", HandleLoginCommand);
MainConsole.Instance.Commands.AddCommand("Users", false, "login reset",
"login reset",
"Reset the login level to allow all users",
HandleLoginCommand);
MainConsole.Instance.Commands.AddCommand("Users", false, "login text",
"login text <text>",
"Set the text users will see on login", HandleLoginCommand);
}
private void HandleLoginCommand(string module, string[] cmd)
{
string subcommand = cmd[1];
switch (subcommand)
{
case "level":
// Set the minimum level to allow login
// Useful to allow grid update without worrying about users.
// or fixing critical issues
//
if (cmd.Length > 2)
{
if (Int32.TryParse(cmd[2], out m_MinLoginLevel))
MainConsole.Instance.OutputFormat("Set minimum login level to {0}", m_MinLoginLevel);
else
MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid login level", cmd[2]);
}
break;
case "reset":
m_MinLoginLevel = 0;
MainConsole.Instance.OutputFormat("Reset min login level to {0}", m_MinLoginLevel);
break;
case "text":
if (cmd.Length > 2)
{
m_WelcomeMessage = cmd[2];
MainConsole.Instance.OutputFormat("Login welcome message set to '{0}'", m_WelcomeMessage);
}
break;
}
}
}
#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
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.UI;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.AspNet.UI.Controls;
using Microsoft.Scripting.AspNet.Util;
namespace Microsoft.Scripting.AspNet.UI {
public class ScriptTemplateControl : IBuildProvider {
private TemplateControl _templateControl;
private ScriptTemplateControlMemberProxy _attribs;
private string _templateControlVirtualPath;
private string _scriptVirtualPath;
private bool _inlineScript;
private TemplateControlBuildResult _buildResult;
private ScriptScope _scope;
private ScriptEngine _scriptEngine;
private ScriptTemplateControlDictionary _scopeDictionary;
private object _dataItem;
private object _bindingContainer;
private bool _dataBinding;
private static ScriptEngine _defaultEngine;
// Get the ScriptTemplateControl object from a TemplateControl
internal static ScriptTemplateControl GetScriptTemplateControl(Control c) {
TemplateControl templateControl = c.TemplateControl;
IScriptTemplateControl iscriptTemplateControl = templateControl as IScriptTemplateControl;
if (iscriptTemplateControl == null) {
throw new Exception("The page '" + templateControl.AppRelativeVirtualPath +
"' doesn't have the expected script base type (i.e. ScriptPage, ScriptUserControl or ScriptMaster)");
}
return iscriptTemplateControl.ScriptTemplateControl;
}
internal ScriptTemplateControl(TemplateControl templateControl) {
_templateControl = templateControl;
}
internal ScriptTemplateControlMemberProxy MemberProxy { get { return _attribs; } }
public ScriptScope ScriptModule { get { return _scope; } }
public ScriptEngine ScriptEngine { get { return _scriptEngine; } }
internal void HookUpScript(string scriptLanguage) {
if (scriptLanguage == null) {
// TODO: Need to revise this, we need to use the InvariantContext here probably
// but it can't actually do calls yet.
_scriptEngine = _defaultEngine;
return;
}
_scriptEngine = EngineHelper.GetScriptEngineByName(scriptLanguage);
_defaultEngine = _defaultEngine ?? _scriptEngine;
_templateControlVirtualPath = VirtualPathUtility.ToAbsolute(_templateControl.AppRelativeVirtualPath);
// First, look for a code behind file named <pagename>.aspx.<ext>, where 'ext' is the extension
// for the page's language
_inlineScript = false;
IList<string> extensions = _scriptEngine.Setup.FileExtensions;
foreach (string extension in extensions) {
_scriptVirtualPath = _templateControlVirtualPath + extension;
if (HookUpScriptFile()) {
return;
}
}
// Then, look for inline script
_inlineScript = true;
_scriptVirtualPath = _templateControlVirtualPath;
HookUpScriptFile();
}
private bool HookUpScriptFile() {
_buildResult = (TemplateControlBuildResult)EngineHelper.GetBuildResult(_scriptVirtualPath, this);
// No script: nothing to do
if (_buildResult == null || _buildResult.CompiledCode == null)
return false;
_scopeDictionary = new ScriptTemplateControlDictionary(_templateControl, this);
_scope = EngineHelper.ScriptRuntime.CreateScope(_scopeDictionary);
_attribs = new ScriptTemplateControlMemberProxy(_scopeDictionary);
EngineHelper.ExecuteCode(_scope, _buildResult.CompiledCode, _buildResult.ScriptVirtualPath);
_buildResult.InitMethods(_templateControl.GetType(), _scope);
_buildResult.HookupEvents(this, _scope, _templateControl);
return true;
}
internal void HookupControlEvent(Control control, string eventName, string handlerName, int line) {
EventInfo eventInfo = control.GetType().GetEvent(eventName);
if (eventInfo == null) {
throw new Exception("Control '" + control.ID + "' doesn't have an event named '" +
eventName + "'");
}
object o = null;
if (_scopeDictionary == null || !_scopeDictionary.TryGetValue(handlerName, out o)) {
Misc.ThrowException("The page doesn't have an event handler named '" + handlerName + "'",
null, _templateControl.AppRelativeVirtualPath, line);
}
DynamicFunction handlerFunction = new DynamicFunction(o);
Delegate handler = EventHandlerWrapper.GetWrapper(this, handlerFunction, _scriptVirtualPath, eventInfo.EventHandlerType);
eventInfo.AddEventHandler(control, handler);
}
#region IBuildProvider Members
ScriptEngine IBuildProvider.GetScriptEngine() {
return _scriptEngine;
}
string IBuildProvider.GetScriptCode() {
// If the file doesn't exist, there is no script code
if (!HostingEnvironment.VirtualPathProvider.FileExists(_scriptVirtualPath)) {
// If it's the aspx/ascx/master file itself that doesn't exist, we're
// probably dealing with a precompiled app, which we don't support.
// REVIEW: Find a better way of detecting a precompiled app, like PrecompiledApp.config
//if (_inlineScript) {
// throw new Exception("Precompilation is not supported on dynamic language pages");
//}
return null;
}
if (_inlineScript) {
// If it's inline, we need to extract the script from the page
return GetScriptFromTemplateControl();
} else {
return Util.Misc.GetStringFromVirtualPath(_scriptVirtualPath);
}
}
BuildResult IBuildProvider.CreateBuildResult(CompiledCode compiledCode, string scriptVirtualPath) {
return new TemplateControlBuildResult(compiledCode, scriptVirtualPath);
}
#endregion
private string GetScriptFromTemplateControl() {
IScriptTemplateControl iscriptTemplateControl = (IScriptTemplateControl)_templateControl;
string code = iscriptTemplateControl.InlineScript;
if (code == null)
return String.Empty;
StringBuilder builder = new StringBuilder();
// Append enough blank lines to reach the start line of the script block in the page
for (int line = 1; line < iscriptTemplateControl.InlineScriptLine; line++) {
builder.AppendLine();
}
builder.Append(code);
return builder.ToString();
}
// Note that dataItem can be null, in which case we go against Page.GetDataItem()
public void SetDataItem(object dataItem) {
Debug.Assert(_dataItem == null && !_dataBinding);
_dataItem = dataItem;
_dataBinding = true;
}
public void ClearDataItem() {
Debug.Assert(_dataBinding);
_dataItem = null;
_dataBinding = false;
}
internal object GetDataItem() {
// Don't try anything if we're not databinding
if (!_dataBinding)
return null;
// If we have our own data item, use it
if (_dataItem != null)
return _dataItem;
// Otherwise, use the data item on the page stack
return _templateControl.Page.GetDataItem();
}
internal object BindingContainer { get { return _bindingContainer; } }
internal object EvaluateDataBindingExpression(Control c, string expr, int line) {
// Try to get a data item
_bindingContainer = c.BindingContainer;
Debug.Assert(_bindingContainer != null);
object dataItem = DataBinder.GetDataItem(_bindingContainer);
// If we got one, make it available
if (dataItem != null)
SetDataItem(dataItem);
try {
return EvaluateExpression(expr, line);
} finally {
if (dataItem != null)
ClearDataItem();
_bindingContainer = null;
}
}
internal object EvaluateExpression(string expr, int line) {
CompiledCode compiledExpression = (CompiledCode) _buildResult.CompiledSnippetExpressions[expr];
if (compiledExpression == null) {
lock (_buildResult.CompiledSnippetExpressions) {
compiledExpression = (CompiledCode)_buildResult.CompiledSnippetExpressions[expr];
if (compiledExpression == null) {
// Need to subtract one from the line since it's 1-based and we want an offset
compiledExpression = EngineHelper.CompileExpression(expr, ScriptEngine, _templateControlVirtualPath, line - 1);
_buildResult.CompiledSnippetExpressions[expr] = compiledExpression;
}
}
}
return EngineHelper.EvaluateCompiledCode(compiledExpression, _scope,
_templateControlVirtualPath, line);
}
internal CompiledCode GetSnippetRenderCode(string cacheKey, SnippetControl snippetControl) {
CompiledCode compiledSnippet = (CompiledCode)_buildResult.CompiledSnippets[cacheKey];
if (compiledSnippet == null) {
lock (_buildResult.CompiledSnippets) {
compiledSnippet = (CompiledCode)_buildResult.CompiledSnippets[cacheKey];
if (compiledSnippet == null) {
// It's not cached, so ask the control for the CodeDom tree and compile it
CodeMemberMethod codeDomMethod = snippetControl.GenerateRenderMemberMethod(_templateControlVirtualPath);
compiledSnippet = EngineHelper.CompileCodeDom(codeDomMethod, ScriptEngine);
// Cache it
_buildResult.CompiledSnippets[cacheKey] = compiledSnippet;
}
}
}
return compiledSnippet;
}
internal void SetProperty(string propertyName, object value) {
// Try to get a dynamic setter for this property
DynamicFunction setterFunction = GetPropertySetter(propertyName);
// If we couldn't find a setter, just set a field by that name
if (setterFunction == null) {
_scope.SetVariable(propertyName, value);
return;
}
// Set the property value
CallFunction(setterFunction, value);
}
private DynamicFunction GetPropertySetter(string propertyName) {
// Prepend "Set" to get the method name
// REVIEW: is this the right naming pattern?
string setterName = "Set" + propertyName;
object setterFunction;
if (!_scope.TryGetVariable(setterName, out setterFunction))
return null;
return new DynamicFunction(setterFunction);
}
public DynamicFunction GetFunction(string name) {
if (ScriptModule == null)
return null;
object val;
if (!ScriptModule.TryGetVariable(name, out val))
return null;
return new DynamicFunction(val);
}
public object CallFunction(DynamicFunction f, params object[] args) {
return EngineHelper.CallMethod(_scriptEngine, f, _scriptVirtualPath, args);
}
public object CallDataBindingFunction(DynamicFunction f, params object[] args) {
return CallDataBindingFunction((object)null, f, args);
}
public object CallDataBindingFunction(object dataItem, DynamicFunction f, params object[] args) {
// We need to inject the data item in the globals dictionary to make it available
SetDataItem(dataItem);
try {
return CallFunction(f, args);
} finally {
ClearDataItem();
}
}
class TemplateControlBuildResult : TypeWithEventsBuildResult {
private const string HandlerPrefix = "Page_";
private List<EventHookupHelper> _eventHandlers;
private Hashtable _compiledSnippetExpressions; // <string, CompiledCode>
private Hashtable _compiledSnippets; // <string, CompiledCode>
internal TemplateControlBuildResult(CompiledCode compiledCode, string scriptVirtualPath)
: base(compiledCode, scriptVirtualPath) { }
// Dictionary of <%= ... %> expression blocks
internal IDictionary CompiledSnippetExpressions {
get {
if (_compiledSnippetExpressions == null)
_compiledSnippetExpressions = new Hashtable();
return _compiledSnippetExpressions;
}
}
// Dictionary of <% ... %> code blocks
internal IDictionary CompiledSnippets {
get {
if (_compiledSnippets == null)
_compiledSnippets = new Hashtable();
return _compiledSnippets;
}
}
internal override bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f) {
// Does it look like a handler?
if (!handlerName.StartsWith(HandlerPrefix))
return false;
string eventName = handlerName.Substring(HandlerPrefix.Length);
EventHookupHelper helper = EventHookupHelper.Create(type, eventName,
handlerName, f, ScriptVirtualPath);
if (helper == null)
return false;
if (_eventHandlers == null)
_eventHandlers = new List<EventHookupHelper>();
_eventHandlers.Add(helper);
return true;
}
internal void HookupEvents(IBuildProvider provider, ScriptScope moduleGlobals, object o) {
if (_eventHandlers == null)
return;
foreach (EventHookupHelper helper in _eventHandlers) {
helper.HookupHandler(provider, moduleGlobals, o);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
/// <summary>
/// System.Collections.IComparer(object,object)
/// </summary>
public class IComparerCompare
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Compare two int value");
try
{
Comparer<object> comparer = Comparer<object>.Default ;
int a = this.GetInt32(0, Int32.MaxValue);
int b = this.GetInt32(a + 1, Int32.MaxValue);
int result = comparer.Compare(a, b);
if (result >= 0)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,a is:" + a + "b is:" + b);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Compare two string ");
try
{
string a = "hello";
string b = "aaaaa";
CultureInfo cultureInfo = new CultureInfo("en-US");
CompareInfo comparer = cultureInfo.CompareInfo;
int result = comparer.Compare(b, a);
if (result >= 0)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Compare two char which are equal");
try
{
char a = 'z';
char b = 'z';
Comparer<char> comparer = Comparer<char>.Default;
int result = comparer.Compare(b, a);
if (result != 0)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Using custom class deriving from the Icomparer to implement the Compare method");
try
{
TestClass testClass = new TestClass();
MyClass a = new MyClass(-10);
MyClass b = new MyClass(100);
int result = testClass.Compare(b, a);
if (result <= 0)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Neither a nor b implements the IComparable interface");
try
{
Comparer<object> comparer = Comparer<object>.Default;
MyClassNotCompareTo a = new MyClassNotCompareTo();
MyClassNotCompareTo b = new MyClassNotCompareTo();
int result = comparer.Compare(b, a);
TestLibrary.TestFramework.LogError("101", "The ArgumentException was not thrown as expected");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The objects to be compared are two different types");
try
{
Comparer<object> comparer = Comparer<object>.Default;
int a = 10;
string b = "boy";
int result = comparer.Compare(b, a);
TestLibrary.TestFramework.LogError("103", "The ArgumentException was not thrown as expected");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
IComparerCompare test = new IComparerCompare();
TestLibrary.TestFramework.BeginTestCase("IComparerCompare");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
public class TestClass : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return (x as IComparable).CompareTo(y);
}
#endregion
}
public class MyClass : IComparable
{
#region IComparable Members
public int CompareTo(object obj)
{
if (this.value < ((MyClass)obj).value)
return -1;
else
{
if (this.value > ((MyClass)obj).value)
return 1;
else
{
return 0;
}
}
}
#endregion
public int value;
public MyClass(int a)
{
value = a;
}
}
public class MyClassNotCompareTo
{
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class NestedProjectNode : HierarchyNode, IPropertyNotifySink
{
#region fields
private IVsHierarchy nestedHierarchy;
Guid projectInstanceGuid = Guid.Empty;
private string projectName = String.Empty;
private string projectPath = String.Empty;
private ImageHandler imageHandler;
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
/// <summary>
/// Sets the dispose flag on the object.
/// </summary>
private bool isDisposed;
// A cooike retrieved when advising on property chnanged events.
private uint projectPropertyNotifySinkCookie;
#endregion
#region properties
internal IVsHierarchy NestedHierarchy
{
get
{
return this.nestedHierarchy;
}
}
#endregion
#region virtual properties
/// <summary>
/// Returns the __VSADDVPFLAGS that will be passed in when calling AddVirtualProjectEx
/// </summary>
protected virtual uint VirtualProjectFlags
{
get { return 0; }
}
#endregion
#region overridden properties
/// <summary>
/// The path of the nested project.
/// </summary>
public override string Url
{
get
{
return this.projectPath;
}
}
/// <summary>
/// The Caption of the nested project.
/// </summary>
public override string Caption
{
get
{
return Path.GetFileNameWithoutExtension(this.projectName);
}
}
public override Guid ItemTypeGuid
{
get
{
return VSConstants.GUID_ItemType_SubProject;
}
}
/// <summary>
/// Defines whether a node can execute a command if in selection.
/// We do this in order to let the nested project to handle the execution of its own commands.
/// </summary>
public override bool CanExecuteCommand
{
get
{
return false;
}
}
public override int SortPriority
{
get { return DefaultSortOrderNode.NestedProjectNode; }
}
protected bool IsDisposed
{
get { return this.isDisposed; }
set { this.isDisposed = value; }
}
#endregion
#region ctor
protected NestedProjectNode()
{
}
public NestedProjectNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.IsExpanded = true;
}
#endregion
#region IPropertyNotifySink Members
/// <summary>
/// Notifies a sink that the [bindable] property specified by dispID has changed.
/// If dispID is DISPID_UNKNOWN, then multiple properties have changed together.
/// The client (owner of the sink) should then retrieve the current value of each property of interest from the object that generated the notification.
/// In our case we will care about the VSLangProj80.VsProjPropId.VBPROJPROPID_FileName and update the changes in the parent project file.
/// </summary>
/// <param name="dispid">Dispatch identifier of the property that is about to change or DISPID_UNKNOWN if multiple properties are about to change.</param>
public virtual void OnChanged(int dispid)
{
if (dispid == (int)VSLangProj80.VsProjPropId.VBPROJPROPID_FileName)
{
// Get the filename of the nested project. Inetead of asking the label on the nested we ask the filename, since the label might not yet been set.
IVsProject3 nestedProject = this.nestedHierarchy as IVsProject3;
if (nestedProject != null)
{
string document;
ErrorHandler.ThrowOnFailure(nestedProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out document));
this.RenameNestedProjectInParentProject(Path.GetFileNameWithoutExtension(document));
// We need to redraw the caption since for some reason, by intervining to the OnChanged event the Caption is not updated.
this.ReDraw(UIHierarchyElement.Caption);
}
}
}
/// <summary>
/// Notifies a sink that a [requestedit] property is about to change and that the object is asking the sink how to proceed.
/// </summary>
/// <param name="dispid">Dispatch identifier of the property that is about to change or DISPID_UNKNOWN if multiple properties are about to change.</param>
public virtual void OnRequestEdit(int dispid)
{
}
#endregion
#region public methods
#endregion
#region overridden methods
/// <summary>
/// Get the automation object for the NestedProjectNode
/// </summary>
/// <returns>An instance of the Automation.OANestedProjectItem type if succeded</returns>
public override object GetAutomationObject()
{
//Validate that we are not disposed or the project is closing
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OANestedProjectItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Gets properties of a given node or of the hierarchy.
/// </summary>
/// <param name="propId">Identifier of the hierarchy property</param>
/// <returns>It return an object which type is dependent on the propid.</returns>
public override object GetProperty(int propId)
{
__VSHPROPID vshPropId = (__VSHPROPID)propId;
switch (vshPropId)
{
default:
return base.GetProperty(propId);
case __VSHPROPID.VSHPROPID_Expandable:
return true;
case __VSHPROPID.VSHPROPID_BrowseObject:
case __VSHPROPID.VSHPROPID_HandlesOwnReload:
return this.DelegateGetPropertyToNested(propId);
}
}
/// <summary>
/// Gets properties whose values are GUIDs.
/// </summary>
/// <param name="propid">Identifier of the hierarchy property</param>
/// <param name="guid"> Pointer to a GUID property specified in propid</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int GetGuidProperty(int propid, out Guid guid)
{
guid = Guid.Empty;
switch ((__VSHPROPID)propid)
{
case __VSHPROPID.VSHPROPID_ProjectIDGuid:
guid = this.projectInstanceGuid;
break;
default:
return base.GetGuidProperty(propid, out guid);
}
CCITracing.TraceCall(String.Format(CultureInfo.CurrentCulture, "Guid for {0} property", propid));
if (guid.CompareTo(Guid.Empty) == 0)
{
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the hierarchy item changed.
/// </summary>
/// <param name="itemId">Item identifier of the hierarchy item contained in VSITEMID</param>
/// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item. </param>
/// <param name="pfDirty">TRUE if the hierarchy item changed.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int IsItemDirty(uint itemId, IntPtr punkDocData, out int pfDirty)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");
// Get an IPersistFileFormat object from docData object
IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");
// Call IsDirty on the IPersistFileFormat interface
ErrorHandler.ThrowOnFailure(persistFileFormat.IsDirty(out pfDirty));
return VSConstants.S_OK;
}
/// <summary>
/// Saves the hierarchy item to disk.
/// </summary>
/// <param name="dwSave">Flags whose values are taken from the VSSAVEFLAGS enumeration.</param>
/// <param name="silentSaveAsName">File name to be applied when dwSave is set to VSSAVE_SilentSave. </param>
/// <param name="itemid">Item identifier of the hierarchy item saved from VSITEMID. </param>
/// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item saved.</param>
/// <param name="pfCancelled">TRUE if the save action was canceled. </param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int SaveItem(VSSAVEFLAGS dwSave, string silentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCancelled)
{
// Don't ignore/unignore file changes
// Use Advise/Unadvise to work around rename situations
try
{
this.StopObservingNestedProjectFile();
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");
// Get an IPersistFileFormat object from docData object (we don't call release on punkDocData since did not increment its ref count)
IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");
IVsUIShell uiShell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
string newName;
ErrorHandler.ThrowOnFailure(uiShell.SaveDocDataToFile(dwSave, persistFileFormat, silentSaveAsName, out newName, out pfCancelled));
// When supported do a rename of the nested project here
}
finally
{
// Succeeded or not we must hook to the file change events
// Don't ignore/unignore file changes
// Use Advise/Unadvise to work around rename situations
this.ObserveNestedProjectFile();
}
return VSConstants.S_OK;
}
/// <summary>
/// Gets the icon handle. It tries first the nested to get the icon handle. If that is not supported it will get it from
/// the image list of the nested if that is supported. If neither of these is supported a default image will be shown.
/// </summary>
/// <returns>An object representing the icon.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsHierarchy.GetProperty(System.UInt32,System.Int32,System.Object@)")]
public override object GetIconHandle(bool open)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
object iconHandle = null;
this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconHandle, out iconHandle);
if (iconHandle == null)
{
if (null == imageHandler)
{
InitImageHandler();
}
// Try to get an icon from the nested hierrachy image list.
if (imageHandler.ImageList != null)
{
object imageIndexAsObject = null;
if (this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconIndex, out imageIndexAsObject) == VSConstants.S_OK &&
imageIndexAsObject != null)
{
int imageIndex = (int)imageIndexAsObject;
if (imageIndex < imageHandler.ImageList.Images.Count)
{
iconHandle = imageHandler.GetIconHandle(imageIndex);
}
}
}
if (null == iconHandle)
{
iconHandle = this.ProjectMgr.ImageHandler.GetIconHandle((int)ProjectNode.ImageName.Application);
}
}
return iconHandle;
}
/// <summary>
/// Return S_OK. Implementation of Closing a nested project is done in CloseNestedProject which is called by CloseChildren.
/// </summary>
/// <returns>S_OK</returns>
public override int Close()
{
return VSConstants.S_OK;
}
/// <summary>
/// Returns the moniker of the nested project.
/// </summary>
/// <returns></returns>
public override string GetMkDocument()
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return String.Empty;
}
return this.projectPath;
}
/// <summary>
/// Called by the shell when a node has been renamed from the GUI
/// </summary>
/// <param name="label">The name of the new label.</param>
/// <returns>A success or failure value.</returns>
public override int SetEditLabel(string label)
{
int result = this.DelegateSetPropertyToNested((int)__VSHPROPID.VSHPROPID_EditLabel, label);
if (ErrorHandler.Succeeded(result))
{
this.RenameNestedProjectInParentProject(label);
}
return result;
}
/// <summary>
/// Called by the shell to get the node caption when the user tries to rename from the GUI
/// </summary>
/// <returns>the node cation</returns>
public override string GetEditLabel()
{
return (string)this.DelegateGetPropertyToNested((int)__VSHPROPID.VSHPROPID_EditLabel);
}
/// <summary>
/// This is temporary until we have support for re-adding a nested item
/// </summary>
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
return false;
}
/// <summary>
/// Delegates the call to the inner hierarchy.
/// </summary>
/// <param name="reserved">Reserved parameter defined at the IVsPersistHierarchyItem2::ReloadItem parameter.</param>
protected internal override void ReloadItem(uint reserved)
{
#region precondition
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
throw new InvalidOperationException();
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
#endregion
IVsPersistHierarchyItem2 persistHierachyItem = this.nestedHierarchy as IVsPersistHierarchyItem2;
// We are expecting that if we get called then the nestedhierarchy supports IVsPersistHierarchyItem2, since then hierrachy should support handling its own reload.
// There should be no errormessage to the user since this is an internal error, that it cannot be fixed at user level.
if (persistHierachyItem == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(persistHierachyItem.ReloadItem(VSConstants.VSITEMID_ROOT, reserved));
}
/// <summary>
/// Flag indicating that changes to a file can be ignored when item is saved or reloaded.
/// </summary>
/// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
protected internal override void IgnoreItemFileChanges(bool ignoreFlag)
{
#region precondition
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
throw new InvalidOperationException();
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
#endregion
this.IgnoreNestedProjectFile(ignoreFlag);
IVsPersistHierarchyItem2 persistHierachyItem = this.nestedHierarchy as IVsPersistHierarchyItem2;
// If the IVsPersistHierarchyItem2 is not implemented by the nested just return
if (persistHierachyItem == null)
{
return;
}
ErrorHandler.ThrowOnFailure(persistHierachyItem.IgnoreItemFileChanges(VSConstants.VSITEMID_ROOT, ignoreFlag ? 1 : 0));
}
/// <summary>
/// Sets the VSADDFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnAddFiles
/// </summary>
/// <param name="files">The files to which an array of VSADDFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSADDFILEFLAGS[] GetAddFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSADDFILEFLAGS[1] { VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags };
}
VSADDFILEFLAGS[] addFileFlags = new VSADDFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
addFileFlags[i] = VSADDFILEFLAGS.VSADDFILEFLAGS_IsNestedProjectFile;
}
return addFileFlags;
}
/// <summary>
/// Sets the VSQUERYADDFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnQueryAddFiles
/// </summary>
/// <param name="files">The files to which an array of VSADDFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSQUERYADDFILEFLAGS[] GetQueryAddFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSQUERYADDFILEFLAGS[1] { VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_NoFlags };
}
VSQUERYADDFILEFLAGS[] queryAddFileFlags = new VSQUERYADDFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
queryAddFileFlags[i] = VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_IsNestedProjectFile;
}
return queryAddFileFlags;
}
/// <summary>
/// Sets the VSREMOVEFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnRemoveFiles
/// </summary>
/// <param name="files">The files to which an array of VSREMOVEFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSREMOVEFILEFLAGS[] GetRemoveFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSREMOVEFILEFLAGS[1] { VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags };
}
VSREMOVEFILEFLAGS[] removeFileFlags = new VSREMOVEFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
removeFileFlags[i] = VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_IsNestedProjectFile;
}
return removeFileFlags;
}
/// <summary>
/// Sets the VSQUERYREMOVEFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnQueryRemoveFiles
/// </summary>
/// <param name="files">The files to which an array of VSQUERYREMOVEFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSQUERYREMOVEFILEFLAGS[] GetQueryRemoveFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSQUERYREMOVEFILEFLAGS[1] { VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_NoFlags };
}
VSQUERYREMOVEFILEFLAGS[] queryRemoveFileFlags = new VSQUERYREMOVEFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
queryRemoveFileFlags[i] = VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_IsNestedProjectFile;
}
return queryRemoveFileFlags;
}
#endregion
#region virtual methods
/// <summary>
/// Initialize the nested hierarhy node.
/// </summary>
/// <param name="fileName">The file name of the nested project.</param>
/// <param name="destination">The location of the nested project.</param>
/// <param name="projectName">The name of the project.</param>
/// <param name="createFlags">The nested project creation flags </param>
/// <remarks>This methos should be called just after a NestedProjectNode object is created.</remarks>
public virtual void Init(string fileName, string destination, string projectName, __VSCREATEPROJFLAGS createFlags)
{
if (String.IsNullOrEmpty(fileName))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "fileName");
}
if (String.IsNullOrEmpty(destination))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "destination");
}
this.projectName = Path.GetFileName(fileName);
this.projectPath = Path.Combine(destination, this.projectName);
// get the IVsSolution interface from the global service provider
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not get the IVsSolution object from the services exposed by this project");
if (solution == null)
{
throw new InvalidOperationException();
}
// Get the project type guid from project element
string typeGuidString = this.ItemNode.GetMetadataAndThrow(ProjectFileConstants.TypeGuid, new InvalidOperationException());
Guid projectFactoryGuid = Guid.Empty;
if (!String.IsNullOrEmpty(typeGuidString))
{
projectFactoryGuid = new Guid(typeGuidString);
}
// Get the project factory.
IVsProjectFactory projectFactory;
ErrorHandler.ThrowOnFailure(solution.GetProjectFactory((uint)0, new Guid[] { projectFactoryGuid }, fileName, out projectFactory));
this.CreateProjectDirectory();
//Create new project using factory
int cancelled;
Guid refiid = NativeMethods.IID_IUnknown;
IntPtr projectPtr = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(projectFactory.CreateProject(fileName, destination, projectName, (uint)createFlags, ref refiid, out projectPtr, out cancelled));
if (projectPtr != IntPtr.Zero)
{
this.nestedHierarchy = Marshal.GetTypedObjectForIUnknown(projectPtr, typeof(IVsHierarchy)) as IVsHierarchy;
Debug.Assert(this.nestedHierarchy != null, "Nested hierarchy could not be created");
Debug.Assert(cancelled == 0);
}
}
finally
{
if (projectPtr != IntPtr.Zero)
{
// We created a new instance of the project, we need to call release to decrement the ref count
// the RCW (this.nestedHierarchy) still has a reference to it which will keep it alive
Marshal.Release(projectPtr);
}
}
if (cancelled != 0 && this.nestedHierarchy == null)
{
ErrorHandler.ThrowOnFailure(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
// Link into the nested VS hierarchy.
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, this.ProjectMgr));
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchyItemid, (object)(int)this.ID));
this.LockRDTEntry();
this.ConnectPropertyNotifySink();
}
/// <summary>
/// Links a nested project as a virtual project to the solution.
/// </summary>
protected internal virtual void AddVirtualProject()
{
// This is the second step in creating and adding a nested project. The inner hierarchy must have been
// already initialized at this point.
#region precondition
if (this.nestedHierarchy == null)
{
throw new InvalidOperationException();
}
#endregion
// get the IVsSolution interface from the global service provider
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not get the IVsSolution object from the services exposed by this project");
if (solution == null)
{
throw new InvalidOperationException();
}
this.InitializeInstanceGuid();
// Add virtual project to solution.
ErrorHandler.ThrowOnFailure(solution.AddVirtualProjectEx(this.nestedHierarchy, this.VirtualProjectFlags, ref this.projectInstanceGuid));
// Now set up to listen on file changes on the nested project node.
this.ObserveNestedProjectFile();
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
// Everybody can go here.
if (!this.isDisposed)
{
try
{
// Synchronize calls to the Dispose simulteniously.
lock (Mutex)
{
if (disposing)
{
this.DisconnectPropertyNotifySink();
this.StopObservingNestedProjectFile();
// If a project cannot load it may happen that the imagehandler is not instantiated.
if (this.imageHandler != null)
{
this.imageHandler.Close();
}
}
}
}
finally
{
base.Dispose(disposing);
this.isDisposed = true;
}
}
}
/// <summary>
/// Creates the project directory if it does not exist.
/// </summary>
/// <returns></returns>
protected virtual void CreateProjectDirectory()
{
string directoryName = Path.GetDirectoryName(this.projectPath);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
}
/// <summary>
/// Lock the RDT Entry for the nested project.
/// By default this document is marked as "Dont Save as". That means the menu File->SaveAs is disabled for the
/// nested project node.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RDT")]
protected virtual void LockRDTEntry()
{
// Define flags for the nested project document
_VSRDTFLAGS flags = _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_ProjSlnDocument; ;
// Request the RDT service
IVsRunningDocumentTable rdt = this.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project");
if (rdt == null)
{
throw new InvalidOperationException();
}
// First we see if someone else has opened the requested view of the file.
uint itemid;
IntPtr docData = IntPtr.Zero;
IVsHierarchy ivsHierarchy;
uint docCookie;
IntPtr projectPtr = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)flags, this.projectPath, out ivsHierarchy, out itemid, out docData, out docCookie));
flags |= _VSRDTFLAGS.RDT_EditLock;
if (ivsHierarchy != null && docCookie != (uint)ShellConstants.VSDOCCOOKIE_NIL)
{
if (docCookie != this.DocCookie)
{
this.DocCookie = docCookie;
}
}
else
{
// get inptr for hierarchy
projectPtr = Marshal.GetIUnknownForObject(this.nestedHierarchy);
Debug.Assert(projectPtr != IntPtr.Zero, " Project pointer for the nested hierarchy has not been initialized");
ErrorHandler.ThrowOnFailure(rdt.RegisterAndLockDocument((uint)flags, this.projectPath, this.ProjectMgr, this.ID, projectPtr, out docCookie));
this.DocCookie = docCookie;
Debug.Assert(this.DocCookie != (uint)ShellConstants.VSDOCCOOKIE_NIL, "Invalid cookie when registering document in the running document table.");
//we must also set the doc cookie on the nested hier
this.SetDocCookieOnNestedHier(this.DocCookie);
}
}
finally
{
// Release all Inptr's that that were given as out pointers
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
if (projectPtr != IntPtr.Zero)
{
Marshal.Release(projectPtr);
}
}
}
/// <summary>
/// Unlock the RDT entry for the nested project
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RDT")]
protected virtual void UnlockRDTEntry()
{
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return;
}
// First we see if someone else has opened the requested view of the file.
IVsRunningDocumentTable rdt = this.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt != null && this.DocCookie != (int)ShellConstants.VSDOCCOOKIE_NIL)
{
_VSRDTFLAGS flags = _VSRDTFLAGS.RDT_EditLock;
ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)flags, (uint)this.DocCookie));
}
this.DocCookie = (int)ShellConstants.VSDOCCOOKIE_NIL;
}
/// <summary>
/// Renames the project file in the parent project structure.
/// </summary>
/// <param name="label">The new label.</param>
protected virtual void RenameNestedProjectInParentProject(string label)
{
string existingLabel = this.Caption;
if (String.Compare(existingLabel, label, StringComparison.Ordinal) == 0)
{
return;
}
string oldFileName = this.projectPath;
string oldPath = this.Url;
try
{
this.StopObservingNestedProjectFile();
this.ProjectMgr.SuspendMSBuild();
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string newFileName = label + Path.GetExtension(oldFileName);
this.SaveNestedProjectItemInProjectFile(newFileName);
string projectDirectory = Path.GetDirectoryName(oldFileName);
// update state.
this.projectName = newFileName;
this.projectPath = Path.Combine(projectDirectory, this.projectName);
// Unload and lock the RDT entries
this.UnlockRDTEntry();
this.LockRDTEntry();
// Since actually this is a rename in our hierarchy notify the tracker that a rename has happened.
this.ProjectMgr.Tracker.OnItemRenamed(oldPath, this.projectPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_IsNestedProjectFile);
}
finally
{
this.ObserveNestedProjectFile();
this.ProjectMgr.ResumeMSBuild(this.ProjectMgr.ReEvaluateProjectFileTargetName);
}
}
/// <summary>
/// Saves the nested project information in the project file.
/// </summary>
/// <param name="newFileName"></param>
protected virtual void SaveNestedProjectItemInProjectFile(string newFileName)
{
string existingInclude = this.ItemNode.Item.EvaluatedInclude;
string existingRelativePath = Path.GetDirectoryName(existingInclude);
string newRelativePath = Path.Combine(existingRelativePath, newFileName);
this.ItemNode.Rename(newRelativePath);
}
#endregion
#region helper methods
/// <summary>
/// Closes a nested project and releases the nested hierrachy pointer.
/// </summary>
internal void CloseNestedProjectNode()
{
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return;
}
uint itemid = VSConstants.VSITEMID_NIL;
try
{
this.DisconnectPropertyNotifySink();
IVsUIHierarchy hier;
IVsWindowFrame windowFrame;
VsShellUtilities.IsDocumentOpen(this.ProjectMgr.Site, this.projectPath, Guid.Empty, out hier, out itemid, out windowFrame);
if (itemid == VSConstants.VSITEMID_NIL)
{
this.UnlockRDTEntry();
}
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
if (solution == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(solution.RemoveVirtualProject(this.nestedHierarchy, 0));
}
finally
{
this.StopObservingNestedProjectFile();
// if we haven't already release the RDT cookie, do so now.
if (itemid == VSConstants.VSITEMID_NIL)
{
this.UnlockRDTEntry();
}
this.Dispose(true);
}
}
private void InitializeInstanceGuid()
{
if (this.projectInstanceGuid != Guid.Empty)
{
return;
}
Guid instanceGuid = Guid.Empty;
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
// This method should be called from the open children method, then we can safely use the IsNewProject property
if (this.ProjectMgr.IsNewProject)
{
instanceGuid = Guid.NewGuid();
this.ItemNode.SetMetadata(ProjectFileConstants.InstanceGuid, instanceGuid.ToString("B"));
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, ref instanceGuid));
}
else
{
// Get a guid from the nested hiererachy.
Guid nestedHiererachyInstanceGuid;
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out nestedHiererachyInstanceGuid));
// Get instance guid from the project file. If it does not exist then we create one.
string instanceGuidAsString = this.ItemNode.GetMetadata(ProjectFileConstants.InstanceGuid);
// 1. nestedHiererachyInstanceGuid is empty and instanceGuidAsString is empty then create a new one.
// 2. nestedHiererachyInstanceGuid is empty and instanceGuidAsString not empty use instanceGuidAsString and update the nested project object by calling SetGuidProperty.
// 3. nestedHiererachyInstanceGuid is not empty instanceGuidAsString is empty then use nestedHiererachyInstanceGuid and update the outer project element.
// 4. nestedHiererachyInstanceGuid is not empty instanceGuidAsString is empty then use nestedHiererachyInstanceGuid and update the outer project element.
if (nestedHiererachyInstanceGuid == Guid.Empty && String.IsNullOrEmpty(instanceGuidAsString))
{
instanceGuid = Guid.NewGuid();
}
else if (nestedHiererachyInstanceGuid == Guid.Empty && !String.IsNullOrEmpty(instanceGuidAsString))
{
instanceGuid = new Guid(instanceGuidAsString);
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, ref instanceGuid));
}
else if (nestedHiererachyInstanceGuid != Guid.Empty)
{
instanceGuid = nestedHiererachyInstanceGuid;
// If the instanceGuidAsString is empty then creating a guid out of it would throw an exception.
if (String.IsNullOrEmpty(instanceGuidAsString) || nestedHiererachyInstanceGuid != new Guid(instanceGuidAsString))
{
this.ItemNode.SetMetadata(ProjectFileConstants.InstanceGuid, instanceGuid.ToString("B"));
}
}
}
this.projectInstanceGuid = instanceGuid;
}
private void SetDocCookieOnNestedHier(uint itemDocCookie)
{
object docCookie = (int)itemDocCookie;
try
{
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ItemDocCookie, docCookie));
}
catch (NotImplementedException)
{
//we swallow this exception on purpose
}
}
private void InitImageHandler()
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
if (null == imageHandler)
{
imageHandler = new ImageHandler();
}
object imageListAsPointer = null;
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconImgList, out imageListAsPointer));
if (imageListAsPointer != null)
{
this.imageHandler.ImageList = Utilities.GetImageList(imageListAsPointer);
}
}
/// <summary>
/// Delegates Getproperty calls to the inner nested.
/// </summary>
/// <param name="propID">The property to delegate.</param>
/// <returns>The return of the GetProperty from nested.</returns>
private object DelegateGetPropertyToNested(int propID)
{
if (!this.ProjectMgr.IsClosed)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
object returnValue;
// Do not throw since some project types will return E_FAIL if they do not support a property.
int result = this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, propID, out returnValue);
if (ErrorHandler.Succeeded(result))
{
return returnValue;
}
}
return null;
}
/// <summary>
/// Delegates Setproperty calls to the inner nested.
/// </summary>
/// <param name="propID">The property to delegate.</param>
/// <param name="value">The property to set.</param>
/// <returns>The return of the SetProperty from nested.</returns>
private int DelegateSetPropertyToNested(int propID, object value)
{
if (this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
// Do not throw since some project types will return E_FAIL if they do not support a property.
return this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, propID, value);
}
/// <summary>
/// Starts observing changes on this file.
/// </summary>
private void ObserveNestedProjectFile()
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
parent.NestedProjectNodeReloader.ObserveItem(this.GetMkDocument(), this.ID);
}
/// <summary>
/// Stops observing changes on this file.
/// </summary>
private void StopObservingNestedProjectFile()
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
parent.NestedProjectNodeReloader.StopObservingItem(this.GetMkDocument());
}
/// <summary>
/// Ignores observing changes on this file depending on the boolean flag.
/// </summary>
/// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
private void IgnoreNestedProjectFile(bool ignoreFlag)
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
parent.NestedProjectNodeReloader.IgnoreItemChanges(this.GetMkDocument(), ignoreFlag);
}
/// <summary>
/// We need to advise property notify sink on project properties so that
/// we know when the project file is renamed through a property.
/// </summary>
private void ConnectPropertyNotifySink()
{
if (this.projectPropertyNotifySinkCookie != (uint)ShellConstants.VSCOOKIE_NIL)
{
return;
}
IConnectionPoint connectionPoint = this.GetConnectionPointFromPropertySink();
if (connectionPoint != null)
{
connectionPoint.Advise(this, out this.projectPropertyNotifySinkCookie);
}
}
/// <summary>
/// Disconnects the propertynotify sink
/// </summary>
private void DisconnectPropertyNotifySink()
{
if (this.projectPropertyNotifySinkCookie == (uint)ShellConstants.VSCOOKIE_NIL)
{
return;
}
IConnectionPoint connectionPoint = this.GetConnectionPointFromPropertySink();
if (connectionPoint != null)
{
connectionPoint.Unadvise(this.projectPropertyNotifySinkCookie);
this.projectPropertyNotifySinkCookie = (uint)ShellConstants.VSCOOKIE_NIL;
}
}
/// <summary>
/// Gets a ConnectionPoint for the IPropertyNotifySink interface.
/// </summary>
/// <returns></returns>
private IConnectionPoint GetConnectionPointFromPropertySink()
{
IConnectionPoint connectionPoint = null;
object browseObject = this.GetProperty((int)__VSHPROPID.VSHPROPID_BrowseObject);
IConnectionPointContainer connectionPointContainer = browseObject as IConnectionPointContainer;
if (connectionPointContainer != null)
{
Guid guid = typeof(IPropertyNotifySink).GUID;
connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint);
}
return connectionPoint;
}
#endregion
}
}
| |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThisToThat;
namespace ThisToThatTests
{
[TestClass]
public class ToInt32Tests
{
/*
SByte to Int32: Test omitted
There is a predefined implicit conversion from SByte to Int32
*/
/*
Byte to Int32: Test omitted
There is a predefined implicit conversion from Byte to Int32
*/
/*
Int16 to Int32: Test omitted
There is a predefined implicit conversion from Int16 to Int32
*/
/*
UInt16 to Int32: Test omitted
There is a predefined implicit conversion from UInt16 to Int32
*/
/// <summary>
/// Makes multiple UInt32 to Int32 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestUInt32ToInt32OrDefault()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Int32? result = source.ToInt32OrDefault(86);
Assert.AreEqual(0, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt32OrDefault(86);
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt32OrDefault(86);
// Here we would expect this conversion to fail (and return the default value of 86),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (2147483647).
Assert.AreEqual(86, result);
Assert.IsInstanceOfType(result, typeof(Int32));
}
/// <summary>
/// Makes multiple UInt32 to nullable Int32 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestUInt32ToInt32Nullable()
{
// Test conversion of source type minimum value
UInt32 source = UInt32.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
Int32? result = source.ToInt32Nullable();
Assert.AreEqual(0, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type value 42 to target type
source = 42u;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt32Nullable();
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = UInt32.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt32));
result = source.ToInt32Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (4294967295) is greater than the target type's maximum value (2147483647).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple Int64 to Int32 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestInt64ToInt32OrDefault()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Int32? result = source.ToInt32OrDefault(86);
// Here we would expect this conversion to fail (and return the default value of 86),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-2147483648).
Assert.AreEqual(86, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt32OrDefault(86);
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt32OrDefault(86);
// Here we would expect this conversion to fail (and return the default value of 86),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (2147483647).
Assert.AreEqual(86, result);
Assert.IsInstanceOfType(result, typeof(Int32));
}
/// <summary>
/// Makes multiple Int64 to nullable Int32 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestInt64ToInt32Nullable()
{
// Test conversion of source type minimum value
Int64 source = Int64.MinValue;
Assert.IsInstanceOfType(source, typeof(Int64));
Int32? result = source.ToInt32Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-2147483648).
Assert.IsNull(result);
// Test conversion of source type value 42 to target type
source = 42L;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt32Nullable();
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = Int64.MaxValue;
Assert.IsInstanceOfType(source, typeof(Int64));
result = source.ToInt32Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (2147483647).
Assert.IsNull(result);
}
/// <summary>
/// Makes multiple UInt64 to Int32 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestUInt64ToInt32OrDefault()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Int32? result = source.ToInt32OrDefault(86);
Assert.AreEqual(0, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt32OrDefault(86);
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt32OrDefault(86);
// Here we would expect this conversion to fail (and return the default value of 86),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (2147483647).
Assert.AreEqual(86, result);
Assert.IsInstanceOfType(result, typeof(Int32));
}
/// <summary>
/// Makes multiple UInt64 to nullable Int32 conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestUInt64ToInt32Nullable()
{
// Test conversion of source type minimum value
UInt64 source = UInt64.MinValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
Int32? result = source.ToInt32Nullable();
Assert.AreEqual(0, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type value 42 to target type
source = 42UL;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt32Nullable();
Assert.AreEqual(42, result);
Assert.IsInstanceOfType(result, typeof(Int32));
// Test conversion of source type maximum value
source = UInt64.MaxValue;
Assert.IsInstanceOfType(source, typeof(UInt64));
result = source.ToInt32Nullable();
// Here we would expect this conversion to fail (and return null),
// since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (2147483647).
Assert.IsNull(result);
}
/*
Single to Int32: Method omitted.
Int32 is an integral type. Single is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Double to Int32: Method omitted.
Int32 is an integral type. Double is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Decimal to Int32: Method omitted.
Int32 is an integral type. Decimal is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/// <summary>
/// Makes multiple String to Int32 or default conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestStringToInt32OrDefault()
{
// Test conversion of target type minimum value
Int32 resultMin = "-2147483648".ToInt32OrDefault();
Assert.AreEqual(-2147483648, resultMin);
// Test conversion of fixed value (42)
Int32 result42 = "42".ToInt32OrDefault();
Assert.AreEqual(42, result42);
// Test conversion of target type maximum value
Int32 resultMax = "2147483647".ToInt32OrDefault();
Assert.AreEqual(2147483647, resultMax);
// Test conversion of "foo"
Int32 resultFoo = "foo".ToInt32OrDefault(86);
Assert.AreEqual(86, resultFoo);
}
/// <summary>
/// Makes multiple String to Int32Nullable conversions and asserts that the results are correct.
/// </summary>
[TestMethod, TestCategory("ToInt32 tests")]
public void TestStringToInt32Nullable()
{
// Test conversion of target type minimum value
Int32? resultMin = "-2147483648".ToInt32Nullable();
Assert.AreEqual(-2147483648, resultMin);
// Test conversion of fixed value (42)
Int32? result42 = "42".ToInt32Nullable();
Assert.AreEqual(42, result42);
// Test conversion of target type maximum value
Int32? resultMax = "2147483647".ToInt32Nullable();
Assert.AreEqual(2147483647, resultMax);
// Test conversion of "foo"
Int32? resultFoo = "foo".ToInt32Nullable();
Assert.IsNull(resultFoo);
}
}
}
| |
// <copyright file="ObservableListCapturedItemsUnitTests.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Collections.Specialized;
using IX.Observable;
using Xunit;
using EnvironmentSettings = IX.StandardExtensions.ComponentModel.EnvironmentSettings;
namespace IX.UnitTests.IX.Observable
{
/// <summary>
/// Captured items test for ObservableList.
/// </summary>
public class ObservableListCapturedItemsUnitTests
{
/// <summary>
/// ObservableList captured item undo/redo.
/// </summary>
[Fact(DisplayName = "ObservableList captured item undo/redo")]
public void UnitTest1()
{
// ARRANGE
using (var item1 = new CapturedItem())
{
using (var list = new ObservableList<CapturedItem>
{
AutomaticallyCaptureSubItems = true,
})
{
// ACT
list.Add(item1);
item1.TestProperty = "aaa";
item1.TestProperty = "bbb";
item1.TestProperty = "ccc";
list.Undo();
// ASSERT
Assert.Equal(
"bbb",
item1.TestProperty);
}
}
}
/// <summary>
/// ObservableList non-captured item undo/redo.
/// </summary>
[Fact(DisplayName = "ObservableList non-captured item undo/redo")]
public void UnitTest2()
{
// ARRANGE
using (var item1 = new CapturedItem())
{
using (var list = new ObservableList<CapturedItem>
{
AutomaticallyCaptureSubItems = false,
})
{
// ACT
list.Add(item1);
item1.TestProperty = "aaa";
item1.TestProperty = "bbb";
item1.TestProperty = "ccc";
list.Undo();
// ASSERT
Assert.Equal(
"ccc",
item1.TestProperty);
Assert.Empty(list);
}
}
}
/// <summary>
/// ObservableList captured item undo/redo and further use.
/// </summary>
[Fact(DisplayName = "ObservableList captured item undo/redo and further use")]
public void UnitTest3()
{
// ARRANGE
EnvironmentSettings.AlwaysSuppressCurrentSynchronizationContext = true;
using (var list = new ObservableList<CapturedItem>
{
new CapturedItem { TestProperty = "1" },
new CapturedItem { TestProperty = "2" },
new CapturedItem { TestProperty = "3" },
new CapturedItem { TestProperty = "4" },
new CapturedItem { TestProperty = "5" },
})
{
list.AutomaticallyCaptureSubItems = true;
var cca = NotifyCollectionChangedAction.Add;
list.CollectionChanged += (
sender,
e) => Assert.Equal(
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line - R# warning
// ReSharper disable once AccessToModifiedClosure - That's the point of the test
cca,
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
e.Action);
// ACT
list.AddRange(
new[]
{
new CapturedItem { TestProperty = "6" },
new CapturedItem { TestProperty = "7" },
new CapturedItem { TestProperty = "8" },
new CapturedItem { TestProperty = "9" },
});
// ASSERT
cca = NotifyCollectionChangedAction.Remove;
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
cca = NotifyCollectionChangedAction.Add;
list.Redo();
Assert.Equal(
9,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "6");
Assert.True(list[6].TestProperty == "7");
Assert.True(list[7].TestProperty == "8");
Assert.True(list[8].TestProperty == "9");
cca = NotifyCollectionChangedAction.Remove;
list.RemoveAt(6);
Assert.Equal(
8,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "6");
Assert.True(list[6].TestProperty == "8");
Assert.True(list[7].TestProperty == "9");
list[7].TestProperty = "10";
Assert.True(list[7].TestProperty == "10");
// No collection changed here
list.Undo();
Assert.Equal(
8,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "6");
Assert.True(list[6].TestProperty == "8");
Assert.True(list[7].TestProperty == "9");
cca = NotifyCollectionChangedAction.Remove;
list.RemoveRange(
2,
4);
Assert.Equal(
4,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "8");
Assert.True(list[3].TestProperty == "9");
cca = NotifyCollectionChangedAction.Reset;
list.Undo();
Assert.Equal(
8,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "6");
Assert.True(list[6].TestProperty == "8");
Assert.True(list[7].TestProperty == "9");
cca = NotifyCollectionChangedAction.Add;
CapturedItem[] items =
{
new CapturedItem { TestProperty = "a" },
new CapturedItem { TestProperty = "b" },
};
list.InsertRange(
5,
items);
Assert.Equal(
10,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "a");
Assert.True(list[6].TestProperty == "b");
Assert.True(list[7].TestProperty == "6");
Assert.True(list[8].TestProperty == "8");
Assert.True(list[9].TestProperty == "9");
cca = NotifyCollectionChangedAction.Remove;
list.Undo();
Assert.Equal(
8,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "6");
Assert.True(list[6].TestProperty == "8");
Assert.True(list[7].TestProperty == "9");
cca = NotifyCollectionChangedAction.Add;
list.Redo();
Assert.Equal(
10,
list.Count);
Assert.True(list[0].TestProperty == "1");
Assert.True(list[1].TestProperty == "2");
Assert.True(list[2].TestProperty == "3");
Assert.True(list[3].TestProperty == "4");
Assert.True(list[4].TestProperty == "5");
Assert.True(list[5].TestProperty == "a");
Assert.True(list[6].TestProperty == "b");
Assert.True(list[7].TestProperty == "6");
Assert.True(list[8].TestProperty == "8");
Assert.True(list[9].TestProperty == "9");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// String.TrimEnd(char[])
/// </summary>
public class StringTrim3
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
// U+200B stops being trimmable http://msdn2.microsoft.com/en-us/library/t97s7bs3.aspx
// U+FEFF has been deprecate as a trimmable space
private string[] spaceStrings = new string[]{"\u0009","\u000A","\u000B","\u000C","\u000D","\u0020",
"\u00A0","\u2000","\u2001","\u2002","\u2003","\u2004","\u2005",
"\u2006","\u2007","\u2008","\u2009","\u200A","\u3000"};
public static int Main()
{
StringTrim3 st3 = new StringTrim3();
TestLibrary.TestFramework.BeginTestCase("StringTrim3");
if (st3.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region PostiveTesting
public bool PosTest1()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest1: empty string trimEnd char[]");
try
{
strA = string.Empty;
charA = new char[] { TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55) };
ActualResult = strA.TrimEnd(charA);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("001", "empty string trimEnd char[] ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest2:normal string trimStart char[] one");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
char char1 = this.GetChar(0, c_MINI_STRING_LENGTH);
char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68);
char char3 = this.GetChar(c_MINI_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2);
char charEnd = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH);
charA = new char[] { char1, char2, char3 };
string strA1 = char1.ToString() + char3.ToString() + strA + charEnd.ToString() + char1.ToString() + char3.ToString();
ActualResult = strA1.TrimEnd(charA);
if (ActualResult.ToString() != char1.ToString() + char3.ToString() + strA.ToString() + charEnd.ToString())
{
TestLibrary.TestFramework.LogError("003", "normal string trimEnd char[] one ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest3:normal string trimEnd char[] two");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
char char1 = this.GetChar(0, c_MINI_STRING_LENGTH);
char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68);
char char3 = this.GetChar(c_MAX_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2);
char charStart = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH);
charA = new char[] { char1, char2, char3 };
string strA1 = char1.ToString() + char3.ToString() + charStart.ToString() + strA + char2.ToString() + charStart.ToString() + char1.ToString() + char3.ToString();
ActualResult = strA1.TrimEnd(charA);
if (ActualResult.ToString() != char1.ToString() + char3.ToString() + charStart.ToString() + strA + char2.ToString() + charStart.ToString())
{
TestLibrary.TestFramework.LogError("005", "normal string trimEnd char[] two ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest4:normal string trimEnd char[] three");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
charA = new char[0];
string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)];
string strA1 = strB + "H" + strA + "D" + strB;
ActualResult = strA1.TrimEnd(charA);
if (ActualResult.ToString() != strB + "H" + strA + "D")
{
TestLibrary.TestFramework.LogError("007", "normal string trimEnd char[] three ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest5:normal string trimEnd char[] four");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
charA = new char[0];
string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)];
string strA1 = strB + "H" + strB + strA + "D" + strB;
ActualResult = strA1.TrimEnd(charA);
if (ActualResult.ToString() != strB + "H" + strB + strA + "D")
{
TestLibrary.TestFramework.LogError("009", "normal string trimEnd char[] four ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help method for geting test data
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Char GetChar(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return Convert.ToChar(minValue);
}
if (minValue < maxValue)
{
return Convert.ToChar(Convert.ToInt32(TestLibrary.Generator.GetChar(-55)) % (maxValue - minValue) + minValue);
}
}
catch
{
throw;
}
return Convert.ToChar(minValue);
}
private string GetString(bool ValidPath, Int32 minValue, Int32 maxValue)
{
StringBuilder sVal = new StringBuilder();
string s;
if (0 == minValue && 0 == maxValue) return String.Empty;
if (minValue > maxValue) return null;
if (ValidPath)
{
return TestLibrary.Generator.GetString(-55, ValidPath, minValue, maxValue);
}
else
{
int length = this.GetInt32(minValue, maxValue);
for (int i = 0; length > i; i++)
{
char c = this.GetChar(minValue, maxValue);
sVal.Append(c);
}
s = sVal.ToString();
return s;
}
}
#endregion
}
| |
/*
*
* (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.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using ASC.Common.Logging;
using ASC.CRM.Core;
using ASC.CRM.Core.Dao;
using ASC.Web.CRM.Core;
using Autofac;
namespace ASC.Web.CRM.Classes
{
public static class CurrencyProvider
{
#region Members
private static readonly ILog _log = LogManager.GetLogger("ASC");
private static readonly object _syncRoot = new object();
private static readonly Dictionary<String, CurrencyInfo> _currencies;
private static Dictionary<String, Decimal> _exchangeRates;
private static DateTime _publisherDate;
private const String _formatDate = "yyyy-MM-ddTHH:mm:ss.fffffffK";
#endregion
#region Constructor
static CurrencyProvider()
{
using (var scope = DIHelper.Resolve())
{
var daoFactory = scope.Resolve<DaoFactory>();
var currencies = daoFactory.CurrencyInfoDao.GetAll();
if (currencies == null || currencies.Count == 0)
{
currencies = new List<CurrencyInfo>
{
new CurrencyInfo("Currency_UnitedStatesDollar", "USD", "$", "US", true, true)
};
}
_currencies = currencies.ToDictionary(c => c.Abbreviation);
}
}
#endregion
#region Property
public static DateTime GetPublisherDate
{
get
{
TryToReadPublisherDate(GetExchangesTempPath());
return _publisherDate;
}
}
#endregion
#region Public Methods
public static CurrencyInfo Get(string currencyAbbreviation)
{
if (!_currencies.ContainsKey(currencyAbbreviation))
return null;
return _currencies[currencyAbbreviation];
}
public static List<CurrencyInfo> GetAll()
{
return _currencies.Values.OrderBy(v => v.Abbreviation).ToList();
}
public static List<CurrencyInfo> GetBasic()
{
return _currencies.Values.Where(c => c.IsBasic).OrderBy(v => v.Abbreviation).ToList();
}
public static List<CurrencyInfo> GetOther()
{
return _currencies.Values.Where(c => !c.IsBasic).OrderBy(v => v.Abbreviation).ToList();
}
public static Dictionary<CurrencyInfo, Decimal> MoneyConvert(CurrencyInfo baseCurrency)
{
if (baseCurrency == null) throw new ArgumentNullException("baseCurrency");
if (!_currencies.ContainsKey(baseCurrency.Abbreviation)) throw new ArgumentOutOfRangeException("baseCurrency", "Not found.");
var result = new Dictionary<CurrencyInfo, Decimal>();
var rates = GetExchangeRates();
foreach (var ci in GetAll())
{
if (baseCurrency.Title == ci.Title)
{
result.Add(ci, 1);
continue;
}
var key = String.Format("{1}/{0}", baseCurrency.Abbreviation, ci.Abbreviation);
if (!rates.ContainsKey(key))
continue;
result.Add(ci, rates[key]);
}
return result;
}
public static bool IsConvertable(String abbreviation)
{
var findedItem = _currencies.Keys.ToList().Find(item => String.Compare(abbreviation, item) == 0);
if (findedItem == null)
throw new ArgumentException(abbreviation);
return _currencies[findedItem].IsConvertable;
}
public static Decimal MoneyConvert(decimal amount, string from, string to)
{
if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to) || string.Compare(from, to, true) == 0) return amount;
var rates = GetExchangeRates();
if (from.Contains('-')) from = new RegionInfo(from).ISOCurrencySymbol;
if (to.Contains('-')) to = new RegionInfo(to).ISOCurrencySymbol;
var key = string.Format("{0}/{1}", to, from);
return Math.Round(rates[key] * amount, 4, MidpointRounding.AwayFromZero);
}
public static Decimal MoneyConvertToDefaultCurrency(decimal amount, string from)
{
return MoneyConvert(amount, from, Global.TenantSettings.DefaultCurrency.Abbreviation);
}
#endregion
#region Private Methods
private static bool ObsoleteData()
{
return _exchangeRates == null || (DateTime.UtcNow.Date.Subtract(_publisherDate.Date).Days > 0);
}
private static string GetExchangesTempPath()
{
var assembly = Assembly.GetExecutingAssembly();
var companyAttribute = assembly?.GetCustomAttribute<AssemblyCompanyAttribute>();
return Path.Combine(TempPath.GetTempPath(), companyAttribute?.Company ?? string.Empty, "exchanges");
}
private static readonly Regex CurRateRegex = new Regex("<td id=\"(?<Currency>[a-zA-Z]{3})\">(?<Rate>[\\d\\.]+)</td>");
private static Dictionary<String, Decimal> GetExchangeRates()
{
if (ObsoleteData())
{
lock (_syncRoot)
{
if (ObsoleteData())
{
try
{
_exchangeRates = new Dictionary<string, decimal>();
var tmppath = GetExchangesTempPath();
TryToReadPublisherDate(tmppath);
var updateEnable = ConfigurationManagerExtension.AppSettings["crm.update.currency.info.enable"] != "false";
var ratesUpdatedFlag = false;
foreach (var ci in _currencies.Values.Where(c => c.IsConvertable))
{
var filepath = Path.Combine(tmppath, ci.Abbreviation + ".html");
if (updateEnable && 0 < (DateTime.UtcNow.Date - _publisherDate.Date).TotalDays || !File.Exists(filepath))
{
var filepath_temp = Path.Combine(tmppath, ci.Abbreviation + "_temp.html");
DownloadCurrencyPage(ci.Abbreviation, filepath_temp);
if (File.Exists(filepath_temp))
{
if (TryGetRatesFromFile(filepath_temp, ci))
{
ratesUpdatedFlag = true;
File.Copy(filepath_temp, filepath, true);
}
File.Delete(filepath_temp);
continue;
}
}
if (File.Exists(filepath) && TryGetRatesFromFile(filepath, ci))
{
ratesUpdatedFlag = true;
}
}
if (ratesUpdatedFlag)
{
_publisherDate = DateTime.UtcNow;
WritePublisherDate(tmppath);
}
}
catch (Exception error)
{
LogManager.GetLogger("ASC.CRM").Error(error);
_publisherDate = DateTime.UtcNow;
}
}
}
}
return _exchangeRates;
}
private static bool TryGetRatesFromFile(string filepath, CurrencyInfo curCI)
{
var success = false;
var currencyLines = File.ReadAllLines(filepath);
for (var i = 0; i < currencyLines.Length; i++)
{
var line = currencyLines[i];
if (line.Contains("id=\"major-currency-table\"") || line.Contains("id=\"minor-currency-table\"") || line.Contains("id=\"exotic-currency-table\""))
{
var currencyInfos = CurRateRegex.Matches(line);
if (currencyInfos.Count > 0)
{
foreach (var curInfo in currencyInfos)
{
_exchangeRates.Add(
String.Format("{0}/{1}", (curInfo as Match).Groups["Currency"].Value.Trim(), curCI.Abbreviation),
Convert.ToDecimal((curInfo as Match).Groups["Rate"].Value.Trim(), CultureInfo.InvariantCulture.NumberFormat));
success = true;
}
}
}
}
return success;
}
private static void TryToReadPublisherDate(string tmppath)
{
if (_publisherDate == default(DateTime))
{
try
{
var timefile = Path.Combine(tmppath, "last.time");
if (File.Exists(timefile))
{
var dateFromFile = File.ReadAllText(timefile);
_publisherDate = DateTime.ParseExact(dateFromFile, _formatDate, null);
}
}
catch (Exception err)
{
LogManager.GetLogger("ASC.CRM").Error(err);
}
}
}
private static void WritePublisherDate(string tmppath)
{
try
{
var timefile = Path.Combine(tmppath, "last.time");
File.WriteAllText(timefile, _publisherDate.ToString(_formatDate));
}
catch (Exception err)
{
LogManager.GetLogger("ASC.CRM").Error(err);
}
}
private static void DownloadCurrencyPage(string currency, string filepath)
{
try
{
var dir = Path.GetDirectoryName(filepath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var destinationURI = new Uri(string.Format("https://themoneyconverter.com/{0}/{0}", currency));
var request = (HttpWebRequest)WebRequest.Create(destinationURI);
request.Method = "GET";
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 2;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0";
request.UseDefaultCredentials = true;
using (var response = (HttpWebResponse)request.GetResponse())
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
var data = responseStream.ReadToEnd();
File.WriteAllText(filepath, data);
}
System.Threading.Thread.Sleep(100); // limit 10 requests per second
}
catch (Exception error)
{
_log.Error(error);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace SignalR.MongoRabbit.Example.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Tools.Test.Utilities;
using System;
using System.IO;
using System.Linq;
using Xunit;
namespace Microsoft.DotNet.Cli.Sln.Remove.Tests
{
public class GivenDotnetSlnRemove : TestBase
{
private const string HelpText = @".NET Remove project(s) from a solution file Command
Usage: dotnet sln <SLN_FILE> remove [options] <args>
Arguments:
<SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one.
<args> Remove the specified project(s) from the solution. The project is not impacted.
Options:
-h, --help Show help information.
";
private const string SlnCommandHelpText = @".NET modify solution file command
Usage: dotnet sln [options] <SLN_FILE> [command]
Arguments:
<SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
Commands:
add <args> .NET Add project(s) to a solution file Command
list .NET List project(s) in a solution file Command
remove <args> .NET Remove project(s) from a solution file Command
";
private const string ExpectedSlnContentsAfterRemove = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
EndGlobalSection
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveAllProjects = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Global
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveNestedProj = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""src"", ""src"", ""{7B86CE74-F620-4B32-99FE-82D40F8D6BF2}""
EndProject
Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""Lib"", ""Lib"", ""{EAB71280-AF32-4531-8703-43CDBA261AA3}""
EndProject
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Lib"", ""src\Lib\Lib.csproj"", ""{84A45D44-B677-492D-A6DA-B3A71135AB8E}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x64.ActiveCfg = Debug|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x64.Build.0 = Debug|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x86.ActiveCfg = Debug|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x86.Build.0 = Debug|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|Any CPU.Build.0 = Release|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x64.ActiveCfg = Release|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x64.Build.0 = Release|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x86.ActiveCfg = Release|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{EAB71280-AF32-4531-8703-43CDBA261AA3} = {7B86CE74-F620-4B32-99FE-82D40F8D6BF2}
{84A45D44-B677-492D-A6DA-B3A71135AB8E} = {EAB71280-AF32-4531-8703-43CDBA261AA3}
EndGlobalSection
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveLastNestedProj = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
EndGlobalSection
EndGlobal
";
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln remove {helpArg}");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput("sln one.sln two.sln three.sln remove");
cmd.Should().Fail();
cmd.StdErr.Should().BeVisuallyEquivalentTo("Unrecognized command or argument 'two.sln'\r\nUnrecognized command or argument 'three.sln'\r\nYou must specify at least one project to remove.");
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Required command was not provided.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(SlnCommandHelpText);
}
[Theory]
[InlineData("idontexist.sln")]
[InlineData("ihave?invalidcharacters")]
[InlineData("ihaveinv@lidcharacters")]
[InlineData("ihaveinvalid/characters")]
[InlineData("ihaveinvalidchar\\acters")]
public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln {solutionName} remove p.csproj");
cmd.Should().Fail();
cmd.StdErr.Should().Be($"Could not find solution or directory `{solutionName}`.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("InvalidSolution")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln InvalidSolution.sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Invalid solution `InvalidSolution.sln`. Expected file header not found.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("InvalidSolution")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "InvalidSolution.sln");
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be($"Invalid solution `{solutionPath}`. Expected file header not found.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenNoProjectIsPassedItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput(@"sln App.sln remove");
cmd.Should().Fail();
cmd.StdErr.Should().Be("You must specify at least one project to remove.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App");
var cmd = new DotnetCommand()
.WithWorkingDirectory(solutionPath)
.ExecuteWithCapturedOutput(@"sln remove App.csproj");
cmd.Should().Fail();
cmd.StdErr.Should().Be($"Specified solution file {solutionPath + Path.DirectorySeparatorChar} does not exist, or there is no solution file in the directory.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithMultipleSlnFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be($"Found more than one solution file in {projectDirectory + Path.DirectorySeparatorChar}. Please specify which one to use.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenPassedAReferenceNotInSlnItPrintsStatus()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var contentBefore = File.ReadAllText(solutionPath);
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput("sln remove referenceDoesNotExistInSln.csproj");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project reference `referenceDoesNotExistInSln.csproj` could not be found.");
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedAReferenceItRemovesTheReferenceButNotOtherReferences()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{projectToRemove}` removed.");
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenDuplicateReferencesArePresentItRemovesThemAll()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndDuplicateProjectReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(3);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
string outputText = $@"Project reference `{projectToRemove}` removed.
Project reference `{projectToRemove}` removed.";
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenPassedMultipleReferencesAndOneOfThemDoesNotExistItRemovesTheOneThatExists()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove idontexist.csproj {projectToRemove} idontexisteither.csproj");
cmd.Should().Pass();
string outputText = $@"Project reference `idontexist.csproj` could not be found.
Project reference `{projectToRemove}` removed.
Project reference `idontexisteither.csproj` could not be found.";
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenReferenceIsRemovedBuildConfigsAreAlsoRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemove);
}
[Fact]
public void WhenReferenceIsRemovedSlnBuilds()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.Execute($"restore App.sln")
.Should().Pass();
new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.Execute("build App.sln --configuration Release")
.Should().Pass();
var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file";
var releaseDirectory = Directory.EnumerateDirectories(
Path.Combine(projectDirectory, "App", "bin"),
"Release",
SearchOption.AllDirectories);
releaseDirectory.Count().Should().Be(1, $"App {reasonString}");
Directory.EnumerateFiles(releaseDirectory.Single(), "App.dll", SearchOption.AllDirectories)
.Count().Should().Be(1, $"App {reasonString}");
}
[Fact]
public void WhenFinalReferenceIsRemovedEmptySectionsAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var appPath = Path.Combine("App", "App.csproj");
var libPath = Path.Combine("Lib", "Lib.csproj");
var projectsToRemove = $"{libPath} {appPath}";
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectsToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveAllProjects);
}
[Fact]
public void WhenNestedProjectIsRemovedItsSolutionFoldersAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojInSubDirToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var projectToRemove = Path.Combine("src", "NotLastProjInSrc", "NotLastProjInSrc.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveNestedProj);
}
[Fact]
public void WhenFinalNestedProjectIsRemovedSolutionFoldersAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndLastCsprojInSubDirToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var projectToRemove = Path.Combine("src", "Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveLastNestedProj);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
/*<bind>*/await M2()/*</bind>*/;
}
static Task M2() => null;
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: System.Void) (Syntax: 'await M2()')
Expression:
IInvocationOperation (System.Threading.Tasks.Task C.M2()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_ParameterReference()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M(Task t)
{
/*<bind>*/await t/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: System.Void) (Syntax: 'await t')
Expression:
IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Threading.Tasks.Task) (Syntax: 't')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_InLambda()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(Task<int> t)
{
Func<Task> f = async () => /*<bind>*/await t/*</bind>*/;
await f();
}
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await t')
Expression:
IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Threading.Tasks.Task<System.Int32>) (Syntax: 't')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_ErrorArgument()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M()
{
/*<bind>*/await UndefinedTask/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: ?, IsInvalid) (Syntax: 'await UndefinedTask')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'UndefinedTask')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'UndefinedTask' does not exist in the current context
// /*<bind>*/await UndefinedTask/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "UndefinedTask").WithArguments("UndefinedTask").WithLocation(9, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_ValueArgument()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int i)
{
/*<bind>*/await i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: ?, IsInvalid) (Syntax: 'await i')
Expression:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'int' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/await i/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "await i").WithArguments("int", "GetAwaiter").WithLocation(9, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_MissingArgument()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M()
{
/*<bind>*/await /*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAwaitOperation (OperationKind.Await, Type: ?, IsInvalid) (Syntax: 'await /*</bind>*/')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ';'
// /*<bind>*/await /*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(9, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<AwaitExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestAwaitExpression_NonAsyncMethod()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static void M(Task<int> t)
{
/*<bind>*/await t;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'await t;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'await t')
Declarators:
IVariableDeclaratorOperation (Symbol: await t) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 't')
Initializer:
null
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0246: The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/await t;/*</bind>*/
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "await").WithArguments("await").WithLocation(9, 19),
// CS0136: A local or parameter named 't' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/await t;/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "t").WithArguments("t").WithLocation(9, 25),
// CS0168: The variable 't' is declared but never used
// /*<bind>*/await t;/*</bind>*/
Diagnostic(ErrorCode.WRN_UnreferencedVar, "t").WithArguments("t").WithLocation(9, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AwaitFlow_01()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
/*<bind>*/{
await M2();
}/*</bind>*/
static Task M2() => null;
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'await M2();')
Expression:
IAwaitOperation (OperationKind.Await, Type: System.Void) (Syntax: 'await M2()')
Expression:
IInvocationOperation (System.Threading.Tasks.Task C.M2()) (OperationKind.Invocation, Type: System.Threading.Tasks.Task) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AwaitFlow_02()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M(bool b, int i)
/*<bind>*/{
i = b ? await M2(2) : await M2(3);
}/*</bind>*/
static Task<int> M2(int i) => Task.FromResult<int>(i);
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'await M2(2)')
Value:
IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await M2(2)')
Expression:
IInvocationOperation (System.Threading.Tasks.Task<System.Int32> C.M2(System.Int32 i)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task<System.Int32>) (Syntax: 'M2(2)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'await M2(3)')
Value:
IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await M2(3)')
Expression:
IInvocationOperation (System.Threading.Tasks.Task<System.Int32> C.M2(System.Int32 i)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task<System.Int32>) (Syntax: 'M2(3)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = b ? awa ... wait M2(3);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = b ? awa ... await M2(3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? await M ... await M2(3)')
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AwaitFlow_03()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M(bool b, int i)
/*<bind>*/{
i = await M2(b ? 2 : 3);
}/*</bind>*/
static Task<int> M2(int i) => Task.FromResult<int>(i);
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = await M2(b ? 2 : 3);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = await M2(b ? 2 : 3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IAwaitOperation (OperationKind.Await, Type: System.Int32) (Syntax: 'await M2(b ? 2 : 3)')
Expression:
IInvocationOperation (System.Threading.Tasks.Task<System.Int32> C.M2(System.Int32 i)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task<System.Int32>) (Syntax: 'M2(b ? 2 : 3)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'b ? 2 : 3')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="H06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H07_RegionObjects"/> of type <see cref="H07_RegionColl"/> (1:M relation to <see cref="H08_Region"/>)<br/>
/// This class is an item of <see cref="H05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class H06_Country : BusinessBase<H06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H07_Country_Child> H07_Country_SingleObjectProperty = RegisterProperty<H07_Country_Child>(p => p.H07_Country_SingleObject, "H07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Country Single Object ("self load" child property).
/// </summary>
/// <value>The H07 Country Single Object.</value>
public H07_Country_Child H07_Country_SingleObject
{
get { return GetProperty(H07_Country_SingleObjectProperty); }
private set { LoadProperty(H07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H07_Country_ReChild> H07_Country_ASingleObjectProperty = RegisterProperty<H07_Country_ReChild>(p => p.H07_Country_ASingleObject, "H07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Country ASingle Object ("self load" child property).
/// </summary>
/// <value>The H07 Country ASingle Object.</value>
public H07_Country_ReChild H07_Country_ASingleObject
{
get { return GetProperty(H07_Country_ASingleObjectProperty); }
private set { LoadProperty(H07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<H07_RegionColl> H07_RegionObjectsProperty = RegisterProperty<H07_RegionColl>(p => p.H07_RegionObjects, "H07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Region Objects ("self load" child property).
/// </summary>
/// <value>The H07 Region Objects.</value>
public H07_RegionColl H07_RegionObjects
{
get { return GetProperty(H07_RegionObjectsProperty); }
private set { LoadProperty(H07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H06_Country"/> object.</returns>
internal static H06_Country NewH06_Country()
{
return DataPortal.CreateChild<H06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="H06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="H06_Country"/> object.</returns>
internal static H06_Country GetH06_Country(SafeDataReader dr)
{
H06_Country obj = new H06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H07_Country_SingleObjectProperty, DataPortal.CreateChild<H07_Country_Child>());
LoadProperty(H07_Country_ASingleObjectProperty, DataPortal.CreateChild<H07_Country_ReChild>());
LoadProperty(H07_RegionObjectsProperty, DataPortal.CreateChild<H07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID"));
LoadProperty(Country_NameProperty, dr.GetString("Country_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H07_Country_SingleObjectProperty, H07_Country_Child.GetH07_Country_Child(Country_ID));
LoadProperty(H07_Country_ASingleObjectProperty, H07_Country_ReChild.GetH07_Country_ReChild(Country_ID));
LoadProperty(H07_RegionObjectsProperty, H07_RegionColl.GetH07_RegionColl(Country_ID));
}
/// <summary>
/// Inserts a new <see cref="H06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteH06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(H07_Country_SingleObjectProperty, DataPortal.CreateChild<H07_Country_Child>());
LoadProperty(H07_Country_ASingleObjectProperty, DataPortal.CreateChild<H07_Country_ReChild>());
LoadProperty(H07_RegionObjectsProperty, DataPortal.CreateChild<H07_RegionColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.DataProtection
{
public unsafe class SecretTests
{
[Fact]
public void Ctor_ArraySegment_Default_Throws()
{
// Act & assert
ExceptionAssert.ThrowsArgument(
testCode: () => new Secret(default(ArraySegment<byte>)),
paramName: "array",
exceptionMessage: null);
}
[Fact]
public void Ctor_ArraySegment_Success()
{
// Arrange
var input = new ArraySegment<byte>(new byte[] { 0x10, 0x20, 0x30, 0x40, 0x50, 0x60 }, 1, 3);
// Act
var secret = new Secret(input);
input.Array[2] = 0xFF; // mutate original array - secret shouldn't be modified
// Assert - length
Assert.Equal(3, secret.Length);
// Assert - managed buffer
var outputSegment = new ArraySegment<byte>(new byte[7], 2, 3);
secret.WriteSecretIntoBuffer(outputSegment);
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputSegment.AsStandaloneArray());
// Assert - unmanaged buffer
var outputBuffer = new byte[3];
fixed (byte* pOutputBuffer = outputBuffer)
{
secret.WriteSecretIntoBuffer(pOutputBuffer, 3);
}
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputBuffer);
}
[Fact]
public void Ctor_Buffer_Success()
{
// Arrange
var input = new byte[] { 0x20, 0x30, 0x40 };
// Act
var secret = new Secret(input);
input[1] = 0xFF; // mutate original array - secret shouldn't be modified
// Assert - length
Assert.Equal(3, secret.Length);
// Assert - managed buffer
var outputSegment = new ArraySegment<byte>(new byte[7], 2, 3);
secret.WriteSecretIntoBuffer(outputSegment);
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputSegment.AsStandaloneArray());
// Assert - unmanaged buffer
var outputBuffer = new byte[3];
fixed (byte* pOutputBuffer = outputBuffer)
{
secret.WriteSecretIntoBuffer(pOutputBuffer, 3);
}
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputBuffer);
}
[Fact]
public void Ctor_Buffer_ZeroLength_Success()
{
// Act
var secret = new Secret(new byte[0]);
// Assert - none of these methods should throw
Assert.Equal(0, secret.Length);
secret.WriteSecretIntoBuffer(new ArraySegment<byte>(new byte[0]));
byte dummy;
secret.WriteSecretIntoBuffer(&dummy, 0);
}
[Fact]
public void Ctor_Pointer_WithNullPointer_ThrowsArgumentNull()
{
// Act & assert
ExceptionAssert.ThrowsArgumentNull(
testCode: () => new Secret(null, 0),
paramName: "secret");
}
[Fact]
public void Ctor_Pointer_WithNegativeLength_ThrowsArgumentOutOfRange()
{
// Act & assert
ExceptionAssert.ThrowsArgumentOutOfRange(
testCode: () =>
{
byte dummy;
new Secret(&dummy, -1);
},
paramName: "secretLength",
exceptionMessage: Resources.Common_ValueMustBeNonNegative);
}
[Fact]
public void Ctor_Pointer_ZeroLength_Success()
{
// Arrange
byte input;
// Act
var secret = new Secret(&input, 0);
// Assert - none of these methods should throw
Assert.Equal(0, secret.Length);
secret.WriteSecretIntoBuffer(new ArraySegment<byte>(new byte[0]));
byte dummy;
secret.WriteSecretIntoBuffer(&dummy, 0);
}
[Fact]
public void Ctor_Pointer_Success()
{
// Arrange
byte* input = stackalloc byte[3];
input[0] = 0x20;
input[1] = 0x30;
input[2] = 0x40;
// Act
var secret = new Secret(input, 3);
input[1] = 0xFF; // mutate original buffer - secret shouldn't be modified
// Assert - length
Assert.Equal(3, secret.Length);
// Assert - managed buffer
var outputSegment = new ArraySegment<byte>(new byte[7], 2, 3);
secret.WriteSecretIntoBuffer(outputSegment);
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputSegment.AsStandaloneArray());
// Assert - unmanaged buffer
var outputBuffer = new byte[3];
fixed (byte* pOutputBuffer = outputBuffer)
{
secret.WriteSecretIntoBuffer(pOutputBuffer, 3);
}
Assert.Equal(new byte[] { 0x20, 0x30, 0x40 }, outputBuffer);
}
[Fact]
public void Random_ZeroLength_Success()
{
// Act
var secret = Secret.Random(0);
// Assert
Assert.Equal(0, secret.Length);
}
[Fact]
public void Random_LengthIsMultipleOf16_Success()
{
// Act
var secret = Secret.Random(32);
// Assert
Assert.Equal(32, secret.Length);
Guid* pGuids = stackalloc Guid[2];
secret.WriteSecretIntoBuffer((byte*)pGuids, 32);
Assert.NotEqual(Guid.Empty, pGuids[0]);
Assert.NotEqual(Guid.Empty, pGuids[1]);
Assert.NotEqual(pGuids[0], pGuids[1]);
}
[Fact]
public void Random_LengthIsNotMultipleOf16_Success()
{
// Act
var secret = Secret.Random(31);
// Assert
Assert.Equal(31, secret.Length);
Guid* pGuids = stackalloc Guid[2];
secret.WriteSecretIntoBuffer((byte*)pGuids, 31);
Assert.NotEqual(Guid.Empty, pGuids[0]);
Assert.NotEqual(Guid.Empty, pGuids[1]);
Assert.NotEqual(pGuids[0], pGuids[1]);
Assert.Equal(0, ((byte*)pGuids)[31]); // last byte shouldn't have been overwritten
}
[Fact]
public void WriteSecretIntoBuffer_ArraySegment_IncorrectlySizedBuffer_Throws()
{
// Arrange
var secret = Secret.Random(16);
// Act & assert
ExceptionAssert.ThrowsArgument(
testCode: () => secret.WriteSecretIntoBuffer(new ArraySegment<byte>(new byte[100])),
paramName: "buffer",
exceptionMessage: Resources.FormatCommon_BufferIncorrectlySized(100, 16));
}
[Fact]
public void WriteSecretIntoBuffer_ArraySegment_Disposed_Throws()
{
// Arrange
var secret = Secret.Random(16);
secret.Dispose();
// Act & assert
Assert.Throws<ObjectDisposedException>(
testCode: () => secret.WriteSecretIntoBuffer(new ArraySegment<byte>(new byte[16])));
}
[Fact]
public void WriteSecretIntoBuffer_Pointer_NullBuffer_Throws()
{
// Arrange
var secret = Secret.Random(16);
// Act & assert
ExceptionAssert.ThrowsArgumentNull(
testCode: () => secret.WriteSecretIntoBuffer(null, 100),
paramName: "buffer");
}
[Fact]
public void WriteSecretIntoBuffer_Pointer_IncorrectlySizedBuffer_Throws()
{
// Arrange
var secret = Secret.Random(16);
// Act & assert
ExceptionAssert.ThrowsArgument(
testCode: () =>
{
byte* pBuffer = stackalloc byte[100];
secret.WriteSecretIntoBuffer(pBuffer, 100);
},
paramName: "bufferLength",
exceptionMessage: Resources.FormatCommon_BufferIncorrectlySized(100, 16));
}
[Fact]
public void WriteSecretIntoBuffer_Pointer_Disposed_Throws()
{
// Arrange
var secret = Secret.Random(16);
secret.Dispose();
// Act & assert
Assert.Throws<ObjectDisposedException>(
testCode: () =>
{
byte* pBuffer = stackalloc byte[16];
secret.WriteSecretIntoBuffer(pBuffer, 16);
});
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Capabilities;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Common;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.VisualStudio.Services.OAuth;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Services.Agent.Listener
{
[ServiceLocator(Default = typeof(MessageListener))]
public interface IMessageListener : IAgentService
{
Task<Boolean> CreateSessionAsync(CancellationToken token);
Task DeleteSessionAsync();
Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token);
Task DeleteMessageAsync(TaskAgentMessage message);
}
public sealed class MessageListener : AgentService, IMessageListener
{
private long? _lastMessageId;
private AgentSettings _settings;
private ITerminal _term;
private IAgentServer _agentServer;
private TaskAgentSession _session;
private TimeSpan _getNextMessageRetryInterval;
private readonly TimeSpan _sessionCreationRetryInterval = TimeSpan.FromSeconds(30);
private readonly TimeSpan _sessionConflictRetryLimit = TimeSpan.FromMinutes(4);
private readonly TimeSpan _clockSkewRetryLimit = TimeSpan.FromMinutes(30);
private readonly Dictionary<string, int> _sessionCreationExceptionTracker = new Dictionary<string, int>();
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_term = HostContext.GetService<ITerminal>();
_agentServer = HostContext.GetService<IAgentServer>();
}
public async Task<Boolean> CreateSessionAsync(CancellationToken token)
{
Trace.Entering();
// Settings
var configManager = HostContext.GetService<IConfigurationManager>();
_settings = configManager.LoadSettings();
var serverUrl = _settings.ServerUrl;
Trace.Info(_settings);
// Capabilities.
_term.WriteLine(StringUtil.Loc("ScanToolCapabilities"));
Dictionary<string, string> systemCapabilities = await HostContext.GetService<ICapabilitiesManager>().GetCapabilitiesAsync(_settings, token);
// Create connection.
Trace.Verbose("Loading Credentials");
var credMgr = HostContext.GetService<ICredentialManager>();
VssCredentials creds = credMgr.LoadCredentials();
Uri uri = new Uri(serverUrl);
VssConnection conn = VssUtil.CreateConnection(uri, creds);
var agent = new TaskAgentReference
{
Id = _settings.AgentId,
Name = _settings.AgentName,
Version = Constants.Agent.Version,
OSDescription = RuntimeInformation.OSDescription,
};
string sessionName = $"{Environment.MachineName ?? "AGENT"}";
var taskAgentSession = new TaskAgentSession(sessionName, agent, systemCapabilities);
string errorMessage = string.Empty;
bool encounteringError = false;
_term.WriteLine(StringUtil.Loc("ConnectToServer"));
while (true)
{
token.ThrowIfCancellationRequested();
Trace.Info($"Attempt to create session.");
try
{
Trace.Info("Connecting to the Agent Server...");
await _agentServer.ConnectAsync(conn);
_session = await _agentServer.CreateAgentSessionAsync(
_settings.PoolId,
taskAgentSession,
token);
Trace.Info($"Session created.");
if (encounteringError)
{
_term.WriteLine(StringUtil.Loc("QueueConnected", DateTime.UtcNow));
_sessionCreationExceptionTracker.Clear();
encounteringError = false;
}
return true;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info("Session creation has been cancelled.");
throw;
}
catch (Exception ex)
{
Trace.Error("Catch exception during create session.");
Trace.Error(ex);
if (!IsSessionCreationExceptionRetriable(ex))
{
_term.WriteError(StringUtil.Loc("SessionCreateFailed", ex.Message));
return false;
}
if (!encounteringError) //print the message only on the first error
{
_term.WriteError(StringUtil.Loc("QueueConError", DateTime.UtcNow, ex.Message, _sessionCreationRetryInterval.TotalSeconds));
encounteringError = true;
}
Trace.Info("Sleeping for {0} seconds before retrying.", _sessionCreationRetryInterval.TotalSeconds);
await HostContext.Delay(_sessionCreationRetryInterval, token);
}
}
}
public async Task DeleteSessionAsync()
{
if (_session != null && _session.SessionId != Guid.Empty)
{
using (var ts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
await _agentServer.DeleteAgentSessionAsync(_settings.PoolId, _session.SessionId, ts.Token);
}
}
}
public async Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token)
{
Trace.Entering();
ArgUtil.NotNull(_session, nameof(_session));
ArgUtil.NotNull(_settings, nameof(_settings));
bool encounteringError = false;
int continuousError = 0;
string errorMessage = string.Empty;
Stopwatch heartbeat = new Stopwatch();
heartbeat.Restart();
while (true)
{
token.ThrowIfCancellationRequested();
TaskAgentMessage message = null;
try
{
message = await _agentServer.GetAgentMessageAsync(_settings.PoolId,
_session.SessionId,
_lastMessageId,
token);
// Decrypt the message body if the session is using encryption
message = DecryptMessage(message);
if (message != null)
{
_lastMessageId = message.MessageId;
}
if (encounteringError) //print the message once only if there was an error
{
_term.WriteLine(StringUtil.Loc("QueueConnected", DateTime.UtcNow));
encounteringError = false;
continuousError = 0;
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info("Get next message has been cancelled.");
throw;
}
catch (Exception ex)
{
Trace.Error("Catch exception during get next message.");
Trace.Error(ex);
// don't retry if SkipSessionRecover = true, DT service will delete agent session to stop agent from taking more jobs.
if (ex is TaskAgentSessionExpiredException && !_settings.SkipSessionRecover && await CreateSessionAsync(token))
{
Trace.Info($"{nameof(TaskAgentSessionExpiredException)} received, recovered by recreate session.");
}
else if (!IsGetNextMessageExceptionRetriable(ex))
{
throw;
}
else
{
continuousError++;
//retry after a random backoff to avoid service throttling
//in case of there is a service error happened and all agents get kicked off of the long poll and all agent try to reconnect back at the same time.
if (continuousError <= 5)
{
// random backoff [15, 30]
_getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), _getNextMessageRetryInterval);
}
else
{
// more aggressive backoff [30, 60]
_getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), _getNextMessageRetryInterval);
}
if (!encounteringError)
{
//print error only on the first consecutive error
_term.WriteError(StringUtil.Loc("QueueConError", DateTime.UtcNow, ex.Message));
encounteringError = true;
}
Trace.Info("Sleeping for {0} seconds before retrying.", _getNextMessageRetryInterval.TotalSeconds);
await HostContext.Delay(_getNextMessageRetryInterval, token);
}
}
if (message == null)
{
if (heartbeat.Elapsed > TimeSpan.FromMinutes(30))
{
Trace.Info($"No message retrieved from session '{_session.SessionId}' within last 30 minutes.");
heartbeat.Restart();
}
else
{
Trace.Verbose($"No message retrieved from session '{_session.SessionId}'.");
}
continue;
}
Trace.Info($"Message '{message.MessageId}' received from session '{_session.SessionId}'.");
return message;
}
}
public async Task DeleteMessageAsync(TaskAgentMessage message)
{
Trace.Entering();
ArgUtil.NotNull(_session, nameof(_session));
if (message != null && _session.SessionId != Guid.Empty)
{
using (var cs = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
await _agentServer.DeleteAgentMessageAsync(_settings.PoolId, message.MessageId, _session.SessionId, cs.Token);
}
}
}
private TaskAgentMessage DecryptMessage(TaskAgentMessage message)
{
if (_session.EncryptionKey == null ||
_session.EncryptionKey.Value.Length == 0 ||
message == null ||
message.IV == null ||
message.IV.Length == 0)
{
return message;
}
using (var aes = Aes.Create())
using (var decryptor = GetMessageDecryptor(aes, message))
using (var body = new MemoryStream(Convert.FromBase64String(message.Body)))
using (var cryptoStream = new CryptoStream(body, decryptor, CryptoStreamMode.Read))
using (var bodyReader = new StreamReader(cryptoStream, Encoding.UTF8))
{
message.Body = bodyReader.ReadToEnd();
}
return message;
}
private ICryptoTransform GetMessageDecryptor(
Aes aes,
TaskAgentMessage message)
{
if (_session.EncryptionKey.Encrypted)
{
// The agent session encryption key uses the AES symmetric algorithm
var keyManager = HostContext.GetService<IRSAKeyManager>();
using (var rsa = keyManager.GetKey())
{
return aes.CreateDecryptor(rsa.Decrypt(_session.EncryptionKey.Value, RSAEncryptionPadding.OaepSHA1), message.IV);
}
}
else
{
return aes.CreateDecryptor(_session.EncryptionKey.Value, message.IV);
}
}
private bool IsGetNextMessageExceptionRetriable(Exception ex)
{
if (ex is TaskAgentNotFoundException ||
ex is TaskAgentPoolNotFoundException ||
ex is TaskAgentSessionExpiredException ||
ex is AccessDeniedException ||
ex is VssUnauthorizedException)
{
Trace.Info($"Non-retriable exception: {ex.Message}");
return false;
}
else
{
Trace.Info($"Retriable exception: {ex.Message}");
return true;
}
}
private bool IsSessionCreationExceptionRetriable(Exception ex)
{
if (ex is TaskAgentNotFoundException)
{
Trace.Info("The agent no longer exists on the server. Stopping the agent.");
_term.WriteError(StringUtil.Loc("MissingAgent"));
return false;
}
else if (ex is TaskAgentSessionConflictException)
{
Trace.Info("The session for this agent already exists.");
_term.WriteError(StringUtil.Loc("SessionExist"));
if (_sessionCreationExceptionTracker.ContainsKey(nameof(TaskAgentSessionConflictException)))
{
_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)]++;
if (_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)] * _sessionCreationRetryInterval.TotalSeconds >= _sessionConflictRetryLimit.TotalSeconds)
{
Trace.Info("The session conflict exception have reached retry limit.");
_term.WriteError(StringUtil.Loc("SessionExistStopRetry", _sessionConflictRetryLimit.TotalSeconds));
return false;
}
}
else
{
_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)] = 1;
}
Trace.Info("The session conflict exception haven't reached retry limit.");
return true;
}
else if (ex is VssOAuthTokenRequestException && ex.Message.Contains("Current server time is"))
{
Trace.Info("Local clock might skewed.");
_term.WriteError(StringUtil.Loc("LocalClockSkewed"));
if (_sessionCreationExceptionTracker.ContainsKey(nameof(VssOAuthTokenRequestException)))
{
_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)]++;
if (_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)] * _sessionCreationRetryInterval.TotalSeconds >= _clockSkewRetryLimit.TotalSeconds)
{
Trace.Info("The OAuth token request exception have reached retry limit.");
_term.WriteError(StringUtil.Loc("ClockSkewStopRetry", _clockSkewRetryLimit.TotalSeconds));
return false;
}
}
else
{
_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)] = 1;
}
Trace.Info("The OAuth token request exception haven't reached retry limit.");
return true;
}
else if (ex is TaskAgentPoolNotFoundException ||
ex is AccessDeniedException ||
ex is VssUnauthorizedException)
{
Trace.Info($"Non-retriable exception: {ex.Message}");
return false;
}
else
{
Trace.Info($"Retriable exception: {ex.Message}");
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace DevelopStuff.EvolveStuff.Core
{
/// <summary>
/// Defines a common environment where <see cref="TIndividual"/>s evolve.
/// </summary>
public class SimpleEnvironment<TIndividual> where TIndividual : Individual, new()
{
#region Fields
private IList<TIndividual> _individuals;
/// <summary>
/// Gets or sets the <see cref="FitnessFunction<TIndividual>"/>.
/// </summary>
public FitnessFunction<TIndividual> FitnessFunction { get; set; }
/// <summary>
/// Gets or sets the <see cref="StrategyConfiguration"/>.
/// </summary>
protected StrategyConfiguration StrategyConfiguration { get; set; }
/// <summary>
/// Gets or sets the <see cref="ParentSelector<TIndividual>"/>.
/// </summary>
public ParentSelector<TIndividual> ParentSelector { get; set; }
#endregion
#region Constructor
public SimpleEnvironment(ParentSelector<TIndividual> parentSelector, FitnessFunction<TIndividual> fitnessFunction, StrategyConfiguration config)
{
this.StrategyConfiguration = config;
this.ParentSelector = parentSelector;
this.FitnessFunction = fitnessFunction;
}
#endregion
#region Properties
/// <summary>
/// Gets the maxium size of a population.
/// </summary>
protected virtual int MaximumPopulation
{
get
{
return this.StrategyConfiguration.MaximumPopulation;
}
}
/// <summary>
/// Gets the current <see cref="Generation"/> within the <see cref="AbstractEnvironment"/>
/// </summary>
public IList<TIndividual> Population
{
get
{
if (this._individuals == null)
{
this._individuals = new List<TIndividual>();
}
return this._individuals;
}
}
#endregion
#region Methods
/// <summary>
/// Get's the most fit <see cref="TIndividual"/>.
/// </summary>
/// <returns></returns>
public TIndividual GetMostFitIndividual()
{
IList<TIndividual> sortedIndividuals = this.GetIndividualsSortedByFitness();
if (sortedIndividuals.Count > 0)
{
return sortedIndividuals[sortedIndividuals.Count - 1];
}
return null;
}
/// <summary>
/// Gets the <see cref="TIndividual"/>s sorted by fitness.
/// </summary>
/// <returns></returns>
public IList<TIndividual> GetIndividualsSortedByFitness()
{
List<TIndividual> sorted = new List<TIndividual>(this.Population);
sorted.Sort(new GenericFitnessComparer<TIndividual>());
return sorted;
}
/// <summary>
/// Returns a collection of the most recently generated <see cref="TInvdividual"/>s.
/// </summary>
/// <returns></returns>
public IList<TIndividual> GetNewIndividuals()
{
List<TIndividual> newIndividuals = new List<TIndividual>();
foreach (TIndividual individual in this.Population)
{
if (individual.GenerationID == Guid.Empty)
{
newIndividuals.Add(individual);
}
}
return newIndividuals;
}
/// <summary>
/// Trims the population.
/// </summary>
public void TrimPopulation()
{
List<TIndividual> individualsToRemove = new List<TIndividual>();
IList<TIndividual> sorted = this.GetIndividualsSortedByFitness();
for (int i = 0; i < (this.Population.Count/4); i++)
{
individualsToRemove.Add(sorted[i]);
}
foreach (TIndividual individual in individualsToRemove)
{
this.RemoveIndividual(individual);
}
}
/// <summary>
/// Triggers the population to reproduce.
/// </summary>
public void Reproduce()
{
int numberToReproduce = this.MaximumPopulation - this.Population.Count;
for (int i = numberToReproduce; i > 0; i--)
{
TIndividual parentA = this.ParentSelector.SelectMate(this);
TIndividual parentB = this.ParentSelector.SelectMate(this);
Individual newIndividual = parentA.Reproduce(parentB, 0);
this.AddIndividual((TIndividual)newIndividual);
}
}
/// <summary>
/// Evaluates the population.
/// </summary>
public void EvaluatePopulation()
{
foreach (TIndividual individual in this.Population)
{
individual.Fitness = this.FitnessFunction.CalculateFitness(this, individual);
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
public virtual void Initialize()
{
this.InitializeFitnessFunction();
this.ClearPopulation();
this.GenerateInitialPopulation();
}
/// <summary>
/// Initializes the <see cref="FitnessFunction"/>
/// </summary>
protected virtual void InitializeFitnessFunction()
{
}
/// <summary>
/// Generates an initial population of <see cref="TIndividual"/>s.
/// </summary>
protected virtual void GenerateInitialPopulation()
{
for (int i = 0; i < this.MaximumPopulation; i++)
{
this.AddIndividual(new TIndividual());
}
}
/// <summary>
/// Clears the population.
/// </summary>
public void ClearPopulation()
{
this.Population.Clear();
}
/// <summary>
/// Removes an <see cref="TIndividual"/> from the <see cref="AbstractEnvironment"/>.
/// </summary>
/// <param name="individual"></param>
public void RemoveIndividual(TIndividual individual)
{
if (this.Population.Contains(individual))
{
this.Population.Remove(individual);
}
}
/// <summary>
/// Adds an <see cref="TIndividual"/> to the <see cref="AbstractEnvironment"/>.
/// </summary>
/// <param name="individual"></param>
public void AddIndividual(TIndividual individual)
{
if (!this.Population.Contains(individual))
{
this.Population.Add(individual);
}
}
#endregion
}
}
| |
/********************************************************************
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.ModelViewer
{
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.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 MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal static class TransportSecurityHelpers
{
// used for HTTP (from HttpChannelUtilities.GetCredential)
public static async Task<NetworkCredential> GetSspiCredentialAsync(SecurityTokenProviderContainer tokenProvider,
OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper, OutWrapper<AuthenticationLevel> authenticationLevelWrapper,
CancellationToken cancellationToken)
{
OutWrapper<bool> dummyExtractWindowsGroupClaimsWrapper = new OutWrapper<bool>();
OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>();
NetworkCredential result = await GetSspiCredentialAsync(tokenProvider.TokenProvider as SspiSecurityTokenProvider,
dummyExtractWindowsGroupClaimsWrapper, impersonationLevelWrapper, allowNtlmWrapper, cancellationToken);
authenticationLevelWrapper.Value = allowNtlmWrapper.Value ?
AuthenticationLevel.MutualAuthRequested : AuthenticationLevel.MutualAuthRequired;
return result;
}
// used by client WindowsStream security (from InitiateUpgrade)
public static Task<NetworkCredential> GetSspiCredentialAsync(SspiSecurityTokenProvider tokenProvider,
OutWrapper<TokenImpersonationLevel> impersonationLevel, OutWrapper<bool> allowNtlm, CancellationToken cancellationToken)
{
OutWrapper<bool> dummyExtractWindowsGroupClaimsWrapper = new OutWrapper<bool>();
return GetSspiCredentialAsync(tokenProvider,
dummyExtractWindowsGroupClaimsWrapper, impersonationLevel, allowNtlm, cancellationToken);
}
// used by server WindowsStream security (from Open)
public static NetworkCredential GetSspiCredential(SecurityTokenManager credentialProvider,
SecurityTokenRequirement sspiTokenRequirement, TimeSpan timeout,
out bool extractGroupsForWindowsAccounts)
{
extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
NetworkCredential result = null;
if (credentialProvider != null)
{
SecurityTokenProvider tokenProvider = credentialProvider.CreateSecurityTokenProvider(sspiTokenRequirement);
if (tokenProvider != null)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
bool success = false;
try
{
OutWrapper<TokenImpersonationLevel> dummyImpersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
OutWrapper<bool> dummyAllowNtlmWrapper = new OutWrapper<bool>();
OutWrapper<bool> extractGroupsForWindowsAccountsWrapper = new OutWrapper<bool>();
result = GetSspiCredentialAsync((SspiSecurityTokenProvider)tokenProvider, extractGroupsForWindowsAccountsWrapper,
dummyImpersonationLevelWrapper, dummyAllowNtlmWrapper, timeoutHelper.GetCancellationToken()).GetAwaiter().GetResult();
success = true;
}
finally
{
if (!success)
{
SecurityUtils.AbortTokenProviderIfRequired(tokenProvider);
}
}
SecurityUtils.CloseTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
}
}
return result;
}
// core Cred lookup code
public static async Task<NetworkCredential> GetSspiCredentialAsync(SspiSecurityTokenProvider tokenProvider,
OutWrapper<bool> extractGroupsForWindowsAccounts,
OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper,
OutWrapper<bool> allowNtlmWrapper,
CancellationToken cancellationToken)
{
NetworkCredential credential = null;
extractGroupsForWindowsAccounts.Value = TransportDefaults.ExtractGroupsForWindowsAccounts;
impersonationLevelWrapper.Value = TokenImpersonationLevel.Identification;
allowNtlmWrapper.Value = ConnectionOrientedTransportDefaults.AllowNtlm;
if (tokenProvider != null)
{
SspiSecurityToken token = await TransportSecurityHelpers.GetTokenAsync<SspiSecurityToken>(tokenProvider, cancellationToken);
if (token != null)
{
extractGroupsForWindowsAccounts.Value = token.ExtractGroupsForWindowsAccounts;
impersonationLevelWrapper.Value = token.ImpersonationLevel;
allowNtlmWrapper.Value = token.AllowNtlm;
if (token.NetworkCredential != null)
{
credential = token.NetworkCredential;
SecurityUtils.FixNetworkCredential(ref credential);
}
}
}
// Initialize to the default value if no token provided. A partial trust app should not have access to the
// default network credentials but should be able to provide credentials. The DefaultNetworkCredentials
// getter will throw under partial trust.
if (credential == null)
{
credential = CredentialCache.DefaultNetworkCredentials;
}
return credential;
}
internal static SecurityTokenRequirement CreateSspiTokenRequirement(string transportScheme, Uri listenUri)
{
RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement();
tokenRequirement.TransportScheme = transportScheme;
tokenRequirement.RequireCryptographicToken = false;
tokenRequirement.ListenUri = listenUri;
tokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential;
return tokenRequirement;
}
internal static SecurityTokenRequirement CreateSspiTokenRequirement(EndpointAddress target, Uri via, string transportScheme)
{
InitiatorServiceModelSecurityTokenRequirement sspiTokenRequirement = new InitiatorServiceModelSecurityTokenRequirement();
sspiTokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential;
sspiTokenRequirement.RequireCryptographicToken = false;
sspiTokenRequirement.TransportScheme = transportScheme;
sspiTokenRequirement.TargetAddress = target;
sspiTokenRequirement.Via = via;
return sspiTokenRequirement;
}
public static SspiSecurityTokenProvider GetSspiTokenProvider(
SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters)
{
if (tokenManager != null)
{
SecurityTokenRequirement sspiRequirement = CreateSspiTokenRequirement(target, via, transportScheme);
sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme;
if (channelParameters != null)
{
sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
}
SspiSecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(sspiRequirement) as SspiSecurityTokenProvider;
return tokenProvider;
}
return null;
}
public static SspiSecurityTokenProvider GetSspiTokenProvider(
SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme,
out IdentityVerifier identityVerifier)
{
identityVerifier = null;
if (tokenManager != null)
{
SspiSecurityTokenProvider tokenProvider =
tokenManager.CreateSecurityTokenProvider(CreateSspiTokenRequirement(target, via, transportScheme)) as SspiSecurityTokenProvider;
if (tokenProvider != null)
{
identityVerifier = IdentityVerifier.CreateDefault();
}
return tokenProvider;
}
return null;
}
public static SecurityTokenProvider GetDigestTokenProvider(
SecurityTokenManager tokenManager, EndpointAddress target, Uri via,
string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters)
{
if (tokenManager != null)
{
InitiatorServiceModelSecurityTokenRequirement digestTokenRequirement =
new InitiatorServiceModelSecurityTokenRequirement();
digestTokenRequirement.TokenType = ServiceModelSecurityTokenTypes.SspiCredential;
digestTokenRequirement.TargetAddress = target;
digestTokenRequirement.Via = via;
digestTokenRequirement.RequireCryptographicToken = false;
digestTokenRequirement.TransportScheme = transportScheme;
digestTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme;
if (channelParameters != null)
{
digestTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
}
return tokenManager.CreateSecurityTokenProvider(digestTokenRequirement) as SspiSecurityTokenProvider;
}
return null;
}
public static SecurityTokenProvider GetCertificateTokenProvider(
SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, ChannelParameterCollection channelParameters)
{
if (tokenManager != null)
{
InitiatorServiceModelSecurityTokenRequirement certificateTokenRequirement =
new InitiatorServiceModelSecurityTokenRequirement();
certificateTokenRequirement.TokenType = SecurityTokenTypes.X509Certificate;
certificateTokenRequirement.TargetAddress = target;
certificateTokenRequirement.Via = via;
certificateTokenRequirement.RequireCryptographicToken = false;
certificateTokenRequirement.TransportScheme = transportScheme;
if (channelParameters != null)
{
certificateTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
}
return tokenManager.CreateSecurityTokenProvider(certificateTokenRequirement);
}
return null;
}
static async Task<T> GetTokenAsync<T>(SecurityTokenProvider tokenProvider, CancellationToken cancellationToken)
where T : SecurityToken
{
SecurityToken result = await tokenProvider.GetTokenAsync(cancellationToken);
if ((result != null) && !(result is T))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.InvalidTokenProvided, tokenProvider.GetType(), typeof(T))));
}
return result as T;
}
public static async Task<NetworkCredential> GetUserNameCredentialAsync(SecurityTokenProviderContainer tokenProvider, CancellationToken cancellationToken)
{
NetworkCredential result = null;
if (tokenProvider != null && tokenProvider.TokenProvider != null)
{
UserNameSecurityToken token = await GetTokenAsync<UserNameSecurityToken>(tokenProvider.TokenProvider, cancellationToken);
if (token != null)
{
result = new NetworkCredential(token.UserName, token.Password);
}
}
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoUserNameTokenProvided));
}
return result;
}
public static SecurityTokenProvider GetUserNameTokenProvider(
SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme,
ChannelParameterCollection channelParameters)
{
SecurityTokenProvider result = null;
if (tokenManager != null)
{
SecurityTokenRequirement usernameRequirement = CreateUserNameTokenRequirement(target, via, transportScheme);
usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme;
if (channelParameters != null)
{
usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
}
result = tokenManager.CreateSecurityTokenProvider(usernameRequirement);
}
return result;
}
public static Uri GetListenUri(Uri baseAddress, string relativeAddress)
{
Uri fullUri = baseAddress;
// Ensure that baseAddress Path does end with a slash if we have a relative address
if (!string.IsNullOrEmpty(relativeAddress))
{
if (!baseAddress.AbsolutePath.EndsWith("/", StringComparison.Ordinal))
{
UriBuilder uriBuilder = new UriBuilder(baseAddress);
FixIpv6Hostname(uriBuilder, baseAddress);
uriBuilder.Path = uriBuilder.Path + "/";
baseAddress = uriBuilder.Uri;
}
fullUri = new Uri(baseAddress, relativeAddress);
}
return fullUri;
}
static InitiatorServiceModelSecurityTokenRequirement CreateUserNameTokenRequirement(
EndpointAddress target, Uri via, string transportScheme)
{
InitiatorServiceModelSecurityTokenRequirement usernameRequirement = new InitiatorServiceModelSecurityTokenRequirement();
usernameRequirement.RequireCryptographicToken = false;
usernameRequirement.TokenType = SecurityTokenTypes.UserName;
usernameRequirement.TargetAddress = target;
usernameRequirement.Via = via;
usernameRequirement.TransportScheme = transportScheme;
return usernameRequirement;
}
// Originally: TcpChannelListener.FixIpv6Hostname
private static void FixIpv6Hostname(UriBuilder uriBuilder, Uri originalUri)
{
if (originalUri.HostNameType == UriHostNameType.IPv6)
{
string ipv6Host = originalUri.DnsSafeHost;
uriBuilder.Host = string.Concat("[", ipv6Host, "]");
}
}
}
static class HttpTransportSecurityHelpers
{
static Dictionary<string, int> s_targetNameCounter = new Dictionary<string, int>();
public static bool AddIdentityMapping(Uri via, EndpointAddress target)
{
// On Desktop, we do mutual auth when the EndpointAddress has an identity. We need
// support from HttpClient before any functionality can be added here.
return false;
}
public static void RemoveIdentityMapping(Uri via, EndpointAddress target, bool validateState)
{
// On Desktop, we do mutual auth when the EndpointAddress has an identity. We need
// support from HttpClient before any functionality can be added here.
}
static Dictionary<HttpRequestMessage, string> serverCertMap = new Dictionary<HttpRequestMessage, string>();
public static void AddServerCertMapping(HttpRequestMessage request, EndpointAddress to)
{
Fx.Assert(request.RequestUri.Scheme == UriEx.UriSchemeHttps,
"Wrong URI scheme for AddServerCertMapping().");
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
// The following condition should have been validated when the channel was created.
Fx.Assert(remoteCertificateIdentity.Certificates.Count <= 1,
"HTTPS server certificate identity contains multiple certificates");
AddServerCertMapping(request, remoteCertificateIdentity.Certificates[0].Thumbprint);
}
}
static void AddServerCertMapping(HttpRequestMessage request, string thumbprint)
{
lock (serverCertMap)
{
serverCertMap.Add(request, thumbprint);
}
}
public static void SetServerCertificateValidationCallback(ServiceModelHttpMessageHandler handler)
{
if (!handler.SupportsCertificateValidationCallback)
{
throw ExceptionHelper.PlatformNotSupported("Server certificate validation not supported yet");
}
handler.ServerCertificateValidationCallback =
ChainValidator(handler.ServerCertificateValidationCallback);
}
static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ChainValidator(Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> previousValidator)
{
if (previousValidator == null)
{
return OnValidateServerCertificate;
}
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> chained =
(request, certificate, chain, sslPolicyErrors) =>
{
bool valid = OnValidateServerCertificate(request, certificate, chain, sslPolicyErrors);
if (valid)
{
return previousValidator(request, certificate, chain, sslPolicyErrors);
}
return false;
};
return chained;
}
static bool OnValidateServerCertificate(HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (request != null)
{
string thumbprint;
lock (serverCertMap)
{
serverCertMap.TryGetValue(request, out thumbprint);
}
if (thumbprint != null)
{
try
{
ValidateServerCertificate(certificate, thumbprint);
}
catch (SecurityNegotiationException)
{
return false;
}
}
}
return (sslPolicyErrors == SslPolicyErrors.None);
}
public static void RemoveServerCertMapping(HttpRequestMessage request)
{
lock (serverCertMap)
{
serverCertMap.Remove(request);
}
}
static void ValidateServerCertificate(X509Certificate2 certificate, string thumbprint)
{
string certHashString = certificate.Thumbprint;
if (!thumbprint.Equals(certHashString))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityNegotiationException(SR.Format(SR.HttpsServerCertThumbprintMismatch,
certificate.Subject, certHashString, thumbprint)));
}
}
}
static class AuthenticationLevelHelper
{
internal static string ToString(AuthenticationLevel authenticationLevel)
{
if (authenticationLevel == AuthenticationLevel.MutualAuthRequested)
{
return "mutualAuthRequested";
}
if (authenticationLevel == AuthenticationLevel.MutualAuthRequired)
{
return "mutualAuthRequired";
}
if (authenticationLevel == AuthenticationLevel.None)
{
return "none";
}
Fx.Assert("unknown authentication level");
return authenticationLevel.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace RemotingLite
{
internal sealed class ParameterTypes
{
internal const byte Unknown = 0x00;
internal const byte Bool = 0x01;
internal const byte Byte = 0x02;
internal const byte SByte = 0x03;
internal const byte Char = 0x04;
internal const byte Decimal = 0x05;
internal const byte Double = 0x06;
internal const byte Float = 0x07;
internal const byte Int = 0x08;
internal const byte UInt = 0x09;
internal const byte Long = 0x0A;
internal const byte ULong = 0x0B;
internal const byte Short = 0x0C;
internal const byte UShort = 0x0D;
internal const byte String = 0x0E;
internal const byte ByteArray = 0x0F;
internal const byte CharArray = 0x10;
internal const byte Null = 0x11;
}
internal sealed class ParameterTransferHelper
{
private Dictionary<Type, byte> _parameterTypes;
internal ParameterTransferHelper()
{
_parameterTypes = new Dictionary<Type, byte>();
_parameterTypes.Add(typeof(bool), ParameterTypes.Bool);
_parameterTypes.Add(typeof(byte), ParameterTypes.Byte);
_parameterTypes.Add(typeof(sbyte), ParameterTypes.SByte);
_parameterTypes.Add(typeof(char), ParameterTypes.Char);
_parameterTypes.Add(typeof(decimal), ParameterTypes.Decimal);
_parameterTypes.Add(typeof(double), ParameterTypes.Double);
_parameterTypes.Add(typeof(float), ParameterTypes.Float);
_parameterTypes.Add(typeof(int), ParameterTypes.Int);
_parameterTypes.Add(typeof(uint), ParameterTypes.UInt);
_parameterTypes.Add(typeof(long), ParameterTypes.Long);
_parameterTypes.Add(typeof(ulong), ParameterTypes.ULong);
_parameterTypes.Add(typeof(short), ParameterTypes.Short);
_parameterTypes.Add(typeof(ushort), ParameterTypes.UShort);
_parameterTypes.Add(typeof(string), ParameterTypes.String);
_parameterTypes.Add(typeof(byte[]), ParameterTypes.ByteArray);
_parameterTypes.Add(typeof(char[]), ParameterTypes.CharArray);
}
internal void SendParameters(BinaryWriter writer, params object[] parameters)
{
MemoryStream ms;
BinaryFormatter formatter = new BinaryFormatter();
//write how many parameters are coming
writer.Write(parameters.Length);
//write data for each parameter
foreach (object parameter in parameters)
{
if (parameter != null)
{
Type type = parameter.GetType();
byte typeByte = GetParameterType(type);
//write the type byte
writer.Write(typeByte);
//write the parameter
switch (typeByte)
{
case ParameterTypes.Bool:
writer.Write((bool)parameter);
break;
case ParameterTypes.Byte:
writer.Write((byte)parameter);
break;
case ParameterTypes.ByteArray:
byte[] byteArray = (byte[])parameter;
writer.Write(byteArray.Length);
writer.Write(byteArray);
break;
case ParameterTypes.Char:
writer.Write((char)parameter);
break;
case ParameterTypes.CharArray:
char[] charArray = (char[])parameter;
writer.Write(charArray.Length);
writer.Write(charArray);
break;
case ParameterTypes.Decimal:
writer.Write((decimal)parameter);
break;
case ParameterTypes.Double:
writer.Write((double)parameter);
break;
case ParameterTypes.Float:
writer.Write((float)parameter);
break;
case ParameterTypes.Int:
writer.Write((int)parameter);
break;
case ParameterTypes.Long:
writer.Write((long)parameter);
break;
case ParameterTypes.SByte:
writer.Write((sbyte)parameter);
break;
case ParameterTypes.Short:
writer.Write((short)parameter);
break;
case ParameterTypes.String:
writer.Write((string)parameter);
break;
case ParameterTypes.UInt:
writer.Write((uint)parameter);
break;
case ParameterTypes.ULong:
writer.Write((ulong)parameter);
break;
case ParameterTypes.UShort:
writer.Write((ushort)parameter);
break;
case ParameterTypes.Unknown:
ms = new MemoryStream();
formatter.Serialize(ms, parameter);
ms.Seek(0, SeekOrigin.Begin);
//write length of data
writer.Write((int)ms.Length);
//write data
writer.Write(ms.ToArray());
break;
default:
throw new Exception(string.Format("Unknown type byte '0x{0:X}'", typeByte));
}
}
else
writer.Write(ParameterTypes.Null);
}
}
internal object[] ReceiveParameters(BinaryReader reader)
{
int parameterCount = reader.ReadInt32();
object[] parameters = new object[parameterCount];
MemoryStream ms;
BinaryFormatter formatter = new BinaryFormatter();
for (int i = 0; i < parameterCount; i++)
{
//read type byte
byte typeByte = reader.ReadByte();
if (typeByte == ParameterTypes.Null)
parameters[i] = null;
else
{
int count;
switch (typeByte)
{
case ParameterTypes.Bool:
parameters[i] = reader.ReadBoolean();
break;
case ParameterTypes.Byte:
parameters[i] = reader.ReadByte();
break;
case ParameterTypes.ByteArray:
count = reader.ReadInt32();
parameters[i] = reader.ReadBytes(count);
break;
case ParameterTypes.Char:
parameters[i] = reader.ReadChar();
break;
case ParameterTypes.CharArray:
count = reader.ReadInt32();
parameters[i] = reader.ReadChars(count);
break;
case ParameterTypes.Decimal:
parameters[i] = reader.ReadDecimal();
break;
case ParameterTypes.Double:
parameters[i] = reader.ReadDouble();
break;
case ParameterTypes.Float:
parameters[i] = reader.ReadSingle();
break;
case ParameterTypes.Int:
parameters[i] = reader.ReadInt32();
break;
case ParameterTypes.Long:
parameters[i] = reader.ReadInt64();
break;
case ParameterTypes.SByte:
parameters[i] = reader.ReadSByte();
break;
case ParameterTypes.Short:
parameters[i] = reader.ReadInt16();
break;
case ParameterTypes.String:
parameters[i] = reader.ReadString();
break;
case ParameterTypes.UInt:
parameters[i] = reader.ReadUInt32();
break;
case ParameterTypes.ULong:
parameters[i] = reader.ReadUInt64();
break;
case ParameterTypes.UShort:
parameters[i] = reader.ReadUInt16();
break;
case ParameterTypes.Unknown:
ms = new MemoryStream(reader.ReadBytes(reader.ReadInt32()));
//deserialize the parameter array
parameters[i] = formatter.Deserialize(ms);
break;
default:
throw new Exception(string.Format("Unknown type byte '0x{0:X}'", typeByte));
}
}
}
return parameters;
}
private byte GetParameterType(Type type)
{
if (_parameterTypes.ContainsKey(type))
return _parameterTypes[type];
else
return ParameterTypes.Unknown;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCDepth : BridgeHelpers
{
//[Variation("XmlReader Depth at the Root", Priority = 0)]
public void TestDepth1()
{
XmlReader DataReader = GetReader();
int iDepth = 0;
PositionOnElement(DataReader, "PLAY");
TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth);
DataReader.Dispose();
}
//[Variation("XmlReader Depth at Empty Tag")]
public void TestDepth2()
{
XmlReader DataReader = GetReader();
int iDepth = 2;
PositionOnElement(DataReader, "EMPTY1");
TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth);
}
//[Variation("XmlReader Depth at Empty Tag with Attributes")]
public void TestDepth3()
{
XmlReader DataReader = GetReader();
int iDepth = 2;
PositionOnElement(DataReader, "ACT1");
TestLog.Compare(DataReader.Depth, iDepth, "Element Depth should be " + (iDepth).ToString());
while (DataReader.MoveToNextAttribute() == true)
{
TestLog.Compare(DataReader.Depth, iDepth + 1, "Attr Depth should be " + (iDepth + 1).ToString());
}
}
//[Variation("XmlReader Depth at Non Empty Tag with Text")]
public void TestDepth4()
{
XmlReader DataReader = GetReader();
int iDepth = 2;
PositionOnElement(DataReader, "NONEMPTY1");
TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth);
while (true == DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Text)
TestLog.Compare(DataReader.Depth, iDepth + 1, "Depth should be " + (iDepth + 1).ToString());
if (DataReader.Name == "NONEMPTY1" && (DataReader.NodeType == XmlNodeType.EndElement)) break;
}
TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth);
}
}
public partial class TCNamespace : BridgeHelpers
{
public static string pNONAMESPACE = "NONAMESPACE";
//[Variation("Namespace test within a scope (no nested element)", Priority = 0)]
public void TestNamespace1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE0");
while (true == DataReader.Read())
{
if (DataReader.Name == "NAMESPACE1") break;
if (DataReader.NodeType == XmlNodeType.Element)
{
TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace");
TestLog.Compare(DataReader.Name, "bar:check", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix");
}
}
}
//[Variation("Namespace test within a scope (with nested element)", Priority = 0)]
public void TestNamespace2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE1");
while (true == DataReader.Read())
{
if (DataReader.Name == "NONAMESPACE") break;
if ((DataReader.NodeType == XmlNodeType.Element) && (DataReader.LocalName == "check"))
{
TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace");
TestLog.Compare(DataReader.Name, "bar:check", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix");
}
}
TestLog.Compare(DataReader.NamespaceURI, String.Empty, "Compare Namespace with String.Empty");
}
//[Variation("Namespace test immediately outside the Namespace scope")]
public void TestNamespace3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, pNONAMESPACE);
TestLog.Compare(DataReader.NamespaceURI, String.Empty, "Compare Namespace with EmptyString");
TestLog.Compare(DataReader.Name, pNONAMESPACE, "Compare Name");
TestLog.Compare(DataReader.LocalName, pNONAMESPACE, "Compare LocalName");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix");
}
//[Variation("Namespace test Attribute should has no default namespace", Priority = 0)]
public void TestNamespace4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE1");
TestLog.Compare(DataReader.NamespaceURI, "1000", "Compare Namespace for Element");
if (DataReader.MoveToFirstAttribute())
{
TestLog.Compare(DataReader.NamespaceURI, String.Empty, "Compare Namespace for Attr");
}
}
//[Variation("Namespace test with multiple Namespace declaration", Priority = 0)]
public void TestNamespace5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE2");
while (true == DataReader.Read())
{
if (DataReader.Name == "NAMESPACE3") break;
if ((DataReader.NodeType == XmlNodeType.Element) && (DataReader.LocalName == "check"))
{
TestLog.Compare(DataReader.NamespaceURI, "2", "Compare Namespace");
TestLog.Compare(DataReader.Name, "bar:check", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix");
}
}
}
//[Variation("Namespace test with multiple Namespace declaration, including default namespace")]
public void TestNamespace6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE3");
while (true == DataReader.Read())
{
if (DataReader.Name == "NONAMESPACE") break;
if (DataReader.NodeType == XmlNodeType.Element)
{
if (DataReader.LocalName == "check")
{
TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace");
TestLog.Compare(DataReader.Name, "check", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix");
}
else if (DataReader.LocalName == "check1")
{
TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace");
TestLog.Compare(DataReader.Name, "check1", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check1", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix");
}
else if (DataReader.LocalName == "check8")
{
TestLog.Compare(DataReader.NamespaceURI, "8", "Compare Namespace");
TestLog.Compare(DataReader.Name, "d:check8", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check8", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, "d", "Compare Prefix");
}
else if (DataReader.LocalName == "check100")
{
TestLog.Compare(DataReader.NamespaceURI, "100", "Compare Namespace");
TestLog.Compare(DataReader.Name, "check100", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check100", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix");
}
else if (DataReader.LocalName == "check5")
{
TestLog.Compare(DataReader.NamespaceURI, "5", "Compare Namespace");
TestLog.Compare(DataReader.Name, "d:check5", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check5", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, "d", "Compare Prefix");
}
else if (DataReader.LocalName == "check14")
{
TestLog.Compare(DataReader.NamespaceURI, "14", "Compare Namespace");
TestLog.Compare(DataReader.Name, "check14", "Compare Name");
TestLog.Compare(DataReader.LocalName, "check14", "Compare LocalName");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix");
}
else if (DataReader.LocalName == "a13")
{
TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace1");
TestLog.Compare(DataReader.Name, "a13", "Compare Name1");
TestLog.Compare(DataReader.LocalName, "a13", "Compare LocalName1");
TestLog.Compare(DataReader.Prefix, String.Empty, "Compare Prefix1");
DataReader.MoveToFirstAttribute();
TestLog.Compare(DataReader.NamespaceURI, "13", "Compare Namespace2");
TestLog.Compare(DataReader.Name, "a:check", "Compare Name2");
TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName2");
TestLog.Compare(DataReader.Prefix, "a", "Compare Prefix2");
TestLog.Compare(DataReader.Value, "Namespace=13", "Compare Name2");
}
}
}
}
//[Variation("Namespace URI for xml prefix", Priority = 0)]
public void TestNamespace7()
{
string strxml = "<ROOT xml:space='preserve'/>";
XmlReader DataReader = GetReader(new StringReader(strxml));
PositionOnElement(DataReader, "ROOT");
DataReader.MoveToFirstAttribute();
TestLog.Compare(DataReader.NamespaceURI, "http://www.w3.org/XML/1998/namespace", "xml");
}
}
public partial class TCLookupNamespace : BridgeHelpers
{
//[Variation("LookupNamespace test within EmptyTag")]
public void LookupNamespace1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY_NAMESPACE");
do
{
TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace");
} while (DataReader.MoveToNextAttribute() == true);
}
//[Variation("LookupNamespace test with Default namespace within EmptyTag", Priority = 0)]
public void LookupNamespace2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY_NAMESPACE1");
do
{
TestLog.Compare(DataReader.LookupNamespace(String.Empty), "14", "Compare LookupNamespace");
} while (DataReader.MoveToNextAttribute() == true);
}
//[Variation("LookupNamespace test within a scope (no nested element)", Priority = 0)]
public void LookupNamespace3()
{
XmlReader DataReader = GetReader();
while (true == DataReader.Read())
{
if (DataReader.Name == "NAMESPACE0") break;
TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace");
}
while (true == DataReader.Read())
{
TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace");
if (DataReader.Name == "NAMESPACE0" && DataReader.NodeType == XmlNodeType.EndElement) break;
}
}
//[Variation("LookupNamespace test within a scope (with nested element)", Priority = 0)]
public void LookupNamespace4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE1");
while (true == DataReader.Read())
{
TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace");
if (DataReader.Name == "NAMESPACE1" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
}
TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace with String.Empty");
}
//[Variation("LookupNamespace test immediately outside the Namespace scope")]
public void LookupNamespace5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace with null");
}
//[Variation("LookupNamespace test with multiple Namespace declaration", Priority = 0)]
public void LookupNamespace6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE2");
string strValue = "1";
while (true == DataReader.Read())
{
if (DataReader.Name == "c")
{
strValue = "2";
TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a");
if (DataReader.NodeType == XmlNodeType.EndElement)
strValue = "1";
}
else
TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a");
if (DataReader.Name == "NAMESPACE2" && DataReader.NodeType == XmlNodeType.EndElement)
{
TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a");
DataReader.Read();
break;
}
}
}
void CompareAllNS(XmlReader DataReader, string strDef, string strA, string strB, string strC, string strD, string strE, string strF, string strG, string strH)
{
TestLog.Compare(DataReader.LookupNamespace(String.Empty), strDef, "Compare LookupNamespace-default");
TestLog.Compare(DataReader.LookupNamespace("a"), strA, "Compare LookupNamespace-a");
TestLog.Compare(DataReader.LookupNamespace("b"), strB, "Compare LookupNamespace-b");
TestLog.Compare(DataReader.LookupNamespace("c"), strC, "Compare LookupNamespace-c");
TestLog.Compare(DataReader.LookupNamespace("d"), strD, "Compare LookupNamespace-d");
TestLog.Compare(DataReader.LookupNamespace("e"), strE, "Compare LookupNamespace-e");
TestLog.Compare(DataReader.LookupNamespace("f"), strF, "Compare LookupNamespace-f");
TestLog.Compare(DataReader.LookupNamespace("g"), strG, "Compare LookupNamespace-g");
TestLog.Compare(DataReader.LookupNamespace("h"), strH, "Compare LookupNamespace-h");
}
//[Variation("Namespace test with multiple Namespace declaration, including default namespace")]
public void LookupNamespace7()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NAMESPACE3");
string strDef = "1";
string strA = null;
string strB = null;
string strC = null;
string strD = null;
string strE = null;
string strF = null;
string strG = null;
string strH = null;
while (true == DataReader.Read())
{
if (DataReader.Name == "a")
{
strA = "2";
strB = "3";
strC = "4";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strA = null;
strB = null;
strC = null;
}
}
else if (DataReader.Name == "b")
{
strD = "5";
strE = "6";
strF = "7";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strD = null;
strE = null;
strF = null;
}
}
else if (DataReader.Name == "c")
{
strD = "8";
strE = "9";
strF = "10";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strD = "5";
strE = "6";
strF = "7";
}
}
else if (DataReader.Name == "d")
{
strG = "11";
strH = "12";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strG = null;
strH = null;
}
}
else if (DataReader.Name == "testns")
{
strDef = "100";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strDef = "1";
}
}
else if (DataReader.Name == "a13")
{
strA = "13";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
do
{
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
} while (DataReader.MoveToNextAttribute() == true);
strA = null;
}
else if (DataReader.Name == "check14")
{
strDef = "14";
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.NodeType == XmlNodeType.EndElement)
{
strDef = "1";
}
}
else
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
if (DataReader.Name == "NAMESPACE3" && DataReader.NodeType == XmlNodeType.EndElement)
{
CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH);
DataReader.Read();
break;
}
}
}
//[Variation("LookupNamespace on whitespace node PreserveWhitespaces = true", Priority = 0)]
public void LookupNamespace8()
{
string strxml = "<ROOT xmlns:p='1'>\n<E1/></ROOT>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnNodeType(DataReader, XmlNodeType.Text);
string ns = DataReader.LookupNamespace("p");
TestLog.Compare(ns, "1", "ln");
}
//[Variation("Different prefix on inner element for the same namespace", Priority = 0)]
public void LookupNamespace9()
{
string ns = "http://www.w3.org/1999/XMLSchema";
string filename = @"TestData\XmlReader\Common\bug_57723.xml";
XmlReader DataReader = GetReader(filename);
PositionOnElement(DataReader, "element");
TestLog.Compare(DataReader.LookupNamespace("q1"), ns, "q11");
TestLog.Compare(DataReader.LookupNamespace("q2"), null, "q21");
DataReader.Read();
PositionOnElement(DataReader, "element");
TestLog.Compare(DataReader.LookupNamespace("q1"), ns, "q12");
TestLog.Compare(DataReader.LookupNamespace("q2"), ns, "q22");
}
//[Variation("LookupNamespace when Namespaces = false", Priority = 0)]
public void LookupNamespace10()
{
string strxml = "<ROOT xmlns:p='1'>\n<E1/></ROOT>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "ROOT");
TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln ROOT");
PositionOnElement(DataReader, "E1");
TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln E1");
DataReader.Read();
TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln /ROOT");
}
}
public partial class TCHasValue : BridgeHelpers
{
//[Variation("HasValue On None")]
public void TestHasValueNodeType_None()
{
XmlReader DataReader = GetReader();
bool b = DataReader.HasValue;
if (b)
throw new TestException(TestResult.Failed, "");
}
//[Variation("HasValue On Element", Priority = 0)]
public void TestHasValueNodeType_Element()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Element))
{
bool b = DataReader.HasValue;
if (b)
throw new TestFailedException("HasValue returns True");
else
return;
}
}
//[Variation("Get node with a scalar value, verify the value with valid ReadString")]
public void TestHasValue1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
DataReader.Read();
TestLog.Compare(DataReader.HasValue, true, "HasValue test");
}
//[Variation("HasValue On Attribute", Priority = 0)]
public void TestHasValueNodeType_Attribute()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Attribute))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestFailedException("HasValue for Attribute returns false");
else
return;
}
}
//[Variation("HasValue On Text", Priority = 0)]
public void TestHasValueNodeType_Text()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Text))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestFailedException("HasValue for Text returns false");
else
return;
}
}
//[Variation("HasValue On CDATA", Priority = 0)]
public void TestHasValueNodeType_CDATA()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.CDATA))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestFailedException("HasValue for CDATA returns false");
else
return;
}
}
//[Variation("HasValue On ProcessingInstruction", Priority = 0)]
public void TestHasValueNodeType_ProcessingInstruction()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestException(TestResult.Failed, "HasValue for PI returns false");
else
return;
}
}
//[Variation("HasValue On Comment", Priority = 0)]
public void TestHasValueNodeType_Comment()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Comment))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestException(TestResult.Failed, "HasValue for Comment returns false");
else
return;
}
}
//[Variation("HasValue On DocumentType", Priority = 0)]
public void TestHasValueNodeType_DocumentType()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.DocumentType))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestException(TestResult.Failed, "HasValue returns True");
else
return;
}
}
//[Variation("HasValue On Whitespace PreserveWhitespaces = true", Priority = 0)]
public void TestHasValueNodeType_Whitespace()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Whitespace))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestException(TestResult.Failed, "HasValue returns False");
else
return;
}
}
//[Variation("HasValue On EndElement")]
public void TestHasValueNodeType_EndElement()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.EndElement))
{
bool b = DataReader.HasValue;
if (b)
throw new TestException(TestResult.Failed, "HasValue returns True");
else
return;
}
}
//[Variation("HasValue On XmlDeclaration", Priority = 0)]
public void TestHasValueNodeType_XmlDeclaration()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.XmlDeclaration))
{
bool b = DataReader.HasValue;
if (!b)
throw new TestException(TestResult.Failed, "HasValue returns False");
else
return;
}
}
//[Variation("HasValue On EntityReference")]
public void TestHasValueNodeType_EntityReference()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.EntityReference))
{
bool b = DataReader.HasValue;
if (b)
throw new TestException(TestResult.Failed, "HasValue returns True");
else
return;
}
}
//[Variation("HasValue On EndEntity")]
public void TestHasValueNodeType_EndEntity()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.EndEntity))
{
bool b = DataReader.HasValue;
if (b)
throw new TestException(TestResult.Failed, "HasValue returns True");
else
return;
}
}
//[Variation("PI Value containing surrogates", Priority = 0)]
public void v13()
{
string strxml = "<root><?target \uD800\uDC00\uDBFF\uDFFF?></root>";
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.ProcessingInstruction, "nt");
TestLog.Compare(DataReader.Value, "\uD800\uDC00\uDBFF\uDFFF", "piv");
}
}
public partial class TCIsEmptyElement2 : BridgeHelpers
{
//[Variation("Set and Get an element that ends with />", Priority = 0)]
public void TestEmpty1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
bool b = DataReader.IsEmptyElement;
if (!b)
throw new TestException(TestResult.Failed, "DataReader is NOT_EMPTY, supposed to be EMPTY");
}
//[Variation("Set and Get an element with an attribute that ends with />", Priority = 0)]
public void TestEmpty2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY2");
bool b = DataReader.IsEmptyElement;
if (!b)
throw new TestException(TestResult.Failed, "DataReader is NOT_EMPTY, supposed to be EMPTY");
}
//[Variation("Set and Get an element that ends without />", Priority = 0)]
public void TestEmpty3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "DataReader is EMPTY, supposed to be NOT_EMPTY");
}
//[Variation("Set and Get an element with an attribute that ends with />", Priority = 0)]
public void TestEmpty4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY2");
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "DataReader is EMPTY, supposed to be NOT_EMPTY");
}
//[Variation("IsEmptyElement On Element", Priority = 0)]
public void TestEmptyNodeType_Element()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Element))
{
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
else
return;
}
}
//[Variation("IsEmptyElement On None")]
public void TestEmptyNodeType_None()
{
XmlReader DataReader = GetReader();
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "");
}
//[Variation("IsEmptyElement On Text")]
public void TestEmptyNodeType_Text()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Text))
{
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
else
return;
}
}
//[Variation("IsEmptyElement On CDATA")]
public void TestEmptyNodeType_CDATA()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.CDATA))
{
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
else
return;
}
}
//[Variation("IsEmptyElement On ProcessingInstruction")]
public void TestEmptyNodeType_ProcessingInstruction()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction))
{
bool b = DataReader.IsEmptyElement;
if (b)
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
else
return;
}
}
//[Variation("IsEmptyElement On Comment")]
public void TestEmptyNodeType_Comment()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Comment))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
//[Variation("IsEmptyElement On DocumentType")]
public void TestEmptyNodeType_DocumentType()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.DocumentType))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
//[Variation("IsEmptyElement On Whitespace PreserveWhitespaces = true")]
public void TestEmptyNodeType_Whitespace()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.Whitespace))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
//[Variation("IsEmptyElement On EndElement")]
public void TestEmptyNodeType_EndElement()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.EndElement))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
//[Variation("IsEmptyElement On EntityReference")]
public void TestEmptyNodeType_EntityReference()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.EntityReference))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
//[Variation("IsEmptyElement On EndEntity")]
public void TestEmptyNodeType_EndEntity()
{
XmlReader DataReader = GetReader();
while (FindNodeType(DataReader, XmlNodeType.EndEntity))
{
bool b = DataReader.IsEmptyElement;
if (!b)
return;
else
throw new TestException(TestResult.Failed, "IsEmptyElement returns True");
}
}
}
public partial class TCXmlSpace : BridgeHelpers
{
//[Variation("XmlSpace test within EmptyTag")]
public void TestXmlSpace1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY_XMLSPACE");
do
{
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default");
} while (DataReader.MoveToNextAttribute() == true);
}
//[Variation("Xmlspace test within a scope (no nested element)", Priority = 0)]
public void TestXmlSpace2()
{
XmlReader DataReader = GetReader();
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLSPACE1") break;
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace with None");
}
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLSPACE1" && (DataReader.NodeType == XmlNodeType.EndElement)) break;
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default");
}
}
//[Variation("Xmlspace test within a scope (with nested element)", Priority = 0)]
public void TestXmlSpace3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "XMLSPACE2");
while (true == DataReader.Read())
{
if (DataReader.Name == "NOSPACE") break;
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Preserve, "Compare XmlSpace with Preserve");
}
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace outside scope");
}
//[Variation("Xmlspace test immediately outside the XmlSpace scope")]
public void TestXmlSpace4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NOSPACE");
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace with None");
}
//[Variation("XmlSpace test with multiple XmlSpace declaration")]
public void TestXmlSpace5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "XMLSPACE2A");
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLSPACE3") break;
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default");
}
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLSPACE4")
{
while (true == DataReader.Read())
{
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default");
if (DataReader.Name == "XMLSPACE4" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
}
}
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Preserve, "Compare XmlSpace with Preserve");
if (DataReader.Name == "XMLSPACE3" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
}
do
{
TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default");
if (DataReader.Name == "XMLSPACE2A" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
} while (true == DataReader.Read());
TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace outside scope");
}
}
public partial class TCXmlLang : BridgeHelpers
{
//[Variation("XmlLang test within EmptyTag")]
public void TestXmlLang1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY_XMLLANG");
do
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US");
} while (DataReader.MoveToNextAttribute() == true);
}
//[Variation("XmlLang test within a scope (no nested element)", Priority = 0)]
public void TestXmlLang2()
{
XmlReader DataReader = GetReader();
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLLANG0") break;
TestLog.Compare(DataReader.XmlLang, String.Empty, "Compare XmlLang with String.Empty");
}
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLLANG0" && (DataReader.NodeType == XmlNodeType.EndElement)) break;
if (DataReader.NodeType == XmlNodeType.EntityReference)
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with EntityRef");
if (DataReader.CanResolveEntity)
{
DataReader.ResolveEntity();
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang after ResolveEntity");
while (DataReader.Read() && DataReader.NodeType != XmlNodeType.EndEntity)
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang While Read ");
}
if (DataReader.NodeType == XmlNodeType.EndEntity)
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang at EndEntity ");
}
}
}
else
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with Preserve");
}
}
//[Variation("XmlLang test within a scope (with nested element)", Priority = 0)]
public void TestXmlLang3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "XMLLANG1");
while (true == DataReader.Read())
{
if (DataReader.Name == "NOXMLLANG") break;
TestLog.Compare(DataReader.XmlLang, "en-GB", "Compare XmlLang with en-GB");
}
}
//[Variation("XmlLang test immediately outside the XmlLang scope")]
public void TestXmlLang4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NOXMLLANG");
TestLog.Compare(DataReader.XmlLang, String.Empty, "Compare XmlLang with EmptyString");
}
//[Variation("XmlLang test with multiple XmlLang declaration")]
public void TestXmlLang5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "XMLLANG2");
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLLANG1") break;
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with Preserve");
}
while (true == DataReader.Read())
{
if (DataReader.Name == "XMLLANG0")
{
while (true == DataReader.Read())
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US");
if (DataReader.Name == "XMLLANG0" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
}
}
TestLog.Compare(DataReader.XmlLang, "en-GB", "Compare XmlLang with en_GB");
if (DataReader.Name == "XMLLANG1" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
}
do
{
TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US");
if (DataReader.Name == "XMLLANG2" && DataReader.NodeType == XmlNodeType.EndElement)
{
DataReader.Read();
break;
}
} while (true == DataReader.Read());
}
// XML 1.0 SE
//[Variation("XmlLang valid values", Priority = 0)]
public void TestXmlLang6()
{
const string ST_VALIDXMLLANG = "VALIDXMLLANG";
string[] aValidLang = { "a", "", "ab-cd-", "a b-cd" };
XmlReader DataReader = GetReader();
for (int i = 0; i < aValidLang.Length; i++)
{
string strelem = ST_VALIDXMLLANG + i;
PositionOnElement(DataReader, strelem);
//DataReader.Read();
TestLog.Compare(DataReader.XmlLang, aValidLang[i], "XmlLang");
}
}
// XML 1.0 SE
//[Variation("More XmlLang valid values")]
public void TestXmlTextReaderLang1()
{
string[] aValidLang = { "", "ab-cd-", "abcdefghi", "ab-cdefghijk", "a b-cd", "ab-c d" };
for (int i = 0; i < aValidLang.Length; i++)
{
string strxml = String.Format("<ROOT xml:lang='{0}'/>", aValidLang[i]);
XmlReader DataReader = GetReaderStr(strxml);
while (DataReader.Read()) ;
}
}
}
public partial class TCSkip : BridgeHelpers
{
public bool VerifySkipOnNodeType(XmlNodeType testNodeType)
{
bool bPassed = false;
XmlNodeType actNodeType;
String strActName;
String strActValue;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, testNodeType);
DataReader.Read();
actNodeType = DataReader.NodeType;
strActName = DataReader.Name;
strActValue = DataReader.Value;
DataReader = GetReader();
PositionOnNodeType(DataReader, testNodeType);
DataReader.Skip();
bPassed = VerifyNode(DataReader, actNodeType, strActName, strActValue);
return bPassed;
}
//[Variation("Call Skip on empty element", Priority = 0)]
public void TestSkip1()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP1");
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP1", String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on element", Priority = 0)]
public void TestSkip2()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP2");
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP2", String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on element with content", Priority = 0)]
public void TestSkip3()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP3");
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP3", String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on text node (leave node)", Priority = 0)]
public void TestSkip4()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP3");
PositionOnElement(DataReader, "ELEM2");
DataReader.Read();
bPassed = (DataReader.NodeType == XmlNodeType.Text);
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.EndElement, "ELEM2", String.Empty) && bPassed;
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip in while read loop", Priority = 0)]
public void skip307543()
{
TestLog.Skip("Utf16 encoding");
string fileName = Path.Combine(XLinqTestCase.RootPath, @"TestData\XmlReader\Common\skip307543.xml");
XmlReader DataReader = GetReader(fileName);
while (DataReader.Read())
DataReader.Skip();
}
//[Variation("Call Skip on text node with another element: <elem2>text<elem3></elem3></elem2>")]
public void TestSkip5()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP4");
PositionOnElement(DataReader, "ELEM2");
DataReader.Read();
bPassed = (DataReader.NodeType == XmlNodeType.Text);
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ELEM3", String.Empty) && bPassed;
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on attribute", Priority = 0)]
public void TestSkip6()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = DataReader.MoveToFirstAttribute();
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ENTITY2", String.Empty) && bPassed;
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on text node of attribute")]
public void TestSkip7()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = DataReader.MoveToFirstAttribute();
bPassed = DataReader.ReadAttributeValue() && bPassed;
bPassed = (DataReader.NodeType == XmlNodeType.Text) && bPassed;
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ENTITY2", String.Empty) && bPassed;
BoolToLTMResult(bPassed);
}
//[Variation("Call Skip on CDATA", Priority = 0)]
public void TestSkip8()
{
XmlReader DataReader = GetReader();
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.CDATA));
}
//[Variation("Call Skip on Processing Instruction", Priority = 0)]
public void TestSkip9()
{
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.ProcessingInstruction));
}
//[Variation("Call Skip on Comment", Priority = 0)]
public void TestSkip10()
{
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.Comment));
}
//[Variation("Call Skip on Document Type")]
public void TestSkip11()
{
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.DocumentType));
}
//[Variation("Call Skip on Whitespace", Priority = 0)]
public void TestSkip12()
{
XmlReader DataReader = GetReader();
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.Whitespace));
}
//[Variation("Call Skip on EndElement", Priority = 0)]
public void TestSkip13()
{
BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.EndElement));
}
//[Variation("Call Skip on root Element")]
public void TestSkip14()
{
bool bPassed;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Element);
DataReader.Skip();
bPassed = VerifyNode(DataReader, XmlNodeType.None, String.Empty, String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("XmlTextReader ArgumentOutOfRangeException when handling ampersands")]
public void XmlTextReaderDoesNotThrowWhenHandlingAmpersands()
{
string xmlStr = @"<a>
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
>
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
fffffffffffffffffffffffffffffffffffffff
&
</a>
";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "a");
DataReader.Skip();
}
}
public partial class TCIsDefault : BridgeHelpers
{
}
public partial class TCBaseURI : BridgeHelpers
{
//[Variation("BaseURI for element node", Priority = 0)]
public void TestBaseURI1()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Element);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for attribute node", Priority = 0)]
public void TestBaseURI2()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Attribute);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for text node", Priority = 0)]
public void TestBaseURI3()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for CDATA node")]
public void TestBaseURI4()
{
XmlReader DataReader = GetReader();
bool bPassed = false;
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for PI node")]
public void TestBaseURI6()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for Comment node")]
public void TestBaseURI7()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for DTD node")]
public void TestBaseURI8()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.DocumentType);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for Whitespace node PreserveWhitespaces = true")]
public void TestBaseURI9()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Whitespace);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for EndElement node")]
public void TestBaseURI10()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("BaseURI for external General Entity")]
public void TestTextReaderBaseURI4()
{
bool bPassed = false;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ENTITY5");
DataReader.Read();
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, "Before ResolveEntity");
bPassed = VerifyNode(DataReader, XmlNodeType.Text, String.Empty, ST_GEN_ENT_VALUE) && bPassed;
bPassed = TestLog.Equals(DataReader.BaseURI, String.Empty, "After ResolveEntity");
BoolToLTMResult(bPassed);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Collections.Tests
{
public abstract partial class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T>
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int(int capacity)
{
HashSet<T> set = new HashSet<T>(capacity);
Assert.Equal(0, set.Count);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity)
{
HashSet<T> set = new HashSet<T>(capacity);
AddToCollection(set, capacity);
Assert.Equal(capacity, set.Count);
AddToCollection(set, capacity + 1);
Assert.Equal(capacity + 1, set.Count);
}
[Fact]
public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity)
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
HashSet<T> set = new HashSet<T>(capacity, comparer);
Assert.Equal(0, set.Count);
if (comparer == null)
Assert.Equal(EqualityComparer<T>.Default, set.Comparer);
else
Assert.Equal(comparer, set.Comparer);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity)
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
HashSet<T> set = new HashSet<T>(capacity, comparer);
AddToCollection(set, capacity);
Assert.Equal(capacity, set.Count);
AddToCollection(set, capacity + 1);
Assert.Equal(capacity + 1, set.Count);
}
[Fact]
public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException()
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer));
}
#region TryGetValue
[Fact]
public void HashSet_Generic_TryGetValue_Contains()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(1);
T actualValue;
Assert.True(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(value, actualValue);
if (!typeof(T).IsValueType)
{
Assert.Same(value, actualValue);
}
}
[Fact]
public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(1);
T actualValue = CreateT(2);
Assert.True(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(value, actualValue);
if (!typeof(T).IsValueType)
{
Assert.Same(value, actualValue);
}
}
[Fact]
public void HashSet_Generic_TryGetValue_NotContains()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(2);
T actualValue;
Assert.False(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(default(T), actualValue);
}
[Fact]
public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(2);
T actualValue = equalValue;
Assert.False(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(default(T), actualValue);
}
#endregion
#region EnsureCapacity
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength)
{
HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength));
var capacity = set.EnsureCapacity(0);
IEnumerator valuesEnum = set.GetEnumerator();
IEnumerator valuesListEnum = new List<T>(set).GetEnumerator();
set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration
while (valuesEnum.MoveNext())
{
valuesListEnum.MoveNext();
Assert.Equal(valuesListEnum.Current, valuesEnum.Current);
}
}
[Fact]
public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
{
var set = new HashSet<T>();
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1));
}
[Fact]
public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero()
{
var set = new HashSet<T>();
Assert.Equal(0, set.EnsureCapacity(0));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
{
var set = new HashSet<T>();
Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
}
[Theory]
[InlineData(3)]
[InlineData(7)]
public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
{
HashSet<T> set;
// assert capacity remains the same when ensuring a capacity smaller or equal than existing
for (int i = 0; i <= currentCapacity; i++)
{
set = new HashSet<T>(currentCapacity);
Assert.Equal(currentCapacity, set.EnsureCapacity(i));
}
}
[Theory]
[InlineData(7)]
[InlineData(89)]
public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
{
var set = new HashSet<T>(capacity);
Assert.Equal(capacity, set.EnsureCapacity(capacity));
set = (HashSet<T>)GenericISetFactory(capacity);
Assert.Equal(capacity, set.EnsureCapacity(capacity));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
int capacity = set.EnsureCapacity(0);
Assert.Equal(capacity, set.EnsureCapacity(0));
set = (HashSet<T>)GenericISetFactory(setLength);
capacity = set.EnsureCapacity(setLength);
Assert.Equal(capacity, set.EnsureCapacity(setLength));
set = (HashSet<T>)GenericISetFactory(setLength);
capacity = set.EnsureCapacity(setLength + 1);
Assert.Equal(capacity, set.EnsureCapacity(setLength + 1));
}
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(7)]
[InlineData(8)]
public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue);
}
[Theory]
[InlineData(7)]
[InlineData(20)]
public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
// get current capacity
int currentCapacity = set.EnsureCapacity(0);
// assert we can update to a larger capacity
int newCapacity = set.EnsureCapacity(currentCapacity * 2);
Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
}
[Fact]
public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
{
var set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(17));
set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(15));
set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(13));
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Security;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A base class for the trace cmdlets that allow you to specify
/// which trace listeners to add to a TraceSource.
/// </summary>
public class TraceListenerCommandBase : TraceCommandBase
{
#region Parameters
/// <summary>
/// The TraceSource parameter determines which TraceSource categories the
/// operation will take place on.
/// </summary>
internal string[] NameInternal { get; set; } = Array.Empty<string>();
/// <summary>
/// The flags to be set on the TraceSource.
/// </summary>
/// <value></value>
internal PSTraceSourceOptions OptionsInternal
{
get
{
return _options;
}
set
{
_options = value;
optionsSpecified = true;
}
}
private PSTraceSourceOptions _options = PSTraceSourceOptions.All;
/// <summary>
/// True if the Options parameter has been set, or false otherwise.
/// </summary>
internal bool optionsSpecified;
/// <summary>
/// The parameter which determines the options for output from the trace listeners.
/// </summary>
internal TraceOptions ListenerOptionsInternal
{
get
{
return _traceOptions;
}
set
{
traceOptionsSpecified = true;
_traceOptions = value;
}
}
private TraceOptions _traceOptions = TraceOptions.None;
/// <summary>
/// True if the TraceOptions parameter was specified, or false otherwise.
/// </summary>
internal bool traceOptionsSpecified;
/// <summary>
/// Adds the file trace listener using the specified file.
/// </summary>
/// <value></value>
internal string FileListener { get; set; }
/// <summary>
/// Property that sets force parameter. This will clear the
/// read-only attribute on an existing file if present.
/// </summary>
/// <remarks>
/// Note that we do not attempt to reset the read-only attribute.
/// </remarks>
public bool ForceWrite { get; set; }
/// <summary>
/// If this parameter is specified the Debugger trace listener will be added.
/// </summary>
/// <value></value>
internal bool DebuggerListener { get; set; }
/// <summary>
/// If this parameter is specified the Msh Host trace listener will be added.
/// </summary>
/// <value></value>
internal SwitchParameter PSHostListener
{
get { return _host; }
set { _host = value; }
}
private bool _host = false;
#endregion Parameters
internal Collection<PSTraceSource> ConfigureTraceSource(
string[] sourceNames,
bool preConfigure,
out Collection<PSTraceSource> preconfiguredSources)
{
preconfiguredSources = new Collection<PSTraceSource>();
// Find the matching and unmatched trace sources.
Collection<string> notMatched = null;
Collection<PSTraceSource> matchingSources = GetMatchingTraceSource(sourceNames, false, out notMatched);
if (preConfigure)
{
// Set the flags if they were specified
if (optionsSpecified)
{
SetFlags(matchingSources);
}
AddTraceListenersToSources(matchingSources);
SetTraceListenerOptions(matchingSources);
}
// Now try to preset options for sources which have not yet been
// constructed.
foreach (string notMatchedName in notMatched)
{
if (string.IsNullOrEmpty(notMatchedName))
{
continue;
}
if (WildcardPattern.ContainsWildcardCharacters(notMatchedName))
{
continue;
}
PSTraceSource newTraceSource =
PSTraceSource.GetNewTraceSource(
notMatchedName,
string.Empty,
true);
preconfiguredSources.Add(newTraceSource);
}
// Preconfigure any trace sources that were not already present
if (preconfiguredSources.Count > 0)
{
if (preConfigure)
{
// Set the flags if they were specified
if (optionsSpecified)
{
SetFlags(preconfiguredSources);
}
AddTraceListenersToSources(preconfiguredSources);
SetTraceListenerOptions(preconfiguredSources);
}
// Add the sources to the preconfigured table so that they are found
// when the trace source finally gets created by the system.
foreach (PSTraceSource sourceToPreconfigure in preconfiguredSources)
{
if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(sourceToPreconfigure.Name))
{
PSTraceSource.PreConfiguredTraceSource.Add(sourceToPreconfigure.Name, sourceToPreconfigure);
}
}
}
return matchingSources;
}
#region AddTraceListeners
/// <summary>
/// Adds the console, debugger, file, or host listener if requested.
/// </summary>
internal void AddTraceListenersToSources(Collection<PSTraceSource> matchingSources)
{
if (DebuggerListener)
{
if (_defaultListener == null)
{
_defaultListener =
new DefaultTraceListener();
// Note, this is not meant to be localized.
_defaultListener.Name = "Debug";
}
AddListenerToSources(matchingSources, _defaultListener);
}
if (PSHostListener)
{
if (_hostListener == null)
{
((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue;
_hostListener = new PSHostTraceListener(this);
// Note, this is not meant to be localized.
_hostListener.Name = "Host";
}
AddListenerToSources(matchingSources, _hostListener);
}
if (FileListener != null)
{
if (_fileListeners == null)
{
_fileListeners = new Collection<TextWriterTraceListener>();
FileStreams = new Collection<FileStream>();
Exception error = null;
try
{
Collection<string> resolvedPaths = new();
try
{
// Resolve the file path
ProviderInfo provider = null;
resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(FileListener, out provider);
// We can only export aliases to the file system
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
throw
new PSNotSupportedException(
StringUtil.Format(TraceCommandStrings.TraceFileOnly,
FileListener,
provider.FullName));
}
}
catch (ItemNotFoundException)
{
// Since the file wasn't found, just make a provider-qualified path out if it
// and use that.
PSDriveInfo driveInfo = null;
ProviderInfo provider = null;
string path =
this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
FileListener,
new CmdletProviderContext(this.Context),
out provider,
out driveInfo);
// We can only export aliases to the file system
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
{
throw
new PSNotSupportedException(
StringUtil.Format(TraceCommandStrings.TraceFileOnly,
FileListener,
provider.FullName));
}
resolvedPaths.Add(path);
}
if (resolvedPaths.Count > 1)
{
throw
new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, FileListener));
}
string resolvedPath = resolvedPaths[0];
Exception fileOpenError = null;
try
{
if (ForceWrite && System.IO.File.Exists(resolvedPath))
{
// remove readonly attributes on the file
System.IO.FileInfo fInfo = new(resolvedPath);
if (fInfo != null)
{
// Save some disk write time by checking whether file is readonly..
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make sure the file is not read only
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
}
// Trace commands always append..So there is no need to set overwrite with force..
FileStream fileStream = new(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
FileStreams.Add(fileStream);
// Open the file stream
TextWriterTraceListener fileListener =
new(fileStream, resolvedPath);
fileListener.Name = FileListener;
_fileListeners.Add(fileListener);
}
catch (IOException ioException)
{
fileOpenError = ioException;
}
catch (SecurityException securityException)
{
fileOpenError = securityException;
}
catch (UnauthorizedAccessException unauthorized)
{
fileOpenError = unauthorized;
}
if (fileOpenError != null)
{
ErrorRecord errorRecord =
new(
fileOpenError,
"FileListenerPathResolutionFailed",
ErrorCategory.OpenError,
resolvedPath);
WriteError(errorRecord);
}
}
catch (ProviderNotFoundException providerNotFound)
{
error = providerNotFound;
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
error = driveNotFound;
}
catch (NotSupportedException notSupported)
{
error = notSupported;
}
if (error != null)
{
ErrorRecord errorRecord =
new(
error,
"FileListenerPathResolutionFailed",
ErrorCategory.InvalidArgument,
FileListener);
WriteError(errorRecord);
}
}
foreach (TraceListener listener in _fileListeners)
{
AddListenerToSources(matchingSources, listener);
}
}
}
private DefaultTraceListener _defaultListener;
private PSHostTraceListener _hostListener;
private Collection<TextWriterTraceListener> _fileListeners;
/// <summary>
/// The file streams that were open by this command.
/// </summary>
internal Collection<FileStream> FileStreams { get; private set; }
private static void AddListenerToSources(Collection<PSTraceSource> matchingSources, TraceListener listener)
{
// Now add the listener to all the sources
foreach (PSTraceSource source in matchingSources)
{
source.Listeners.Add(listener);
}
}
#endregion AddTraceListeners
#region RemoveTraceListeners
/// <summary>
/// Removes the tracelisteners from the specified trace sources.
/// </summary>
internal static void RemoveListenersByName(
Collection<PSTraceSource> matchingSources,
string[] listenerNames,
bool fileListenersOnly)
{
Collection<WildcardPattern> listenerMatcher =
SessionStateUtilities.CreateWildcardsFromStrings(
listenerNames,
WildcardOptions.IgnoreCase);
// Loop through all the matching sources and remove the matching listeners
foreach (PSTraceSource source in matchingSources)
{
// Get the indexes of the listeners that need to be removed.
// This is done because we cannot remove the listeners while
// we are enumerating them.
for (int index = source.Listeners.Count - 1; index >= 0; --index)
{
TraceListener listenerToRemove = source.Listeners[index];
if (fileListenersOnly && listenerToRemove is not TextWriterTraceListener)
{
// Since we only want to remove file listeners, skip any that
// aren't file listeners
continue;
}
// Now match the names
if (SessionStateUtilities.MatchesAnyWildcardPattern(
listenerToRemove.Name,
listenerMatcher,
true))
{
listenerToRemove.Flush();
listenerToRemove.Dispose();
source.Listeners.RemoveAt(index);
}
}
}
}
#endregion RemoveTraceListeners
#region SetTraceListenerOptions
/// <summary>
/// Sets the trace listener options based on the ListenerOptions parameter.
/// </summary>
internal void SetTraceListenerOptions(Collection<PSTraceSource> matchingSources)
{
// Set the trace options if they were specified
if (traceOptionsSpecified)
{
foreach (PSTraceSource source in matchingSources)
{
foreach (TraceListener listener in source.Listeners)
{
listener.TraceOutputOptions = this.ListenerOptionsInternal;
}
}
}
}
#endregion SetTraceListenerOptions
#region SetFlags
/// <summary>
/// Sets the flags for all the specified TraceSources.
/// </summary>
internal void SetFlags(Collection<PSTraceSource> matchingSources)
{
foreach (PSTraceSource structuredSource in matchingSources)
{
structuredSource.Options = this.OptionsInternal;
}
}
#endregion SetFlags
#region TurnOnTracing
/// <summary>
/// Turns on tracing for the TraceSources, flags, and listeners defined by the parameters.
/// </summary>
internal void TurnOnTracing(Collection<PSTraceSource> matchingSources, bool preConfigured)
{
foreach (PSTraceSource source in matchingSources)
{
// Store the current state of the TraceSource
if (!_storedTraceSourceState.ContainsKey(source))
{
// Copy the listeners into a different collection
Collection<TraceListener> listenerCollection = new();
foreach (TraceListener listener in source.Listeners)
{
listenerCollection.Add(listener);
}
if (preConfigured)
{
// If the source is a preconfigured source, then the default options
// and listeners should be stored as the existing state.
_storedTraceSourceState[source] =
new KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>(
PSTraceSourceOptions.None,
new Collection<TraceListener>());
}
else
{
_storedTraceSourceState[source] =
new KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>(
source.Options,
listenerCollection);
}
}
// Now set the new flags
source.Options = this.OptionsInternal;
}
// Now turn on the listeners
AddTraceListenersToSources(matchingSources);
SetTraceListenerOptions(matchingSources);
}
#endregion TurnOnTracing
#region ResetTracing
/// <summary>
/// Resets tracing to the previous level for the TraceSources defined by the parameters.
/// Note, TurnOnTracing must be called before calling ResetTracing or else all
/// TraceSources will be turned off.
/// </summary>
internal void ResetTracing(Collection<PSTraceSource> matchingSources)
{
foreach (PSTraceSource source in matchingSources)
{
// First flush all the existing trace listeners
foreach (TraceListener listener in source.Listeners)
{
listener.Flush();
}
if (_storedTraceSourceState.ContainsKey(source))
{
// Restore the TraceSource to its original state
KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>> storedState =
_storedTraceSourceState[source];
source.Listeners.Clear();
foreach (TraceListener listener in storedState.Value)
{
source.Listeners.Add(listener);
}
source.Options = storedState.Key;
}
else
{
// Since we don't have any stored state for this TraceSource,
// just turn it off.
source.Listeners.Clear();
source.Options = PSTraceSourceOptions.None;
}
}
}
#endregion ResetTracing
#region stored state
/// <summary>
/// Clears the store TraceSource state.
/// </summary>
protected void ClearStoredState()
{
// First close all listeners
foreach (KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>> pair in _storedTraceSourceState.Values)
{
foreach (TraceListener listener in pair.Value)
{
listener.Flush();
listener.Dispose();
}
}
_storedTraceSourceState.Clear();
}
private readonly Dictionary<PSTraceSource, KeyValuePair<PSTraceSourceOptions, Collection<TraceListener>>> _storedTraceSourceState =
new();
#endregion stored state
}
}
| |
// 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.Apis.GroupsMigration.v1
{
/// <summary>The GroupsMigration Service.</summary>
public class GroupsMigrationService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GroupsMigrationService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GroupsMigrationService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Archive = new ArchiveResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "groupsmigration";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://groupsmigration.googleapis.com/";
#else
"https://groupsmigration.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://groupsmigration.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Groups Migration API.</summary>
public class Scope
{
/// <summary>Upload messages to any Google group in your domain</summary>
public static string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Groups Migration API.</summary>
public static class ScopeConstants
{
/// <summary>Upload messages to any Google group in your domain</summary>
public const string AppsGroupsMigration = "https://www.googleapis.com/auth/apps.groups.migration";
}
/// <summary>Gets the Archive resource.</summary>
public virtual ArchiveResource Archive { get; }
}
/// <summary>A base abstract class for GroupsMigration requests.</summary>
public abstract class GroupsMigrationBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new GroupsMigrationBaseServiceRequest instance.</summary>
protected GroupsMigrationBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes GroupsMigration parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "archive" collection of methods.</summary>
public class ArchiveResource
{
private const string Resource = "archive";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ArchiveResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <param name="groupId">The group ID</param>
public virtual InsertRequest Insert(string groupId)
{
return new InsertRequest(service, groupId);
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
public class InsertRequest : GroupsMigrationBaseServiceRequest<Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, string groupId) : base(service)
{
GroupId = groupId;
InitParameters();
}
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "insert";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "groups/v1/groups/{groupId}/archive";
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("groupId", new Google.Apis.Discovery.Parameter
{
Name = "groupId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Inserts a new mail into the archive of the Google group.</summary>
/// <remarks>
/// Considerations regarding <paramref name="stream"/>:
/// <list type="bullet">
/// <item>
/// <description>
/// If <paramref name="stream"/> is seekable, then the stream position will be reset to <c>0</c> before reading
/// commences. If <paramref name="stream"/> is not seekable, then it will be read from its current position
/// </description>
/// </item>
/// <item>
/// <description>
/// Caller is responsible for maintaining the <paramref name="stream"/> open until the upload is completed
/// </description>
/// </item>
/// <item><description>Caller is responsible for closing the <paramref name="stream"/></description></item>
/// </list>
/// </remarks>
/// <param name="groupId">The group ID</param>
/// <param name="stream">The stream to upload. See remarks for further information.</param>
/// <param name="contentType">The content type of the stream to upload.</param>
public virtual InsertMediaUpload Insert(string groupId, System.IO.Stream stream, string contentType)
{
return new InsertMediaUpload(service, groupId, stream, contentType);
}
/// <summary>Insert media upload which supports resumable upload.</summary>
public class InsertMediaUpload : Google.Apis.Upload.ResumableUpload<string, Google.Apis.GroupsMigration.v1.Data.Groups>
{
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned
/// to a user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>The group ID</summary>
[Google.Apis.Util.RequestParameterAttribute("groupId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string GroupId { get; private set; }
/// <summary>Constructs a new Insert media upload instance.</summary>
/// <remarks>
/// Considerations regarding <paramref name="stream"/>:
/// <list type="bullet">
/// <item>
/// <description>
/// If <paramref name="stream"/> is seekable, then the stream position will be reset to <c>0</c> before
/// reading commences. If <paramref name="stream"/> is not seekable, then it will be read from its current
/// position
/// </description>
/// </item>
/// <item>
/// <description>
/// Caller is responsible for maintaining the <paramref name="stream"/> open until the upload is completed
/// </description>
/// </item>
/// <item><description>Caller is responsible for closing the <paramref name="stream"/></description></item>
/// </list>
/// </remarks>
public InsertMediaUpload(Google.Apis.Services.IClientService service, string groupId, System.IO.Stream stream, string contentType)
: base(service, string.Format("/{0}/{1}{2}", "upload", service.BasePath, "groups/v1/groups/{groupId}/archive"), "POST", stream, contentType)
{
GroupId = groupId;
}
}
}
}
namespace Google.Apis.GroupsMigration.v1.Data
{
/// <summary>JSON response template for groups migration API.</summary>
public class Groups : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The kind of insert resource this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The status of the insert request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseCode")]
public virtual string ResponseCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
/*
* 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 NUnit.Framework;
using OpenMetaverse;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Basic scene object status tests
/// </summary>
[TestFixture]
public class SceneObjectStatusTests : OpenSimTestCase
{
private TestScene m_scene;
private UUID m_ownerId = TestHelpers.ParseTail(0x1);
private SceneObjectGroup m_so1;
private SceneObjectGroup m_so2;
[SetUp]
public void Init()
{
m_scene = new SceneHelpers().SetupScene();
m_so1 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so1", 0x10);
m_so2 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so2", 0x20);
}
[Test]
public void TestSetTemporary()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_so1.ScriptSetTemporaryStatus(true);
// Is this really the correct flag?
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.TemporaryOnRez));
Assert.That(m_so1.Backup, Is.False);
// Test setting back to non-temporary
m_so1.ScriptSetTemporaryStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Backup, Is.True);
}
[Test]
public void TestSetPhantomSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhantomStatus(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom));
m_so1.ScriptSetPhantomStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetNonPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetVolumeDetect(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
m_so1.ScriptSetVolumeDetect(true);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom | PrimFlags.Physics));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
}
[Test]
public void TestSetPhysicsLinkset()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsBothPhysical()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsRootPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsChildPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
}
}
}
| |
// -----------------------------------------------------------
//
// This file was generated, please do not modify.
//
// -----------------------------------------------------------
namespace EmptyKeys.UserInterface.Generated {
using System;
using System.CodeDom.Compiler;
using System.Collections.ObjectModel;
using EmptyKeys.UserInterface;
using EmptyKeys.UserInterface.Charts;
using EmptyKeys.UserInterface.Data;
using EmptyKeys.UserInterface.Controls;
using EmptyKeys.UserInterface.Controls.Primitives;
using EmptyKeys.UserInterface.Input;
using EmptyKeys.UserInterface.Media;
using EmptyKeys.UserInterface.Media.Animation;
using EmptyKeys.UserInterface.Media.Imaging;
using EmptyKeys.UserInterface.Shapes;
using EmptyKeys.UserInterface.Renderers;
using EmptyKeys.UserInterface.Themes;
[GeneratedCodeAttribute("Empty Keys UI Generator", "1.11.0.0")]
public partial class LoginForm : UIRoot {
private Grid e_0;
private StackPanel e_1;
private TextBlock e_2;
private StackPanel e_3;
private StackPanel e_4;
private TextBlock e_5;
private TextBox UsernameBox;
private StackPanel e_6;
private TextBlock e_7;
private PasswordBox PasswordBox;
private Button LoginBtn;
private Button ForgotPasswordBtn;
private Button NoAccountBtn;
public LoginForm() :
base() {
this.Initialize();
}
public LoginForm(int width, int height) :
base(width, height) {
this.Initialize();
}
private void Initialize() {
Style style = RootStyle.CreateRootStyle();
style.TargetType = this.GetType();
this.Style = style;
this.InitializeComponent();
}
private void InitializeComponent() {
this.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
InitializeElementResources(this);
// e_0 element
this.e_0 = new Grid();
this.Content = this.e_0;
this.e_0.Name = "e_0";
// e_1 element
this.e_1 = new StackPanel();
this.e_0.Children.Add(this.e_1);
this.e_1.Name = "e_1";
this.e_1.HorizontalAlignment = HorizontalAlignment.Center;
this.e_1.VerticalAlignment = VerticalAlignment.Center;
this.e_1.Orientation = Orientation.Vertical;
// e_2 element
this.e_2 = new TextBlock();
this.e_1.Children.Add(this.e_2);
this.e_2.Name = "e_2";
this.e_2.Margin = new Thickness(10F, 10F, 10F, 30F);
this.e_2.HorizontalAlignment = HorizontalAlignment.Center;
this.e_2.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255));
this.e_2.Text = "MP Tanks 2D";
this.e_2.FontFamily = new FontFamily("JHUF");
this.e_2.FontSize = 72F;
// e_3 element
this.e_3 = new StackPanel();
this.e_1.Children.Add(this.e_3);
this.e_3.Name = "e_3";
this.e_3.HorizontalAlignment = HorizontalAlignment.Center;
this.e_3.VerticalAlignment = VerticalAlignment.Center;
this.e_3.Orientation = Orientation.Vertical;
// e_4 element
this.e_4 = new StackPanel();
this.e_3.Children.Add(this.e_4);
this.e_4.Name = "e_4";
this.e_4.Orientation = Orientation.Horizontal;
// e_5 element
this.e_5 = new TextBlock();
this.e_4.Children.Add(this.e_5);
this.e_5.Name = "e_5";
this.e_5.Width = 150F;
this.e_5.Margin = new Thickness(0F, 0F, 10F, 0F);
this.e_5.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255));
this.e_5.Text = "Email";
this.e_5.Padding = new Thickness(10F, 10F, 10F, 10F);
this.e_5.FontFamily = new FontFamily("JHUF");
this.e_5.FontSize = 18F;
// UsernameBox element
this.UsernameBox = new TextBox();
this.e_4.Children.Add(this.UsernameBox);
this.UsernameBox.Name = "UsernameBox";
this.UsernameBox.Width = 300F;
this.UsernameBox.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.UsernameBox.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255));
// e_6 element
this.e_6 = new StackPanel();
this.e_3.Children.Add(this.e_6);
this.e_6.Name = "e_6";
this.e_6.Margin = new Thickness(0F, 10F, 0F, 0F);
this.e_6.Orientation = Orientation.Horizontal;
// e_7 element
this.e_7 = new TextBlock();
this.e_6.Children.Add(this.e_7);
this.e_7.Name = "e_7";
this.e_7.Width = 150F;
this.e_7.Margin = new Thickness(0F, 0F, 10F, 0F);
this.e_7.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255));
this.e_7.Text = "Password";
this.e_7.Padding = new Thickness(10F, 10F, 10F, 10F);
this.e_7.FontFamily = new FontFamily("JHUF");
this.e_7.FontSize = 18F;
// PasswordBox element
this.PasswordBox = new PasswordBox();
this.e_6.Children.Add(this.PasswordBox);
this.PasswordBox.Name = "PasswordBox";
this.PasswordBox.Width = 300F;
this.PasswordBox.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.PasswordBox.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255));
// LoginBtn element
this.LoginBtn = new Button();
this.e_3.Children.Add(this.LoginBtn);
this.LoginBtn.Name = "LoginBtn";
this.LoginBtn.Width = 450F;
this.LoginBtn.Margin = new Thickness(0F, 10F, 0F, 0F);
this.LoginBtn.HorizontalAlignment = HorizontalAlignment.Center;
this.LoginBtn.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.LoginBtn.BorderBrush = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.LoginBtn.Padding = new Thickness(10F, 10F, 10F, 10F);
this.LoginBtn.Foreground = new SolidColorBrush(new ColorW(255, 255, 255, 255));
this.LoginBtn.FontFamily = new FontFamily("JHUF");
this.LoginBtn.FontSize = 36F;
this.LoginBtn.Content = "Log in";
Binding binding_LoginBtn_Command = new Binding("HostGameCommand");
this.LoginBtn.SetBinding(Button.CommandProperty, binding_LoginBtn_Command);
// ForgotPasswordBtn element
this.ForgotPasswordBtn = new Button();
this.e_3.Children.Add(this.ForgotPasswordBtn);
this.ForgotPasswordBtn.Name = "ForgotPasswordBtn";
this.ForgotPasswordBtn.Width = 450F;
this.ForgotPasswordBtn.Margin = new Thickness(0F, 10F, 0F, 0F);
this.ForgotPasswordBtn.HorizontalAlignment = HorizontalAlignment.Center;
this.ForgotPasswordBtn.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.ForgotPasswordBtn.BorderBrush = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.ForgotPasswordBtn.Padding = new Thickness(5F, 5F, 5F, 5F);
this.ForgotPasswordBtn.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255));
this.ForgotPasswordBtn.FontFamily = new FontFamily("JHUF");
this.ForgotPasswordBtn.FontSize = 18F;
this.ForgotPasswordBtn.Content = "Forgot your password?";
// NoAccountBtn element
this.NoAccountBtn = new Button();
this.e_3.Children.Add(this.NoAccountBtn);
this.NoAccountBtn.Name = "NoAccountBtn";
this.NoAccountBtn.Width = 450F;
this.NoAccountBtn.Margin = new Thickness(0F, 10F, 0F, 0F);
this.NoAccountBtn.HorizontalAlignment = HorizontalAlignment.Center;
this.NoAccountBtn.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.NoAccountBtn.BorderBrush = new SolidColorBrush(new ColorW(255, 255, 255, 0));
this.NoAccountBtn.Padding = new Thickness(5F, 5F, 5F, 5F);
this.NoAccountBtn.Foreground = new SolidColorBrush(new ColorW(128, 128, 128, 255));
this.NoAccountBtn.FontFamily = new FontFamily("JHUF");
this.NoAccountBtn.FontSize = 18F;
this.NoAccountBtn.Content = "No account? Buy MP Tanks!";
FontManager.Instance.AddFont("JHUF", 36F, FontStyle.Regular, "JHUF_27_Regular");
FontManager.Instance.AddFont("JHUF", 18F, FontStyle.Regular, "JHUF_13.5_Regular");
FontManager.Instance.AddFont("JHUF", 24F, FontStyle.Regular, "JHUF_18_Regular");
FontManager.Instance.AddFont("JHUF", 72F, FontStyle.Regular, "JHUF_54_Regular");
}
private static void InitializeElementResources(UIElement elem) {
elem.Resources.MergedDictionaries.Add(UITemplateDictionary.Instance);
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NLog.Common;
using NLog.Config;
/// <summary>
/// Scans (breadth-first) the object graph following all the edges whose are
/// instances have <see cref="NLogConfigurationItemAttribute"/> attached and returns
/// all objects implementing a specified interfaces.
/// </summary>
internal static class ObjectGraphScanner
{
/// <summary>
/// Finds the objects which have attached <see cref="NLogConfigurationItemAttribute"/> which are reachable
/// from any of the given root objects when traversing the object graph over public properties.
/// </summary>
/// <typeparam name="T">Type of the objects to return.</typeparam>
/// <param name="aggressiveSearch">Also search the properties of the wanted objects.</param>
/// <param name="rootObjects">The root objects.</param>
/// <returns>Ordered list of objects implementing T.</returns>
public static List<T> FindReachableObjects<T>(bool aggressiveSearch, params object[] rootObjects)
where T : class
{
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("FindReachableObject<{0}>:", typeof(T));
}
var result = new List<T>();
var visitedObjects = new HashSet<object>(SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default);
foreach (var rootObject in rootObjects)
{
ScanProperties(aggressiveSearch, result, rootObject, 0, visitedObjects);
}
return result;
}
/// <remarks>ISet is not there in .net35, so using HashSet</remarks>
private static void ScanProperties<T>(bool aggressiveSearch, List<T> result, object o, int level, HashSet<object> visitedObjects)
where T : class
{
if (o == null)
{
return;
}
if (visitedObjects.Contains(o))
{
return;
}
var type = o.GetType();
if (!IncludeConfigurationItem(o, type, level))
{
return;
}
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), type.Name, o);
}
if (o is T t)
{
result.Add(t);
if (!aggressiveSearch)
{
return;
}
}
foreach (PropertyInfo prop in PropertyHelper.GetAllReadableProperties(type))
{
var propValue = GetConfigurationPropertyValue(o, prop, level);
if (propValue == null)
continue;
visitedObjects.Add(o);
ScanPropertyForObject(prop, propValue, aggressiveSearch, result, level, visitedObjects);
}
}
private static void ScanPropertyForObject<T>(PropertyInfo prop, object propValue, bool aggressiveSearch, List<T> result, int level, HashSet<object> visitedObjects) where T : class
{
if (InternalLogger.IsTraceEnabled)
{
InternalLogger.Trace("{0}Scanning Property {1} '{2}' {3}", new string(' ', level + 1), prop.Name, propValue.ToString(), prop.PropertyType.Namespace);
}
if (propValue is IList list)
{
if (list.Count > 0)
{
if (list.IsReadOnly)
{
ScanPropertiesList(aggressiveSearch, result, list, level + 1, visitedObjects);
}
else
{
List<object> elements = new List<object>(list.Count);
lock (list.SyncRoot)
{
for (int i = 0; i < list.Count; i++)
{
elements.Add(list[i]);
}
}
ScanPropertiesList(aggressiveSearch, result, elements, level + 1, visitedObjects);
}
}
}
else if (propValue is IEnumerable enumerable)
{
//new list to prevent: Collection was modified after the enumerator was instantiated.
var elements = enumerable as IList<object> ?? enumerable.Cast<object>().ToList();
//note .Cast is tread-unsafe! But at least it isn't a ICollection / IList
if (elements.Count > 0)
{
ScanPropertiesList(aggressiveSearch, result, elements, level + 1, visitedObjects);
}
}
else
{
if (IgnoreSimpleType(prop.PropertyType))
{
return;
}
#if NETSTANDARD
if (!prop.PropertyType.IsDefined(typeof(NLogConfigurationItemAttribute), true))
{
return; // .NET native doesn't always allow reflection of System-types (Ex. Encoding)
}
#endif
ScanProperties(aggressiveSearch, result, propValue, level + 1, visitedObjects);
}
}
private static object GetConfigurationPropertyValue(object o, PropertyInfo prop, int level)
{
if (prop == null || IgnoreSimpleType(prop.PropertyType))
{
return null;
}
try
{
if (prop.IsDefined(typeof(NLogConfigurationIgnorePropertyAttribute), true))
{
return null;
}
}
catch (System.Exception ex)
{
InternalLogger.Info(ex, "{0}Type reflection not possible for property {1}. Maybe because of .NET Native.", new string(' ', level + 1), prop.Name);
return null;
}
return prop.GetValue(o, null);
}
private static bool IncludeConfigurationItem(object item, Type itemType, int level)
{
try
{
if (itemType == null)
return false;
if (item is NLog.LayoutRenderers.LayoutRenderer)
return true;
if (item is NLog.Layouts.Layout)
return true;
if (item is NLog.Targets.Target)
return true;
if (item is LoggingRule)
return true;
if (itemType.IsDefined(typeof(NLogConfigurationItemAttribute), true))
return true;
}
catch (System.Exception ex)
{
InternalLogger.Info(ex, "{0}Type reflection not possible for: {1}. Maybe because of .NET Native.", new string(' ', level), item.ToString());
}
return false;
}
private static bool IgnoreSimpleType(Type type)
{
return type == null || type.IsPrimitive() || type.IsEnum() || type == typeof(string) || type == typeof(System.Globalization.CultureInfo) || type == typeof(Type);
}
private static void ScanPropertiesList<T>(bool aggressiveSearch, List<T> result, IEnumerable elements, int level, HashSet<object> visitedObjects) where T : class
{
foreach (object element in elements)
{
if (element == null || IgnoreSimpleType(element.GetType()))
continue;
ScanProperties(aggressiveSearch, result, element, level, visitedObjects);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using log4net;
using Gearman.Packets.Worker;
namespace Gearman
{
/// <summary>
/// This class is a "worker" in the client <--> manager <--> worker model that Gearman follows.
/// A worker is a simply an intermediary between some actual code and the Gearman network. The onus
/// is on the user to write the methods that perform the actual work requested and respond with the
/// correct results. The worker simply talks to the manager to get requests for work, and then makes
/// calls to callback methods written by the user.
/// </summary>
/// <example>
/// The following provides a very simple worker program that is capable of counting the words in a byte[] array
/// using the newline charavter as the delimiter between 'words' (thus acting more like a 'line count' technically)
///
/// <code>
/// private static byte[] wctest(Packet jobPacket, Connection c)
/// {
/// int words = 0;
/// byte[] outdata = new byte[1024];
/// byte[] indata = jobPacket.Data;
/// for(int i = 0; i < indata.Length; i++)
/// {
/// if (indata[i] == 10)
/// words++;
/// }
///
/// outdata = BitConverter.GetBytes(words);
/// Console.WriteLine("Found {0} words", words);
/// return outdata;
/// }
///
/// public static void Main(String[] args)
/// {
/// Worker w = new Worker("localhost");
/// w.registerFunction("wc", wctest);
/// w.workLoop();
/// }
/// </code>
/// </example>
/// <summary>
/// Task delegate must take a packet and a connection and return a byte array
/// The connection is required to send data back (such as progress updates), and
/// the packet is used to get information such as job handle, packet data, etc.
/// </summary>
public delegate void taskdelegate(Job j);
public class Worker
{
// Manager connection
// TODO: Add round-robin or multiple servers to the worker
private Connection c;
// Dictionary of method mappings (string -> delegate)
private Dictionary<string, taskdelegate> methodMap;
// Running thread
private Thread t;
private static readonly ILog Log = LogManager.GetLogger(typeof(Worker));
/// <summary>
/// Default constructor, initialize empty method map of strings -> delegates
/// </summary>
public Worker()
{
methodMap = new Dictionary<string, taskdelegate>();
}
/// <summary>
/// Constructor requiring both the host and the port number to connect to
/// </summary>
/// <param name="host">
/// A <see cref="System.String"/> representing the host to connect to
/// </param>
/// <param name="port">
/// A <see cref="System.Int32"/> port to connect to (if other than the default of 4730)
/// </param>
public Worker (string host, int port) : this()
{
this.c = new Connection(host, port);
}
/// <summary>
/// Constructor requiring only the host name; the default port of 4730 is used
/// </summary>
/// <param name="host">
/// A <see cref="System.String"/> representing the host to connect to
/// </param>
public Worker (string host) : this(host, 4730)
{ }
/// <summary>
/// Add a task <--> delegate mapping to this worker. A task name is a short string that the worker registers
/// with the manager, for example "reverse". The delegate is a callback that the worker calls when it receives a
/// packet of work to do that has a task name matching the registered name.
/// </summary>
/// <param name="taskname">
/// A <see cref="System.String"/> that is the 'name' of the task being registered with the server
/// </param>
/// <param name="function">
/// A <see cref="taskdelegate"/> that is the actual callback function
/// (must match the <see cref="taskdelegate"/> specification)
/// </param>
public void registerFunction(string taskname, taskdelegate function)
{
if(!methodMap.ContainsKey(taskname))
{
c.sendPacket(new CanDo(taskname));
}
methodMap[taskname] = function;
}
/// <summary>
/// Get this thing going.
/// </summary>
public void workLoop()
{
t = new Thread(new ThreadStart(run));
t.Start();
}
/// <summary>
/// Terminate the work thread.
/// </summary>
public void stopWorkLoop()
{
if (t != null)
{
t.Abort();
}
}
/// <summary>
/// Obligatory run method for the Thread. Runs indefinitely, checking for a job every 2 seconds
/// TODO: make this time adjustable if needed
/// </summary>
public void run()
{
while(true)
{
checkForJob();
Log.DebugFormat("Sleeping for 2 seconds");
Thread.Sleep(2000);
}
}
/// <summary>
/// Checks with the manager for a new job to work on. The manager has a record of all the tasks that the
/// worker is capable of working on, so most of the real work here is done by the manager to find something
/// for the worker to work on. If something is assigned, load the data, execute the callback and then return
/// the data to the manager so that the worker can move on to something else.
/// </summary>
private void checkForJob()
{
ASCIIEncoding encoder = new ASCIIEncoding();
// Grab job from server (if available)
Log.DebugFormat("Checking for job...");
c.sendPacket(new GrabJob());
Packet response = c.getNextPacket();
if (response.Type == PacketType.JOB_ASSIGN)
{
Job job = new Job((JobAssign)response, this);
Log.DebugFormat("Assigned job: {0}", job.jobhandle);
Log.DebugFormat("Payload length: {0}", job.data.Length);
Log.DebugFormat("Task: {0}", job.taskname);
// Fire event for listeners
methodMap[job.taskname](job);
} else if (response.Type == PacketType.NO_JOB) {
Log.DebugFormat("Nothing to do!");
}
}
public Connection connection {
get {
return c;
}
set { }
}
}
}
| |
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
/*
** BYTEmark (tm)
** BYTE Magazine's Native Mode benchmarks
** Rick Grehan, BYTE Magazine
**
** Create:
** Revision: 3/95
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
**
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
*/
/********************************
** BACK PROPAGATION NEURAL NET **
*********************************
** This code is a modified version of the code
** that was submitted to BYTE Magazine by
** Maureen Caudill. It accomanied an article
** that I CANNOT NOW RECALL.
** The author's original heading/comment was
** as follows:
**
** Backpropagation Network
** Written by Maureen Caudill
** in Think C 4.0 on a Macintosh
**
** (c) Maureen Caudill 1988-1991
** This network will accept 5x7 input patterns
** and produce 8 bit output patterns.
** The source code may be copied or modified without restriction,
** but no fee may be charged for its use.
**
** ++++++++++++++
** I have modified the code so that it will work
** on systems other than a Macintosh -- RG
*/
/***********
** DoNNet **
************
** Perform the neural net benchmark.
** Note that this benchmark is one of the few that
** requires an input file. That file is "NNET.DAT" and
** should be on the local directory (from which the
** benchmark program in launched).
*/
using System;
using System.IO;
public class NeuralJagged : NNetStruct
{
public override string Name()
{
return "NEURAL NET(jagged)";
}
/*
** DEFINES
*/
public static int T = 1; /* TRUE */
public static int F = 0; /* FALSE */
public static int ERR = -1;
public static int MAXPATS = 10; /* max number of patterns in data file */
public static int IN_X_SIZE = 5; /* number of neurodes/row of input layer */
public static int IN_Y_SIZE = 7; /* number of neurodes/col of input layer */
public static int IN_SIZE = 35; /* equals IN_X_SIZE*IN_Y_SIZE */
public static int MID_SIZE = 8; /* number of neurodes in middle layer */
public static int OUT_SIZE = 8; /* number of neurodes in output layer */
public static double MARGIN = 0.1; /* how near to 1,0 do we have to come to stop? */
public static double BETA = 0.09; /* beta learning constant */
public static double ALPHA = 0.09; /* momentum term constant */
public static double STOP = 0.1; /* when worst_error less than STOP, training is done */
/*
** MAXNNETLOOPS
**
** This constant sets the max number of loops through the neural
** net that the system will attempt before giving up. This
** is not a critical constant. You can alter it if your system
** has sufficient horsepower.
*/
public static int MAXNNETLOOPS = 50000;
/*
** GLOBALS
*/
public static double[][] mid_wts = new double[MID_SIZE][];
public static double[][] out_wts = new double[OUT_SIZE][];
public static double[] mid_out = new double[MID_SIZE];
public static double[] out_out = new double[OUT_SIZE];
public static double[] mid_error = new double[MID_SIZE];
public static double[] out_error = new double[OUT_SIZE];
public static double[][] mid_wt_change = new double[MID_SIZE][];
public static double[][] out_wt_change = new double[OUT_SIZE][];
public static double[][] in_pats = new double[MAXPATS][];
public static double[][] out_pats = new double[MAXPATS][];
public static double[] tot_out_error = new double[MAXPATS];
public static double[][] out_wt_cum_change = new double[OUT_SIZE][];
public static double[][] mid_wt_cum_change = new double[MID_SIZE][];
public static double worst_error = 0.0; /* worst error each pass through the data */
public static double average_error = 0.0; /* average error each pass through the data */
public static double[] avg_out_error = new double[MAXPATS];
public static int iteration_count = 0; /* number of passes thru network so far */
public static int numpats = 0; /* number of patterns in data file */
public static int numpasses = 0; /* number of training passes through data file */
public static int learned = 0; /* flag--if TRUE, network has learned all patterns */
/*
** The Neural Net test requires an input data file.
** The name is specified here.
*/
public static string inpath = "NNET.DAT";
public static void Init()
{
for (int i = 0; i < MID_SIZE; i++)
{
mid_wts[i] = new double[IN_SIZE];
mid_wt_cum_change[i] = new double[IN_SIZE];
mid_wt_change[i] = new double[IN_SIZE];
}
for (int i = 0; i < OUT_SIZE; i++)
{
out_wt_change[i] = new double[MID_SIZE];
out_wts[i] = new double[MID_SIZE];
out_wt_cum_change[i] = new double[MID_SIZE];
}
for (int i = 0; i < MAXPATS; i++)
{
in_pats[i] = new double[IN_SIZE];
out_pats[i] = new double[OUT_SIZE];
}
}
public override
double Run()
{
Init();
return DoNNET(this);
}
/*********************
** read_data_file() **
**********************
** Read in the input data file and store the patterns in
** in_pats and out_pats.
** The format for the data file is as follows:
**
** line# data expected
** ----- ------------------------------
** 1 In-X-size,in-y-size,out-size
** 2 number of patterns in file
** 3 1st X row of 1st input pattern
** 4.. following rows of 1st input pattern pattern
** in-x+2 y-out pattern
** 1st X row of 2nd pattern
** etc.
**
** Each row of data is separated by commas or spaces.
** The data is expected to be ascii text corresponding to
** either a +1 or a 0.
**
** Sample input for a 1-pattern file (The comments to the
** right may NOT be in the file unless more sophisticated
** parsing of the input is done.):
**
** 5,7,8 input is 5x7 grid, output is 8 bits
** 1 one pattern in file
** 0,1,1,1,0 beginning of pattern for "O"
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,0
** 0,1,1,1,0
** 0,1,0,0,1,1,1,1 ASCII code for "O" -- 0100 1111
**
** Clearly, this simple scheme can be expanded or enhanced
** any way you like.
**
** Returns -1 if any file error occurred, otherwise 0.
**/
private
void read_data_file()
{
int xinsize = 0, yinsize = 0, youtsize = 0;
int patt = 0, element = 0, i = 0, row = 0;
int vals_read = 0;
int val1 = 0, val2 = 0, val3 = 0, val4 = 0, val5 = 0, val6 = 0, val7 = 0, val8 = 0;
Object[] results = new Object[8];
string input = NeuralData.Input;
StringReader infile = new StringReader(input);
vals_read = Utility.fscanf(infile, "%d %d %d", results);
xinsize = (int)results[0];
yinsize = (int)results[1];
youtsize = (int)results[2];
if (vals_read != 3)
{
throw new Exception("NNET: error reading input");
}
vals_read = Utility.fscanf(infile, "%d", results);
numpats = (int)results[0];
if (vals_read != 1)
{
throw new Exception("NNET: error reading input");
}
if (numpats > MAXPATS)
numpats = MAXPATS;
for (patt = 0; patt < numpats; patt++)
{
element = 0;
for (row = 0; row < yinsize; row++)
{
vals_read = Utility.fscanf(infile, "%d %d %d %d %d", results);
val1 = (int)results[0];
val2 = (int)results[1];
val3 = (int)results[2];
val4 = (int)results[3];
val5 = (int)results[4];
if (vals_read != 5)
{
throw new Exception("NNET: error reading input");
}
element = row * xinsize;
in_pats[patt][element] = (double)val1; element++;
in_pats[patt][element] = (double)val2; element++;
in_pats[patt][element] = (double)val3; element++;
in_pats[patt][element] = (double)val4; element++;
in_pats[patt][element] = (double)val5; element++;
}
for (i = 0; i < IN_SIZE; i++)
{
if (in_pats[patt][i] >= 0.9)
in_pats[patt][i] = 0.9;
if (in_pats[patt][i] <= 0.1)
in_pats[patt][i] = 0.1;
}
element = 0;
vals_read = Utility.fscanf(infile, "%d %d %d %d %d %d %d %d", results);
val1 = (int)results[0];
val2 = (int)results[1];
val3 = (int)results[2];
val4 = (int)results[3];
val5 = (int)results[4];
val6 = (int)results[5];
val7 = (int)results[6];
val8 = (int)results[7];
out_pats[patt][element] = (double)val1; element++;
out_pats[patt][element] = (double)val2; element++;
out_pats[patt][element] = (double)val3; element++;
out_pats[patt][element] = (double)val4; element++;
out_pats[patt][element] = (double)val5; element++;
out_pats[patt][element] = (double)val6; element++;
out_pats[patt][element] = (double)val7; element++;
out_pats[patt][element] = (double)val8; element++;
}
}
private
double DoNNET(NNetStruct locnnetstruct)
{
// string errorcontext = "CPU:NNET";
// int systemerror = 0;
long accumtime = 0;
double iterations = 0.0;
/*
** Init random number generator.
** NOTE: It is important that the random number generator
** be re-initialized for every pass through this test.
** The NNET algorithm uses the random number generator
** to initialize the net. Results are sensitive to
** the initial neural net state.
*/
ByteMark.randnum(3);
/*
** Read in the input and output patterns. We'll do this
** only once here at the beginning. These values don't
** change once loaded.
*/
read_data_file();
/*
** See if we need to perform self adjustment loop.
*/
if (locnnetstruct.adjust == 0)
{
/*
** Do self-adjustment. This involves initializing the
** # of loops and increasing the loop count until we
** get a number of loops that we can use.
*/
for (locnnetstruct.loops = 1;
locnnetstruct.loops < MAXNNETLOOPS;
locnnetstruct.loops++)
{
ByteMark.randnum(3);
if (DoNNetIteration(locnnetstruct.loops) > global.min_ticks)
break;
}
}
/*
** All's well if we get here. Do the test.
*/
accumtime = 0L;
iterations = (double)0.0;
do
{
ByteMark.randnum(3); /* Gotta do this for Neural Net */
accumtime += DoNNetIteration(locnnetstruct.loops);
iterations += (double)locnnetstruct.loops;
} while (ByteMark.TicksToSecs(accumtime) < locnnetstruct.request_secs);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
locnnetstruct.iterspersec = iterations / ByteMark.TicksToFracSecs(accumtime);
if (locnnetstruct.adjust == 0)
locnnetstruct.adjust = 1;
return locnnetstruct.iterspersec;
}
/********************
** DoNNetIteration **
*********************
** Do a single iteration of the neural net benchmark.
** By iteration, we mean a "learning" pass.
*/
public static long DoNNetIteration(long nloops)
{
long elapsed; /* Elapsed time */
int patt;
/*
** Run nloops learning cycles. Notice that, counted with
** the learning cycle is the weight randomization and
** zeroing of changes. This should reduce clock jitter,
** since we don't have to stop and start the clock for
** each iteration.
*/
elapsed = ByteMark.StartStopwatch();
while (nloops-- != 0)
{
randomize_wts();
zero_changes();
iteration_count = 1;
learned = F;
numpasses = 0;
while (learned == F)
{
for (patt = 0; patt < numpats; patt++)
{
worst_error = 0.0; /* reset this every pass through data */
move_wt_changes(); /* move last pass's wt changes to momentum array */
do_forward_pass(patt);
do_back_pass(patt);
iteration_count++;
}
numpasses++;
learned = check_out_error();
}
}
return (ByteMark.StopStopwatch(elapsed));
}
/*************************
** do_mid_forward(patt) **
**************************
** Process the middle layer's forward pass
** The activation of middle layer's neurode is the weighted
** sum of the inputs from the input pattern, with sigmoid
** function applied to the inputs.
**/
public static void do_mid_forward(int patt)
{
double sum;
int neurode, i;
for (neurode = 0; neurode < MID_SIZE; neurode++)
{
sum = 0.0;
for (i = 0; i < IN_SIZE; i++)
{ /* compute weighted sum of input signals */
sum += mid_wts[neurode][i] * in_pats[patt][i];
}
/*
** apply sigmoid function f(x) = 1/(1+exp(-x)) to weighted sum
*/
sum = 1.0 / (1.0 + Math.Exp(-sum));
mid_out[neurode] = sum;
}
return;
}
/*********************
** do_out_forward() **
**********************
** process the forward pass through the output layer
** The activation of the output layer is the weighted sum of
** the inputs (outputs from middle layer), modified by the
** sigmoid function.
**/
public static void do_out_forward()
{
double sum;
int neurode, i;
for (neurode = 0; neurode < OUT_SIZE; neurode++)
{
sum = 0.0;
for (i = 0; i < MID_SIZE; i++)
{ /*
** compute weighted sum of input signals
** from middle layer
*/
sum += out_wts[neurode][i] * mid_out[i];
}
/*
** Apply f(x) = 1/(1+Math.Exp(-x)) to weighted input
*/
sum = 1.0 / (1.0 + Math.Exp(-sum));
out_out[neurode] = sum;
}
return;
}
/*************************
** display_output(patt) **
**************************
** Display the actual output vs. the desired output of the
** network.
** Once the training is complete, and the "learned" flag set
** to TRUE, then display_output sends its output to both
** the screen and to a text output file.
**
** NOTE: This routine has been disabled in the benchmark
** version. -- RG
**/
/*
public static void display_output(int patt)
{
int i;
fprintf(outfile,"\n Iteration # %d",iteration_count);
fprintf(outfile,"\n Desired Output: ");
for (i=0; i<OUT_SIZE; i++)
{
fprintf(outfile,"%6.3f ",out_pats[patt][i]);
}
fprintf(outfile,"\n Actual Output: ");
for (i=0; i<OUT_SIZE; i++)
{
fprintf(outfile,"%6.3f ",out_out[i]);
}
fprintf(outfile,"\n");
return;
}
*/
/**********************
** do_forward_pass() **
***********************
** control function for the forward pass through the network
** NOTE: I have disabled the call to display_output() in
** the benchmark version -- RG.
**/
public static void do_forward_pass(int patt)
{
do_mid_forward(patt); /* process forward pass, middle layer */
do_out_forward(); /* process forward pass, output layer */
/* display_output(patt); ** display results of forward pass */
return;
}
/***********************
** do_out_error(patt) **
************************
** Compute the error for the output layer neurodes.
** This is simply Desired - Actual.
**/
public static void do_out_error(int patt)
{
int neurode;
double error, tot_error, sum;
tot_error = 0.0;
sum = 0.0;
for (neurode = 0; neurode < OUT_SIZE; neurode++)
{
out_error[neurode] = out_pats[patt][neurode] - out_out[neurode];
/*
** while we're here, also compute magnitude
** of total error and worst error in this pass.
** We use these to decide if we are done yet.
*/
error = out_error[neurode];
if (error < 0.0)
{
sum += -error;
if (-error > tot_error)
tot_error = -error; /* worst error this pattern */
}
else
{
sum += error;
if (error > tot_error)
tot_error = error; /* worst error this pattern */
}
}
avg_out_error[patt] = sum / OUT_SIZE;
tot_out_error[patt] = tot_error;
return;
}
/***********************
** worst_pass_error() **
************************
** Find the worst and average error in the pass and save it
**/
public static void worst_pass_error()
{
double error, sum;
int i;
error = 0.0;
sum = 0.0;
for (i = 0; i < numpats; i++)
{
if (tot_out_error[i] > error) error = tot_out_error[i];
sum += avg_out_error[i];
}
worst_error = error;
average_error = sum / numpats;
return;
}
/*******************
** do_mid_error() **
********************
** Compute the error for the middle layer neurodes
** This is based on the output errors computed above.
** Note that the derivative of the sigmoid f(x) is
** f'(x) = f(x)(1 - f(x))
** Recall that f(x) is merely the output of the middle
** layer neurode on the forward pass.
**/
public static void do_mid_error()
{
double sum;
int neurode, i;
for (neurode = 0; neurode < MID_SIZE; neurode++)
{
sum = 0.0;
for (i = 0; i < OUT_SIZE; i++)
sum += out_wts[i][neurode] * out_error[i];
/*
** apply the derivative of the sigmoid here
** Because of the choice of sigmoid f(I), the derivative
** of the sigmoid is f'(I) = f(I)(1 - f(I))
*/
mid_error[neurode] = mid_out[neurode] * (1 - mid_out[neurode]) * sum;
}
return;
}
/*********************
** adjust_out_wts() **
**********************
** Adjust the weights of the output layer. The error for
** the output layer has been previously propagated back to
** the middle layer.
** Use the Delta Rule with momentum term to adjust the weights.
**/
public static void adjust_out_wts()
{
int weight, neurode;
double learn, delta, alph;
learn = BETA;
alph = ALPHA;
for (neurode = 0; neurode < OUT_SIZE; neurode++)
{
for (weight = 0; weight < MID_SIZE; weight++)
{
/* standard delta rule */
delta = learn * out_error[neurode] * mid_out[weight];
/* now the momentum term */
delta += alph * out_wt_change[neurode][weight];
out_wts[neurode][weight] += delta;
/* keep track of this pass's cum wt changes for next pass's momentum */
out_wt_cum_change[neurode][weight] += delta;
}
}
return;
}
/*************************
** adjust_mid_wts(patt) **
**************************
** Adjust the middle layer weights using the previously computed
** errors.
** We use the Generalized Delta Rule with momentum term
**/
public static void adjust_mid_wts(int patt)
{
int weight, neurode;
double learn, alph, delta;
learn = BETA;
alph = ALPHA;
for (neurode = 0; neurode < MID_SIZE; neurode++)
{
for (weight = 0; weight < IN_SIZE; weight++)
{
/* first the basic delta rule */
delta = learn * mid_error[neurode] * in_pats[patt][weight];
/* with the momentum term */
delta += alph * mid_wt_change[neurode][weight];
mid_wts[neurode][weight] += delta;
/* keep track of this pass's cum wt changes for next pass's momentum */
mid_wt_cum_change[neurode][weight] += delta;
}
}
return;
}
/*******************
** do_back_pass() **
********************
** Process the backward propagation of error through network.
**/
public static void do_back_pass(int patt)
{
do_out_error(patt);
do_mid_error();
adjust_out_wts();
adjust_mid_wts(patt);
return;
}
/**********************
** move_wt_changes() **
***********************
** Move the weight changes accumulated last pass into the wt-change
** array for use by the momentum term in this pass. Also zero out
** the accumulating arrays after the move.
**/
public static void move_wt_changes()
{
int i, j;
for (i = 0; i < MID_SIZE; i++)
for (j = 0; j < IN_SIZE; j++)
{
mid_wt_change[i][j] = mid_wt_cum_change[i][j];
/*
** Zero it out for next pass accumulation.
*/
mid_wt_cum_change[i][j] = 0.0;
}
for (i = 0; i < OUT_SIZE; i++)
for (j = 0; j < MID_SIZE; j++)
{
out_wt_change[i][j] = out_wt_cum_change[i][j];
out_wt_cum_change[i][j] = 0.0;
}
return;
}
/**********************
** check_out_error() **
***********************
** Check to see if the error in the output layer is below
** MARGIN*OUT_SIZE for all output patterns. If so, then
** assume the network has learned acceptably well. This
** is simply an arbitrary measure of how well the network
** has learned -- many other standards are possible.
**/
public static int check_out_error()
{
int result, i, error;
result = T;
error = F;
worst_pass_error(); /* identify the worst error in this pass */
for (i = 0; i < numpats; i++)
{
if (worst_error >= STOP) result = F;
if (tot_out_error[i] >= 16.0) error = T;
}
if (error == T) result = ERR;
return (result);
}
/*******************
** zero_changes() **
********************
** Zero out all the wt change arrays
**/
public static void zero_changes()
{
int i, j;
for (i = 0; i < MID_SIZE; i++)
{
for (j = 0; j < IN_SIZE; j++)
{
mid_wt_change[i][j] = 0.0;
mid_wt_cum_change[i][j] = 0.0;
}
}
for (i = 0; i < OUT_SIZE; i++)
{
for (j = 0; j < MID_SIZE; j++)
{
out_wt_change[i][j] = 0.0;
out_wt_cum_change[i][j] = 0.0;
}
}
return;
}
/********************
** randomize_wts() **
*********************
** Intialize the weights in the middle and output layers to
** random values between -0.25..+0.25
** Function rand() returns a value between 0 and 32767.
**
** NOTE: Had to make alterations to how the random numbers were
** created. -- RG.
**/
public static void randomize_wts()
{
int neurode, i;
double value;
/*
** Following not used int benchmark version -- RG
**
** printf("\n Please enter a random number seed (1..32767): ");
** scanf("%d", &i);
** srand(i);
*/
for (neurode = 0; neurode < MID_SIZE; neurode++)
{
for (i = 0; i < IN_SIZE; i++)
{
value = (double)ByteMark.abs_randwc(100000);
value = value / (double)100000.0 - (double)0.5;
mid_wts[neurode][i] = value / 2;
}
}
for (neurode = 0; neurode < OUT_SIZE; neurode++)
{
for (i = 0; i < MID_SIZE; i++)
{
value = (double)ByteMark.abs_randwc(100000);
value = value / (double)10000.0 - (double)0.5;
out_wts[neurode][i] = value / 2;
}
}
return;
}
/**********************
** display_mid_wts() **
***********************
** Display the weights on the middle layer neurodes
** NOTE: This routine is not used in the benchmark
** test -- RG
**/
/* static void display_mid_wts()
{
int neurode, weight, row, col;
fprintf(outfile,"\n Weights of Middle Layer neurodes:");
for (neurode=0; neurode<MID_SIZE; neurode++)
{
fprintf(outfile,"\n Mid Neurode # %d",neurode);
for (row=0; row<IN_Y_SIZE; row++)
{
fprintf(outfile,"\n ");
for (col=0; col<IN_X_SIZE; col++)
{
weight = IN_X_SIZE * row + col;
fprintf(outfile," %8.3f ", mid_wts[neurode,weight]);
}
}
}
return;
}
*/
/**********************
** display_out_wts() **
***********************
** Display the weights on the output layer neurodes
** NOTE: This code is not used in the benchmark
** test -- RG
*/
/* void display_out_wts()
{
int neurode, weight;
fprintf(outfile,"\n Weights of Output Layer neurodes:");
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
fprintf(outfile,"\n Out Neurode # %d \n",neurode);
for (weight=0; weight<MID_SIZE; weight++)
{
fprintf(outfile," %8.3f ", out_wts[neurode,weight]);
}
}
return;
}
*/
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
#region class StreamOperationAsyncResult
internal abstract partial class StreamOperationAsyncResult : IAsyncResult
{
private AsyncCallback _userCompletionCallback = null;
private Object _userAsyncStateInfo = null;
private IAsyncInfo _asyncStreamOperation = null;
private volatile bool _completed = false;
private volatile bool _callbackInvoked = false;
private volatile ManualResetEvent _waitHandle = null;
private Int64 _bytesCompleted = 0;
private ExceptionDispatchInfo _errorInfo = null;
private readonly bool _processCompletedOperationInCallback;
private IAsyncInfo _completedOperation = null;
protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
bool processCompletedOperationInCallback)
{
if (asyncStreamOperation == null)
throw new ArgumentNullException("asyncReadOperation");
_userCompletionCallback = userCompletionCallback;
_userAsyncStateInfo = userAsyncStateInfo;
_asyncStreamOperation = asyncStreamOperation;
_completed = false;
_callbackInvoked = false;
_bytesCompleted = 0;
_errorInfo = null;
_processCompletedOperationInCallback = processCompletedOperationInCallback;
}
public object AsyncState
{
get { return _userAsyncStateInfo; }
}
internal bool ProcessCompletedOperationInCallback
{
get { return _processCompletedOperationInCallback; }
}
#pragma warning disable 420 // "a reference to a volatile field will not be treated as volatile"
public WaitHandle AsyncWaitHandle
{
get
{
ManualResetEvent wh = _waitHandle;
if (wh != null)
return wh;
// What if someone calls this public property and decides to wait on it?
// > Use 'completed' in the ctor - this way the handle wait will return as appropriate.
wh = new ManualResetEvent(_completed);
ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
// We lost the race. Dispose OUR handle and return OTHER handle:
if (otherHandle != null)
{
wh.Dispose();
return otherHandle;
}
// We won the race. Return OUR new handle:
return wh;
}
}
#pragma warning restore 420 // "a reference to a volatile field will not be treated as volatile"
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return _completed; }
}
internal void Wait()
{
if (_completed)
return;
WaitHandle wh = AsyncWaitHandle;
while (_completed == false)
wh.WaitOne();
}
internal Int64 BytesCompleted
{
get { return _bytesCompleted; }
}
internal bool HasError
{
get { return _errorInfo != null; }
}
internal void ThrowCachedError()
{
if (_errorInfo == null)
return;
_errorInfo.Throw();
}
internal bool CancelStreamOperation()
{
if (_callbackInvoked)
return false;
_asyncStreamOperation.Cancel();
return true;
}
internal void CloseStreamOperation()
{
try
{
if (_asyncStreamOperation != null)
_asyncStreamOperation.Close();
}
catch { }
_asyncStreamOperation = null;
}
~StreamOperationAsyncResult()
{
// This finalisation is not critical, but we can still make an effort to notify the underlying WinRT stream
// that we are not any longer interested in the results:
CancelStreamOperation();
}
internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted);
private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, String errMsg)
{
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
if (errInfoSrc == null)
throw new InvalidOperationException(errMsg);
else
throw new InvalidOperationException(errMsg, errInfoSrc);
}
internal void ProcessCompletedOperation()
{
// The error handling is slightly tricky here:
// Before processing the IO results, we are verifying some basic assumptions and if they do not hold, we are
// throwing InvalidOperation. However, by the time this method is called, we might have already stored something
// into errorInfo, e.g. if an error occurred in StreamOperationCompletedCallback. If that is the case, then that
// previous exception might include some important info relevant for detecting the problem. So, we take that
// previous exception and attach it as the inner exception to the InvalidOperationException being thrown.
// In cases where we have a good understanding of the previously saved errorInfo, and we know for sure that it
// the immediate reason for the state validation to fail, we can avoid throwing InvalidOperation altogether
// and only rethrow the errorInfo.
if (!_callbackInvoked)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (!_processCompletedOperationInCallback && !_completed)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (_completedOperation == null)
{
ExceptionDispatchInfo errInfo = _errorInfo;
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
// See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path):
if (errInfoSrc != null && errInfoSrc is NullReferenceException
&& SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message))
{
errInfo.Throw();
}
else
{
throw new InvalidOperationException(SR.InvalidOperation_CannotCallThisMethodInCurrentState);
}
}
if (_completedOperation.Id != _asyncStreamOperation.Id)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID);
if (_completedOperation.Status == AsyncStatus.Error)
{
_bytesCompleted = 0;
ThrowWithIOExceptionDispatchInfo(_completedOperation.ErrorCode);
}
ProcessConcreteCompletedOperation(_completedOperation, out _bytesCompleted);
}
internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus)
{
try
{
if (_callbackInvoked)
throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation);
_callbackInvoked = true;
// This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11.
// Moreover, this can happen if the underlying WinRT stream has a faulty user implementation.
// If we did not do this check, we would either get the same exception without the explaining message when dereferencing
// completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be
// aggregated and the user will know what went wrong.
if (completedOperation == null)
throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo);
_completedOperation = completedOperation;
// processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult.
// In that case calls on completedOperation may deadlock if completedOperation is not free threaded.
// By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it
// will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results.
if (_processCompletedOperationInCallback)
ProcessCompletedOperation();
}
catch (Exception ex)
{
_bytesCompleted = 0;
_errorInfo = ExceptionDispatchInfo.Capture(ex);
}
finally
{
_completed = true;
Interlocked.MemoryBarrier();
// From this point on, AsyncWaitHandle would create a handle that is readily set,
// so we do not need to check if it is being produced asynchronously.
if (_waitHandle != null)
_waitHandle.Set();
}
if (_userCompletionCallback != null)
_userCompletionCallback(this);
}
} // class StreamOperationAsyncResult
#endregion class StreamOperationAsyncResult
#region class StreamReadAsyncResult
internal class StreamReadAsyncResult : StreamOperationAsyncResult
{
private IBuffer _userBuffer = null;
internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, UInt32> asyncStreamReadOperation, IBuffer buffer,
AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
_userBuffer = buffer;
asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<IBuffer, UInt32>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<IBuffer, UInt32> completedOperation, out Int64 bytesCompleted)
{
IBuffer resultBuffer = completedOperation.GetResults();
Debug.Assert(resultBuffer != null);
WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
bytesCompleted = _userBuffer.Length;
}
} // class StreamReadAsyncResult
#endregion class StreamReadAsyncResult
#region class StreamWriteAsyncResult
internal class StreamWriteAsyncResult : StreamOperationAsyncResult
{
internal StreamWriteAsyncResult(IAsyncOperationWithProgress<UInt32, UInt32> asyncStreamWriteOperation,
AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<UInt32, UInt32>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<UInt32, UInt32> completedOperation, out Int64 bytesCompleted)
{
UInt32 bytesWritten = completedOperation.GetResults();
bytesCompleted = bytesWritten;
}
} // class StreamWriteAsyncResult
#endregion class StreamWriteAsyncResult
#region class StreamFlushAsyncResult
internal class StreamFlushAsyncResult : StreamOperationAsyncResult
{
internal StreamFlushAsyncResult(IAsyncOperation<Boolean> asyncStreamFlushOperation, bool processCompletedOperationInCallback)
: base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback)
{
asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out Int64 bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperation<Boolean>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperation<Boolean> completedOperation, out Int64 bytesCompleted)
{
Boolean success = completedOperation.GetResults();
bytesCompleted = (success ? 0 : -1);
}
} // class StreamFlushAsyncResult
#endregion class StreamFlushAsyncResult
} // namespace
// StreamOperationAsyncResult.cs
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public sealed partial class FileInfo : FileSystemInfo
{
private string _name;
private FileInfo() { }
public FileInfo(string fileName)
: this(fileName, isNormalized: false)
{
}
internal FileInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
// Want to throw the original argument name
OriginalPath = originalPath ?? throw new ArgumentNullException("fileName");
fullPath = fullPath ?? originalPath;
Debug.Assert(!isNormalized || !PathInternal.IsPartiallyQualified(fullPath), "should be fully qualified if normalized");
FullPath = isNormalized ? fullPath ?? originalPath : Path.GetFullPath(fullPath);
_name = fileName ?? Path.GetFileName(originalPath);
DisplayPath = originalPath;
}
public override string Name
{
get { return _name; }
}
public long Length
{
get
{
if ((FileSystemObject.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, DisplayPath), DisplayPath);
}
return FileSystemObject.Length;
}
}
/* Returns the name of the directory that the file is in */
public string DirectoryName
{
get
{
return Path.GetDirectoryName(FullPath);
}
}
/* Creates an instance of the parent directory */
public DirectoryInfo Directory
{
get
{
string dirName = DirectoryName;
if (dirName == null)
return null;
return new DirectoryInfo(dirName);
}
}
public bool IsReadOnly
{
get
{
return (Attributes & FileAttributes.ReadOnly) != 0;
}
set
{
if (value)
Attributes |= FileAttributes.ReadOnly;
else
Attributes &= ~FileAttributes.ReadOnly;
}
}
public StreamReader OpenText()
{
return new StreamReader(FullPath, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
}
public StreamWriter CreateText()
{
return new StreamWriter(FullPath, append: false);
}
public StreamWriter AppendText()
{
return new StreamWriter(FullPath, append: true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(string, string, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public FileInfo CopyTo(string destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
return new FileInfo(File.InternalCopy(FullPath, destFileName, false), isNormalized: true);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public FileInfo CopyTo(string destFileName, bool overwrite)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
return new FileInfo(File.InternalCopy(FullPath, destFileName, overwrite), isNormalized: true);
}
public FileStream Create()
{
return File.Create(FullPath);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped. On Win95, the file will be
// deleted irregardless of whether the file is being used.
//
// Your application must have Delete permission to the target file.
//
public override void Delete()
{
FileSystem.Current.DeleteFile(FullPath);
}
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
//
// Your application must have Read permission for the target directory.
public override bool Exists
{
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode)
{
return Open(mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access)
{
return Open(mode, access, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(FullPath, mode, access, share);
}
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
public FileStream OpenWrite()
{
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
public void MoveTo(string destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
string fullDestFileName = Path.GetFullPath(destFileName);
// These checks are in place to ensure Unix error throwing happens the same way
// as it does on Windows.These checks can be removed if a solution to #2460 is
// found that doesn't require validity checks before making an API call.
if (!new DirectoryInfo(Path.GetDirectoryName(FullName)).Exists)
{
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullName));
}
if (!Exists)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, FullName), FullName);
}
FileSystem.Current.MoveFile(FullPath, fullDestFileName);
FullPath = fullDestFileName;
OriginalPath = destFileName;
_name = Path.GetFileName(fullDestFileName);
DisplayPath = destFileName;
// Flush any cached information about the file.
Invalidate();
}
public FileInfo Replace(string destinationFileName, string destinationBackupFileName)
{
return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false);
}
public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
{
File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
return new FileInfo(destinationFileName);
}
// Returns the display path
public override string ToString()
{
return DisplayPath;
}
public void Decrypt()
{
File.Decrypt(FullPath);
}
public void Encrypt()
{
File.Encrypt(FullPath);
}
}
}
| |
using NBitcoin;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Gui.Suggestions;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Gui.Tabs.WalletManager.RecoverWallets
{
internal class RecoverWalletViewModel : CategoryViewModel
{
private int _caretIndex;
private string _password;
private string _mnemonicWords;
private string _walletName;
private string _accountKeyPath;
private string _minGapLimit;
private ObservableCollection<SuggestionViewModel> _suggestions;
public RecoverWalletViewModel(WalletManagerViewModel owner) : base("Recover Wallet")
{
Global = Locator.Current.GetService<Global>();
WalletManager = Global.WalletManager;
this.ValidateProperty(x => x.Password, ValidatePassword);
this.ValidateProperty(x => x.MinGapLimit, ValidateMinGapLimit);
this.ValidateProperty(x => x.AccountKeyPath, ValidateAccountKeyPath);
MnemonicWords = "";
var canExecute = Observable
.Merge(Observable.FromEventPattern(this, nameof(ErrorsChanged)).Select(_ => Unit.Default))
.Merge(this.WhenAnyValue(x => x.MnemonicWords).Select(_ => Unit.Default))
.ObserveOn(RxApp.MainThreadScheduler)
.Select(_ => !Validations.AnyErrors && MnemonicWords.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length == 12);
RecoverCommand = ReactiveCommand.Create(() => RecoverWallet(owner), canExecute);
this.WhenAnyValue(x => x.MnemonicWords).Subscribe(UpdateSuggestions);
_suggestions = new ObservableCollection<SuggestionViewModel>();
RecoverCommand.ThrownExceptions
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
private void RecoverWallet(WalletManagerViewModel owner)
{
WalletName = Guard.Correct(WalletName);
MnemonicWords = Guard.Correct(MnemonicWords).ToLowerInvariant();
Password = Guard.Correct(Password); // Do not let whitespaces to the beginning and to the end.
string walletFilePath = WalletManager.WalletDirectories.GetWalletFilePaths(WalletName).walletFilePath;
if (string.IsNullOrWhiteSpace(WalletName))
{
NotificationHelpers.Error("Invalid wallet name.");
}
else if (File.Exists(walletFilePath))
{
NotificationHelpers.Error("Wallet name is already taken.");
}
else if (string.IsNullOrWhiteSpace(MnemonicWords))
{
NotificationHelpers.Error("Recovery Words were not supplied.");
}
else
{
var minGapLimit = int.Parse(MinGapLimit);
var keyPath = KeyPath.Parse(AccountKeyPath);
try
{
var mnemonic = new Mnemonic(MnemonicWords);
var km = KeyManager.Recover(mnemonic, Password, filePath: null, keyPath, minGapLimit);
km.SetNetwork(Global.Network);
km.SetFilePath(walletFilePath);
WalletManager.AddWallet(km);
NotificationHelpers.Success("Wallet was recovered.");
owner.SelectLoadWallet(km);
}
catch (Exception ex)
{
Logger.LogError(ex);
NotificationHelpers.Error(ex.ToUserFriendlyString());
}
}
}
private Global Global { get; }
private Wallets.WalletManager WalletManager { get; }
private void ValidatePassword(IValidationErrors errors) => PasswordHelper.ValidatePassword(errors, Password);
public string Password
{
get => _password;
set => this.RaiseAndSetIfChanged(ref _password, value);
}
public string MnemonicWords
{
get => _mnemonicWords;
set => this.RaiseAndSetIfChanged(ref _mnemonicWords, value);
}
public ObservableCollection<SuggestionViewModel> Suggestions
{
get => _suggestions;
set => this.RaiseAndSetIfChanged(ref _suggestions, value);
}
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public int CaretIndex
{
get => _caretIndex;
set => this.RaiseAndSetIfChanged(ref _caretIndex, value);
}
public string AccountKeyPath
{
get => _accountKeyPath;
set => this.RaiseAndSetIfChanged(ref _accountKeyPath, value);
}
public string MinGapLimit
{
get => _minGapLimit;
set => this.RaiseAndSetIfChanged(ref _minGapLimit, value);
}
public ReactiveCommand<Unit, Unit> RecoverCommand { get; }
private static IEnumerable<string> EnglishWords { get; } = Wordlist.English.GetWords();
public override void OnCategorySelected()
{
base.OnCategorySelected();
Password = null;
MnemonicWords = "";
WalletName = WalletManager.WalletDirectories.GetNextWalletName();
AccountKeyPath = $"m/{KeyManager.DefaultAccountKeyPath}";
MinGapLimit = (KeyManager.AbsoluteMinGapLimit * 3).ToString();
}
private void UpdateSuggestions(string words)
{
if (string.IsNullOrWhiteSpace(words))
{
Suggestions?.Clear();
return;
}
string[] enteredWordList = words.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var lastWord = enteredWordList.LastOrDefault().Replace("\t", "");
if (lastWord.Length < 1)
{
Suggestions.Clear();
return;
}
var suggestedWords = EnglishWords.Where(w => w.StartsWith(lastWord)).Take(7);
Suggestions.Clear();
foreach (var suggestion in suggestedWords)
{
Suggestions.Add(new SuggestionViewModel(suggestion, OnAddWord));
}
}
public void OnAddWord(string word)
{
string[] words = MnemonicWords.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
{
MnemonicWords = word + " ";
}
else
{
words[^1] = word;
MnemonicWords = string.Join(' ', words) + " ";
}
CaretIndex = MnemonicWords.Length;
Suggestions.Clear();
}
private void ValidateMinGapLimit(IValidationErrors errors)
{
if (!int.TryParse(MinGapLimit, out int minGapLimit) || minGapLimit < KeyManager.AbsoluteMinGapLimit || minGapLimit > KeyManager.MaxGapLimit)
{
errors.Add(ErrorSeverity.Error, $"Must be a number between {KeyManager.AbsoluteMinGapLimit} and {KeyManager.MaxGapLimit}.");
}
}
private void ValidateAccountKeyPath(IValidationErrors errors)
{
if (string.IsNullOrWhiteSpace(AccountKeyPath))
{
errors.Add(ErrorSeverity.Error, "Path is not valid.");
}
else if (KeyPath.TryParse(AccountKeyPath, out var keyPath))
{
var accountKeyPath = keyPath.GetAccountKeyPath();
if (keyPath.Length != accountKeyPath.Length || accountKeyPath.Length != KeyManager.DefaultAccountKeyPath.Length)
{
errors.Add(ErrorSeverity.Error, "Path is not a compatible account derivation path.");
}
}
else
{
errors.Add(ErrorSeverity.Error, "Path is not a valid derivation path.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using EFSqlTranslator.Translation.DbObjects;
namespace EFSqlTranslator.Translation
{
internal static class SqlTranslationHelper
{
public static bool IsNullVal(this IDbObject obj)
{
if (!(obj is IDbConstant dbConst))
return false;
return dbConst.Val == null;
}
public static bool IsAnonymouse(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return type.Name.StartsWith("<>") || type.Name.StartsWith("VB$");
}
public static bool IsNumeric(this Type type)
{
return (type == typeof(Byte) ||
type == typeof(Int16) ||
type == typeof(Int32) ||
type == typeof(Int64) ||
type == typeof(SByte) ||
type == typeof(UInt16) ||
type == typeof(UInt32) ||
type == typeof(UInt64) ||
type == typeof(BigInteger) ||
type == typeof(Decimal) ||
type == typeof(Double) ||
type == typeof(Single));
}
public static Type StripNullable(this Type type)
{
return Nullable.GetUnderlyingType(type) ?? type;
}
public static bool IsGrouping(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return type.GenericTypeArguments.Length == 2 &&
type == typeof(IGrouping<,>).MakeGenericType(type.GenericTypeArguments);
}
public static bool IsEnumerable(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return type.IsConstructedGenericType &&
typeof(IEnumerable<>).MakeGenericType(type.GenericTypeArguments).IsAssignableFrom(type);
}
public static bool IsValueType(this Type type)
{
return type.GetTypeInfo().IsValueType || type == typeof(string);
}
public static void UpdateWhereClause(this IDbSelect dbSelect, IDbBinary whereClause, IDbObjectFactory dbFactory)
{
if (whereClause == null)
return;
dbSelect.Where = dbSelect.Where.UpdateBinary(whereClause, dbFactory);
}
public static IDbBinary UpdateBinary(this IDbBinary whereClause, IDbBinary predicate, IDbObjectFactory dbFactory)
{
if (predicate == null)
return whereClause;
return whereClause != null
? dbFactory.BuildBinary(whereClause, DbOperator.And, predicate)
: predicate;
}
/// update all joins that are related to dbRef to be left outer join
/// this is required by method such as Select or GroupBy
public static void UpdateJoinType(DbReference dbRef, DbJoinType dbJoinType = DbJoinType.LeftOuter)
{
var joins = dbRef?.OwnerSelect?.Joins.Where(j => ReferenceEquals(j.To, dbRef));
if (joins == null)
return;
foreach(var dbJoin in joins)
{
dbJoin.Type = dbJoinType;
var relatedRefs = dbJoin.Condition.GetOperands().
Select(op => (op as IDbSelectable)?.Ref).
Where(r => r != null && !ReferenceEquals(r, dbJoin.To));
foreach(var relatedRef in relatedRefs)
UpdateJoinType(relatedRef);
}
}
public static IDbBinary ToBinary(this IDbObject dbElement, IDbObjectFactory dbFactory)
{
switch (dbElement)
{
case null:
return null;
case IDbBinary dbBinary:
return dbBinary;
}
var one = dbFactory.BuildConstant(true);
return dbFactory.BuildBinary(dbElement, DbOperator.Equal, one);
}
public static IDbSelectable[] ProcessSelection(IDbObject dbObj, IDbObjectFactory factory)
{
switch (dbObj)
{
case IDbList<DbKeyValue> dbList:
var keyVals = dbList;
return keyVals.SelectMany(kv => ProcessSelection(kv, factory)).ToArray();
case DbReference obj:
var dbRef = obj;
return new IDbSelectable[] { factory.BuildRefColumn(dbRef, dbRef.RefColumnAlias) };
case IDbBinary dbBinary when (
dbBinary.Operator == DbOperator.Equal ||
dbBinary.Operator == DbOperator.NotEqual ||
dbBinary.Operator == DbOperator.GreaterThan ||
dbBinary.Operator == DbOperator.GreaterThanOrEqual ||
dbBinary.Operator == DbOperator.LessThan ||
dbBinary.Operator == DbOperator.LessThanOrEqual ||
dbBinary.Operator == DbOperator.Is ||
dbBinary.Operator == DbOperator.IsNot):
var dbTrue = factory.BuildConstant(true);
var tuple = Tuple.Create<IDbBinary, IDbObject>(dbBinary, dbTrue);
return new IDbSelectable[] { factory.BuildCondition(new [] { tuple }, factory.BuildConstant(false)) };
}
if (!(dbObj is DbKeyValue keyValue))
return new[] {(IDbSelectable) dbObj};
var selectables = ProcessSelection(keyValue.Value, factory);
foreach(var selectable in selectables)
selectable.Alias = keyValue.Key;
return selectables;
}
public static DbOperator GetDbOperator(ExpressionType type)
{
switch (type)
{
case ExpressionType.AndAlso:
return DbOperator.And;
case ExpressionType.OrElse:
return DbOperator.Or;
case ExpressionType.Add:
return DbOperator.Add;
case ExpressionType.Subtract:
return DbOperator.Subtract;
case ExpressionType.Multiply:
return DbOperator.Multiply;
case ExpressionType.Divide:
return DbOperator.Divide;
case ExpressionType.Equal:
return DbOperator.Equal;
case ExpressionType.NotEqual:
return DbOperator.NotEqual;
case ExpressionType.Not:
return DbOperator.Not;
case ExpressionType.GreaterThan:
return DbOperator.GreaterThan;
case ExpressionType.GreaterThanOrEqual:
return DbOperator.GreaterThan;
case ExpressionType.LessThan:
return DbOperator.LessThan;
case ExpressionType.LessThanOrEqual:
return DbOperator.LessThanOrEqual;
default:
throw new NotSupportedException(type.ToString());
}
}
public static string GetSqlOperator(DbOperator optr)
{
switch (optr)
{
case DbOperator.And:
return "and";
case DbOperator.Or:
return "or";
case DbOperator.Add:
return "+";
case DbOperator.Subtract:
return "-";
case DbOperator.Multiply:
return "*";
case DbOperator.Divide:
return "/";
case DbOperator.Is:
return "is";
case DbOperator.IsNot:
return "is not";
case DbOperator.Equal:
return "=";
case DbOperator.NotEqual:
return "!=";
case DbOperator.Not:
return "not";
case DbOperator.GreaterThan:
return ">";
case DbOperator.GreaterThanOrEqual:
return ">=";
case DbOperator.LessThan:
return "<";
case DbOperator.LessThanOrEqual:
return "<=";
case DbOperator.Like:
return "like";
case DbOperator.StringAdd:
return "||";
case DbOperator.In:
return "in";
case DbOperator.Any:
return "any";
default:
throw new NotSupportedException(optr.ToString());
}
}
}
}
| |
/*
* SVM.NET Library
* Copyright (C) 2008 Matthew Johnson
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Threading;
using System.Globalization;
namespace SVM
{
/// <summary>
/// Encapsulates an SVM Model.
/// </summary>
[Serializable]
public class Model
{
internal Model()
{
}
/// <summary>
/// Parameter object.
/// </summary>
public Parameter Parameter{get;set;}
/// <summary>
/// Number of classes in the model.
/// </summary>
public int NumberOfClasses{get;set;}
/// <summary>
/// Total number of support vectors.
/// </summary>
public int SupportVectorCount { get; set; }
/// <summary>
/// The support vectors.
/// </summary>
public Node[][] SupportVectors{get;set;}
/// <summary>
/// The coefficients for the support vectors.
/// </summary>
public double[][] SupportVectorCoefficients{get;set;}
/// <summary>
/// Values in [1,...,num_training_data] to indicate SVs in the training set
/// </summary>
public int[] SupportVectorIndices { get; set; }
/// <summary>
/// Constants in decision functions
/// </summary>
public double[] Rho{get;set;}
/// <summary>
/// First pairwise probability.
/// </summary>
public double[] PairwiseProbabilityA{get;set;}
/// <summary>
/// Second pairwise probability.
/// </summary>
public double[] PairwiseProbabilityB{get;set;}
// for classification only
/// <summary>
/// Class labels.
/// </summary>
public int[] ClassLabels{get;set;}
/// <summary>
/// Number of support vectors per class.
/// </summary>
public int[] NumberOfSVPerClass{get;set;}
public override bool Equals(object obj)
{
Model test = obj as Model;
if (test == null)
return false;
bool same = ClassLabels.IsEqual(test.ClassLabels);
same = same && NumberOfClasses == test.NumberOfClasses;
same = same && NumberOfSVPerClass.IsEqual(test.NumberOfSVPerClass);
if(PairwiseProbabilityA != null)
same = same && PairwiseProbabilityA.IsEqual(test.PairwiseProbabilityA);
if(PairwiseProbabilityB != null)
same = same && PairwiseProbabilityB.IsEqual(test.PairwiseProbabilityB);
same = same && Parameter.Equals(test.Parameter);
same = same && Rho.IsEqual(test.Rho);
same = same && SupportVectorCoefficients.IsEqual(test.SupportVectorCoefficients);
same = same && SupportVectorCount == test.SupportVectorCount;
same = same && SupportVectors.IsEqual(test.SupportVectors);
return same;
}
public override int GetHashCode()
{
return ClassLabels.ComputeHashcode() +
NumberOfClasses.GetHashCode() +
NumberOfSVPerClass.ComputeHashcode() +
PairwiseProbabilityA.ComputeHashcode() +
PairwiseProbabilityB.ComputeHashcode() +
Parameter.GetHashCode() +
Rho.ComputeHashcode() +
SupportVectorCoefficients.ComputeHashcode() +
SupportVectorCount.GetHashCode() +
SupportVectors.ComputeHashcode();
}
/// <summary>
/// Reads a Model from the provided file.
/// </summary>
/// <param name="filename">The name of the file containing the Model</param>
/// <returns>the Model</returns>
public static Model Read(string filename)
{
FileStream input = File.OpenRead(filename);
try
{
return Read(input);
}
finally
{
input.Close();
}
}
/// <summary>
/// Reads a Model from the provided stream.
/// </summary>
/// <param name="stream">The stream from which to read the Model.</param>
/// <returns>the Model</returns>
public static Model Read(Stream stream)
{
TemporaryCulture.Start();
StreamReader input = new StreamReader(stream);
// read parameters
Model model = new Model();
Parameter param = new Parameter();
model.Parameter = param;
model.Rho = null;
model.PairwiseProbabilityA = null;
model.PairwiseProbabilityB = null;
model.ClassLabels = null;
model.NumberOfSVPerClass = null;
bool headerFinished = false;
while (!headerFinished)
{
string line = input.ReadLine();
string cmd, arg;
int splitIndex = line.IndexOf(' ');
if (splitIndex >= 0)
{
cmd = line.Substring(0, splitIndex);
arg = line.Substring(splitIndex + 1);
}
else
{
cmd = line;
arg = "";
}
arg = arg.ToLower();
int i,n;
switch(cmd){
case "svm_type":
param.SvmType = (SvmType)Enum.Parse(typeof(SvmType), arg.ToUpper());
break;
case "kernel_type":
if (arg == "polynomial")
arg = "poly";
param.KernelType = (KernelType)Enum.Parse(typeof(KernelType), arg.ToUpper());
break;
case "degree":
param.Degree = int.Parse(arg);
break;
case "gamma":
param.Gamma = double.Parse(arg);
break;
case "coef0":
param.Coefficient0 = double.Parse(arg);
break;
case "nr_class":
model.NumberOfClasses = int.Parse(arg);
break;
case "total_sv":
model.SupportVectorCount = int.Parse(arg);
break;
case "rho":
n = model.NumberOfClasses * (model.NumberOfClasses - 1) / 2;
model.Rho = new double[n];
string[] rhoParts = arg.Split();
for(i=0; i<n; i++)
model.Rho[i] = double.Parse(rhoParts[i]);
break;
case "label":
n = model.NumberOfClasses;
model.ClassLabels = new int[n];
string[] labelParts = arg.Split();
for (i = 0; i < n; i++)
model.ClassLabels[i] = int.Parse(labelParts[i]);
break;
case "probA":
n = model.NumberOfClasses * (model.NumberOfClasses - 1) / 2;
model.PairwiseProbabilityA = new double[n];
string[] probAParts = arg.Split();
for (i = 0; i < n; i++)
model.PairwiseProbabilityA[i] = double.Parse(probAParts[i]);
break;
case "probB":
n = model.NumberOfClasses * (model.NumberOfClasses - 1) / 2;
model.PairwiseProbabilityB = new double[n];
string[] probBParts = arg.Split();
for (i = 0; i < n; i++)
model.PairwiseProbabilityB[i] = double.Parse(probBParts[i]);
break;
case "nr_sv":
n = model.NumberOfClasses;
model.NumberOfSVPerClass = new int[n];
string[] nrsvParts = arg.Split();
for (i = 0; i < n; i++)
model.NumberOfSVPerClass[i] = int.Parse(nrsvParts[i]);
break;
case "SV":
headerFinished = true;
break;
default:
throw new Exception("Unknown text in model file");
}
}
// read sv_coef and SV
int m = model.NumberOfClasses - 1;
int l = model.SupportVectorCount;
model.SupportVectorCoefficients = new double[m][];
for (int i = 0; i < m; i++)
{
model.SupportVectorCoefficients[i] = new double[l];
}
model.SupportVectors = new Node[l][];
for (int i = 0; i < l; i++)
{
string[] parts = input.ReadLine().Trim().Split();
for (int k = 0; k < m; k++)
model.SupportVectorCoefficients[k][i] = double.Parse(parts[k]);
int n = parts.Length-m;
model.SupportVectors[i] = new Node[n];
for (int j = 0; j < n; j++)
{
string[] nodeParts = parts[m + j].Split(':');
model.SupportVectors[i][j] = new Node();
model.SupportVectors[i][j].Index = int.Parse(nodeParts[0]);
model.SupportVectors[i][j].Value = double.Parse(nodeParts[1]);
}
}
TemporaryCulture.Stop();
return model;
}
/// <summary>
/// Writes a model to the provided filename. This will overwrite any previous data in the file.
/// </summary>
/// <param name="filename">The desired file</param>
/// <param name="model">The Model to write</param>
public static void Write(string filename, Model model)
{
FileStream stream = File.Open(filename, FileMode.Create);
try
{
Write(stream, model);
}
finally
{
stream.Close();
}
}
/// <summary>
/// Writes a model to the provided stream.
/// </summary>
/// <param name="stream">The output stream</param>
/// <param name="model">The model to write</param>
public static void Write(Stream stream, Model model)
{
TemporaryCulture.Start();
StreamWriter output = new StreamWriter(stream);
Parameter param = model.Parameter;
output.Write("svm_type {0}\n", param.SvmType);
output.Write("kernel_type {0}\n", param.KernelType);
if (param.KernelType == KernelType.POLY)
output.Write("degree {0}\n", param.Degree);
if (param.KernelType == KernelType.POLY || param.KernelType == KernelType.RBF || param.KernelType == KernelType.SIGMOID)
output.Write("gamma {0:0.000000}\n", param.Gamma);
if (param.KernelType == KernelType.POLY || param.KernelType == KernelType.SIGMOID)
output.Write("coef0 {0:0.000000}\n", param.Coefficient0);
int nr_class = model.NumberOfClasses;
int l = model.SupportVectorCount;
output.Write("nr_class {0}\n", nr_class);
output.Write("total_sv {0}\n", l);
{
output.Write("rho");
for (int i = 0; i < nr_class * (nr_class - 1) / 2; i++)
output.Write(" {0:0.000000}", model.Rho[i]);
output.Write("\n");
}
if (model.ClassLabels != null)
{
output.Write("label");
for (int i = 0; i < nr_class; i++)
output.Write(" {0}", model.ClassLabels[i]);
output.Write("\n");
}
if (model.PairwiseProbabilityA != null)
// regression has probA only
{
output.Write("probA");
for (int i = 0; i < nr_class * (nr_class - 1) / 2; i++)
output.Write(" {0:0.000000}", model.PairwiseProbabilityA[i]);
output.Write("\n");
}
if (model.PairwiseProbabilityB != null)
{
output.Write("probB");
for (int i = 0; i < nr_class * (nr_class - 1) / 2; i++)
output.Write(" {0:0.000000}", model.PairwiseProbabilityB[i]);
output.Write("\n");
}
if (model.NumberOfSVPerClass != null)
{
output.Write("nr_sv");
for (int i = 0; i < nr_class; i++)
output.Write(" {0}", model.NumberOfSVPerClass[i]);
output.Write("\n");
}
output.Write("SV\n");
double[][] sv_coef = model.SupportVectorCoefficients;
Node[][] SV = model.SupportVectors;
for (int i = 0; i < l; i++)
{
for (int j = 0; j < nr_class - 1; j++)
output.Write("{0:0.000000} ", sv_coef[j][i]);
Node[] p = SV[i];
if (p.Length == 0)
{
output.Write("\n");
continue;
}
if (param.KernelType == KernelType.PRECOMPUTED)
output.Write("0:{0:0.000000}", (int)p[0].Value);
else
{
output.Write("{0}:{1:0.000000}", p[0].Index, p[0].Value);
for (int j = 1; j < p.Length; j++)
output.Write(" {0}:{1:0.000000}", p[j].Index, p[j].Value);
}
output.Write("\n");
}
output.Flush();
TemporaryCulture.Stop();
}
}
}
| |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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.Runtime.InteropServices;
using System.Collections.Generic;
namespace renderdoc
{
// this isn't an Interop struct, since it needs to be passed C# -> C++ and
// it's not POD which we don't support. It's here just as a utility container
public class EnvironmentModification
{
public string variable;
public string value;
public EnvironmentModificationType type;
public EnvironmentSeparator separator;
public string GetTypeString()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append, {0}", separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend, {0}", separator.Str());
else
ret = "Set";
return ret;
}
public string GetDescription()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append {0} with {1} using {2}", variable, value, separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend {0} with {1} using {2}", variable, value, separator.Str());
else
ret = String.Format("Set {0} to {1}", variable, value);
return ret;
}
}
[StructLayout(LayoutKind.Sequential)]
public class TargetControlMessage
{
public TargetControlMessageType Type;
[StructLayout(LayoutKind.Sequential)]
public struct NewCaptureData
{
public UInt32 ID;
public UInt64 timestamp;
[CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
public byte[] thumbnail;
public Int32 thumbWidth;
public Int32 thumbHeight;
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string path;
public bool local;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewCaptureData NewCapture;
[StructLayout(LayoutKind.Sequential)]
public struct RegisterAPIData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string APIName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public RegisterAPIData RegisterAPI;
[StructLayout(LayoutKind.Sequential)]
public struct BusyData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string ClientName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public BusyData Busy;
[StructLayout(LayoutKind.Sequential)]
public struct NewChildData
{
public UInt32 PID;
public UInt32 ident;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewChildData NewChild;
};
public class ReplayOutput
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetTextureDisplay(IntPtr real, TextureDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetMeshDisplay(IntPtr real, MeshDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_ClearThumbnails(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_AddThumbnail(IntPtr real, UInt32 windowSystem, IntPtr wnd, ResourceId texID, FormatComponentType typeHint);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_Display(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetPixelContext(IntPtr real, UInt32 windowSystem, IntPtr wnd);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_SetPixelContextLocation(IntPtr real, UInt32 x, UInt32 y);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_DisablePixelContext(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetCustomShaderTexID(IntPtr real, ref ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetDebugOverlayTexID(IntPtr real, ref ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetMinMax(IntPtr real, IntPtr outminval, IntPtr outmaxval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetHistogram(IntPtr real, float minval, float maxval, bool[] channels, IntPtr outhistogram);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_PickPixel(IntPtr real, ResourceId texID, bool customShader,
UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample, IntPtr outval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 ReplayOutput_PickVertex(IntPtr real, UInt32 eventID, UInt32 x, UInt32 y, IntPtr outPickedInstance);
private IntPtr m_Real = IntPtr.Zero;
public ReplayOutput(IntPtr real) { m_Real = real; }
public void SetTextureDisplay(TextureDisplay o)
{
ReplayOutput_SetTextureDisplay(m_Real, o);
}
public void SetMeshDisplay(MeshDisplay o)
{
ReplayOutput_SetMeshDisplay(m_Real, o);
}
public void ClearThumbnails()
{
ReplayOutput_ClearThumbnails(m_Real);
}
public bool AddThumbnail(IntPtr wnd, ResourceId texID, FormatComponentType typeHint)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_AddThumbnail(m_Real, 1u, wnd, texID, typeHint);
}
public void Display()
{
ReplayOutput_Display(m_Real);
}
public bool SetPixelContext(IntPtr wnd)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_SetPixelContext(m_Real, 1u, wnd);
}
public void SetPixelContextLocation(UInt32 x, UInt32 y)
{
ReplayOutput_SetPixelContextLocation(m_Real, x, y);
}
public void DisablePixelContext()
{
ReplayOutput_DisablePixelContext(m_Real);
}
public ResourceId GetCustomShaderTexID()
{
ResourceId ret = ResourceId.Null;
ReplayOutput_GetCustomShaderTexID(m_Real, ref ret);
return ret;
}
public ResourceId GetDebugOverlayTexID()
{
ResourceId ret = ResourceId.Null;
ReplayOutput_GetDebugOverlayTexID(m_Real, ref ret);
return ret;
}
public void GetMinMax(out PixelValue minval, out PixelValue maxval)
{
IntPtr mem1 = CustomMarshal.Alloc(typeof(PixelValue));
IntPtr mem2 = CustomMarshal.Alloc(typeof(PixelValue));
ReplayOutput_GetMinMax(m_Real, mem1, mem2);
minval = (PixelValue)CustomMarshal.PtrToStructure(mem1, typeof(PixelValue), true);
maxval = (PixelValue)CustomMarshal.PtrToStructure(mem2, typeof(PixelValue), true);
CustomMarshal.Free(mem1);
CustomMarshal.Free(mem2);
}
public void GetHistogram(float minval, float maxval,
bool Red, bool Green, bool Blue, bool Alpha,
out UInt32[] histogram)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool[] channels = new bool[] { Red, Green, Blue, Alpha };
ReplayOutput_GetHistogram(m_Real, minval, maxval, channels, mem);
histogram = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
}
public PixelValue PickPixel(ResourceId texID, bool customShader, UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample)
{
IntPtr mem = CustomMarshal.Alloc(typeof(PixelValue));
ReplayOutput_PickPixel(m_Real, texID, customShader, x, y, sliceFace, mip, sample, mem);
PixelValue ret = (PixelValue)CustomMarshal.PtrToStructure(mem, typeof(PixelValue), false);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 PickVertex(UInt32 eventID, UInt32 x, UInt32 y, out UInt32 pickedInstance)
{
IntPtr mem = CustomMarshal.Alloc(typeof(UInt32));
UInt32 pickedVertex = ReplayOutput_PickVertex(m_Real, eventID, x, y, mem);
pickedInstance = (UInt32)CustomMarshal.PtrToStructure(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return pickedVertex;
}
};
public class ReplayRenderer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetAPIProperties(IntPtr real, IntPtr propsOut);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ReplayRenderer_CreateOutput(IntPtr real, UInt32 windowSystem, IntPtr WindowHandle, OutputType type);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_ShutdownOutput(IntPtr real, IntPtr replayOutput);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ReplayRenderer_ReplayLoop(IntPtr real, UInt32 windowSystem, IntPtr WindowHandle, ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ReplayRenderer_CancelReplayLoop(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FileChanged(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_HasCallstacks(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_InitResolver(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_SetFrameEvent(IntPtr real, UInt32 eventID, bool force);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetD3D11PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetD3D12PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetGLPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetVulkanPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDisassemblyTargets(IntPtr real, IntPtr targets);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DisassembleShader(IntPtr real, IntPtr refl, IntPtr target, IntPtr isa);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildCustomShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FreeCustomShader(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildTargetShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_ReplaceResource(IntPtr real, ResourceId from, ResourceId to);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_RemoveReplacement(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FreeTargetResource(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetFrameInfo(IntPtr real, IntPtr outframe);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDrawcalls(IntPtr real, IntPtr outdraws);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FetchCounters(IntPtr real, IntPtr counters, UInt32 numCounters, IntPtr outresults);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_EnumerateCounters(IntPtr real, IntPtr outcounters);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DescribeCounter(IntPtr real, UInt32 counter, IntPtr outdesc);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetTextures(IntPtr real, IntPtr outtexs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetBuffers(IntPtr real, IntPtr outbufs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetResolve(IntPtr real, UInt64[] callstack, UInt32 callstackLen, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetDebugMessages(IntPtr real, IntPtr outmsgs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_PixelHistory(IntPtr real, ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint, IntPtr history);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugVertex(IntPtr real, UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugPixel(IntPtr real, UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_DebugThread(IntPtr real, UInt32[] groupid, UInt32[] threadid, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetUsage(IntPtr real, ResourceId id, IntPtr outusage);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetCBufferVariableContents(IntPtr real, ResourceId shader, IntPtr entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs, IntPtr outvars);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_SaveTexture(IntPtr real, TextureSave saveData, IntPtr path);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetPostVSData(IntPtr real, UInt32 instID, MeshDataStage stage, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetBufferData(IntPtr real, ResourceId buff, UInt64 offset, UInt64 len, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetTextureData(IntPtr real, ResourceId tex, UInt32 arrayIdx, UInt32 mip, IntPtr outdata);
private IntPtr m_Real = IntPtr.Zero;
public IntPtr Real { get { return m_Real; } }
public ReplayRenderer(IntPtr real) { m_Real = real; }
public void Shutdown()
{
if (m_Real != IntPtr.Zero)
{
ReplayRenderer_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
}
public APIProperties GetAPIProperties()
{
IntPtr mem = CustomMarshal.Alloc(typeof(APIProperties));
ReplayRenderer_GetAPIProperties(m_Real, mem);
APIProperties ret = (APIProperties)CustomMarshal.PtrToStructure(mem, typeof(APIProperties), true);
CustomMarshal.Free(mem);
return ret;
}
public void ReplayLoop(IntPtr WindowHandle, ResourceId texid)
{
if (WindowHandle == IntPtr.Zero)
return;
// 1 == eWindowingSystem_Win32
ReplayRenderer_ReplayLoop(m_Real, 1u, WindowHandle, texid);
}
public void CancelReplayLoop()
{
ReplayRenderer_CancelReplayLoop(m_Real);
}
public ReplayOutput CreateOutput(IntPtr WindowHandle, OutputType type)
{
// 0 == eWindowingSystem_Unknown
// 1 == eWindowingSystem_Win32
IntPtr ret = ReplayRenderer_CreateOutput(m_Real, WindowHandle == IntPtr.Zero ? 0u : 1u, WindowHandle, type);
if (ret == IntPtr.Zero)
return null;
return new ReplayOutput(ret);
}
public void FileChanged()
{ ReplayRenderer_FileChanged(m_Real); }
public bool HasCallstacks()
{ return ReplayRenderer_HasCallstacks(m_Real); }
public bool InitResolver()
{ return ReplayRenderer_InitResolver(m_Real); }
public void SetFrameEvent(UInt32 eventID, bool force)
{ ReplayRenderer_SetFrameEvent(m_Real, eventID, force); }
public GLPipelineState GetGLPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(GLPipelineState));
ReplayRenderer_GetGLPipelineState(m_Real, mem);
GLPipelineState ret = (GLPipelineState)CustomMarshal.PtrToStructure(mem, typeof(GLPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D11PipelineState GetD3D11PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D11PipelineState));
ReplayRenderer_GetD3D11PipelineState(m_Real, mem);
D3D11PipelineState ret = (D3D11PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D11PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D12PipelineState GetD3D12PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D12PipelineState));
ReplayRenderer_GetD3D12PipelineState(m_Real, mem);
D3D12PipelineState ret = (D3D12PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D12PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public VulkanPipelineState GetVulkanPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(VulkanPipelineState));
ReplayRenderer_GetVulkanPipelineState(m_Real, mem);
VulkanPipelineState ret = (VulkanPipelineState)CustomMarshal.PtrToStructure(mem, typeof(VulkanPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public string[] GetDisassemblyTargets()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDisassemblyTargets(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public string DisassembleShader(ShaderReflection refl, string target)
{
IntPtr disasmMem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr target_mem = CustomMarshal.MakeUTF8String(target);
ReplayRenderer_DisassembleShader(m_Real, refl.origPtr, target_mem, disasmMem);
string disasm = CustomMarshal.TemplatedArrayToString(disasmMem, true);
CustomMarshal.Free(target_mem);
CustomMarshal.Free(disasmMem);
return disasm;
}
public ResourceId BuildCustomShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildCustomShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public void FreeCustomShader(ResourceId id)
{ ReplayRenderer_FreeCustomShader(m_Real, id); }
public ResourceId BuildTargetShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildTargetShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public void ReplaceResource(ResourceId from, ResourceId to)
{ ReplayRenderer_ReplaceResource(m_Real, from, to); }
public void RemoveReplacement(ResourceId id)
{ ReplayRenderer_RemoveReplacement(m_Real, id); }
public void FreeTargetResource(ResourceId id)
{ ReplayRenderer_FreeTargetResource(m_Real, id); }
public FetchFrameInfo GetFrameInfo()
{
IntPtr mem = CustomMarshal.Alloc(typeof(FetchFrameInfo));
ReplayRenderer_GetFrameInfo(m_Real, mem);
FetchFrameInfo ret = (FetchFrameInfo)CustomMarshal.PtrToStructure(mem, typeof(FetchFrameInfo), true);
CustomMarshal.Free(mem);
return ret;
}
private void PopulateDraws(ref Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
map.Add((Int64)d.eventID, d);
PopulateDraws(ref map, d.children);
}
}
private void FixupDraws(Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
if (d.previousDrawcall != 0 && map.ContainsKey(d.previousDrawcall)) d.previous = map[d.previousDrawcall];
if (d.nextDrawcall != 0 && map.ContainsKey(d.nextDrawcall)) d.next = map[d.nextDrawcall];
if (d.parentDrawcall != 0 && map.ContainsKey(d.parentDrawcall)) d.parent = map[d.parentDrawcall];
FixupDraws(map, d.children);
}
}
public Dictionary<uint, List<CounterResult>> FetchCounters(UInt32[] counters)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr countersmem = CustomMarshal.Alloc(typeof(UInt32), counters.Length);
// there's no Marshal.Copy for uint[], which is stupid.
for (int i = 0; i < counters.Length; i++)
Marshal.WriteInt32(countersmem, sizeof(UInt32) * i, (int)counters[i]);
ReplayRenderer_FetchCounters(m_Real, countersmem, (uint)counters.Length, mem);
CustomMarshal.Free(countersmem);
Dictionary<uint, List<CounterResult>> ret = null;
{
CounterResult[] resultArray = (CounterResult[])CustomMarshal.GetTemplatedArray(mem, typeof(CounterResult), true);
// fixup previous/next/parent pointers
ret = new Dictionary<uint, List<CounterResult>>();
foreach (var result in resultArray)
{
if (!ret.ContainsKey(result.eventID))
ret.Add(result.eventID, new List<CounterResult>());
ret[result.eventID].Add(result);
}
}
CustomMarshal.Free(mem);
return ret;
}
public UInt32[] EnumerateCounters()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_EnumerateCounters(m_Real, mem);
UInt32[] ret = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return ret;
}
public CounterDescription DescribeCounter(UInt32 counterID)
{
IntPtr mem = CustomMarshal.Alloc(typeof(CounterDescription));
ReplayRenderer_DescribeCounter(m_Real, counterID, mem);
CounterDescription ret = (CounterDescription)CustomMarshal.PtrToStructure(mem, typeof(CounterDescription), false);
CustomMarshal.Free(mem);
return ret;
}
public FetchDrawcall[] GetDrawcalls()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDrawcalls(m_Real, mem);
FetchDrawcall[] ret = null;
{
ret = (FetchDrawcall[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchDrawcall), true);
// fixup previous/next/parent pointers
var map = new Dictionary<Int64, FetchDrawcall>();
PopulateDraws(ref map, ret);
FixupDraws(map, ret);
}
CustomMarshal.Free(mem);
return ret;
}
public FetchTexture[] GetTextures()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetTextures(m_Real, mem);
FetchTexture[] ret = (FetchTexture[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchTexture), true);
CustomMarshal.Free(mem);
return ret;
}
public FetchBuffer[] GetBuffers()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetBuffers(m_Real, mem);
FetchBuffer[] ret = (FetchBuffer[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchBuffer), true);
CustomMarshal.Free(mem);
return ret;
}
public string[] GetResolve(UInt64[] callstack)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
UInt32 len = (UInt32)callstack.Length;
ReplayRenderer_GetResolve(m_Real, callstack, len, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public DebugMessage[] GetDebugMessages()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetDebugMessages(m_Real, mem);
DebugMessage[] ret = (DebugMessage[])CustomMarshal.GetTemplatedArray(mem, typeof(DebugMessage), true);
CustomMarshal.Free(mem);
return ret;
}
public PixelModification[] PixelHistory(ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_PixelHistory(m_Real, target, x, y, slice, mip, sampleIdx, typeHint, mem);
PixelModification[] ret = (PixelModification[])CustomMarshal.GetTemplatedArray(mem, typeof(PixelModification), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugVertex(UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugVertex(m_Real, vertid, instid, idx, instOffset, vertOffset, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugPixel(UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugPixel(m_Real, x, y, sample, primitive, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugThread(UInt32[] groupid, UInt32[] threadid)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
ReplayRenderer_DebugThread(m_Real, groupid, threadid, mem);
ShaderDebugTrace ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public EventUsage[] GetUsage(ResourceId id)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetUsage(m_Real, id, mem);
EventUsage[] ret = (EventUsage[])CustomMarshal.GetTemplatedArray(mem, typeof(EventUsage), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderVariable[] GetCBufferVariableContents(ResourceId shader, string entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entryPoint);
ReplayRenderer_GetCBufferVariableContents(m_Real, shader, entry_mem, cbufslot, buffer, offs, mem);
ShaderVariable[] ret = (ShaderVariable[])CustomMarshal.GetTemplatedArray(mem, typeof(ShaderVariable), true);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(mem);
return ret;
}
public bool SaveTexture(TextureSave saveData, string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
bool ret = ReplayRenderer_SaveTexture(m_Real, saveData, path_mem);
CustomMarshal.Free(path_mem);
return ret;
}
public MeshFormat GetPostVSData(UInt32 instID, MeshDataStage stage)
{
IntPtr mem = CustomMarshal.Alloc(typeof(MeshFormat));
ReplayRenderer_GetPostVSData(m_Real, instID, stage, mem);
MeshFormat ret = (MeshFormat)CustomMarshal.PtrToStructure(mem, typeof(MeshFormat), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetBufferData(ResourceId buff, UInt64 offset, UInt64 len)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetBufferData(m_Real, buff, offset, len, mem);
byte[] ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetTextureData(ResourceId tex, UInt32 arrayIdx, UInt32 mip)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ReplayRenderer_GetTextureData(m_Real, tex, arrayIdx, mip, mem);
byte[] ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
};
public class RemoteServer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownServerAndConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool RemoteServer_Ping(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_LocalProxies(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_RemoteSupportedReplays(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_GetHomeFolder(IntPtr real, IntPtr outfolder);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ListFolder(IntPtr real, IntPtr path, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RemoteServer_ExecuteAndInject(IntPtr real, IntPtr app, IntPtr workingDir, IntPtr cmdLine, IntPtr env, CaptureOptions opts);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_TakeOwnershipCapture(IntPtr real, IntPtr filename);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureToRemote(IntPtr real, IntPtr filename, ref float progress, IntPtr remotepath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureFromRemote(IntPtr real, IntPtr remotepath, IntPtr localpath, ref float progress);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern ReplayCreateStatus RemoteServer_OpenCapture(IntPtr real, UInt32 proxyid, IntPtr logfile, ref float progress, ref IntPtr rendPtr);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CloseCapture(IntPtr real, IntPtr rendPtr);
// static exports for lists of environment modifications
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr RENDERDOC_MakeEnvironmentModificationList(int numElems);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_SetEnvironmentModification(IntPtr mem, int idx, IntPtr variable, IntPtr value,
EnvironmentModificationType type, EnvironmentSeparator separator);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_FreeEnvironmentModificationList(IntPtr mem);
private IntPtr m_Real = IntPtr.Zero;
public RemoteServer(IntPtr real) { m_Real = real; }
public void ShutdownConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public void ShutdownServerAndConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownServerAndConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public string GetHomeFolder()
{
IntPtr homepath_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_GetHomeFolder(m_Real, homepath_mem);
string home = CustomMarshal.TemplatedArrayToString(homepath_mem, true);
CustomMarshal.Free(homepath_mem);
// normalise to /s and with no trailing /s
home = home.Replace('\\', '/');
if (home[home.Length - 1] == '/')
home = home.Remove(0, home.Length - 1);
return home;
}
public DirectoryFile[] ListFolder(string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
IntPtr out_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_ListFolder(m_Real, path_mem, out_mem);
DirectoryFile[] ret = (DirectoryFile[])CustomMarshal.GetTemplatedArray(out_mem, typeof(DirectoryFile), true);
CustomMarshal.Free(out_mem);
CustomMarshal.Free(path_mem);
Array.Sort(ret);
return ret;
}
public bool Ping()
{
return RemoteServer_Ping(m_Real);
}
public string[] LocalProxies()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_LocalProxies(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public string[] RemoteSupportedReplays()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_RemoteSupportedReplays(m_Real, mem);
string[] ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 ExecuteAndInject(string app, string workingDir, string cmdLine, EnvironmentModification[] env, CaptureOptions opts)
{
IntPtr app_mem = CustomMarshal.MakeUTF8String(app);
IntPtr workingDir_mem = CustomMarshal.MakeUTF8String(workingDir);
IntPtr cmdLine_mem = CustomMarshal.MakeUTF8String(cmdLine);
IntPtr env_mem = RENDERDOC_MakeEnvironmentModificationList(env.Length);
for (int i = 0; i < env.Length; i++)
{
IntPtr var_mem = CustomMarshal.MakeUTF8String(env[i].variable);
IntPtr val_mem = CustomMarshal.MakeUTF8String(env[i].value);
RENDERDOC_SetEnvironmentModification(env_mem, i, var_mem, val_mem, env[i].type, env[i].separator);
CustomMarshal.Free(var_mem);
CustomMarshal.Free(val_mem);
}
UInt32 ret = RemoteServer_ExecuteAndInject(m_Real, app_mem, workingDir_mem, cmdLine_mem, env_mem, opts);
RENDERDOC_FreeEnvironmentModificationList(env_mem);
CustomMarshal.Free(app_mem);
CustomMarshal.Free(workingDir_mem);
CustomMarshal.Free(cmdLine_mem);
return ret;
}
public void TakeOwnershipCapture(string filename)
{
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_TakeOwnershipCapture(m_Real, filename_mem);
CustomMarshal.Free(filename_mem);
}
public string CopyCaptureToRemote(string filename, ref float progress)
{
IntPtr remotepath = CustomMarshal.Alloc(typeof(templated_array));
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_CopyCaptureToRemote(m_Real, filename_mem, ref progress, remotepath);
CustomMarshal.Free(filename_mem);
string remote = CustomMarshal.TemplatedArrayToString(remotepath, true);
CustomMarshal.Free(remotepath);
return remote;
}
public void CopyCaptureFromRemote(string remotepath, string localpath, ref float progress)
{
IntPtr remotepath_mem = CustomMarshal.MakeUTF8String(remotepath);
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
RemoteServer_CopyCaptureFromRemote(m_Real, remotepath_mem, localpath_mem, ref progress);
CustomMarshal.Free(remotepath_mem);
CustomMarshal.Free(localpath_mem);
}
public ReplayRenderer OpenCapture(int proxyid, string logfile, ref float progress)
{
IntPtr rendPtr = IntPtr.Zero;
IntPtr logfile_mem = CustomMarshal.MakeUTF8String(logfile);
ReplayCreateStatus ret = RemoteServer_OpenCapture(m_Real, proxyid == -1 ? UInt32.MaxValue : (UInt32)proxyid, logfile_mem, ref progress, ref rendPtr);
CustomMarshal.Free(logfile_mem);
if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
{
throw new ReplayCreateException(ret, "Failed to set up local proxy replay with remote connection");
}
return new ReplayRenderer(rendPtr);
}
public void CloseCapture(ReplayRenderer renderer)
{
RemoteServer_CloseCapture(m_Real, renderer.Real);
}
};
public class TargetControl
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetTarget(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetAPI(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 TargetControl_GetPID(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetBusyClient(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_TriggerCapture(IntPtr real, UInt32 numFrames);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_QueueCapture(IntPtr real, UInt32 frameNumber);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_CopyCapture(IntPtr real, UInt32 remoteID, IntPtr localpath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_DeleteCapture(IntPtr real, UInt32 remoteID);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_ReceiveMessage(IntPtr real, IntPtr outmsg);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RENDERDOC_EnumerateRemoteConnections(IntPtr host, UInt32[] idents);
private IntPtr m_Real = IntPtr.Zero;
private bool m_Connected;
public TargetControl(IntPtr real)
{
m_Real = real;
if (real == IntPtr.Zero)
{
m_Connected = false;
Target = "";
API = "";
BusyClient = "";
}
else
{
m_Connected = true;
Target = CustomMarshal.PtrToStringUTF8(TargetControl_GetTarget(m_Real));
API = CustomMarshal.PtrToStringUTF8(TargetControl_GetAPI(m_Real));
PID = TargetControl_GetPID(m_Real);
BusyClient = CustomMarshal.PtrToStringUTF8(TargetControl_GetBusyClient(m_Real));
}
CaptureExists = false;
CaptureCopied = false;
InfoUpdated = false;
}
public static UInt32[] GetRemoteIdents(string host)
{
UInt32 numIdents = RENDERDOC_EnumerateRemoteConnections(IntPtr.Zero, null);
UInt32[] idents = new UInt32[numIdents];
IntPtr host_mem = CustomMarshal.MakeUTF8String(host);
RENDERDOC_EnumerateRemoteConnections(host_mem, idents);
CustomMarshal.Free(host_mem);
return idents;
}
public bool Connected { get { return m_Connected; } }
public void Shutdown()
{
m_Connected = false;
if (m_Real != IntPtr.Zero) TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
public void TriggerCapture(UInt32 numFrames)
{
TargetControl_TriggerCapture(m_Real, numFrames);
}
public void QueueCapture(UInt32 frameNum)
{
TargetControl_QueueCapture(m_Real, frameNum);
}
public void CopyCapture(UInt32 id, string localpath)
{
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
TargetControl_CopyCapture(m_Real, id, localpath_mem);
CustomMarshal.Free(localpath_mem);
}
public void DeleteCapture(UInt32 id)
{
TargetControl_DeleteCapture(m_Real, id);
}
public void ReceiveMessage()
{
if (m_Real != IntPtr.Zero)
{
TargetControlMessage msg = null;
{
IntPtr mem = CustomMarshal.Alloc(typeof(TargetControlMessage));
TargetControl_ReceiveMessage(m_Real, mem);
if (mem != IntPtr.Zero)
msg = (TargetControlMessage)CustomMarshal.PtrToStructure(mem, typeof(TargetControlMessage), true);
CustomMarshal.Free(mem);
}
if (msg == null)
return;
if (msg.Type == TargetControlMessageType.Disconnected)
{
m_Connected = false;
TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
else if (msg.Type == TargetControlMessageType.NewCapture)
{
CaptureFile = msg.NewCapture;
CaptureExists = true;
}
else if (msg.Type == TargetControlMessageType.CaptureCopied)
{
CaptureFile.ID = msg.NewCapture.ID;
CaptureFile.path = msg.NewCapture.path;
CaptureCopied = true;
}
else if (msg.Type == TargetControlMessageType.RegisterAPI)
{
API = msg.RegisterAPI.APIName;
InfoUpdated = true;
}
else if (msg.Type == TargetControlMessageType.NewChild)
{
NewChild = msg.NewChild;
ChildAdded = true;
}
}
}
public string BusyClient;
public string Target;
public string API;
public UInt32 PID;
public bool CaptureExists;
public bool ChildAdded;
public bool CaptureCopied;
public bool InfoUpdated;
public TargetControlMessage.NewCaptureData CaptureFile = new TargetControlMessage.NewCaptureData();
public TargetControlMessage.NewChildData NewChild = new TargetControlMessage.NewChildData();
};
};
| |
// 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.NotificationHubs
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Azure NotificationHub client
/// </summary>
public partial class NotificationHubsManagementClient : Microsoft.Rest.ServiceClient<NotificationHubsManagementClient>, INotificationHubsManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the INamespacesOperations.
/// </summary>
public virtual INamespacesOperations Namespaces { get; private set; }
/// <summary>
/// Gets the INotificationHubsOperations.
/// </summary>
public virtual INotificationHubsOperations NotificationHubs { get; private set; }
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NotificationHubsManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NotificationHubsManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NotificationHubsManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NotificationHubsManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NotificationHubsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NotificationHubsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NotificationHubsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NotificationHubsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NotificationHubsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Namespaces = new NamespacesOperations(this);
this.NotificationHubs = new NotificationHubsOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.ApiVersion = "2016-03-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
#if !SILVERLIGHT
using System.Drawing;
#else
using System.Windows.Media.Imaging;
#endif
using System.IO;
using System.Text;
using NUnit.Framework;
using ZXing.Common;
using ZXing.Common.Test;
namespace ZXing.PDF417.Test
{
/// <summary>
/// This class tests Macro PDF417 barcode specific functionality. It ensures that information, which is split into
/// several barcodes can be properly combined again to yield the original data content.
/// @author Guenther Grau
/// </summary>
[TestFixture]
public sealed class PDF417BlackBox4TestCase : AbstractBlackBoxTestCase
{
#if !SILVERLIGHT
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#else
private static readonly DanielVaughan.Logging.ILog log = DanielVaughan.Logging.LogManager.GetLog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endif
private static readonly Encoding UTF8 = Encoding.UTF8;
private static readonly Encoding ISO88591 = Encoding.GetEncoding("ISO8859-1");
private const String TEST_BASE_PATH_SUFFIX = "test/data/blackbox/pdf417-4";
private readonly PDF417Reader barcodeReader = new PDF417Reader();
private readonly List<TestResult> testResults = new List<TestResult>();
private String testBase;
public PDF417BlackBox4TestCase()
: base(TEST_BASE_PATH_SUFFIX, null, BarcodeFormat.PDF_417)
{
// A little workaround to prevent aggravation in my IDE
if (!Directory.Exists(TEST_BASE_PATH_SUFFIX))
{
// try starting with 'core' since the test base is often given as the project root
testBase = Path.Combine("..\\..\\..\\Source", TEST_BASE_PATH_SUFFIX);
}
else
{
testBase = TEST_BASE_PATH_SUFFIX;
}
testResults.Add(new TestResult(2, 2, 0, 0, 0.0f));
}
[Test]
public override void testBlackBox()
{
testPDF417BlackBoxCountingResults(true);
}
private void testPDF417BlackBoxCountingResults(bool assertOnFailure)
{
Assert.IsFalse(testResults.Count == 0);
IDictionary<String, List<String>> imageFiles = getImageFileLists();
int testCount = testResults.Count;
int[] passedCounts = new int[testCount];
int[] tryHarderCounts = new int[testCount];
foreach (KeyValuePair<String, List<String>> testImageGroup in imageFiles)
{
log.InfoFormat("Starting Image Group {0}", testImageGroup.Key);
String fileBaseName = testImageGroup.Key;
String expectedText;
String expectedTextFile = fileBaseName + ".txt";
if (File.Exists(expectedTextFile))
{
expectedText = File.ReadAllText(expectedTextFile, UTF8);
}
else
{
expectedTextFile = fileBaseName + ".bin";
Assert.IsTrue(File.Exists(expectedTextFile));
expectedText = File.ReadAllText(expectedTextFile, ISO88591);
}
for (int x = 0; x < testCount; x++)
{
List<Result> results = new List<Result>();
foreach (var imageFile in testImageGroup.Value)
{
#if !SILVERLIGHT
var image = new Bitmap(Image.FromFile(imageFile));
#else
var image = new WriteableBitmap(0, 0);
image.SetSource(File.OpenRead(imageFile));
#endif
var rotation = testResults[x].Rotation;
var rotatedImage = rotateImage(image, rotation);
var source = new BitmapLuminanceSource(rotatedImage);
var bitmap = new BinaryBitmap(new HybridBinarizer(source));
try
{
results.AddRange(decode(bitmap, false));
}
catch (ReaderException )
{
// ignore
}
}
results.Sort((arg0, arg1) =>
{
PDF417ResultMetadata resultMetadata = getMeta(arg0);
PDF417ResultMetadata otherResultMetadata = getMeta(arg1);
return resultMetadata.SegmentIndex - otherResultMetadata.SegmentIndex;
});
var resultText = new StringBuilder();
String fileId = null;
foreach (Result result in results)
{
PDF417ResultMetadata resultMetadata = getMeta(result);
Assert.NotNull(resultMetadata, "resultMetadata");
if (fileId == null)
{
fileId = resultMetadata.FileId;
}
Assert.AreEqual(fileId, resultMetadata.FileId, "FileId");
resultText.Append(result.Text);
}
Assert.AreEqual(expectedText, resultText.ToString(), "ExpectedText");
passedCounts[x]++;
tryHarderCounts[x]++;
}
}
// Print the results of all tests first
int totalFound = 0;
int totalMustPass = 0;
int numberOfTests = imageFiles.Count;
for (int x = 0; x < testResults.Count; x++)
{
TestResult testResult = testResults[x];
log.InfoFormat("Rotation {0} degrees:", (int) testResult.Rotation);
log.InfoFormat(" {0} of {1} images passed ({2} required)", passedCounts[x], numberOfTests,
testResult.MustPassCount);
log.InfoFormat(" {0} of {1} images passed with try harder ({2} required)", tryHarderCounts[x],
numberOfTests, testResult.TryHarderCount);
totalFound += passedCounts[x] + tryHarderCounts[x];
totalMustPass += testResult.MustPassCount + testResult.TryHarderCount;
}
int totalTests = numberOfTests*testCount*2;
log.InfoFormat("Decoded {0} images out of {1} ({2}%, {3} required)", totalFound, totalTests, totalFound*
100/
totalTests, totalMustPass);
if (totalFound > totalMustPass)
{
log.WarnFormat("+++ Test too lax by {0} images", totalFound - totalMustPass);
}
else if (totalFound < totalMustPass)
{
log.WarnFormat("--- Test failed by {0} images", totalMustPass - totalFound);
}
// Then run through again and assert if any failed
if (assertOnFailure)
{
for (int x = 0; x < testCount; x++)
{
TestResult testResult = testResults[x];
String label = "Rotation " + testResult.Rotation + " degrees: Too many images failed";
Assert.IsTrue(passedCounts[x] >= testResult.MustPassCount, label);
Assert.IsTrue(tryHarderCounts[x] >= testResult.TryHarderCount, "Try harder, " + label);
}
}
}
private static PDF417ResultMetadata getMeta(Result result)
{
return result.ResultMetadata == null ? null : (PDF417ResultMetadata) result.ResultMetadata[ResultMetadataType.PDF417_EXTRA_METADATA];
}
private Result[] decode(BinaryBitmap source, bool tryHarder)
{
IDictionary<DecodeHintType, Object> hints = new Dictionary<DecodeHintType, object>();
if (tryHarder)
{
hints[DecodeHintType.TRY_HARDER] = true;
}
return barcodeReader.decodeMultiple(source, hints);
}
private IDictionary<String, List<String>> getImageFileLists()
{
IDictionary<String, List<String>> result = new Dictionary<string, List<String>>();
foreach (string fileName in getImageFiles())
{
String testImageFileName = fileName;
String fileBaseName = testImageFileName.Substring(0, testImageFileName.LastIndexOf('-'));
List<String> files;
if (!result.ContainsKey(fileBaseName))
{
files = new List<String>();
result[fileBaseName] = files;
}
else
{
files = result[fileBaseName];
}
files.Add(fileName);
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
public static class CharTests
{
[Fact]
public static void TestCompareTo()
{
// Int32 Char.CompareTo(Char)
char h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
}
[Fact]
public static void TestSystemIComparableCompareTo()
{
// Int32 Char.System.IComparable.CompareTo(Object)
IComparable h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
Assert.True(h.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => h.CompareTo("H"));
}
private static void ValidateConvertFromUtf32(int i, string expected)
{
try
{
string s = char.ConvertFromUtf32(i);
Assert.Equal(expected, s);
}
catch (ArgumentOutOfRangeException)
{
Assert.True(expected == null, "Expected an ArgumentOutOfRangeException");
}
}
[Fact]
public static void TestConvertFromUtf32()
{
// String Char.ConvertFromUtf32(Int32)
ValidateConvertFromUtf32(0x10000, "\uD800\uDC00");
ValidateConvertFromUtf32(0x103FF, "\uD800\uDFFF");
ValidateConvertFromUtf32(0xFFFFF, "\uDBBF\uDFFF");
ValidateConvertFromUtf32(0x10FC00, "\uDBFF\uDC00");
ValidateConvertFromUtf32(0x10FFFF, "\uDBFF\uDFFF");
ValidateConvertFromUtf32(0, "\0");
ValidateConvertFromUtf32(0x3FF, "\u03FF");
ValidateConvertFromUtf32(0xE000, "\uE000");
ValidateConvertFromUtf32(0xFFFF, "\uFFFF");
ValidateConvertFromUtf32(0xD800, null);
ValidateConvertFromUtf32(0xDC00, null);
ValidateConvertFromUtf32(0xDFFF, null);
ValidateConvertFromUtf32(0x110000, null);
ValidateConvertFromUtf32(-1, null);
ValidateConvertFromUtf32(Int32.MaxValue, null);
ValidateConvertFromUtf32(Int32.MinValue, null);
}
private static void ValidateconverToUtf32<T>(string s, int i, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(s, i);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32StrInt()
{
// Int32 Char.ConvertToUtf32(String, Int32)
ValidateconverToUtf32<Exception>("\uD800\uDC00", 0, 0x10000);
ValidateconverToUtf32<Exception>("\uD800\uD800\uDFFF", 1, 0x103FF);
ValidateconverToUtf32<Exception>("\uDBBF\uDFFF", 0, 0xFFFFF);
ValidateconverToUtf32<Exception>("\uDBFF\uDC00", 0, 0x10FC00);
ValidateconverToUtf32<Exception>("\uDBFF\uDFFF", 0, 0x10FFFF);
// Not surrogate pairs
ValidateconverToUtf32<Exception>("\u0000\u0001", 0, 0);
ValidateconverToUtf32<Exception>("\u0000\u0001", 1, 1);
ValidateconverToUtf32<Exception>("\u0000", 0, 0);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 0, 32);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 1, 0xD7FF);
ValidateconverToUtf32<Exception>("abcde", 4, (int)'e');
ValidateconverToUtf32<Exception>("\uD800\uD7FF", 1, 0xD7FF); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uD800\u0000", 1, 0); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uDF01\u0000", 1, 0); // low, non-surrogate
// Invalid inputs
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 0, Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uD800\uD7FF", 0, Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\u0000", 0, Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 0, Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 0, Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentException>("\uDF01\u0000", 0, Int32.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 1, Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 1, Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 1, Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentNullException>(null, 0, Int32.MinValue); // null string
ValidateconverToUtf32<ArgumentOutOfRangeException>("", 0, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("", -1, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", -1, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", 5, Int32.MinValue); // index out of range
}
private static void ValidateconverToUtf32<T>(char c1, char c2, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(c1, c2);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32()
{
// Int32 Char.ConvertToUtf32(Char, Char)
ValidateconverToUtf32<Exception>('\uD800', '\uDC00', 0x10000);
ValidateconverToUtf32<Exception>('\uD800', '\uDFFF', 0x103FF);
ValidateconverToUtf32<Exception>('\uDBBF', '\uDFFF', 0xFFFFF);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDC00', 0x10FC00);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDFFF', 0x10FFFF);
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD800', Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD7FF', Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\u0000', Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDC01', '\uD940', Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDD00', '\uDE00', Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDF01', '\u0000', Int32.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0032', '\uD7FF', Int32.MinValue); // both non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0000', '\u0000', Int32.MinValue); // both non-surrogate
}
[Fact]
public static void TestEquals()
{
// Boolean Char.Equals(Char)
char a = 'a';
Assert.True(a.Equals('a'));
Assert.False(a.Equals('b'));
Assert.False(a.Equals('A'));
}
[Fact]
public static void TestEqualsObj()
{
// Boolean Char.Equals(Object)
char a = 'a';
Assert.True(a.Equals((object)'a'));
Assert.False(a.Equals((object)'b'));
Assert.False(a.Equals((object)'A'));
Assert.False(a.Equals(null));
int i = (int)'a';
Assert.False(a.Equals(i));
Assert.False(a.Equals("a"));
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Char.GetHashCode()
char a = 'a';
char b = 'b';
Assert.NotEqual(a.GetHashCode(), b.GetHashCode());
}
[Fact]
public static void TestGetNumericValueStrInt()
{
Assert.Equal(Char.GetNumericValue("\uD800\uDD07", 0), 1);
Assert.Equal(Char.GetNumericValue("9", 0), 9);
Assert.Equal(Char.GetNumericValue("Test 7", 5), 7);
Assert.Equal(Char.GetNumericValue("T", 0), -1);
}
[Fact]
public static void TestGetNumericValue()
{
Assert.Equal(Char.GetNumericValue('9'), 9);
Assert.Equal(Char.GetNumericValue('z'), -1);
}
[Fact]
public static void TestIsControl()
{
// Boolean Char.IsControl(Char)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void TestIsControlStrInt()
{
// Boolean Char.IsControl(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsControl(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", 4));
}
[Fact]
public static void TestIsDigit()
{
// Boolean Char.IsDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void TestIsDigitStrInt()
{
// Boolean Char.IsDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", 4));
}
[Fact]
public static void TestIsLetter()
{
// Boolean Char.IsLetter(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void TestIsLetterStrInt()
{
// Boolean Char.IsLetter(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetter(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", 4));
}
[Fact]
public static void TestIsLetterOrDigit()
{
// Boolean Char.IsLetterOrDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void TestIsLetterOrDigitStrInt()
{
// Boolean Char.IsLetterOrDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetterOrDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", 4));
}
[Fact]
public static void TestIsLower()
{
// Boolean Char.IsLower(Char)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void TestIsLowerStrInt()
{
// Boolean Char.IsLower(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLower(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", 4));
}
[Fact]
public static void TestIsNumber()
{
// Boolean Char.IsNumber(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void TestIsNumberStrInt()
{
// Boolean Char.IsNumber(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsNumber(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", 4));
}
[Fact]
public static void TestIsPunctuation()
{
// Boolean Char.IsPunctuation(Char)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void TestIsPunctuationStrInt()
{
// Boolean Char.IsPunctuation(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsPunctuation(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", 4));
}
[Fact]
public static void TestIsSeparator()
{
// Boolean Char.IsSeparator(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void TestIsSeparatorStrInt()
{
// Boolean Char.IsSeparator(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSeparator(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", 4));
}
[Fact]
public static void TestIsLowSurrogate()
{
// Boolean Char.IsLowSurrogate(Char)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void TestIsLowSurrogateStrInt()
{
// Boolean Char.IsLowSurrogate(String, Int32)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLowSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", 4));
}
[Fact]
public static void TestIsHighSurrogate()
{
// Boolean Char.IsHighSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void TestIsHighSurrogateStrInt()
{
// Boolean Char.IsHighSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsHighSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogate()
{
// Boolean Char.IsSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void TestIsSurrogateStrInt()
{
// Boolean Char.IsSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogatePair()
{
// Boolean Char.IsSurrogatePair(Char, Char)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void TestIsSurrogatePairStrInt()
{
// Boolean Char.IsSurrogatePair(String, Int32)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
}
[Fact]
public static void TestIsSymbol()
{
// Boolean Char.IsSymbol(Char)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void TestIsSymbolStrInt()
{
// Boolean Char.IsSymbol(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSymbol(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", 4));
}
[Fact]
public static void TestIsUpper()
{
// Boolean Char.IsUpper(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void TestIsUpperStrInt()
{
// Boolean Char.IsUpper(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsUpper(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", 4));
}
[Fact]
public static void TestIsWhiteSpace()
{
// Boolean Char.IsWhiteSpace(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'));
Assert.True(char.IsWhiteSpace('\u0085'));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void TestIsWhiteSpaceStrInt()
{
// Boolean Char.IsWhiteSpace(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'.ToString(), 0));
Assert.True(char.IsWhiteSpace('\u0085'.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
Assert.Throws<ArgumentNullException>(() => char.IsWhiteSpace(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", 4));
}
[Fact]
public static void TestMaxValue()
{
// Char Char.MaxValue
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void TestMinValue()
{
// Char Char.MinValue
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void TestToLower()
{
// Char Char.ToLower(Char)
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLower(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToLowerInvariant()
{
// Char Char.ToLowerInvariant(Char)
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLowerInvariant(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToString()
{
// String Char.ToString()
Assert.Equal(new string('a', 1), 'a'.ToString());
Assert.Equal(new string('\uabcd', 1), '\uabcd'.ToString());
}
[Fact]
public static void TestToStringChar()
{
// String Char.ToString(Char)
Assert.Equal(new string('a', 1), char.ToString('a'));
Assert.Equal(new string('\uabcd', 1), char.ToString('\uabcd'));
}
[Fact]
public static void TestToUpper()
{
// Char Char.ToUpper(Char)
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpper(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToUpperInvariant()
{
// Char Char.ToUpperInvariant(Char)
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpperInvariant(c);
Assert.Equal(c, lc);
}
}
private static void ValidateTryParse(string s, char expected, bool shouldSucceed)
{
char result;
Assert.Equal(shouldSucceed, char.TryParse(s, out result));
if (shouldSucceed)
Assert.Equal(expected, result);
}
[Fact]
public static void TestTryParse()
{
// Boolean Char.TryParse(String, Char)
ValidateTryParse("a", 'a', true);
ValidateTryParse("4", '4', true);
ValidateTryParse(" ", ' ', true);
ValidateTryParse("\n", '\n', true);
ValidateTryParse("\0", '\0', true);
ValidateTryParse("\u0135", '\u0135', true);
ValidateTryParse("\u05d9", '\u05d9', true);
ValidateTryParse("\ud801", '\ud801', true); // high surrogate
ValidateTryParse("\udc01", '\udc01', true); // low surrogate
ValidateTryParse("\ue001", '\ue001', true); // private use codepoint
// Fail cases
ValidateTryParse(null, '\0', false);
ValidateTryParse("", '\0', false);
ValidateTryParse("\n\r", '\0', false);
ValidateTryParse("kj", '\0', false);
ValidateTryParse(" a", '\0', false);
ValidateTryParse("a ", '\0', false);
ValidateTryParse("\\u0135", '\0', false);
ValidateTryParse("\u01356", '\0', false);
ValidateTryParse("\ud801\udc01", '\0', false); // surrogate pair
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][] {
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][] {
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u037f','\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
}
| |
using System;
using System.Text;
public class Test
{
public Boolean runTest()
{
TestLibrary.Logging.WriteLine( "parse testing started." );
bool passing = true;
try
{
//input is null
passing &= VerifyParseException(null, typeof(ArgumentNullException), false);
//input is empty
passing &= VerifyParseException(String.Empty, typeof(ArgumentException), false);
//input is whitespace
passing &= VerifyParseException(" ", typeof(ArgumentException), false);
//input has 1 component
passing &= VerifyParseException("1234", typeof(ArgumentException), false);
//input has 5 components
passing &= VerifyParseException("123.123.123.324.543", typeof(ArgumentException), false);
//input has a negative component
passing &= NormalCasesException("-123", typeof(ArgumentOutOfRangeException), false);
//component > Int32
passing &= NormalCasesException((((long)Int32.MaxValue) + 1).ToString("d"), typeof(OverflowException), false);
//component has extra whitespace (internal and external)
passing &= NormalCases(" 123");
passing &= NormalCases("123 ");
passing &= NormalCases(" 123 ");
passing &= NormalCasesException("1 23", typeof(FormatException), false);
//component in hex format
passing &= NormalCasesException("0x123", typeof(FormatException), false);
//component in exp format
passing &= NormalCasesException("12e2", typeof(FormatException), false);
//component has leading sign
passing &= NormalCases("+123");
//component has trailing sign
passing &= NormalCasesException("123+", typeof(FormatException), false);
passing &= NormalCasesException("123-", typeof(FormatException), false);
//component has commas
passing &= NormalCasesException("12,345", typeof(FormatException), false);
//component has hex chars
passing &= NormalCasesException("ac", typeof(FormatException), false);
//component has non-digit
passing &= NormalCasesException("12v3", typeof(FormatException), false);
passing &= NormalCasesException("12^3", typeof(FormatException), false);
passing &= NormalCasesException("12#3", typeof(FormatException), false);
passing &= NormalCasesException("1*23", typeof(FormatException), false);
//component has wrong seperator
passing &= VerifyParseException("123,123,123,324", typeof(ArgumentException), false);
passing &= VerifyParseException("123:123:123:324", typeof(ArgumentException), false);
passing &= VerifyParseException("123;123;123;324", typeof(ArgumentException), false);
passing &= VerifyParseException("123-123-123-324", typeof(ArgumentException), false);
passing &= VerifyParseException("123 123 123 324", typeof(ArgumentException), false);
//added "V" at start
passing &= VerifyParseException("V123.123.123.324", typeof(FormatException), false);
passing &= VerifyParseException("v123.123.123.324", typeof(FormatException), false);
//normal case
passing &= VerifyParse("123.123");
passing &= VerifyParse("123.123.123");
passing &= VerifyParse("123.123.123.123");
//valid 0 case
passing &= NormalCases("0");
passing &= VerifyParse("0.0.0.0");
//Int32.MaxValue cases
passing &= NormalCases(Int32.MaxValue.ToString("d"));
}
catch(Exception exc_general)
{
TestLibrary.Logging.WriteLine("Error: Unexpected Exception: {0}", exc_general);
passing = false;
}
if (passing)
{
TestLibrary.Logging.WriteLine("Passed!");
}
else
{
TestLibrary.Logging.WriteLine( "Failed!" );
}
return passing;
}
private bool NormalCasesException(string input, Type exceptionType, bool tryThrows)
{
bool passing = true;
passing &= VerifyParseException(String.Format("{0}.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}", input), exceptionType, false);
passing &= VerifyParseException(String.Format("{0}.123.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}.123", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.{0}", input), exceptionType, false);
passing &= VerifyParseException(String.Format("{0}.123.123.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.{0}.123.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.{0}.324", input), exceptionType, false);
passing &= VerifyParseException(String.Format("123.123.123.{0}", input), exceptionType, false);
return passing;
}
private bool VerifyParseException(string input, Type exceptionType, bool tryThrows)
{
bool result = true;
TestLibrary.Logging.WriteLine("");
TestLibrary.Logging.WriteLine("Testing input: \"{0}\"", input);
try
{
try
{
Version.Parse(input);
TestLibrary.Logging.WriteLine("Version.Parse:: Expected Exception not thrown.");
result = false;
}
catch (Exception e)
{
if (e.GetType() != exceptionType)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Wrong Exception thrown: Expected:{0} Got:{1}", exceptionType, e);
result = false;
}
}
Version test;
if (tryThrows)
{
try
{
Version.TryParse(input, out test);
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected Exception not thrown.");
result = false;
}
catch (Exception e)
{
if (e.GetType() != exceptionType)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Wrong Exception thrown: Expected:{0} Got:{1}", exceptionType, e);
result = false;
}
}
}
else
{
bool rVal;
rVal = Version.TryParse(input, out test);
if (rVal)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected failure parsing, got true return value.");
result = false;
}
if (!IsDefaultVersion(test))
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected null, got {0} value.", test);
result = false;
}
}
}
catch (Exception exc)
{
TestLibrary.Logging.WriteLine("Unexpected exception for input: \"{0}\" exception: {1}", input, exc);
result = false;
}
if (!result)
{
TestLibrary.Logging.WriteLine("Incorrect result for input: \"{0}\"", input);
}
return result;
}
private bool NormalCases(string input)
{
bool passing = true;
passing &= VerifyParse(String.Format("{0}.123", input));
passing &= VerifyParse(String.Format("123.{0}", input));
passing &= VerifyParse(String.Format("{0}.123.123", input));
passing &= VerifyParse(String.Format("123.{0}.123", input));
passing &= VerifyParse(String.Format("123.123.{0}", input));
passing &= VerifyParse(String.Format("{0}.123.123.324", input));
passing &= VerifyParse(String.Format("123.{0}.123.324", input));
passing &= VerifyParse(String.Format("123.123.{0}.324", input));
passing &= VerifyParse(String.Format("123.123.123.{0}", input));
return passing;
}
private bool VerifyParse(string input)
{
bool result = true;
TestLibrary.Logging.WriteLine("");
TestLibrary.Logging.WriteLine("Testing input: \"{0}\"", input);
try
{
String[] parts = input.Split('.');
int major = Int32.Parse(parts[0]);
int minor = Int32.Parse(parts[1]);
int build = 0;
int revision = 0;
if (parts.Length > 2) build = Int32.Parse(parts[2]);
if (parts.Length > 3) revision = Int32.Parse(parts[3]);
Version expected = null;
if (parts.Length == 2) expected = new Version(major, minor);
if (parts.Length == 3) expected = new Version(major, minor, build);
if (parts.Length > 3) expected = new Version(major, minor, build, revision);
Version test;
try
{
test = Version.Parse(input);
if (test.CompareTo(expected) != 0)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Expected Result. Expected {0}, Got {1}", expected, test);
result = false;
}
}
catch (Exception e)
{
TestLibrary.Logging.WriteLine("Version.Parse:: Unexpected Exception thrown: {0}", e);
result = false;
}
try
{
bool rVal;
rVal = Version.TryParse(input, out test);
if (!rVal)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected no failure parsing, got false return value.");
result = false;
}
if (test.CompareTo(expected) != 0)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Expected {0}, Got {1}", expected, test);
result = false;
}
}
catch (Exception e)
{
TestLibrary.Logging.WriteLine("Version.TryParse:: Unexpected Exception thrown: {0}", e);
result = false;
}
}
catch (Exception exc)
{
TestLibrary.Logging.WriteLine("Unexpected exception for input: \"{0}\" exception:{1}", input, exc);
result = false;
}
if (!result)
{
TestLibrary.Logging.WriteLine("Incorrect result for input: \"{0}\"", input);
}
return result;
}
private bool IsDefaultVersion(Version input)
{
bool ret = false;
if (input == null)
{
ret = true;
}
return ret;
//use to return Version of 0.0.0.0 on failure - now returning null.
//return (input.CompareTo(new Version()) == 0);
}
public static int Main(String[] args)
{
Boolean bResult = false;
Test test = new Test();
try
{
bResult = test.runTest();
}
catch (Exception exc)
{
bResult = false;
TestLibrary.Logging.WriteLine("Unexpected Exception thrown: {0}", exc);
}
if (bResult == false) return 1;
return 100;
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Cuyahoga.Core.Domain;
using Cuyahoga.Core.Service;
using Cuyahoga.Core.Util;
namespace Cuyahoga.Web.Admin
{
/// <summary>
/// Summary description for UserEdit.
/// </summary>
public class UserEdit : Cuyahoga.Web.Admin.UI.AdminBasePage
{
private User _activeUser;
protected System.Web.UI.WebControls.TextBox txtUsername;
protected System.Web.UI.WebControls.TextBox txtLastname;
protected System.Web.UI.WebControls.TextBox txtEmail;
protected System.Web.UI.WebControls.TextBox txtPassword1;
protected System.Web.UI.WebControls.TextBox txtPassword2;
protected System.Web.UI.WebControls.Repeater rptRoles;
protected System.Web.UI.WebControls.RegularExpressionValidator revEmail;
protected System.Web.UI.WebControls.CompareValidator covPassword;
protected System.Web.UI.WebControls.Button btnSave;
protected System.Web.UI.WebControls.Button btnCancel;
protected System.Web.UI.WebControls.Button btnDelete;
protected System.Web.UI.WebControls.Label lblUsername;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvUsername;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvEmail;
protected System.Web.UI.WebControls.CheckBox chkActive;
protected System.Web.UI.WebControls.DropDownList ddlTimeZone;
protected System.Web.UI.WebControls.TextBox txtWebsite;
protected System.Web.UI.WebControls.TextBox txtFirstname;
private void Page_Load(object sender, System.EventArgs e)
{
this.Title = "Edit user";
if (Context.Request.QueryString["UserId"] != null)
{
if (Int32.Parse(Context.Request.QueryString["UserId"]) == -1)
{
// Create a new user instance
this._activeUser = new User();
}
else
{
// Get user data
this._activeUser = (Cuyahoga.Core.Domain.User)base.CoreRepository.GetObjectById(typeof(Cuyahoga.Core.Domain.User)
, Int32.Parse(Context.Request.QueryString["UserId"]));
}
if (! this.IsPostBack)
{
BindTimeZones();
BindUserControls();
BindRoles();
}
}
}
private void BindTimeZones()
{
this.ddlTimeZone.DataSource = TimeZoneUtil.GetTimeZones();
this.ddlTimeZone.DataValueField = "Key";
this.ddlTimeZone.DataTextField = "Value";
this.ddlTimeZone.DataBind();
}
private void BindUserControls()
{
if (this._activeUser.Id > 0)
{
this.txtUsername.Visible = false;
this.lblUsername.Text = this._activeUser.UserName;
this.lblUsername.Visible = true;
this.rfvUsername.Enabled = false;
}
else
{
this.txtUsername.Text = this._activeUser.UserName;
this.txtUsername.Visible = true;
this.lblUsername.Visible = false;
this.rfvUsername.Enabled = true;
}
this.txtFirstname.Text = this._activeUser.FirstName;
this.txtLastname.Text = this._activeUser.LastName;
this.txtEmail.Text = this._activeUser.Email;
this.txtWebsite.Text = this._activeUser.Website;
this.ddlTimeZone.Items.FindByValue(this._activeUser.TimeZone.ToString()).Selected = true;
this.chkActive.Checked = this._activeUser.IsActive;
this.btnDelete.Visible = (this._activeUser.Id > 0);
this.btnDelete.Attributes.Add("onclick", "return confirmDeleteUser();");
}
private void BindRoles()
{
IList roles = base.CoreRepository.GetAll(typeof(Role), "PermissionLevel");
FilterAnonymousRoles(roles);
this.rptRoles.ItemDataBound += new RepeaterItemEventHandler(rptRoles_ItemDataBound);
this.rptRoles.DataSource = roles;
this.rptRoles.DataBind();
}
/// <summary>
/// Filter the anonymous roles from the list.
/// </summary>
private void FilterAnonymousRoles(IList roles)
{
int roleCount = roles.Count;
for (int i = roleCount -1; i >= 0; i--)
{
Role role = (Role)roles[i];
if (role.PermissionLevel == (int)AccessLevel.Anonymous)
{
roles.Remove(role);
}
}
}
private void SetRoles()
{
this._activeUser.Roles.Clear();
foreach (RepeaterItem ri in rptRoles.Items)
{
// HACK: RoleId is stored in the ViewState because the repeater doesn't have a DataKeys property.
// Another HACK: we're only using the role id's to save database roundtrips.
CheckBox chkRole = (CheckBox)ri.FindControl("chkRole");
if (chkRole.Checked)
{
int roleId = (int)this.ViewState[ri.ClientID];
Role role = (Role)base.CoreRepository.GetObjectById(typeof(Role), roleId);
this._activeUser.Roles.Add(role);
}
}
// Check if the Adminstrator role is not accidently deleted for the superuser.
string adminRole = Config.GetConfiguration()["AdministratorRole"];
if (this._activeUser.UserName == Config.GetConfiguration()["SuperUser"]
&& ! this._activeUser.IsInRole(adminRole))
{
throw new Exception(String.Format("The user '{0}' has to have the '{1}' role."
, this._activeUser.UserName, adminRole));
}
}
private void SaveUser()
{
try
{
SetRoles();
if (this._activeUser.Id == -1)
{
base.CoreRepository.SaveObject(this._activeUser);
Context.Response.Redirect("UserEdit.aspx?UserId=" + this._activeUser.Id + "&message=User created successfully");
}
else
{
base.CoreRepository.UpdateObject(this._activeUser);
ShowMessage("User saved");
}
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnCancel_Click(object sender, System.EventArgs e)
{
Context.Response.Redirect("Users.aspx");
}
private void rptRoles_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Role role = e.Item.DataItem as Role;
if (role != null)
{
CheckBox chkRole = (CheckBox)e.Item.FindControl("chkRole");
chkRole.Checked = this._activeUser.IsInRole(role);
// Add RoleId to the ViewState with the ClientID of the repeateritem as key.
this.ViewState[e.Item.ClientID] = role.Id;
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
if (this.IsValid)
{
if (this._activeUser.Id == -1)
{
this._activeUser.UserName = this.txtUsername.Text;
}
else
{
this._activeUser.UserName = this.lblUsername.Text;
}
if (this.txtFirstname.Text.Length > 0)
{
this._activeUser.FirstName = this.txtFirstname.Text;
}
if (this.txtLastname.Text.Length > 0)
{
this._activeUser.LastName = this.txtLastname.Text;
}
this._activeUser.Email = this.txtEmail.Text;
this._activeUser.Website = this.txtWebsite.Text;
this._activeUser.IsActive = this.chkActive.Checked;
this._activeUser.TimeZone = Int32.Parse(this.ddlTimeZone.SelectedValue);
if (this.txtPassword1.Text.Length > 0 && this.txtPassword2.Text.Length > 0)
{
try
{
this._activeUser.Password = Core.Domain.User.HashPassword(this.txtPassword1.Text);
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
if (this._activeUser.Id == -1 && this._activeUser.Password == null)
{
ShowError("Password is required");
}
else
{
SaveUser();
}
}
}
private void btnDelete_Click(object sender, System.EventArgs e)
{
if (this._activeUser.Id > 0)
{
if (this._activeUser.Id != ((Cuyahoga.Core.Domain.User)this.Page.User.Identity).Id)
{
if (this._activeUser.UserName != Config.GetConfiguration()["SuperUser"])
{
try
{
base.CoreRepository.DeleteObject(this._activeUser);
Context.Response.Redirect("Users.aspx");
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
else
{
ShowError("You can't delete the superuser.");
}
}
else
{
ShowError("You can't delete yourself.");
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.Metadata;
namespace SalesAssister.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
NormalizedName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityRole", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(nullable: true),
NormalizedUserName = table.Column<string>(nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SalesPersons",
columns: table => new
{
SalesPersonId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Company = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SalesPerson", x => x.SalesPersonId);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityRoleClaim<string>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserClaim<string>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserLogin<string>", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
ClientId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Email = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true),
SalesPersonId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Client", x => x.ClientId);
table.ForeignKey(
name: "FK_Client_SalesPerson_SalesPersonId",
column: x => x.SalesPersonId,
principalTable: "SalesPersons",
principalColumn: "SalesPersonId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Contacts",
columns: table => new
{
ContactId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClientId = table.Column<int>(nullable: false),
Notes = table.Column<string>(nullable: true),
SalesPersonId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => x.ContactId);
table.ForeignKey(
name: "FK_Contact_Client_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "ClientId",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Contact_SalesPerson_SalesPersonId",
column: x => x.SalesPersonId,
principalTable: "SalesPersons",
principalColumn: "SalesPersonId",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("AspNetRoleClaims");
migrationBuilder.DropTable("AspNetUserClaims");
migrationBuilder.DropTable("AspNetUserLogins");
migrationBuilder.DropTable("AspNetUserRoles");
migrationBuilder.DropTable("Contacts");
migrationBuilder.DropTable("AspNetRoles");
migrationBuilder.DropTable("AspNetUsers");
migrationBuilder.DropTable("Clients");
migrationBuilder.DropTable("SalesPersons");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Jint.Native.Function;
using Jint.Runtime;
using Xunit;
namespace Jint.Tests.Runtime
{
public class ExecutionConstraintTests
{
[Fact]
public void ShouldThrowStatementCountOverflow()
{
Assert.Throws<StatementsCountOverflowException>(
() => new Engine(cfg => cfg.MaxStatements(100)).Evaluate("while(true);")
);
}
[Fact]
public void ShouldThrowMemoryLimitExceeded()
{
Assert.Throws<MemoryLimitExceededException>(
() => new Engine(cfg => cfg.LimitMemory(2048)).Evaluate("a=[]; while(true){ a.push(0); }")
);
}
[Fact]
public void ShouldThrowTimeout()
{
Assert.Throws<TimeoutException>(
() => new Engine(cfg => cfg.TimeoutInterval(new TimeSpan(0, 0, 0, 0, 500))).Evaluate("while(true);")
);
}
[Fact]
public void ShouldThrowExecutionCanceled()
{
Assert.Throws<ExecutionCanceledException>(
() =>
{
using (var tcs = new CancellationTokenSource())
using (var waitHandle = new ManualResetEvent(false))
{
var engine = new Engine(cfg => cfg.CancellationToken(tcs.Token));
ThreadPool.QueueUserWorkItem(state =>
{
waitHandle.WaitOne();
tcs.Cancel();
});
engine.SetValue("waitHandle", waitHandle);
engine.Evaluate(@"
function sleep(millisecondsTimeout) {
var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
while (new Date() < totalMilliseconds) { }
}
sleep(100);
waitHandle.Set();
sleep(5000);
");
}
}
);
}
[Fact]
public void CanDiscardRecursion()
{
var script = @"var factorial = function(n) {
if (n>1) {
return n * factorial(n - 1);
}
};
var result = factorial(500);
";
Assert.Throws<RecursionDepthOverflowException>(
() => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
);
}
[Fact]
public void ShouldDiscardHiddenRecursion()
{
var script = @"var renamedFunc;
var exec = function(callback) {
renamedFunc = callback;
callback();
};
var result = exec(function() {
renamedFunc();
});
";
Assert.Throws<RecursionDepthOverflowException>(
() => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
);
}
[Fact]
public void ShouldRecognizeAndDiscardChainedRecursion()
{
var script = @" var funcRoot, funcA, funcB, funcC, funcD;
var funcRoot = function() {
funcA();
};
var funcA = function() {
funcB();
};
var funcB = function() {
funcC();
};
var funcC = function() {
funcD();
};
var funcD = function() {
funcRoot();
};
funcRoot();
";
Assert.Throws<RecursionDepthOverflowException>(
() => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
);
}
[Fact]
public void ShouldProvideCallChainWhenDiscardRecursion()
{
var script = @" var funcRoot, funcA, funcB, funcC, funcD;
var funcRoot = function() {
funcA();
};
var funcA = function() {
funcB();
};
var funcB = function() {
funcC();
};
var funcC = function() {
funcD();
};
var funcD = function() {
funcRoot();
};
funcRoot();
";
RecursionDepthOverflowException exception = null;
try
{
new Engine(cfg => cfg.LimitRecursion()).Execute(script);
}
catch (RecursionDepthOverflowException ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
Assert.Equal("funcRoot", exception.CallExpressionReference);
}
[Fact]
public void ShouldAllowShallowRecursion()
{
var script = @"var factorial = function(n) {
if (n>1) {
return n * factorial(n - 1);
}
};
var result = factorial(8);
";
new Engine(cfg => cfg.LimitRecursion(20)).Execute(script);
}
[Fact]
public void ShouldDiscardDeepRecursion()
{
var script = @"var factorial = function(n) {
if (n>1) {
return n * factorial(n - 1);
}
};
var result = factorial(38);
";
Assert.Throws<RecursionDepthOverflowException>(
() => new Engine(cfg => cfg.LimitRecursion(20)).Execute(script)
);
}
[Fact]
public void ShouldAllowRecursionLimitWithoutReferencedName()
{
const string input = @"(function () {
var factorial = function(n) {
if (n>1) {
return n * factorial(n - 1);
}
};
var result = factorial(38);
})();
";
var engine = new Engine(o => o.LimitRecursion(20));
Assert.Throws<RecursionDepthOverflowException>(() => engine.Execute(input));
}
[Fact]
public void ShouldLimitRecursionWithAllFunctionInstances()
{
var engine = new Engine(cfg =>
{
// Limit recursion to 5 invocations
cfg.LimitRecursion(5);
cfg.Strict();
});
var ex = Assert.Throws<RecursionDepthOverflowException>(() => engine.Evaluate(@"
var myarr = new Array(5000);
for (var i = 0; i < myarr.length; i++) {
myarr[i] = function(i) {
myarr[i + 1](i + 1);
}
}
myarr[0](0);
"));
}
[Fact]
public void ShouldLimitRecursionWithGetters()
{
const string code = @"var obj = { get test() { return this.test + '2'; } }; obj.test;";
var engine = new Engine(cfg => cfg.LimitRecursion(10));
Assert.Throws<RecursionDepthOverflowException>(() => engine.Evaluate(code));
}
[Fact]
public void ShouldLimitArraySizeForConcat()
{
var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("for (let a = [1, 2, 3];; a = a.concat(a)) ;"));
}
[Fact]
public void ShouldLimitArraySizeForFill()
{
var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("var arr = Array(1000000000).fill(new Array(1000000000));"));
}
[Fact]
public void ShouldLimitArraySizeForJoin()
{
var engine = new Engine(o => o.MaxStatements(1_000).MaxArraySize(1_000_000));
Assert.Throws<MemoryLimitExceededException>(() => engine.Evaluate("new Array(2147483647).join('*')"));
}
[Fact]
public void ShouldConsiderConstraintsWhenCallingInvoke()
{
var engine = new Engine(options =>
{
options.TimeoutInterval(TimeSpan.FromMilliseconds(100));
});
var myApi = new MyApi();
engine.SetValue("myApi", myApi);
engine.Execute("myApi.addEventListener('DataReceived', (data) => { myApi.log(data) })");
var dataReceivedCallbacks = myApi.Callbacks.Where(kvp => kvp.Key == "DataReceived");
foreach (var callback in dataReceivedCallbacks)
{
engine.Invoke(callback.Value, "Data Received #1");
Thread.Sleep(101);
engine.Invoke(callback.Value, "Data Received #2");
}
}
private class MyApi
{
public readonly Dictionary<string, ScriptFunctionInstance> Callbacks = new Dictionary<string, ScriptFunctionInstance>();
public void AddEventListener(string eventName, ScriptFunctionInstance callback)
{
Callbacks.Add(eventName, callback);
}
public void Log(string logMessage)
{
Console.WriteLine(logMessage);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Net.HttpListenerRequest.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Net
{
sealed public partial class HttpListenerRequest
{
#region Methods and constructors
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, Object state)
{
Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);
return default(IAsyncResult);
}
public System.Security.Cryptography.X509Certificates.X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
return default(System.Security.Cryptography.X509Certificates.X509Certificate2);
}
public System.Security.Cryptography.X509Certificates.X509Certificate2 GetClientCertificate()
{
return default(System.Security.Cryptography.X509Certificates.X509Certificate2);
}
internal HttpListenerRequest()
{
}
#endregion
#region Properties and indexers
public string[] AcceptTypes
{
get
{
return default(string[]);
}
}
public int ClientCertificateError
{
get
{
return default(int);
}
}
public Encoding ContentEncoding
{
get
{
return default(Encoding);
}
}
public long ContentLength64
{
get
{
return default(long);
}
}
public string ContentType
{
get
{
return default(string);
}
}
public CookieCollection Cookies
{
get
{
Contract.Ensures(Contract.Result<System.Net.CookieCollection>() != null);
return default(CookieCollection);
}
}
public bool HasEntityBody
{
get
{
return default(bool);
}
}
public System.Collections.Specialized.NameValueCollection Headers
{
get
{
Contract.Ensures(Contract.Result<System.Collections.Specialized.NameValueCollection>() != null);
return default(System.Collections.Specialized.NameValueCollection);
}
}
public string HttpMethod
{
get
{
return default(string);
}
}
public Stream InputStream
{
get
{
Contract.Ensures(Contract.Result<System.IO.Stream>() != null);
return default(Stream);
}
}
public bool IsAuthenticated
{
get
{
return default(bool);
}
}
public bool IsLocal
{
get
{
Contract.Requires(this.LocalEndPoint != null);
Contract.Requires(this.RemoteEndPoint != null);
Contract.Ensures(Contract.Result<bool>() == (this.LocalEndPoint.Address.Equals(this.RemoteEndPoint.Address)));
return default(bool);
}
}
public bool IsSecureConnection
{
get
{
return default(bool);
}
}
public bool KeepAlive
{
get
{
return default(bool);
}
}
public IPEndPoint LocalEndPoint
{
get
{
return default(IPEndPoint);
}
}
public Version ProtocolVersion
{
get
{
return default(Version);
}
}
public System.Collections.Specialized.NameValueCollection QueryString
{
get
{
Contract.Requires(this.Url != null);
Contract.Requires(this.Url.Query != null);
Contract.Ensures(Contract.Result<System.Collections.Specialized.NameValueCollection>() != null);
return default(System.Collections.Specialized.NameValueCollection);
}
}
public string RawUrl
{
get
{
return default(string);
}
}
public IPEndPoint RemoteEndPoint
{
get
{
return default(IPEndPoint);
}
}
public Guid RequestTraceIdentifier
{
get
{
return default(Guid);
}
}
public string ServiceName
{
get
{
return default(string);
}
internal set
{
}
}
public TransportContext TransportContext
{
get
{
Contract.Ensures(Contract.Result<System.Net.TransportContext>() != null);
return default(TransportContext);
}
}
public Uri Url
{
get
{
return default(Uri);
}
}
public Uri UrlReferrer
{
get
{
return default(Uri);
}
}
public string UserAgent
{
get
{
return default(string);
}
}
public string UserHostAddress
{
get
{
Contract.Requires(this.LocalEndPoint != null);
return default(string);
}
}
public string UserHostName
{
get
{
return default(string);
}
}
public string[] UserLanguages
{
get
{
return default(string[]);
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using BizHawk.Common;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk;
using BizHawk.Client.EmuHawk.FilterManager;
using BizHawk.Bizware.BizwareGL;
using BizHawk.Bizware.BizwareGL.Drivers.OpenTK;
using OpenTK;
using OpenTK.Graphics;
namespace BizHawk.Client.EmuHawk.Filters
{
/// <summary>
/// applies letterboxing logic to figure out how to fit the source dimensions into the target dimensions.
/// In the future this could also apply rules like integer-only scaling, etc.
/// </summary>
class LetterboxingLogic
{
/// <summary>
/// the location within the destination region of the output content (scaled and translated)
/// </summary>
public int vx, vy, vw, vh;
/// <summary>
/// the scale factor eventually used
/// </summary>
public float WidthScale, HeightScale;
/// <summary>
/// In case you want to do it yourself
/// </summary>
public LetterboxingLogic() { }
//do maths on the viewport and the native resolution and the user settings to get a display rectangle
public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWidth, int targetHeight, int sourceWidth, int sourceHeight, Size textureSize, Size virtualSize)
{
int textureWidth = textureSize.Width;
int textureHeight = textureSize.Height;
int virtualWidth = virtualSize.Width;
int virtualHeight = virtualSize.Height;
//zero 02-jun-2014 - we passed these in, but ignored them. kind of weird..
int oldSourceWidth = sourceWidth;
int oldSourceHeight = sourceHeight;
sourceWidth = (int)virtualWidth;
sourceHeight = (int)virtualHeight;
//this doesnt make sense
if (!maintainAspect)
maintainInteger = false;
float widthScale = (float)targetWidth / sourceWidth;
float heightScale = (float)targetHeight / sourceHeight;
if (maintainAspect
//zero 20-jul-2014 - hacks upon hacks, this function needs rewriting
&& !maintainInteger
)
{
if (widthScale > heightScale) widthScale = heightScale;
if (heightScale > widthScale) heightScale = widthScale;
}
if (maintainInteger)
{
//just totally different code
//apply the zooming algorithm (pasted and reworked, for now)
//ALERT COPYPASTE LAUNDROMAT
Vector2 VS = new Vector2(virtualWidth, virtualHeight);
Vector2 BS = new Vector2(textureWidth, textureHeight);
Vector2 AR = Vector2.Divide(VS, BS);
float target_par = (AR.X / AR.Y);
Vector2 PS = new Vector2(1, 1); //this would malfunction for AR <= 0.5 or AR >= 2.0
for(;;)
{
//TODO - would be good not to run this per frame....
Vector2[] trials = new[] {
PS + new Vector2(1, 0),
PS + new Vector2(0, 1),
PS + new Vector2(1, 1)
};
bool[] trials_limited = new bool[3] { false,false,false};
int bestIndex = -1;
float bestValue = 1000.0f;
for (int t = 0; t < trials.Length; t++)
{
Vector2 vTrial = trials[t];
trials_limited[t] = false;
//check whether this is going to exceed our allotted area
int test_vw = (int)(vTrial.X * textureWidth);
int test_vh = (int)(vTrial.Y * textureHeight);
if (test_vw > targetWidth) trials_limited[t] = true;
if (test_vh > targetHeight) trials_limited[t] = true;
//I.
float test_ar = vTrial.X / vTrial.Y;
//II.
//Vector2 calc = Vector2.Multiply(trials[t], VS);
//float test_ar = calc.X / calc.Y;
//not clear which approach is superior
float deviation_linear = Math.Abs(test_ar - target_par);
float deviation_geom = test_ar / target_par;
if (deviation_geom < 1) deviation_geom = 1.0f / deviation_geom;
float value = deviation_linear;
if (value < bestValue)
{
bestIndex = t;
bestValue = value;
}
}
//last result was best, so bail out
if (bestIndex == -1)
break;
//if the winner ran off the edge, bail out
if (trials_limited[bestIndex])
break;
PS = trials[bestIndex];
}
//"fix problems with gameextrapadding in >1x window scales" (other edits were made, maybe theyre whats important)
//vw = (int)(PS.X * oldSourceWidth);
//vh = (int)(PS.Y * oldSourceHeight);
vw = (int)(PS.X * sourceWidth);
vh = (int)(PS.Y * sourceHeight);
widthScale = PS.X;
heightScale = PS.Y;
}
else
{
vw = (int)(widthScale * sourceWidth);
vh = (int)(heightScale * sourceHeight);
}
//theres only one sensible way to letterbox in case we're shrinking a dimension: "pan & scan" to the center
//this is unlikely to be what the user wants except in the one case of maybe shrinking off some overscan area
//instead, since we're more about biz than gaming, lets shrink the view to fit in the small dimension
if (targetWidth < vw)
vw = targetWidth;
if (targetHeight < vh)
vh = targetHeight;
//determine letterboxing parameters
vx = (targetWidth - vw) / 2;
vy = (targetHeight - vh) / 2;
//zero 09-oct-2014 - changed this for TransformPoint. scenario: basic 1x (but system-specified AR) NES window.
//vw would be 293 but WidthScale would be 1.0. I think it should be something different.
//FinalPresentation doesnt use the LL.WidthScale, so this is unlikely to be breaking anything old that depends on it
//WidthScale = widthScale;
//HeightScale = heightScale;
WidthScale = (float)vw / oldSourceWidth;
HeightScale = (float)vh / oldSourceHeight;
}
}
public class FinalPresentation : BaseFilter
{
public enum eFilterOption
{
None, Bilinear, Bicubic
}
public eFilterOption FilterOption = eFilterOption.None;
public RetroShaderChain BicubicFilter;
public FinalPresentation(Size size)
{
this.OutputSize = size;
}
Size OutputSize, InputSize;
public Size TextureSize, VirtualTextureSize;
public int BackgroundColor;
public bool AutoPrescale;
public IGuiRenderer GuiRenderer;
public bool Flip;
public IGL GL;
bool nop;
LetterboxingLogic LL;
Size ContentSize;
public bool Config_FixAspectRatio, Config_FixScaleInteger, Config_PadOnly;
/// <summary>
/// only use with Config_PadOnly
/// </summary>
public System.Windows.Forms.Padding Padding;
public override void Initialize()
{
DeclareInput();
nop = false;
}
public override Size PresizeOutput(string channel, Size size)
{
if (FilterOption == eFilterOption.Bicubic)
{
size.Width = LL.vw;
size.Height = LL.vh;
return size;
}
return base.PresizeOutput(channel, size);
}
public override Size PresizeInput(string channel, Size size)
{
if (FilterOption != eFilterOption.Bicubic)
return size;
if (Config_PadOnly)
{
//TODO - redundant fix
LL = new LetterboxingLogic();
LL.vx += Padding.Left;
LL.vy += Padding.Top;
LL.vw = size.Width;
LL.vh = size.Height;
}
else
{
LL = new LetterboxingLogic(Config_FixAspectRatio, Config_FixScaleInteger, OutputSize.Width, OutputSize.Height, size.Width, size.Height, TextureSize, VirtualTextureSize);
LL.vx += Padding.Left;
LL.vy += Padding.Top;
}
return size;
}
public override void SetInputFormat(string channel, SurfaceState state)
{
bool need = false;
if (state.SurfaceFormat.Size != OutputSize)
need = true;
if (FilterOption != eFilterOption.None)
need = true;
if (Flip)
need = true;
if (!need)
{
nop = true;
ContentSize = state.SurfaceFormat.Size;
return;
}
FindInput().SurfaceDisposition = SurfaceDisposition.Texture;
DeclareOutput(new SurfaceState(new SurfaceFormat(OutputSize), SurfaceDisposition.RenderTarget));
InputSize = state.SurfaceFormat.Size;
if (Config_PadOnly)
{
//TODO - redundant fix
LL = new LetterboxingLogic();
LL.vx += Padding.Left;
LL.vy += Padding.Top;
LL.vw = InputSize.Width;
LL.vh = InputSize.Height;
LL.WidthScale = 1;
LL.HeightScale = 1;
}
else
{
int ow = OutputSize.Width;
int oh = OutputSize.Height;
ow -= Padding.Horizontal;
oh -= Padding.Vertical;
LL = new LetterboxingLogic(Config_FixAspectRatio, Config_FixScaleInteger, ow, oh, InputSize.Width, InputSize.Height, TextureSize, VirtualTextureSize);
LL.vx += Padding.Left;
LL.vy += Padding.Top;
}
ContentSize = new Size(LL.vw,LL.vh);
if (InputSize == OutputSize) //any reason we need to check vx and vy?
IsNOP = true;
}
public Size GetContentSize() { return ContentSize; }
public override Vector2 UntransformPoint(string channel, Vector2 point)
{
if (nop)
return point;
point.X -= LL.vx;
point.Y -= LL.vy;
point.X /= LL.WidthScale;
point.Y /= LL.HeightScale;
return point;
}
public override Vector2 TransformPoint(string channel, Vector2 point)
{
if (nop)
return point;
point.X *= LL.WidthScale;
point.Y *= LL.HeightScale;
point.X += LL.vx;
point.Y += LL.vy;
return point;
}
public override void Run()
{
if (nop)
return;
GL.SetClearColor(Color.FromArgb(BackgroundColor));
GL.Clear(OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit);
GuiRenderer.Begin(OutputSize.Width, OutputSize.Height);
GuiRenderer.SetBlendState(GL.BlendNoneCopy);
if(FilterOption != eFilterOption.None)
InputTexture.SetFilterLinear();
else
InputTexture.SetFilterNearest();
if (FilterOption == eFilterOption.Bicubic)
{
//this was handled earlier by another filter
}
GuiRenderer.Modelview.Translate(LL.vx, LL.vy);
if (Flip)
{
GuiRenderer.Modelview.Scale(1, -1);
GuiRenderer.Modelview.Translate(0, -LL.vh);
}
GuiRenderer.Draw(InputTexture,0,0,LL.vw,LL.vh);
GuiRenderer.End();
}
}
//TODO - turn this into a NOP at 1x, just in case something accidentally activates it with 1x
public class PrescaleFilter : BaseFilter
{
public int Scale;
public override void Initialize()
{
DeclareInput(SurfaceDisposition.Texture);
}
public override void SetInputFormat(string channel, SurfaceState state)
{
var OutputSize = state.SurfaceFormat.Size;
OutputSize.Width *= Scale;
OutputSize.Height *= Scale;
var ss = new SurfaceState(new SurfaceFormat(OutputSize), SurfaceDisposition.RenderTarget);
DeclareOutput(ss, channel);
}
public override void Run()
{
var outSize = FindOutput().SurfaceFormat.Size;
FilterProgram.GuiRenderer.Begin(outSize);
FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNoneCopy);
FilterProgram.GuiRenderer.Modelview.Scale(Scale);
FilterProgram.GuiRenderer.Draw(InputTexture);
FilterProgram.GuiRenderer.End();
}
}
public class AutoPrescaleFilter : BaseFilter
{
Size OutputSize, InputSize;
int XIS, YIS;
public override void Initialize()
{
DeclareInput(SurfaceDisposition.Texture);
}
public override void SetInputFormat(string channel, SurfaceState state)
{
//calculate integer scaling factors
XIS = OutputSize.Width / state.SurfaceFormat.Size.Width;
YIS = OutputSize.Height / state.SurfaceFormat.Size.Height;
if (XIS == 0) XIS = 1;
if (YIS == 0) YIS = 1;
OutputSize = state.SurfaceFormat.Size;
if (XIS <= 1 && YIS <= 1)
{
IsNOP = true;
}
else
{
OutputSize.Width *= XIS;
OutputSize.Height *= YIS;
}
var outState = new SurfaceState();
outState.SurfaceFormat = new SurfaceFormat(OutputSize);
outState.SurfaceDisposition = SurfaceDisposition.RenderTarget;
DeclareOutput(outState);
}
public override Size PresizeOutput(string channel, Size size)
{
OutputSize = size;
return base.PresizeOutput(channel, size);
}
public override Size PresizeInput(string channel, Size insize)
{
InputSize = insize;
return insize;
}
public override void Run()
{
FilterProgram.GuiRenderer.Begin(OutputSize); //hope this didnt change
FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNoneCopy);
FilterProgram.GuiRenderer.Modelview.Scale(XIS,YIS);
FilterProgram.GuiRenderer.Draw(InputTexture);
FilterProgram.GuiRenderer.End();
}
}
public class LuaLayer : BaseFilter
{
public override void Initialize()
{
DeclareInput(SurfaceDisposition.RenderTarget);
}
public override void SetInputFormat(string channel, SurfaceState state)
{
DeclareOutput(state);
}
Texture2d Texture;
public void SetTexture(Texture2d tex)
{
Texture = tex;
}
public override void Run()
{
var outSize = FindOutput().SurfaceFormat.Size;
FilterProgram.GuiRenderer.Begin(outSize);
FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNormal);
FilterProgram.GuiRenderer.Draw(Texture);
FilterProgram.GuiRenderer.End();
}
}
public class OSD : BaseFilter
{
//this class has the ability to disable its operations for higher performance when the callback is removed,
//without having to take it out of the chain. although, its presence in the chain may slow down performance due to added resolves/renders
//so, we should probably rebuild the chain.
public override void Initialize()
{
if (RenderCallback == null) return;
DeclareInput(SurfaceDisposition.RenderTarget);
}
public override void SetInputFormat(string channel, SurfaceState state)
{
if (RenderCallback == null) return;
DeclareOutput(state);
}
public Action RenderCallback;
public override void Run()
{
if (RenderCallback == null) return;
RenderCallback();
}
}
}
| |
/*
* 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 OpenSim.Region.ScriptEngine.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Lifetime;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject, IScript
{
// For tracing GC while debugging
public static bool GCDummy = false;
private Dictionary<string, MethodInfo> inits = new Dictionary<string, MethodInfo>();
// private ScriptSponsor m_sponser;
private Executor m_Executor = null;
private Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
private Dictionary<string, object> m_InitialValues =
new Dictionary<string, object>();
public ScriptBaseClass()
{
m_Executor = new Executor(this);
MethodInfo[] myArrayMethodInfo = GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo mi in myArrayMethodInfo)
{
if (mi.Name.Length > 7 && mi.Name.Substring(0, 7) == "ApiType")
{
string type = mi.Name.Substring(7);
inits[type] = mi;
}
}
// m_sponser = new ScriptSponsor();
}
~ScriptBaseClass()
{
GCDummy = true;
}
public void Close()
{
// m_sponser.Close();
}
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
m_Executor.ExecuteEvent(state, FunctionName, args);
}
public string[] GetApis()
{
string[] apis = new string[inits.Count];
inits.Keys.CopyTo(apis, 0);
return apis;
}
public int GetStateEventFlags(string state)
{
return (int)m_Executor.GetStateEventFlags(state);
}
public Dictionary<string, object> GetVars()
{
Dictionary<string, object> vars = new Dictionary<string, object>();
if (m_Fields == null)
return vars;
m_Fields.Clear();
Type t = GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo field in fields)
{
m_Fields[field.Name] = field;
if (field.FieldType == typeof(LSL_Types.list)) // ref type, copy
{
LSL_Types.list v = (LSL_Types.list)field.GetValue(this);
Object[] data = new Object[v.Data.Length];
Array.Copy(v.Data, 0, data, 0, v.Data.Length);
LSL_Types.list c = new LSL_Types.list();
c.Data = data;
vars[field.Name] = c;
}
else if (field.FieldType == typeof(LSL_Types.LSLInteger) ||
field.FieldType == typeof(LSL_Types.LSLString) ||
field.FieldType == typeof(LSL_Types.LSLFloat) ||
field.FieldType == typeof(Int32) ||
field.FieldType == typeof(Double) ||
field.FieldType == typeof(Single) ||
field.FieldType == typeof(String) ||
field.FieldType == typeof(Byte) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(LSL_Types.Vector3) ||
field.FieldType == typeof(LSL_Types.Quaternion))
{
vars[field.Name] = field.GetValue(this);
}
}
return vars;
}
public void InitApi(string api, IScriptApi data)
{
if (!inits.ContainsKey(api))
return;
//ILease lease = (ILease)RemotingServices.GetLifetimeService(data as MarshalByRefObject);
//RemotingServices.GetLifetimeService(data as MarshalByRefObject);
// lease.Register(m_sponser);
MethodInfo mi = inits[api];
Object[] args = new Object[1];
args[0] = data;
mi.Invoke(this, args);
m_InitialValues = GetVars();
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
// Infinite
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
#if DEBUG
#endif
public void NoOp()
{
// Does what is says on the packet. Nowt, nada, nothing.
// Required for insertion after a jump label to do what it says on the packet!
// With a bit of luck the compiler may even optimize it out.
}
public void ResetVars()
{
SetVars(m_InitialValues);
}
public void SetVars(Dictionary<string, object> vars)
{
foreach (KeyValuePair<string, object> var in vars)
{
if (m_Fields.ContainsKey(var.Key))
{
if (m_Fields[var.Key].FieldType == typeof(LSL_Types.list))
{
LSL_Types.list v = (LSL_Types.list)m_Fields[var.Key].GetValue(this);
Object[] data = ((LSL_Types.list)var.Value).Data;
v.Data = new Object[data.Length];
Array.Copy(data, 0, v.Data, 0, data.Length);
m_Fields[var.Key].SetValue(this, v);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLInteger) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLString) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLFloat) ||
m_Fields[var.Key].FieldType == typeof(Int32) ||
m_Fields[var.Key].FieldType == typeof(Double) ||
m_Fields[var.Key].FieldType == typeof(Single) ||
m_Fields[var.Key].FieldType == typeof(String) ||
m_Fields[var.Key].FieldType == typeof(Byte) ||
m_Fields[var.Key].FieldType == typeof(short) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Vector3) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Quaternion)
)
{
m_Fields[var.Key].SetValue(this, var.Value);
}
}
}
}
public virtual void StateChange(string newState)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
[Serializable]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string _name; // The name used to construct this CompareInfo
[NonSerialized]
private string _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion _sortVersion;
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
internal CompareInfo(CultureInfo culture)
{
_name = culture._name;
InitSort(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
Contract.EndContractBlock();
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(string name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
Contract.EndContractBlock();
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
if (GlobalizationMode.Invariant)
{
return true;
}
char *pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (text.Length == 0)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
if (GlobalizationMode.Invariant)
{
return true;
}
fixed (char *pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
_name = null;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
if (_name != null)
{
InitSort(CultureInfo.GetCultureInfo(_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual string Name
{
get
{
Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
if (_name == "zh-CHT" || _name == "zh-CHS")
{
return _name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, string string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
public unsafe virtual int Compare(string string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length);
return String.CompareOrdinal(string1, string2);
}
return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2);
return CompareOrdinal(string1, offset1, length1, string2, offset2, length2);
}
return CompareString(string1, offset1, length1,
string2, offset2, length2,
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
int length = Math.Min(lengthA, lengthB);
int range = length;
fixed (char* ap = strA) fixed (char* bp = strB)
{
char* a = ap + indexA;
char* b = bp + indexB;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80);
while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
// Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return lengthA - lengthB;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(string source, string prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsSuffix(string source, string suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(string source, string suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int IndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, value, startIndex, count, options, null);
}
// The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated
// and the caller is passing a valid matchLengthPtr pointer.
internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(matchLengthPtr != null);
*matchLengthPtr = 0;
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex >= source.Length)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
if (_invariantMode)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
}
return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public virtual int LastIndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
if (_invariantMode)
return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
if (_invariantMode)
return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value, startIndex, count, options);
}
internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
}
return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public virtual SortKey GetSortKey(string source, CompareOptions options)
{
if (_invariantMode)
return InvariantCreateSortKey(source, options);
return CreateSortKey(source, options);
}
public virtual SortKey GetSortKey(string source)
{
if (_invariantMode)
return InvariantCreateSortKey(source, CompareOptions.None);
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
Contract.EndContractBlock();
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (_sortVersion == null)
{
if (_invariantMode)
{
_sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
(byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
}
else
{
_sortVersion = GetSortVersion();
}
}
return _sortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
using System;
using System.Xml;
using System.IO;
namespace BinxEd
{
/// <summary>
/// The BinX Parser.
/// </summary>
public class Parser
{
private const string sBinx = "binx";
private const string sDefinitions = "definitions";
private const string sDataset = "dataset";
/// <summary>
/// Parse a BinX document from a file and save extracted definitions and data elements in the given containers.
/// </summary>
/// <param name="filePath">File path and name to parse</param>
/// <param name="definitions">Container object reference for definitions</param>
/// <param name="dataset">Container object reference for dataset elements</param>
/// <returns>true if successful</returns>
public static bool load(string filePath, ref DefinitionsNode definitions, ref DatasetNode dataset)
{
bool bBinxDoc = false;
try
{
XmlTextReader reader = new XmlTextReader(filePath);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (bBinxDoc)
{
if (reader.LocalName.Equals(sDefinitions))
{
//<definitions>
loadDefinitions(reader, ref definitions);
}
else if (reader.LocalName.Equals(sDataset))
{
//<dataset>
loadDataset(reader, ref dataset);
}
}
else if (reader.LocalName.Equals(sBinx))
{
bBinxDoc = true;
}
}
}
reader.Close();
return true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Bad XML file");
return false;
}
}
/// <summary>
/// Load definition section only, for import defined types.
/// </summary>
/// <param name="filePath">BinX file to load definitions from</param>
/// <param name="definitions">Reference to the Definitions class to hold the imported definitions</param>
public static void loadDefinitions(string filePath, ref DefinitionsNode definitions)
{
bool bBinxDoc = false;
try
{
XmlTextReader reader = new XmlTextReader(filePath);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (bBinxDoc)
{
if (reader.LocalName.Equals(sDefinitions))
{
//<definitions>
loadDefinitions(reader, ref definitions);
}
}
else if (reader.LocalName.Equals(sBinx))
{
bBinxDoc = true;
}
}
}
reader.Close();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Bad XML file");
}
}
/// <summary>
/// Load definitions section.
/// </summary>
/// <param name="reader"></param>
protected static void loadDefinitions(XmlTextReader reader, ref DefinitionsNode definitions)
{
DefineTypeNode ut = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName.Equals("defineType"))
{
string sTypename = reader.GetAttribute("typeName");
ut = new DefineTypeNode(sTypename);
}
else if (reader.LocalName.Equals("struct") && ut!=null)
{
ut.setBaseType( LoadStruct(reader) );
}
else if (reader.LocalName.Equals("union") && ut!=null)
{
ut.setBaseType( LoadUnion(reader) );
}
else if (reader.LocalName.StartsWith("array") && ut!=null)
{
ut.setBaseType( LoadArray(reader) );
}
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
if (reader.LocalName.Equals("defineType") && ut!=null)
{
definitions.addChild(ut);
ut = null;
}
else if (reader.LocalName.Equals(sDefinitions))
{
return;
}
}
}
}
/// <summary>
/// Load dataset section from BinX document.
/// </summary>
/// <param name="reader"></param>
protected static void loadDataset(XmlTextReader reader, ref DatasetNode dataset)
{
dataset.setBinaryFileName(reader.GetAttribute("src"));
dataset.setBigEndian(reader.GetAttribute("byteOrder").Equals("bigEndian"));
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
AbstractNode it = ParseNode(reader);
dataset.addChild(it);
}
else if (reader.NodeType==XmlNodeType.EndElement)
{
if (reader.LocalName.Equals("dataset"))
{
return;
}
}
}
}
/// <summary>
/// Load a struct block
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
protected static StructNode LoadStruct(XmlTextReader reader)
{
StructNode st = new StructNode();
string varname = reader.GetAttribute("varName");
string blocksize = reader.GetAttribute("blockSize");
if (varname != null)
{
st.setVarName( varname );
}
if (blocksize != null)
{
st.setBlockSize( Convert.ToInt32(blocksize) );
}
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
st.addChild( ParseNode(reader) );
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
if (reader.LocalName.Equals("struct"))
{
break;
}
}
}
return st;
}
/// <summary>
/// Parse and load a union element type
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
protected static UnionNode LoadUnion(XmlTextReader reader)
{
string vname = reader.GetAttribute("varName");
string blocksize = reader.GetAttribute("blockSize");
UnionNode ut = new UnionNode();
if (vname != null)
{
ut.setVarName( vname );
}
if (blocksize != null)
{
ut.setBlockSize( Convert.ToInt32(blocksize) );
}
bool inDiscriminantSection = false;
bool inCaseSection = false;
string dv = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName.Equals("discriminant"))
{
inDiscriminantSection = true;
}
else if (reader.LocalName.Equals("case"))
{
inCaseSection = true;
dv = reader.GetAttribute("discriminantValue");
}
else
{
AbstractNode it = ParseNode(reader);
if (inDiscriminantSection)
{
ut.setDiscriminantType( it.getTypeName() );
}
else if (inCaseSection)
{
CaseNode c = new CaseNode(dv, it);
ut.addCase(c);
}
}
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
if (reader.LocalName.Equals("discriminant"))
{
inDiscriminantSection = false;
}
else if (reader.LocalName.Equals("case"))
{
inCaseSection = false;
}
else if (reader.LocalName.Equals("union"))
{
break;
}
}
}
return ut;
}
/// <summary>
/// Parse and load an array element type
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
protected static ArrayNode LoadArray(XmlTextReader reader)
{
string aname = reader.LocalName;
string vname = reader.GetAttribute("varName");
string blocksize = reader.GetAttribute("blockSize");
ArrayNode a = new ArrayNode(aname);
if (vname != null)
{
a.setVarName( vname );
}
if (blocksize != null)
{
a.setBlockSize( Convert.ToInt32(blocksize) );
}
bool inSizeRefSection = false;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName.Equals("sizeRef"))
{
inSizeRefSection = true;
}
else if (reader.LocalName.Equals("dim"))
{
string dname = reader.GetAttribute("name");
int nCount = 0;
string indexTo = reader.GetAttribute("indexTo");
if (indexTo == null)
{
string count = reader.GetAttribute("count");
if (count != null)
{
nCount = Convert.ToInt32(count);
}
}
else
{
nCount = Convert.ToInt32(indexTo) + 1;
}
a.addDimension(dname, nCount);
}
else if (inSizeRefSection)
{
a.setSizeRef( ParseNode(reader) );
}
else
{
a.setElement( ParseNode(reader) );
}
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
if (reader.LocalName.Equals("sizeRef"))
{
inSizeRefSection = false;
}
else if (reader.LocalName.StartsWith("array"))
{
break;
}
}
}
return a;
}
/// <summary>
/// Parse a node for data types (primitive, complex, useType)
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
protected static AbstractNode ParseNode(XmlTextReader reader)
{
AbstractNode it = null;
string byteOrder = reader.GetAttribute("byteOrder");
if (reader.LocalName.Equals("struct"))
{
it = LoadStruct(reader);
}
else if (reader.LocalName.Equals("union"))
{
it = LoadUnion(reader);
}
else if (reader.LocalName.StartsWith("array"))
{
it = LoadArray(reader);
}
else if (reader.LocalName.Equals("useType"))
{
string typeName = reader.GetAttribute("typeName");
string blockSize = reader.GetAttribute("blockSize");
it = new UseTypeNode(typeName);
if (blockSize != null)
{
((UseTypeNode)it).setBlockSize( Convert.ToInt16(blockSize) );
}
string varName = reader.GetAttribute("varName");
it.setVarName( varName );
}
else //primitive
{
string varName = reader.GetAttribute("varName");
it = new PrimitiveNode(reader.LocalName);
if (varName!=null)
{
it.setVarName( varName );
}
}
if (byteOrder != null)
{
it.setBigEndian( (byteOrder.Equals("bigEndian"))?true:false );
}
return it;
}
}
}
| |
// 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.Contracts;
using System.Linq;
using Xunit;
using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableSetTest : ImmutablesTestBase
{
[Fact]
public void AddTest()
{
this.AddTestHelper(this.Empty<int>(), 3, 5, 4, 3);
}
[Fact]
public void AddDuplicatesTest()
{
var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray();
this.AddTestHelper(this.Empty<int>(), arrayWithDuplicates);
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3);
}
[Fact]
public void AddRemoveLoadTest()
{
var data = this.GenerateDummyFillData();
this.AddRemoveLoadTestHelper(Empty<double>(), data);
}
[Fact]
public void RemoveNonExistingTest()
{
this.RemoveNonExistingTest(this.Empty<int>());
}
[Fact]
public void AddBulkFromImmutableToEmpty()
{
var set = this.Empty<int>().Add(5);
var empty2 = this.Empty<int>();
Assert.Same(set, empty2.Union(set)); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
}
[Fact]
public void ExceptTest()
{
this.ExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), 3, 7);
}
/// <summary>
/// Verifies that Except *does* enumerate its argument if the collection is empty.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply lack of an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would be
/// observed previously, but would no longer be thrown if this behavior changed.
/// So this is a test to lock the behavior in place or be thoughtful if adding the optimization.
/// </remarks>
/// <seealso cref="ImmutableListTest.RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty"/>
[Fact]
public void ExceptDoesEnumerateSequenceIfThisIsEmpty()
{
bool enumerated = false;
Empty<int>().Except(Enumerable.Range(1, 1).Select(n => { enumerated = true; return n; }));
Assert.True(enumerated);
}
[Fact]
public void SymmetricExceptTest()
{
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 9).ToArray());
this.SymmetricExceptTestHelper(Empty<int>().Add(1).Add(3).Add(5).Add(7), Enumerable.Range(0, 5).ToArray());
}
[Fact]
public void EnumeratorTest()
{
IComparer<double> comparer = null;
var set = this.Empty<double>();
var sortedSet = set as ISortKeyCollection<double>;
if (sortedSet != null)
{
comparer = sortedSet.KeyComparer;
}
this.EnumeratorTestHelper(set, comparer, 3, 5, 1);
double[] data = this.GenerateDummyFillData();
this.EnumeratorTestHelper(set, comparer, data);
}
[Fact]
public void IntersectTest()
{
this.IntersectTestHelper(Empty<int>().Union(Enumerable.Range(1, 10)), 8, 3, 5);
}
[Fact]
public void UnionTest()
{
this.UnionTestHelper(this.Empty<int>(), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2, 4, 6 }), new[] { 1, 3, 5, 7 });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 1, 2, 3 }), new int[0] { });
this.UnionTestHelper(this.Empty<int>().Union(new[] { 2 }), Enumerable.Range(0, 1000).ToArray());
}
[Fact]
public void SetEqualsTest()
{
Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
var nonEmptySet = this.Empty<int>().Add(5);
Assert.True(nonEmptySet.SetEquals(nonEmptySet));
this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios());
}
[Fact]
public void IsProperSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, this.GetIsProperSubsetOfScenarios());
}
[Fact]
public void IsProperSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, this.GetIsProperSubsetOfScenarios().Select(Flip));
}
[Fact]
public void IsSubsetOfTest()
{
this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, this.GetIsSubsetOfScenarios());
}
[Fact]
public void IsSupersetOfTest()
{
this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, this.GetIsSubsetOfScenarios().Select(Flip));
}
[Fact]
public void OverlapsTest()
{
this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, this.GetOverlapsScenarios());
}
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int>().Equals(null));
Assert.False(Empty<int>().Equals("hi"));
Assert.True(Empty<int>().Equals(Empty<int>()));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3)));
Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5)));
}
[Fact]
public void GetHashCodeTest()
{
// verify that get hash code is the default address based one.
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode());
}
[Fact]
public void ClearTest()
{
var originalSet = this.Empty<int>();
var nonEmptySet = originalSet.Add(5);
var clearedSet = nonEmptySet.Clear();
Assert.Same(originalSet, clearedSet);
}
[Fact]
public void ISetMutationMethods()
{
var set = (ISet<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(0));
Assert.Throws<NotSupportedException>(() => set.ExceptWith(null));
Assert.Throws<NotSupportedException>(() => set.UnionWith(null));
Assert.Throws<NotSupportedException>(() => set.IntersectWith(null));
Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null));
}
[Fact]
public void ICollectionOfTMembers()
{
var set = (ICollection<int>)this.Empty<int>();
Assert.Throws<NotSupportedException>(() => set.Add(1));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove(1));
Assert.True(set.IsReadOnly);
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = (ICollection)this.Empty<string>();
string[] array = new string[0];
builder.CopyTo(array, 0);
builder = (ICollection)this.Empty<string>().Add("a");
array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.True(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
protected abstract bool IncludesGetHashCodeDerivative { get; }
internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence)
{
Contract.Requires(sequence != null);
var list = new List<T>();
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add((T)enumerator.Current);
}
return list;
}
protected abstract IImmutableSet<T> Empty<T>();
protected abstract ISet<T> EmptyMutable<T>();
internal abstract IBinaryTree GetRootNode<T>(IImmutableSet<T> set);
protected void TryGetValueTestHelper(IImmutableSet<string> set)
{
Requires.NotNull(set, nameof(set));
string expected = "egg";
set = set.Add(expected);
string actual;
string lookupValue = expected.ToUpperInvariant();
Assert.True(set.TryGetValue(lookupValue, out actual));
Assert.Same(expected, actual);
Assert.False(set.TryGetValue("foo", out actual));
Assert.Equal("foo", actual);
Assert.False(set.Clear().TryGetValue("nonexistent", out actual));
Assert.Equal("nonexistent", actual);
}
protected IImmutableSet<T> SetWith<T>(params T[] items)
{
return this.Empty<T>().Union(items);
}
protected void CustomSortTestHelper<T>(IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues)
{
Contract.Requires(emptySet != null);
Contract.Requires(injectedValues != null);
Contract.Requires(expectedValues != null);
var set = emptySet;
foreach (T value in injectedValues)
{
set = set.Add(value);
}
Assert.Equal(expectedValues.Length, set.Count);
if (matchOrder)
{
Assert.Equal<T>(expectedValues, set.ToList());
}
else
{
CollectionAssertAreEquivalent(expectedValues, set.ToList());
}
}
/// <summary>
/// Tests various aspects of a set. This should be called only from the unordered or sorted overloads of this method.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
protected void EmptyTestHelper<T>(IImmutableSet<T> emptySet)
{
Contract.Requires(emptySet != null);
Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0");
Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements.");
Assert.Same(emptySet, emptySet.Clear());
}
private IEnumerable<SetTriad> GetSetEqualsScenarios()
{
return new List<SetTriad>
{
new SetTriad(SetWith<int>(), new int[] { }, true),
new SetTriad(SetWith<int>(5), new int[] { 5 }, true),
new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true),
new SetTriad(SetWith<int>(5), new int[] { }, false),
new SetTriad(SetWith<int>(), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false),
new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false),
new SetTriad(SetWith<int>(5, 8), SetWith<int>(5, 8), true),
};
}
private IEnumerable<SetTriad> GetIsProperSubsetOfScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { }, new int[] { 1 }, true),
};
}
private IEnumerable<SetTriad> GetIsSubsetOfScenarios()
{
var results = new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1 }, new int[] { }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
};
// By definition, any proper subset is also a subset.
// But because a subset may not be a proper subset, we filter the proper- scenarios.
results.AddRange(this.GetIsProperSubsetOfScenarios().Where(s => s.Item3));
return results;
}
private IEnumerable<SetTriad> GetOverlapsScenarios()
{
return new List<SetTriad>
{
new SetTriad(new int[] { }, new int[] { }, false),
new SetTriad(new int[] { }, new int[] { 1 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false),
new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true),
};
}
private void SetCompareTestHelper<T>(Func<IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios)
{
//const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}";
int iteration = 0;
foreach (var scenario in scenarios)
{
iteration++;
// Figure out the response expected based on the BCL mutable collections.
var baselineSet = this.EmptyMutable<T>();
baselineSet.UnionWith(scenario.Item1);
var expectedFunc = baselineOperation(baselineSet);
bool expected = expectedFunc(scenario.Item2);
Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior.");
var actualFunc = operation(this.SetWith(scenario.Item1.ToArray()));
var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) };
Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args);
Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args);
}
}
private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario)
{
return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3);
}
private void RemoveTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Except(Enumerable.Empty<T>()));
int initialCount = set.Count;
int removedCount = 0;
foreach (T value in values)
{
var nextSet = set.Remove(value);
Assert.NotSame(set, nextSet);
Assert.Equal(initialCount - removedCount, set.Count);
Assert.Equal(initialCount - removedCount - 1, nextSet.Count);
Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference.");
removedCount++;
set = nextSet;
}
Assert.Equal(initialCount - removedCount, set.Count);
}
private void RemoveNonExistingTest(IImmutableSet<int> emptySet)
{
Assert.Same(emptySet, emptySet.Remove(5));
// Also fill up a set with many elements to build up the tree, then remove from various places in the tree.
const int Size = 200;
var set = emptySet;
for (int i = 0; i < Size; i += 2)
{ // only even numbers!
set = set.Add(i);
}
// Verify that removing odd numbers doesn't change anything.
for (int i = 1; i < Size; i += 2)
{
var setAfterRemoval = set.Remove(i);
Assert.Same(set, setAfterRemoval);
}
}
private void AddRemoveLoadTestHelper<T>(IImmutableSet<T> set, T[] data)
{
Contract.Requires(set != null);
Contract.Requires(data != null);
foreach (T value in data)
{
var newSet = set.Add(value);
Assert.NotSame(set, newSet);
set = newSet;
}
foreach (T value in data)
{
Assert.True(set.Contains(value));
}
foreach (T value in data)
{
var newSet = set.Remove(value);
Assert.NotSame(set, newSet);
set = newSet;
}
}
protected void EnumeratorTestHelper<T>(IImmutableSet<T> emptySet, IComparer<T> comparer, params T[] values)
{
var set = emptySet;
foreach (T value in values)
{
set = set.Add(value);
}
var nonGenericEnumerableList = ToListNonGeneric<T>(set);
CollectionAssertAreEquivalent(nonGenericEnumerableList, values);
var list = set.ToList();
CollectionAssertAreEquivalent(list, values);
if (comparer != null)
{
Array.Sort(values, comparer);
Assert.Equal<T>(values, list);
}
// Apply some less common uses to the enumerator to test its metal.
IEnumerator<T> enumerator;
using (enumerator = set.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset(); // reset isn't usually called before MoveNext
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
ManuallyEnumerateTest(list, enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
private void ExceptTestHelper<T>(IImmutableSet<T> set, params T[] valuesToRemove)
{
Contract.Requires(set != null);
Contract.Requires(valuesToRemove != null);
var expectedSet = new HashSet<T>(set);
expectedSet.ExceptWith(valuesToRemove);
var actualSet = set.Except(valuesToRemove);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
this.VerifyAvlTreeState(actualSet);
}
private void SymmetricExceptTestHelper<T>(IImmutableSet<T> set, params T[] otherCollection)
{
Contract.Requires(set != null);
Contract.Requires(otherCollection != null);
var expectedSet = new HashSet<T>(set);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
this.VerifyAvlTreeState(actualSet);
}
private void IntersectTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.True(set.Intersect(Enumerable.Empty<T>()).Count == 0);
var expected = new HashSet<T>(set);
expected.IntersectWith(values);
var actual = set.Intersect(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
this.VerifyAvlTreeState(actual);
}
private void UnionTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
var expected = new HashSet<T>(set);
expected.UnionWith(values);
var actual = set.Union(values);
CollectionAssertAreEquivalent(expected.ToList(), actual.ToList());
this.VerifyAvlTreeState(actual);
}
private void AddTestHelper<T>(IImmutableSet<T> set, params T[] values)
{
Contract.Requires(set != null);
Contract.Requires(values != null);
Assert.Same(set, set.Union(Enumerable.Empty<T>()));
int initialCount = set.Count;
var uniqueValues = new HashSet<T>(values);
var enumerateAddSet = set.Union(values);
Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count);
foreach (T value in values)
{
Assert.True(enumerateAddSet.Contains(value));
}
int addedCount = 0;
foreach (T value in values)
{
bool duplicate = set.Contains(value);
var nextSet = set.Add(value);
Assert.True(nextSet.Count > 0);
Assert.Equal(initialCount + addedCount, set.Count);
int expectedCount = initialCount + addedCount;
if (!duplicate)
{
expectedCount++;
}
Assert.Equal(expectedCount, nextSet.Count);
Assert.Equal(duplicate, set.Contains(value));
Assert.True(nextSet.Contains(value));
if (!duplicate)
{
addedCount++;
}
// Next assert temporarily disabled because Roslyn's set doesn't follow this rule.
Assert.Same(nextSet, nextSet.Add(value)); //, "Adding duplicate value {0} should keep the original reference.", value);
set = nextSet;
}
}
private void VerifyAvlTreeState<T>(IImmutableSet<T> set)
{
var rootNode = this.GetRootNode(set);
rootNode.VerifyBalanced();
rootNode.VerifyHeightIsWithinTolerance(set.Count);
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Analyst;
using Encog.App.Analyst.Script;
using Encog.App.Analyst.Script.Normalize;
using Encog.App.Analyst.Script.Prop;
using Encog.ML;
using Encog.Neural.Flat;
using Encog.Neural.Networks;
using Encog.Persist;
using Encog.Util;
using Encog.Util.Arrayutil;
namespace Encog.App.Generate.Generators.MQL4
{
/// <summary>
/// Generate MQL4.
/// </summary>
public class GenerateMQL4 : AbstractTemplateGenerator
{
public override String NullArray
{
get { return "{-1}"; }
}
public override String TemplatePath
{
get { return "Encog.Resources.mt4.mql4"; }
}
private void ProcessCalc()
{
AnalystField firstOutputField = null;
int barsNeeded = Math.Abs(Analyst.DetermineMinTimeSlice());
int inputCount = Analyst.DetermineInputCount();
int outputCount = Analyst.DetermineOutputCount();
IndentLevel = 2;
AddLine("if( _inputCount>0 && Bars>=" + barsNeeded + " )");
AddLine("{");
IndentIn();
AddLine("double input[" + inputCount + "];");
AddLine("double output[" + outputCount + "];");
int idx = 0;
foreach (AnalystField field in Analyst.Script.Normalize
.NormalizedFields)
{
if (field.Input)
{
DataField df = Analyst.Script.FindDataField(field.Name);
String str;
switch (field.Action)
{
case NormalizationAction.PassThrough:
str = EngineArray.Replace(df.Source, "##", "pos+"
+ (-field.TimeSlice));
AddLine("input[" + idx + "]=" + str + ";");
idx++;
break;
case NormalizationAction.Normalize:
str = EngineArray.Replace(df.Source, "##", "pos+"
+ (-field.TimeSlice));
AddLine("input[" + idx + "]=Norm(" + str + ","
+ field.NormalizedHigh + ","
+ field.NormalizedLow + ","
+ field.ActualHigh + ","
+ field.ActualLow + ");");
idx++;
break;
case NormalizationAction.Ignore:
break;
default:
throw new AnalystCodeGenerationError(
"Can't generate Ninjascript code, unsupported normalizatoin action: "
+ field.Action.ToString());
}
}
if (field.Output)
{
if (firstOutputField == null)
{
firstOutputField = field;
}
}
}
if (firstOutputField == null)
{
throw new AnalystCodeGenerationError(
"Could not find an output field.");
}
AddLine("Compute(input,output);");
AddLine("ExtMapBuffer1[pos] = DeNorm(output[0]" + ","
+ firstOutputField.NormalizedHigh + ","
+ firstOutputField.NormalizedLow + ","
+ firstOutputField.ActualHigh + ","
+ firstOutputField.ActualLow + ");");
IndentOut();
AddLine("}");
IndentLevel = 2;
}
private void ProcessHeaders()
{
DataField[] fields = Analyst.Script.Fields;
var line = new StringBuilder();
line.Append("FileWrite(iHandle");
foreach (DataField df in fields)
{
line.Append(",");
line.Append("\"");
line.Append(df.Name);
line.Append("\"");
}
line.Append(");");
AddLine(line.ToString());
}
private void ProcessMainBlock()
{
EncogAnalyst analyst = Analyst;
String processID = analyst.Script.Properties
.GetPropertyString(ScriptProperties.PROCESS_CONFIG_SOURCE_FILE);
String methodID = analyst
.Script
.Properties
.GetPropertyString(
ScriptProperties.MlConfigMachineLearningFile);
FileInfo methodFile = analyst.Script.ResolveFilename(methodID);
FileInfo processFile = analyst.Script.ResolveFilename(processID);
IMLMethod method = null;
int[] contextTargetOffset = null;
int[] contextTargetSize = null;
bool hasContext = false;
int inputCount = 0;
int[] layerContextCount = null;
int[] layerCounts = null;
int[] layerFeedCounts = null;
int[] layerIndex = null;
double[] layerOutput = null;
double[] layerSums = null;
int outputCount = 0;
int[] weightIndex = null;
double[] weights = null;
int neuronCount = 0;
int layerCount = 0;
int[] activation = null;
double[] p = null;
if (methodFile.Exists)
{
method = (IMLMethod) EncogDirectoryPersistence
.LoadObject(methodFile);
FlatNetwork flat = ((BasicNetwork) method).Flat;
contextTargetOffset = flat.ContextTargetOffset;
contextTargetSize = flat.ContextTargetSize;
hasContext = flat.HasContext;
inputCount = flat.InputCount;
layerContextCount = flat.LayerContextCount;
layerCounts = flat.LayerCounts;
layerFeedCounts = flat.LayerFeedCounts;
layerIndex = flat.LayerIndex;
layerOutput = flat.LayerOutput;
layerSums = flat.LayerSums;
outputCount = flat.OutputCount;
weightIndex = flat.WeightIndex;
weights = flat.Weights;
activation = CreateActivations(flat);
p = CreateParams(flat);
neuronCount = flat.LayerOutput.Length;
layerCount = flat.LayerCounts.Length;
}
IndentLevel = 2;
IndentIn();
AddNameValue("string EXPORT_FILENAME", "\"" + processFile
+ "\"");
AddNameValue("int _neuronCount", neuronCount);
AddNameValue("int _layerCount", layerCount);
AddNameValue("int _contextTargetOffset[]", contextTargetOffset);
AddNameValue("int _contextTargetSize[]", contextTargetSize);
AddNameValue("bool _hasContext", hasContext ? "true" : "false");
AddNameValue("int _inputCount", inputCount);
AddNameValue("int _layerContextCount[]", layerContextCount);
AddNameValue("int _layerCounts[]", layerCounts);
AddNameValue("int _layerFeedCounts[]", layerFeedCounts);
AddNameValue("int _layerIndex[]", layerIndex);
AddNameValue("double _layerOutput[]", layerOutput);
AddNameValue("double _layerSums[]", layerSums);
AddNameValue("int _outputCount", outputCount);
AddNameValue("int _weightIndex[]", weightIndex);
AddNameValue("double _weights[]", weights);
AddNameValue("int _activation[]", activation);
AddNameValue("double _p[]", p);
IndentOut();
IndentLevel = 0;
}
private void ProcessObtain()
{
IndentLevel = 3;
AddLine("FileWrite(iHandle, when,");
DataField[] fields = Analyst.Script.Fields;
String lastLine = null;
foreach (DataField field in fields)
{
DataField df = field;
if (string.Compare(df.Name, "time", true) != 0
&& string.Compare(df.Name, "prediction", true) != 0)
{
String str = EngineArray.Replace(df.Source, "##",
"pos");
if (lastLine != null)
{
AddLine(lastLine + ",");
}
lastLine = str;
}
}
if (lastLine != null)
{
AddLine(lastLine);
}
AddLine(");");
IndentLevel = 0;
}
public override void ProcessToken(String command)
{
if (string.Compare(command, "MAIN-BLOCK", true) == 0)
{
ProcessMainBlock();
}
else if (command.Equals("CALC"))
{
ProcessCalc();
}
else if (command.Equals("OBTAIN"))
{
ProcessObtain();
}
else if (command.Equals("HEADERS"))
{
ProcessHeaders();
}
IndentLevel = 0;
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// DemographicsThemesV2
/// </summary>
[DataContract]
public partial class DemographicsThemesV2 : IEquatable<DemographicsThemesV2>
{
/// <summary>
/// Initializes a new instance of the <see cref="DemographicsThemesV2" /> class.
/// </summary>
/// <param name="PopulationTheme">PopulationTheme.</param>
/// <param name="RaceAndEthnicityTheme">RaceAndEthnicityTheme.</param>
/// <param name="HealthTheme">HealthTheme.</param>
/// <param name="EducationTheme">EducationTheme.</param>
/// <param name="IncomeTheme">IncomeTheme.</param>
/// <param name="AssetsAndWealthTheme">AssetsAndWealthTheme.</param>
/// <param name="HouseholdsTheme">HouseholdsTheme.</param>
/// <param name="HousingTheme">HousingTheme.</param>
/// <param name="EmploymentTheme">EmploymentTheme.</param>
/// <param name="ExpenditureTheme">ExpenditureTheme.</param>
/// <param name="SupplyAndDemandTheme">SupplyAndDemandTheme.</param>
public DemographicsThemesV2(PopulationTheme PopulationTheme = null, RaceAndEthnicityTheme RaceAndEthnicityTheme = null, HealthTheme HealthTheme = null, EducationTheme EducationTheme = null, IncomeThemeV2 IncomeTheme = null, AssetsAndWealthTheme AssetsAndWealthTheme = null, HouseholdsTheme HouseholdsTheme = null, HousingTheme HousingTheme = null, EmploymentTheme EmploymentTheme = null, ExpenditureTheme ExpenditureTheme = null, SupplyAndDemandTheme SupplyAndDemandTheme = null)
{
this.PopulationTheme = PopulationTheme;
this.RaceAndEthnicityTheme = RaceAndEthnicityTheme;
this.HealthTheme = HealthTheme;
this.EducationTheme = EducationTheme;
this.IncomeTheme = IncomeTheme;
this.AssetsAndWealthTheme = AssetsAndWealthTheme;
this.HouseholdsTheme = HouseholdsTheme;
this.HousingTheme = HousingTheme;
this.EmploymentTheme = EmploymentTheme;
this.ExpenditureTheme = ExpenditureTheme;
this.SupplyAndDemandTheme = SupplyAndDemandTheme;
}
/// <summary>
/// Gets or Sets PopulationTheme
/// </summary>
[DataMember(Name="populationTheme", EmitDefaultValue=false)]
public PopulationTheme PopulationTheme { get; set; }
/// <summary>
/// Gets or Sets RaceAndEthnicityTheme
/// </summary>
[DataMember(Name="raceAndEthnicityTheme", EmitDefaultValue=false)]
public RaceAndEthnicityTheme RaceAndEthnicityTheme { get; set; }
/// <summary>
/// Gets or Sets HealthTheme
/// </summary>
[DataMember(Name="healthTheme", EmitDefaultValue=false)]
public HealthTheme HealthTheme { get; set; }
/// <summary>
/// Gets or Sets EducationTheme
/// </summary>
[DataMember(Name="educationTheme", EmitDefaultValue=false)]
public EducationTheme EducationTheme { get; set; }
/// <summary>
/// Gets or Sets IncomeTheme
/// </summary>
[DataMember(Name="incomeTheme", EmitDefaultValue=false)]
public IncomeThemeV2 IncomeTheme { get; set; }
/// <summary>
/// Gets or Sets AssetsAndWealthTheme
/// </summary>
[DataMember(Name="assetsAndWealthTheme", EmitDefaultValue=false)]
public AssetsAndWealthTheme AssetsAndWealthTheme { get; set; }
/// <summary>
/// Gets or Sets HouseholdsTheme
/// </summary>
[DataMember(Name="householdsTheme", EmitDefaultValue=false)]
public HouseholdsTheme HouseholdsTheme { get; set; }
/// <summary>
/// Gets or Sets HousingTheme
/// </summary>
[DataMember(Name="housingTheme", EmitDefaultValue=false)]
public HousingTheme HousingTheme { get; set; }
/// <summary>
/// Gets or Sets EmploymentTheme
/// </summary>
[DataMember(Name="employmentTheme", EmitDefaultValue=false)]
public EmploymentTheme EmploymentTheme { get; set; }
/// <summary>
/// Gets or Sets ExpenditureTheme
/// </summary>
[DataMember(Name="expenditureTheme", EmitDefaultValue=false)]
public ExpenditureTheme ExpenditureTheme { get; set; }
/// <summary>
/// Gets or Sets SupplyAndDemandTheme
/// </summary>
[DataMember(Name="supplyAndDemandTheme", EmitDefaultValue=false)]
public SupplyAndDemandTheme SupplyAndDemandTheme { 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 DemographicsThemesV2 {\n");
sb.Append(" PopulationTheme: ").Append(PopulationTheme).Append("\n");
sb.Append(" RaceAndEthnicityTheme: ").Append(RaceAndEthnicityTheme).Append("\n");
sb.Append(" HealthTheme: ").Append(HealthTheme).Append("\n");
sb.Append(" EducationTheme: ").Append(EducationTheme).Append("\n");
sb.Append(" IncomeTheme: ").Append(IncomeTheme).Append("\n");
sb.Append(" AssetsAndWealthTheme: ").Append(AssetsAndWealthTheme).Append("\n");
sb.Append(" HouseholdsTheme: ").Append(HouseholdsTheme).Append("\n");
sb.Append(" HousingTheme: ").Append(HousingTheme).Append("\n");
sb.Append(" EmploymentTheme: ").Append(EmploymentTheme).Append("\n");
sb.Append(" ExpenditureTheme: ").Append(ExpenditureTheme).Append("\n");
sb.Append(" SupplyAndDemandTheme: ").Append(SupplyAndDemandTheme).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DemographicsThemesV2);
}
/// <summary>
/// Returns true if DemographicsThemesV2 instances are equal
/// </summary>
/// <param name="other">Instance of DemographicsThemesV2 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DemographicsThemesV2 other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.PopulationTheme == other.PopulationTheme ||
this.PopulationTheme != null &&
this.PopulationTheme.Equals(other.PopulationTheme)
) &&
(
this.RaceAndEthnicityTheme == other.RaceAndEthnicityTheme ||
this.RaceAndEthnicityTheme != null &&
this.RaceAndEthnicityTheme.Equals(other.RaceAndEthnicityTheme)
) &&
(
this.HealthTheme == other.HealthTheme ||
this.HealthTheme != null &&
this.HealthTheme.Equals(other.HealthTheme)
) &&
(
this.EducationTheme == other.EducationTheme ||
this.EducationTheme != null &&
this.EducationTheme.Equals(other.EducationTheme)
) &&
(
this.IncomeTheme == other.IncomeTheme ||
this.IncomeTheme != null &&
this.IncomeTheme.Equals(other.IncomeTheme)
) &&
(
this.AssetsAndWealthTheme == other.AssetsAndWealthTheme ||
this.AssetsAndWealthTheme != null &&
this.AssetsAndWealthTheme.Equals(other.AssetsAndWealthTheme)
) &&
(
this.HouseholdsTheme == other.HouseholdsTheme ||
this.HouseholdsTheme != null &&
this.HouseholdsTheme.Equals(other.HouseholdsTheme)
) &&
(
this.HousingTheme == other.HousingTheme ||
this.HousingTheme != null &&
this.HousingTheme.Equals(other.HousingTheme)
) &&
(
this.EmploymentTheme == other.EmploymentTheme ||
this.EmploymentTheme != null &&
this.EmploymentTheme.Equals(other.EmploymentTheme)
) &&
(
this.ExpenditureTheme == other.ExpenditureTheme ||
this.ExpenditureTheme != null &&
this.ExpenditureTheme.Equals(other.ExpenditureTheme)
) &&
(
this.SupplyAndDemandTheme == other.SupplyAndDemandTheme ||
this.SupplyAndDemandTheme != null &&
this.SupplyAndDemandTheme.Equals(other.SupplyAndDemandTheme)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.PopulationTheme != null)
hash = hash * 59 + this.PopulationTheme.GetHashCode();
if (this.RaceAndEthnicityTheme != null)
hash = hash * 59 + this.RaceAndEthnicityTheme.GetHashCode();
if (this.HealthTheme != null)
hash = hash * 59 + this.HealthTheme.GetHashCode();
if (this.EducationTheme != null)
hash = hash * 59 + this.EducationTheme.GetHashCode();
if (this.IncomeTheme != null)
hash = hash * 59 + this.IncomeTheme.GetHashCode();
if (this.AssetsAndWealthTheme != null)
hash = hash * 59 + this.AssetsAndWealthTheme.GetHashCode();
if (this.HouseholdsTheme != null)
hash = hash * 59 + this.HouseholdsTheme.GetHashCode();
if (this.HousingTheme != null)
hash = hash * 59 + this.HousingTheme.GetHashCode();
if (this.EmploymentTheme != null)
hash = hash * 59 + this.EmploymentTheme.GetHashCode();
if (this.ExpenditureTheme != null)
hash = hash * 59 + this.ExpenditureTheme.GetHashCode();
if (this.SupplyAndDemandTheme != null)
hash = hash * 59 + this.SupplyAndDemandTheme.GetHashCode();
return hash;
}
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
//Clipper library for boolean operations of the polygons: http://sourceforge.net/projects/polyclipping/?source=navbar
using ClipperLib;
using INTPolygon = System.Collections.Generic.List<ClipperLib.IntPoint>;
using INTPolygons = System.Collections.Generic.List<System.Collections.Generic.List<ClipperLib.IntPoint>>;
using SpatialAnalysis;
using System.Windows;
using SpatialAnalysis.Geometry;
using System.Windows.Media.Media3D;
using SpatialAnalysis.Miscellaneous;
namespace SpatialAnalysis.Interoperability
{
/// <summary>
/// This class provides a list of public members and functions that should be implemented to read BIM data according to its format.
/// This class uses Clipper Library for polygonal boolean operations. This library represents polygons with a list of integer points.
/// </summary>
public abstract class BIM_To_OSM_Base
{
protected Length_Unit_Types unitType;
/// <summary>
/// Gets the unit of length for OSM
/// </summary>
public Length_Unit_Types UnitType
{
get { return unitType; }
}
/// <summary>
/// Gets or sets the length of line segments to approximate curves with polygons
/// </summary>
/// <value>The length of the curve approximation.</value>
public double CurveApproximationLength { get; set; }
private int _polygonalBooleanPrecision;
//PolygonalBooleanPrecision
/// <summary>
/// Gets or sets an integer used to determine decimals of the polygonal boolean precision.
/// </summary>
/// <value>The polygonal boolean precision.</value>
/// <exception cref="ArgumentException">The number of digits cannot be larger than 8.</exception>
protected int PolygonalBooleanPrecision
{
get { return _polygonalBooleanPrecision; }
set
{
if (value > 9)
{
throw new ArgumentException("The number of digits cannot be larger than 8.");
}
this._polygonalBooleanPrecision = value;
}
}
/// <summary>
/// Gets or sets the footprint integer polygons of visual barriers.
/// </summary>
/// <value>The foot print integer polygons of visual barriers.</value>
public INTPolygons FootPrintPolygonsOfVisualBarriers { get; set; }
/// <summary>
/// Gets or sets the footprint integer polygons of physical barriers.
/// </summary>
/// <value>The footprint integer polygons of physical barriers.</value>
public INTPolygons FootPrintPolygonsOfPhysicalBarriers { get; set; }
/// <summary>
/// Gets or sets the footprint integer polygons of field with voids.
/// </summary>
/// <value>The footprint integer polygons of field with voids.</value>
public INTPolygons FootPrintPolygonsOfFieldWithVoids { get; set; }
/// <summary>
/// Gets or sets the footprint integer polygons of field without voids.
/// </summary>
/// <value>The footprint integer polygons of field with out voids.</value>
public INTPolygons FootPrintPolygonsOfFieldWithOutVoids { get; set; }
// holes, visual and physical
/// <summary>
/// Gets or sets the footprint integer polygons of all barriers.
/// </summary>
/// <value>The footprint integer polygons of all barriers.</value>
public INTPolygons FootPrintOfAllBarriers { get; set; }
/// <summary>
/// The number of purged points
/// </summary>
protected int PurgedPoints = 0;
/// <summary>
/// The minimum length of lines in the polygons
/// </summary>
public double MinimumLengthOfLine;
/// <summary>
/// Gets or sets the physical barriers.
/// </summary>
/// <value>The physical barriers.</value>
public BarrierPolygon[] PhysicalBarriers { get; set; }
/// <summary>
/// Gets or sets the visual barriers.
/// </summary>
/// <value>The visual barriers.</value>
public BarrierPolygon[] VisualBarriers { get; set; }
/// <summary>
/// Gets or sets the field barriers.
/// </summary>
/// <value>The field barriers.</value>
public BarrierPolygon[] FieldBarriers { get; set; }
/// <summary>
/// Gets or sets the field without holes.
/// </summary>
/// <value>The field without holes.</value>
public BarrierPolygon[] FieldWithoutHoles { get; set; }
/// <summary>
/// The floor minimum bound
/// </summary>
public UV FloorMinBound;
/// <summary>
/// The floor maximum bound
/// </summary>
public UV FloorMaxBound;
/// <summary>
/// Gets or sets the height of the obstacle. Objects with higher heights will be considered visual barriers and lower heights will be considered physical barriers.
/// </summary>
/// <value>The height of the obstacle.</value>
public double VisibilityObstacleHeight { get; set; }//VisualObstacleHeight
/// <summary>
/// Gets or sets the report which are generated during the data format exchange.
/// </summary>
/// <value>The report.</value>
public string Report { get; set; }
/// <summary>
/// Gets or sets the minimum line length squared.
/// </summary>
/// <value>The minimum line length squared.</value>
public double MinimumLineLengthSquared { get; set; }
/// <summary>
/// Gets or sets the elevation.
/// </summary>
/// <value>The elevation.</value>
public double PlanElevation { get; set; }
/// <summary>
/// Gets or sets the plan name of the BIM model.
/// </summary>
/// <value>The plan name.</value>
public string PlanName { get; set; }
/// <summary>
/// Simplifies an list INTPolygons using expand and shrink technique.
/// </summary>
/// <param name="polygons">The INTPolygons.</param>
/// <param name="value">The value used for expand and shrink.</param>
/// <returns>INTPolygons.</returns>
public INTPolygons SimplifyINTPolygons(INTPolygons polygons, double value)
{
double simplificationFactor = Math.Pow(10.0, this.PolygonalBooleanPrecision) * UnitConversion.Convert(value, Length_Unit_Types.FEET, UnitType);
ClipperOffset clipperOffset = new ClipperOffset();
clipperOffset.AddPaths(polygons, ClipperLib.JoinType.jtMiter, EndType.etClosedPolygon);
INTPolygons shrink = new INTPolygons();
clipperOffset.Execute(ref shrink, -simplificationFactor);
//expanding to return the polygons to their original position
clipperOffset.Clear();
clipperOffset.AddPaths(shrink, ClipperLib.JoinType.jtMiter, EndType.etClosedPolygon);
INTPolygons expand = new INTPolygons();
clipperOffset.Execute(ref expand, simplificationFactor);
shrink = null;
clipperOffset = null;
return expand;
}
/// <summary>
/// Gets the BIM Model as a list of meshes to which the materials are attached. The parsed model should be sliced with A plane at obstacle height. Implementation is required for this abstract method.
/// </summary>
/// <param name="min">The lover left corner of the territory.</param>
/// <param name="Max">The upper right corner of the territory.</param>
/// <param name="offset">The offset value of the bounding box.</param>
/// <returns>List<GeometryModel3D> which will be used for data visualization.</returns>
public abstract List<object> GetSlicedMeshGeometries(UV min, UV Max, double offset);
/// <summary>
/// /// Gets the BIM Model as a list of meshes to which the materials are attached. Implementation is required for this abstract method.
/// </summary>
/// <param name="min">The lover left corner of the territory.</param>
/// <param name="Max">The upper right corner of the territory.</param>
/// <param name="offset">The offset value of the bounding box.</param>
/// <returns>List<GeometryModel3D>.</returns>
public abstract List<object> ParseBIM(UV min, UV Max, double offset);
/// <summary>
/// Converts a list of UV points to a list of IntPoints (i.e. an INTPolygon) which can be used for polygonal operations.
/// </summary>
/// <param name="UVs">The list of UV points.</param>
/// <returns>INTPolygon.</returns>
public INTPolygon ConvertUVListToINTPolygon(List<UV> UVs)
{
INTPolygon contour = new INTPolygon();
for (int i = 0; i < UVs.Count; i++)
{
contour.Add(ConvertUVToIntPoint(UVs[i]));
}
return contour;
}
/// <summary>
/// Converts a UV to an IntPoint.
/// </summary>
/// <param name="uv">The uv.</param>
/// <returns>IntPoint.</returns>
/// <exception cref="ArgumentException"></exception>
public IntPoint ConvertUVToIntPoint(UV uv)
{
IntPoint pnt = new IntPoint();
try
{
long x = Convert.ToInt64(Math.Floor(uv.U * Math.Pow(10, this.PolygonalBooleanPrecision)));
long y = Convert.ToInt64(Math.Floor(uv.V * Math.Pow(10, this.PolygonalBooleanPrecision)));
pnt = new IntPoint(x, y);
}
catch (Exception e)
{
throw new ArgumentException(e.Report());
}
return pnt;
}
/// <summary>
/// Converts the IntPoint to a UV.
/// </summary>
/// <param name="pnt">The IntPoint.</param>
/// <returns>UV.</returns>
public UV ConvertIntPointToUV(IntPoint pnt)
{
double x = Convert.ToDouble(pnt.X) / Math.Pow(10, this.PolygonalBooleanPrecision);
double y = Convert.ToDouble(pnt.Y) / Math.Pow(10, this.PolygonalBooleanPrecision);
UV xy = new UV(x, y);
return xy;
}
/// <summary>
/// Converts the INTPolygon to BarrierPolygons.
/// </summary>
/// <param name="ply">The ply.</param>
/// <returns>BarrierPolygons.</returns>
public BarrierPolygon ConvertINTPolygonToBarrierPolygon(INTPolygon ply)
{
List<UV> pnts = new List<UV>();
for (int i = 0; i < ply.Count; i++)
{
pnts.Add(ConvertIntPointToUV(ply[i]));
}
pnts = SimplifyPolygon(pnts);
return new BarrierPolygon(pnts.ToArray());
}
/// <summary>
/// Simplifies the polygon.
/// </summary>
/// <param name="uvs">A list of uv points.</param>
/// <param name="proportionOfMinimumLengthOfLine">The proportion of minimum length of line parameter by default set to 3.</param>
/// <param name="angle">The angle by default set to zero.</param>
/// <returns>List<UV>.</returns>
public List<UV> SimplifyPolygon(List<UV> uvs, UInt16 proportionOfMinimumLengthOfLine = 3, double angle = 0.0d)
{
SpatialAnalysis.Geometry.PLine pln = new PLine(uvs, true);
return pln.Simplify(this.MinimumLengthOfLine / proportionOfMinimumLengthOfLine);
}
/// <summary>
/// Returns an array of barriers that is used for autonomous walking scenarios
/// </summary>
/// <param name="offsetValue">Human body size which is the distance that you want the agents from barriers</param>
/// <returns>Expanded version of all barrier polygons including field naked edges and holes, visual barriers and physical barriers </returns>
public BarrierPolygon[] ExpandAllBarrierPolygons(double offsetValue)
{
ClipperOffset clipperOffset = new ClipperOffset();
//clipperOffset.AddPaths(this.FootPrintOfAllBarriers, JoinType.jtSquare, EndType.etClosedPolygon);
clipperOffset.AddPaths(this.FootPrintPolygonsOfFieldWithVoids, JoinType.jtSquare, EndType.etClosedPolygon);
INTPolygons plygns = new INTPolygons();
double uniqueOffsetValue = -Math.Pow(10.0, this.PolygonalBooleanPrecision) * offsetValue;
clipperOffset.Execute(ref plygns, uniqueOffsetValue);
List<BarrierPolygon> brrs = new List<BarrierPolygon>();
for (int i = 0; i < plygns.Count; i++)
{
BarrierPolygon brr = this.ConvertINTPolygonToBarrierPolygon(plygns[i]);
if (brr.Length > 0)
{
brrs.Add(brr);
}
}
clipperOffset.Clear();
plygns.Clear();
return brrs.ToArray();
}
/// <summary>
/// Sets the territory.
/// </summary>
protected void setTerritory()
{
double xMin = double.PositiveInfinity, xMax = double.NegativeInfinity, yMin = double.PositiveInfinity, yMax = double.NegativeInfinity;
foreach (BarrierPolygon item in this.VisualBarriers)
{
foreach (UV p in item.BoundaryPoints)
{
xMin = (p.U < xMin) ? p.U : xMin;
xMax = (p.U > xMax) ? p.U : xMax;
yMin = (p.V < yMin) ? p.V : yMin;
yMax = (p.V > yMax) ? p.V : yMax;
}
}
foreach (BarrierPolygon item in this.FieldBarriers)
{
foreach (UV p in item.BoundaryPoints)
{
xMin = (p.U < xMin) ? p.U : xMin;
xMax = (p.U > xMax) ? p.U : xMax;
yMin = (p.V < yMin) ? p.V : yMin;
yMax = (p.V > yMax) ? p.V : yMax;
}
}
this.FloorMinBound = new UV(xMin, yMin);
this.FloorMaxBound = new UV(xMax, yMax);
}
#region Polygonal Isovist Claculation
private INTPolygon createCircle(UV center, double r)
{
int n = (int)(Math.PI * 2 * r / this.CurveApproximationLength) + 1;
INTPolygon circle = new INTPolygon();
for (int i = 0; i < n; i++)
{
UV direction = new UV(r * Math.Cos(i * Math.PI * 2 / n), r * Math.Sin(i * Math.PI * 2 / n));
circle.Add(ConvertUVToIntPoint(direction + center));
}
return circle;
}
private INTPolygon excludedArea(UV center, double r, UVLine edge)
{
INTPolygon area = new INTPolygon();
double ds = edge.Start.DistanceTo(center);
double de = edge.End.DistanceTo(center);
r = (r > ds) ? r : ds;
r = (r > de) ? r : de;
double R = 1.43 * r; // somthing larger than Math.Sqrt(2)*r
UV os = edge.Start - center;
os.Unitize();
UV oe = edge.End - center;
oe.Unitize();
List<UV> pnts = new List<UV>();
double x = oe.DotProduct(os);
if (x == 0)
{
return area;
}
else if (x >= 0)
{
pnts.Add(edge.Start);
pnts.Add(center + os * R);
pnts.Add(center + oe * R);
pnts.Add(edge.End);
}
else // if (x<0)
{
UV om = (os + oe) / 2;
om.Unitize();
pnts.Add(edge.Start);
pnts.Add(center + os * R);
pnts.Add(center + om * R);
pnts.Add(center + oe * R);
pnts.Add(edge.End);
}
return this.ConvertUVListToINTPolygon(pnts);
}
/// <summary>
/// Gets the Isovist polygon.
/// </summary>
/// <param name="vantagePoint">The vantage point.</param>
/// <param name="viewDepth">The view depth.</param>
/// <param name="edges">The edges.</param>
/// <returns>BarrierPolygons.</returns>
public BarrierPolygon IsovistPolygon(UV vantagePoint, double viewDepth, HashSet<UVLine> edges)
{
/*first and expand and shrink operation is performed to merge the shadowing edges*/
double expandShrinkFactor = Math.Pow(10.0, this.PolygonalBooleanPrecision) * UnitConversion.Convert(0.075, Length_Unit_Types.FEET, UnitType);
//offsetting the excluded area of each edge
INTPolygons offsetedPolygons = new INTPolygons();
ClipperOffset clipperOffset = new ClipperOffset();
foreach (UVLine edgeItem in edges)
{
clipperOffset.AddPath(this.excludedArea(vantagePoint, viewDepth + 1, edgeItem), ClipperLib.JoinType.jtMiter, EndType.etClosedPolygon);
INTPolygons plygns = new INTPolygons();
clipperOffset.Execute(ref plygns, expandShrinkFactor);
offsetedPolygons.AddRange(plygns);
clipperOffset.Clear();
}
//Unioning the expanded exclusions
INTPolygons offsetUnioned = new INTPolygons();
Clipper c = new Clipper();
c.AddPaths(offsetedPolygons, PolyType.ptSubject, true);
c.Execute(ClipType.ctUnion, offsetUnioned, PolyFillType.pftNonZero, PolyFillType.pftNonZero);
//shrink the polygons to retain their original size
INTPolygons results = new INTPolygons();
clipperOffset.Clear();
clipperOffset.AddPaths(offsetUnioned, JoinType.jtMiter, EndType.etClosedPolygon);
clipperOffset.Execute(ref results, -expandShrinkFactor);
clipperOffset.Clear();
offsetUnioned.Clear();
/*
* What ever is a hole in the resulting mereged polygon is the visibility polygon
* Now we classify the polygons based on being a hole or not
*/
//filtering out the holes that do not include the center
INTPolygons holesNOT = new INTPolygons();
INTPolygons holesIncludingCenter = new INTPolygons();
IntPoint iCenter = ConvertUVToIntPoint(vantagePoint);
foreach (INTPolygon item in results)
{
if (!Clipper.Orientation(item))
{
if (Clipper.PointInPolygon(iCenter, item) == 1)
{
holesIncludingCenter.Add(item);
}
}
else
{
holesNOT.Add(item);
}
}
if (holesIncludingCenter.Count == 0)
{
//there is no hole. The shadow polygones should clip the potential field of visibility (i.e. circle) by an subtraction operation
INTPolygon circle = createCircle(vantagePoint, viewDepth);
//subtraction
c.Clear();
c.AddPath(circle, PolyType.ptSubject, true);
c.AddPaths(holesNOT, PolyType.ptClip, true);
INTPolygons isovistPolygon = new INTPolygons();
c.Execute(ClipType.ctDifference, isovistPolygon);
//searching for a polygon that includes the center
foreach (INTPolygon item in isovistPolygon)
{
if (Clipper.PointInPolygon(iCenter, item) == 1)
{
BarrierPolygon isovist = this.ConvertINTPolygonToBarrierPolygon(item);
results = null;
c = null;
clipperOffset = null;
offsetedPolygons = null;
circle = null;
holesNOT = null;
holesIncludingCenter = null;
isovistPolygon = null;
return isovist;
}
}
MessageBox.Show(string.Format("Isovist not found!\nNo hole detected\n{0} polygons can be isovist", isovistPolygon.Count.ToString()));
}
else if (holesIncludingCenter.Count == 1)
{
INTPolygons isovistPolygon = holesIncludingCenter;
foreach (INTPolygon item in isovistPolygon)
{
if (Clipper.PointInPolygon(iCenter, item) == 1)
{
item.Reverse();
BarrierPolygon isovist = this.ConvertINTPolygonToBarrierPolygon(item);
results = null;
c = null;
clipperOffset = null;
offsetedPolygons = null;
holesNOT = null;
holesIncludingCenter = null;
isovistPolygon = null;
return isovist;
}
}
MessageBox.Show(string.Format("Isovist not found!\nOne hole detected\n{0} polygons can be isovist", isovistPolygon.Count.ToString()));
}
else if (holesIncludingCenter.Count > 1)
{
MessageBox.Show("Isovist not found!\nMore than one hole found that can include the vantage point");
}
return null;
}
#endregion
}
}
| |
namespace WindowsApplication2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.Label idLabel;
System.Windows.Forms.Label nameLabel;
this.idTextBox = new System.Windows.Forms.TextBox();
this.nameTextBox = new System.Windows.Forms.TextBox();
this.childrenBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.childrenDataGridView = new System.Windows.Forms.DataGridView();
this.grandchildrenBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.grandchildrenDataGridView = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.rootBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
idLabel = new System.Windows.Forms.Label();
nameLabel = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.childrenBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.childrenDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grandchildrenBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grandchildrenDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rootBindingSource)).BeginInit();
this.SuspendLayout();
//
// idLabel
//
idLabel.AutoSize = true;
idLabel.Location = new System.Drawing.Point(12, 21);
idLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
idLabel.Name = "idLabel";
idLabel.Size = new System.Drawing.Size(36, 26);
idLabel.TabIndex = 1;
idLabel.Text = "Id:";
//
// nameLabel
//
nameLabel.AutoSize = true;
nameLabel.Location = new System.Drawing.Point(12, 71);
nameLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
nameLabel.Name = "nameLabel";
nameLabel.Size = new System.Drawing.Size(77, 26);
nameLabel.TabIndex = 3;
nameLabel.Text = "Name:";
//
// idTextBox
//
this.idTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.rootBindingSource, "Id", true));
this.idTextBox.Location = new System.Drawing.Point(100, 15);
this.idTextBox.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.idTextBox.Name = "idTextBox";
this.idTextBox.Size = new System.Drawing.Size(196, 32);
this.idTextBox.TabIndex = 2;
//
// nameTextBox
//
this.nameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.rootBindingSource, "Name", true));
this.nameTextBox.Location = new System.Drawing.Point(100, 65);
this.nameTextBox.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Size = new System.Drawing.Size(196, 32);
this.nameTextBox.TabIndex = 4;
//
// childrenBindingSource
//
this.childrenBindingSource.DataMember = "Children";
this.childrenBindingSource.DataSource = this.rootBindingSource;
//
// childrenDataGridView
//
this.childrenDataGridView.AutoGenerateColumns = false;
this.childrenDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.childrenDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.childrenDataGridView.ColumnHeadersHeight = 32;
this.childrenDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewTextBoxColumn1,
this.dataGridViewTextBoxColumn2});
this.childrenDataGridView.DataSource = this.childrenBindingSource;
this.childrenDataGridView.Location = new System.Drawing.Point(18, 138);
this.childrenDataGridView.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.childrenDataGridView.Name = "childrenDataGridView";
this.childrenDataGridView.RowTemplate.Height = 32;
this.childrenDataGridView.Size = new System.Drawing.Size(409, 254);
this.childrenDataGridView.TabIndex = 5;
//
// grandchildrenBindingSource
//
this.grandchildrenBindingSource.DataMember = "Grandchildren";
this.grandchildrenBindingSource.DataSource = this.childrenBindingSource;
//
// grandchildrenDataGridView
//
this.grandchildrenDataGridView.AutoGenerateColumns = false;
this.grandchildrenDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.grandchildrenDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.grandchildrenDataGridView.ColumnHeadersHeight = 32;
this.grandchildrenDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewTextBoxColumn3,
this.dataGridViewTextBoxColumn4});
this.grandchildrenDataGridView.DataSource = this.grandchildrenBindingSource;
this.grandchildrenDataGridView.Location = new System.Drawing.Point(17, 404);
this.grandchildrenDataGridView.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.grandchildrenDataGridView.Name = "grandchildrenDataGridView";
this.grandchildrenDataGridView.RowTemplate.Height = 32;
this.grandchildrenDataGridView.Size = new System.Drawing.Size(410, 254);
this.grandchildrenDataGridView.TabIndex = 6;
//
// button1
//
this.button1.Location = new System.Drawing.Point(636, 15);
this.button1.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(150, 44);
this.button1.TabIndex = 7;
this.button1.Text = "Apply";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ApplyButton_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(636, 65);
this.button2.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(150, 44);
this.button2.TabIndex = 8;
this.button2.Text = "Cancel";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.CancelButton_Click);
//
// dataGridViewTextBoxColumn3
//
this.dataGridViewTextBoxColumn3.DataPropertyName = "Id";
this.dataGridViewTextBoxColumn3.HeaderText = "Id";
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
this.dataGridViewTextBoxColumn3.Width = 55;
//
// dataGridViewTextBoxColumn4
//
this.dataGridViewTextBoxColumn4.DataPropertyName = "Name";
this.dataGridViewTextBoxColumn4.HeaderText = "Name";
this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
this.dataGridViewTextBoxColumn4.Width = 96;
//
// rootBindingSource
//
this.rootBindingSource.DataSource = typeof(WindowsApplication2.Root);
//
// dataGridViewTextBoxColumn1
//
this.dataGridViewTextBoxColumn1.DataPropertyName = "Id";
this.dataGridViewTextBoxColumn1.HeaderText = "Id";
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
this.dataGridViewTextBoxColumn1.Width = 55;
//
// dataGridViewTextBoxColumn2
//
this.dataGridViewTextBoxColumn2.DataPropertyName = "Name";
this.dataGridViewTextBoxColumn2.HeaderText = "Name";
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
this.dataGridViewTextBoxColumn2.Width = 96;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1424, 864);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.grandchildrenDataGridView);
this.Controls.Add(this.childrenDataGridView);
this.Controls.Add(idLabel);
this.Controls.Add(this.idTextBox);
this.Controls.Add(nameLabel);
this.Controls.Add(this.nameTextBox);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.childrenBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.childrenDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grandchildrenBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grandchildrenDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rootBindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.BindingSource rootBindingSource;
private System.Windows.Forms.TextBox idTextBox;
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.BindingSource childrenBindingSource;
private System.Windows.Forms.DataGridView childrenDataGridView;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.BindingSource grandchildrenBindingSource;
private System.Windows.Forms.DataGridView grandchildrenDataGridView;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Security.Permissions;
using System.Windows.Forms;
using XenAdmin.Controls;
using XenAdmin.Core;
using Message = System.Windows.Forms.Message;
using System.Runtime.InteropServices;
namespace XenAdmin.Controls
{
public partial class SnapshotTreeView : ListView
{
private const int straightLineLength = 8;
private SnapshotIcon root;
//We need this fake thing to make the scrollbars work with the customdrawdate.
private ListViewItem whiteIcon = new ListViewItem();
private Color linkLineColor = SystemColors.ControlDark;
private float linkLineWidth = 2.0f;
private int hGap = 50;
private int vGap = 20;
private readonly CustomLineCap linkLineArrow = new AdjustableArrowCap(4f, 4f, true);
#region Properties
[Browsable(true), Category("Appearance"), Description("Color used to draw connecting lines")]
[DefaultValue(typeof(Color), "ControlDark")]
public Color LinkLineColor
{
get { return linkLineColor; }
set
{
linkLineColor = value;
Invalidate();
}
}
[Browsable(true), Category("Appearance"), Description("Width of connecting lines")]
[DefaultValue(2.0f)]
public float LinkLineWidth
{
get { return linkLineWidth; }
set
{
linkLineWidth = value;
Invalidate();
}
}
[Browsable(true), Category("Appearance"), Description("Horizontal gap between icons")]
[DefaultValue(50)]
public int HGap
{
get { return hGap; }
set
{
if (value < 4 * straightLineLength)
value = 4 * straightLineLength;
hGap = value;
PerformLayout(this, "HGap");
}
}
[Browsable(true), Category("Appearance"), Description("Vertical gap between icons")]
[DefaultValue(20)]
public int VGap
{
get { return vGap; }
set
{
if (value < 0)
value = 0;
vGap = value;
PerformLayout(this, "VGap");
}
}
#endregion
private ImageList imageList = new ImageList();
public SnapshotTreeView(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
container.Add(this);
InitializeComponent();
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
base.Items.Add(whiteIcon);
//Init image list
imageList.ColorDepth = ColorDepth.Depth32Bit;
imageList.ImageSize=new Size(32,32);
imageList.Images.Add(Properties.Resources._000_HighLightVM_h32bit_32);
imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32);
imageList.Images.Add(Properties.Resources.VMTemplate_h32bit_32);
imageList.Images.Add(Properties.Resources._000_VMSnapShotDiskOnly_h32bit_32);
imageList.Images.Add(Properties.Resources._000_VMSnapshotDiskMemory_h32bit_32);
imageList.Images.Add(Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_32);
imageList.Images.Add(Properties.Resources._000_ScheduledVMSnapshotDiskMemory_h32bit_32);
imageList.Images.Add(Properties.Resources.SpinningFrame0);
imageList.Images.Add(Properties.Resources.SpinningFrame1);
imageList.Images.Add(Properties.Resources.SpinningFrame2);
imageList.Images.Add(Properties.Resources.SpinningFrame3);
imageList.Images.Add(Properties.Resources.SpinningFrame4);
imageList.Images.Add(Properties.Resources.SpinningFrame5);
imageList.Images.Add(Properties.Resources.SpinningFrame6);
imageList.Images.Add(Properties.Resources.SpinningFrame7);
this.LargeImageList = imageList;
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters",
MessageId = "System.InvalidOperationException.#ctor(System.String)",
Justification = "Indicates a programming error - not user facing")]
internal ListViewItem AddSnapshot(SnapshotIcon snapshot)
{
if (snapshot == null)
throw new ArgumentNullException("snapshot");
if (snapshot.Parent != null)
{
snapshot.Parent.AddChild(snapshot);
snapshot.Parent.Invalidate();
}
else if (root != null)
{
throw new InvalidOperationException("Adding a new root!");
}
else
{
root = snapshot;
}
if (snapshot.ImageIndex == SnapshotIcon.VMImageIndex)
{
//Sort all the parents of the VM to make the path to the VM the first one.
SnapshotIcon current = snapshot;
while (current.Parent != null)
{
if (current.Parent.Children.Count > 1)
{
int indexCurrent = current.Parent.Children.IndexOf(current);
SnapshotIcon temp = current.Parent.Children[0];
current.Parent.Children[0] = current;
current.Parent.Children[indexCurrent] = temp;
}
current.IsInVMBranch = true;
current = current.Parent;
}
}
ListViewItem item = Items.Add(snapshot);
if (Items.Count == 1)
Items.Add(whiteIcon);
return item;
}
public new void Clear()
{
base.Clear();
RemoveSnapshot(root);
}
internal void RemoveSnapshot(SnapshotIcon snapshot)
{
if (snapshot != null && snapshot.Parent != null)
{
IList<SnapshotIcon> siblings = snapshot.Parent.Children;
int pos = siblings.IndexOf(snapshot);
siblings.Remove(snapshot);
// add our children in our place
foreach (SnapshotIcon child in snapshot.Children)
{
siblings.Insert(pos++, child);
child.Parent = snapshot.Parent;
}
snapshot.Parent.Invalidate();
snapshot.Parent = null;
}
else
{
root = null;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (SelectedItems.Count == 1)
{
SnapshotIcon item = SelectedItems[0] as SnapshotIcon;
if (item != null && !item.Selectable)
{
item.Selected = false;
item.Focused = false;
}
}
else if (this.SelectedItems.Count > 1)
{
foreach (ListViewItem item in SelectedItems)
{
SnapshotIcon snapItem = item as SnapshotIcon;
if (snapItem != null && !snapItem.Selectable)
{
item.Selected = false;
item.Focused = false;
}
}
}
base.OnSelectedIndexChanged(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
ListViewItem item = this.HitTest(e.X, e.Y).Item;
if (item == null)
{
ListViewItem item2 = this.HitTest(e.X, e.Y - 23).Item;
if (item2 != null)
{
item2.Selected = true;
item2.Focused = true;
}
else
{
base.OnMouseUp(new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y - 23, e.Delta));
return;
}
}
base.OnMouseUp(e);
}
#region Layout
protected override void OnLayout(LayoutEventArgs levent)
{
if (root != null && this.Parent != null)
{
//This is needed to maximize and minimize properly, there is some issue in the ListView Control
Win32.POINT pt = new Win32.POINT();
IntPtr hResult = SendMessage(Handle, LVM_GETORIGIN, IntPtr.Zero, ref pt);
origin = pt;
root.InvalidateAll();
int x = Math.Max(this.HGap, this.Size.Width / 2 - root.SubtreeWidth / 2);
int y = Math.Max(this.VGap, this.Size.Height / 2 - root.SubtreeHeight / 2);
PositionSnapshots(root, x, y);
Invalidate();
whiteIcon.Position = new Point(x + origin.X, y + root.SubtreeHeight - 20 + origin.Y);
}
}
protected override void OnParentChanged(EventArgs e)
{
//We need to cancel the parent changes when we change to the other view
}
private void PositionSnapshots(SnapshotIcon icon, int x, int y)
{
try
{
Size iconSize = icon.DefaultSize;
Point newPoint = new Point(x, y + icon.CentreHeight - iconSize.Height / 2);
icon.Position = new Point(newPoint.X + origin.X, newPoint.Y + origin.Y);
x += iconSize.Width + HGap;
for (int i = 0; i < icon.Children.Count; i++)
{
SnapshotIcon child = icon.Children[i];
PositionSnapshots(child, x, y);
y += child.SubtreeHeight;
}
}
catch (Exception)
{
// Debugger.Break();
}
}
public const int LVM_GETORIGIN = 0x1000 + 41;
private Win32.POINT origin = new Win32.POINT();
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref Win32.POINT pt);
public override Size GetPreferredSize(Size proposedSize)
{
if (root == null && Parent != null)
{
return DefaultSize;
}
return new Size(root.SubtreeWidth, root.SubtreeHeight);
}
#endregion
#region Drawing
private bool m_empty = false;
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
const int WM_HSCROLL = 0x0114;
const int WM_VSCROLL = 0x0115;
const int WM_MOUSEWHEEL = 0x020A;
const int WM_PAINT = 0x000F;
base.WndProc(ref m);
if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL || (m.Msg == WM_MOUSEWHEEL && (IsVerticalScrollBarVisible(this) || IsHorizontalScrollBarVisible(this))))
{
Invalidate();
}
if (m.Msg == WM_PAINT)
{
Graphics gg = CreateGraphics();
if (this.Items.Count == 0)
{
m_empty = true;
Graphics g = CreateGraphics();
string text = Messages.SNAPSHOTS_EMPTY;
SizeF proposedSize = g.MeasureString(text, Font, 275);
float x = this.Width / 2 - proposedSize.Width / 2;
float y = this.Height / 2 - proposedSize.Height / 2;
RectangleF rect = new RectangleF(x, y, proposedSize.Width, proposedSize.Height);
using (var brush = new SolidBrush(BackColor))
g.FillRectangle(brush, rect);
g.DrawString(text, Font, Brushes.Black, rect);
}
}
else if (m_empty && this.Items.Count > 0)
{
m_empty = false;
this.Invalidate();
}
}
private const int WS_HSCROLL = 0x100000;
private const int WS_VSCROLL = 0x200000;
private const int GWL_STYLE = (-16);
[System.Runtime.InteropServices.DllImport("user32",
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int GetWindowLong(IntPtr hwnd, int nIndex);
internal static bool IsVerticalScrollBarVisible(Control ctrl)
{
if (!ctrl.IsHandleCreated)
return false;
return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_VSCROLL) != 0;
}
internal static bool IsHorizontalScrollBarVisible(Control ctrl)
{
if (!ctrl.IsHandleCreated)
return false;
return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_HSCROLL) != 0;
}
private void SnapshotTreeView_DrawItem(object sender, DrawListViewItemEventArgs e)
{
if (this.Parent != null)
{
e.DrawDefault = true;
SnapshotIcon icon = e.Item as SnapshotIcon;
if (icon == null)
return;
DrawDate(e, icon, false);
if (icon.Parent != null)
PaintLine(e.Graphics, icon.Parent, icon, icon.IsInVMBranch);
for (int i = 0; i < icon.Children.Count; i++)
{
SnapshotIcon child = icon.Children[i];
PaintLine(e.Graphics, icon, child, child.IsInVMBranch);
}
}
}
public void DrawRoundRect(Graphics g, Brush b, float x, float y, float width, float height, float radius)
{
GraphicsPath gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line
gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner
gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line
gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner
gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line
gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner
gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure();
g.FillPath(b, gp);
}
private void DrawDate(DrawListViewItemEventArgs e, SnapshotIcon icon, bool background)
{
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
//Time
int timeX = e.Bounds.X;
int timeY = e.Bounds.Y + e.Bounds.Height;
Size proposedSizeName = new Size(e.Bounds.Width,
Int32.MaxValue);
Size timeSize = TextRenderer.MeasureText(e.Graphics, icon.LabelCreationTime,
new Font(this.Font.FontFamily, this.Font.Size - 1), proposedSizeName, TextFormatFlags.WordBreak);
timeSize = new Size(e.Bounds.Width, timeSize.Height);
Rectangle timeRect = new Rectangle(new Point(timeX, timeY), timeSize);
if (background)
{
e.Graphics.FillRectangle(Brushes.GreenYellow, timeRect);
}
e.Graphics.DrawString(icon.LabelCreationTime, new Font(this.Font.FontFamily, this.Font.Size - 1), Brushes.Black, timeRect, stringFormat);
}
private void PaintLine(Graphics g, SnapshotIcon icon, SnapshotIcon child, bool highlight)
{
if (child.Index == -1)
return;
try
{
Rectangle leftItemBounds = icon.GetBounds(ItemBoundsPortion.Entire);
Rectangle rightItemBounds = child.GetBounds(ItemBoundsPortion.Entire);
leftItemBounds.Size = icon.DefaultSize;
rightItemBounds.Size = child.DefaultSize;
int left = leftItemBounds.Right + 6;
int right = rightItemBounds.Left;
int mid = (left + right) / 2;
Point start = new Point(left, (leftItemBounds.Bottom + leftItemBounds.Top) / 2);
Point end = new Point(right, (rightItemBounds.Top + rightItemBounds.Bottom) / 2);
Point curveStart = start;
curveStart.Offset(straightLineLength, 0);
Point curveEnd = end;
curveEnd.Offset(-straightLineLength, 0);
Point control1 = new Point(mid + straightLineLength, start.Y);
Point control2 = new Point(mid - straightLineLength, end.Y);
Color lineColor = LinkLineColor;
float lineWidth = LinkLineWidth;
if (highlight)
{
lineColor = Color.ForestGreen;
lineWidth = 2.5f;
}
using (Pen p = new Pen(lineColor, lineWidth))
{
p.SetLineCap(LineCap.Round, LineCap.Custom, DashCap.Flat);
p.CustomEndCap = linkLineArrow;
g.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath path = new GraphicsPath();
path.AddLine(start, curveStart);
path.AddBezier(curveStart, control1, control2, curveEnd);
path.AddLine(curveEnd, end);
g.DrawPath(p, path);
}
}
catch (Exception)
{
//Debugger.Break();
}
}
#endregion
private string _spinningMessage = "";
public string SpinningMessage { get { return _spinningMessage; } }
internal void ChangeVMToSpinning(bool p, string message)
{
_spinningMessage = message;
foreach (var item in Items)
{
SnapshotIcon snapshotIcon = item as SnapshotIcon;
if (snapshotIcon != null && (snapshotIcon.ImageIndex == SnapshotIcon.VMImageIndex || snapshotIcon.ImageIndex > SnapshotIcon.UnknownImage))
{
if (string.IsNullOrEmpty(message))
{
snapshotIcon.ChangeSpinningIcon(p, _spinningMessage);
}
else
{
snapshotIcon.ChangeSpinningIcon(p, _spinningMessage);
}
return;
}
}
}
}
internal class SnapshotIcon : ListViewItem
{
public const int VMImageIndex = 0;
public const int Template = 1;
public const int CustomTemplate = 2;
public const int DiskSnapshot = 3;
public const int DiskAndMemorySnapshot = 4;
public const int ScheduledDiskSnapshot = 5;
public const int ScheduledDiskMemorySnapshot = 6;
public const int UnknownImage = 6;
private SnapshotIcon parent;
private readonly SnapshotTreeView treeView;
private readonly List<SnapshotIcon> children = new List<SnapshotIcon>();
private readonly string _name;
private readonly string _creationTime;
public Size DefaultSize = new Size(70, 64);
private Timer spinningTimer = new Timer();
#region Cached dimensions
private int subtreeWidth;
private int subtreeHeight;
private int subtreeWeight;
private int centreHeight;
#endregion
#region Properties
public string LabelCreationTime
{
get { return _creationTime; }
}
public string LabelName
{
get { return _name; }
}
internal SnapshotIcon Parent
{
get { return parent; }
set { parent = value; }
}
internal IList<SnapshotIcon> Children
{
get { return children; }
}
internal bool Selectable
{
get
{
// It's selectable if it's a snapshot; otherwise not
return ImageIndex == DiskSnapshot || ImageIndex == DiskAndMemorySnapshot || ImageIndex == ScheduledDiskSnapshot || ImageIndex == ScheduledDiskMemorySnapshot;
}
}
#endregion
public SnapshotIcon(string name, string createTime, SnapshotIcon parent, SnapshotTreeView treeView, int imageIndex)
: base(name.Ellipsise(35))
{
this._name = name.Ellipsise(35);
this._creationTime = createTime;
this.parent = parent;
this.treeView = treeView;
this.UseItemStyleForSubItems = false;
this.ToolTipText = String.Format("{0} {1}", name, createTime);
this.ImageIndex = imageIndex;
if (imageIndex == SnapshotIcon.VMImageIndex)
{
spinningTimer.Tick += new EventHandler(timer_Tick);
spinningTimer.Interval = 150;
}
}
private int currentSpinningFrame = 7;
private void timer_Tick(object sender, EventArgs e)
{
this.ImageIndex = currentSpinningFrame <= 14 ? currentSpinningFrame++ : currentSpinningFrame = 7;
}
internal void ChangeSpinningIcon(bool enabled, string message)
{
if (this.ImageIndex > UnknownImage || this.ImageIndex == VMImageIndex)
{
this.ImageIndex = enabled ? 7 : VMImageIndex;
this.Text = enabled ? message : Messages.NOW;
if (enabled)
spinningTimer.Start();
else
spinningTimer.Stop();
}
}
private bool _isInVMBranch = false;
public bool IsInVMBranch
{
get { return _isInVMBranch; }
set { _isInVMBranch = value; }
}
internal void AddChild(SnapshotIcon icon)
{
children.Add(icon);
Invalidate();
}
public override void Remove()
{
SnapshotTreeView view = (SnapshotTreeView)ListView;
view.RemoveSnapshot(this);
base.Remove();
view.PerformLayout();
}
/// <summary>
/// Causes the item and its ancestors to forget their cached dimensions.
/// </summary>
public void Invalidate()
{
subtreeWeight = 0;
subtreeHeight = 0;
centreHeight = 0;
subtreeWidth = 0;
if (parent != null)
parent.Invalidate();
}
/// <summary>
/// Causes the item and all its descendents to forget their cached dimensions.
/// </summary>
public void InvalidateAll()
{
subtreeWeight = 0;
subtreeHeight = 0;
centreHeight = 0;
subtreeWidth = 0;
foreach (SnapshotIcon icon in children)
{
icon.InvalidateAll();
}
}
#region Layout/Dimensions
public int SubtreeWidth
{
get
{
if (subtreeWidth == 0)
{
int currentWidth = this.DefaultSize.Width + treeView.HGap;
if (children.Count > 0)
{
int maxWidth = 0;
foreach (SnapshotIcon icon in children)
{
int childSubtree = icon.SubtreeWidth;
if (currentWidth + childSubtree > maxWidth)
maxWidth = currentWidth + childSubtree;
}
if (maxWidth > currentWidth)
subtreeWidth = maxWidth;
else
subtreeWidth = currentWidth;
}
}
return subtreeWidth;
}
}
/// <summary>
/// Height of the subtree rooted at this node, including the margin above and below.
/// </summary>
public int SubtreeHeight
{
get
{
if (subtreeHeight == 0)
{
subtreeHeight = this.DefaultSize.Height + treeView.VGap;
if (children.Count > 0)
{
int height = 0;
foreach (SnapshotIcon icon in children)
{
height += icon.SubtreeHeight; // recurse
}
if (height > subtreeHeight)
subtreeHeight = height;
}
}
return subtreeHeight;
}
}
/// <summary>
/// The number of items rooted at this node (including the node itself)
/// </summary>
public int SubtreeWeight
{
get
{
if (subtreeWeight == 0)
{
int weight = 1; // this
foreach (SnapshotIcon icon in children)
{
weight += icon.SubtreeWeight;
}
subtreeWeight = weight;
}
return subtreeWeight;
}
}
/// <summary>
/// The weighted mean centre height for this node, within the range 0 - SubtreeHeight
/// </summary>
public int CentreHeight
{
get
{
if (centreHeight == 0)
{
int top = 0;
int totalWeight = 0;
int weightedCentre = 0;
foreach (SnapshotIcon icon in children)
{
int iconWeight = icon.SubtreeWeight;
totalWeight += iconWeight;
weightedCentre += iconWeight * (top + icon.CentreHeight); // recurse
top += icon.SubtreeHeight;
}
if (totalWeight > 0)
centreHeight = weightedCentre / totalWeight;
else
centreHeight = (top + SubtreeHeight) / 2;
}
return centreHeight;
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.CodeSearch;
namespace CodeSearch
{
/// <summary>
/// Summary description for CodeSearch.
/// </summary>
public class CodeSearch : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TreeView FeedView;
private ArrayList entryList;
private System.Windows.Forms.TextBox CodeSearchURI;
private System.Windows.Forms.TextBox Query;
private System.Windows.Forms.Button Fetch_Code;
public CodeSearch()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.entryList = new ArrayList();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new CodeSearch());
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.CodeSearchURI = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.Query = new System.Windows.Forms.TextBox();
this.Fetch_Code = new System.Windows.Forms.Button();
this.FeedView = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// CodeSearchURI
//
this.CodeSearchURI.Location = new System.Drawing.Point(88, 16);
this.CodeSearchURI.Name = "CodeSearchURI";
this.CodeSearchURI.Size = new System.Drawing.Size(296, 20);
this.CodeSearchURI.TabIndex = 1;
this.CodeSearchURI.Text = "http://www.google.com/codesearch/feeds/search";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 16);
this.label1.TabIndex = 2;
this.label1.Text = "URL:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 24);
this.label2.TabIndex = 3;
this.label2.Text = "Query";
//
// Query
//
this.Query.Location = new System.Drawing.Point(88, 48);
this.Query.Name = "Query";
this.Query.Size = new System.Drawing.Size(296, 20);
this.Query.TabIndex = 5;
this.Query.Text = "<termToLookFor>";
//
// Fetch_Code
//
this.Fetch_Code.Location = new System.Drawing.Point(440, 16);
this.Fetch_Code.Name = "Fetch_Code";
this.Fetch_Code.Size = new System.Drawing.Size(104, 24);
this.Fetch_Code.TabIndex = 7;
this.Fetch_Code.Text = "&Fetch Code";
this.Fetch_Code.Click += new System.EventHandler(this.Go_Click);
//
// FeedView
//
this.FeedView.ImageIndex = -1;
this.FeedView.Location = new System.Drawing.Point(16, 112);
this.FeedView.Name = "FeedView";
this.FeedView.SelectedImageIndex = -1;
this.FeedView.Size = new System.Drawing.Size(544, 280);
this.FeedView.TabIndex = 8;
//
// CodeSearch
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(592, 414);
this.Controls.Add(this.FeedView);
this.Controls.Add(this.Fetch_Code);
this.Controls.Add(this.Query);
this.Controls.Add(this.CodeSearchURI);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Cursor = System.Windows.Forms.Cursors.Arrow;
this.Name = "CodeSearch";
this.Text = "Google Code Search Demo";
this.ResumeLayout(false);
}
#endregion
private void Go_Click(object sender, System.EventArgs e)
{
RefreshFeedList();
}
private void RefreshFeedList()
{
string codeSearchURI = this.CodeSearchURI.Text;
FeedQuery query = new FeedQuery();
CodeSearchService service = new CodeSearchService("CodeSearchSampleApp");
query.Uri = new Uri(codeSearchURI);
query.Query = this.Query.Text;
query.StartIndex = 1;
query.NumberToRetrieve = 2;
// start repainting
this.FeedView.BeginUpdate();
Cursor.Current = Cursors.WaitCursor;
// send the request.
CodeSearchFeed feed = service.Query(query);
// Clear the TreeView each time the method is called.
this.FeedView.Nodes.Clear();
int iIndex = this.FeedView.Nodes.Add(new TreeNode(feed.Title.Text));
this.FeedView.Nodes.Add(new TreeNode("Number of entries "));
this.FeedView.Nodes.Add(new TreeNode(feed.Entries.Count.ToString()));
if (iIndex >= 0)
{
foreach (CodeSearchEntry entry in feed.Entries)
{
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
"Entry title: " + entry.Title.Text));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
"File Name"));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
entry.FileElement.Name));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
"Package Name"));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
entry.PackageElement.Name));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
"Package Uri"));
this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
entry.PackageElement.Uri));
int jIndex = this.FeedView.Nodes[iIndex].Nodes.Add(new TreeNode(
"Matches:"));
foreach (Match m in entry.Matches)
{
this.FeedView.Nodes[iIndex].Nodes[jIndex].Nodes.Add(new TreeNode(
m.LineNumber + ": " +
m.LineTextElement));
}
}
}
// Reset the cursor to the default for all controls.
Cursor.Current = Cursors.Default;
// End repainting the combobox
this.FeedView.EndUpdate();
}
}
}
| |
// Copyright (c) 2010, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Gablarski;
using Gablarski.Server;
namespace Gablarski.Tests
{
public class MockUser
: IUser
{
public MockUser (int userId, string username, string password)
{
UserId = userId;
Username = username;
Password = password;
}
public int UserId
{
get; private set;
}
public string Username
{
get; private set;
}
public string Password
{
get; private set;
}
}
public class MockUserProvider
: IUserProvider
{
public event EventHandler BansChanged;
public bool UpdateSupported
{
get; set;
}
public UserRegistrationMode RegistrationMode
{
get; set;
}
public string RegistrationContent
{
get; set;
}
public void AddUser (MockUser user)
{
users.Add (user);
}
public IEnumerable<string> GetAwaitingRegistrations()
{
return this.awaitingApproval.Select (mu => mu.Username);
}
public void ApproveRegistration (string username)
{
if (username == null)
throw new ArgumentNullException ("username");
if (RegistrationMode != UserRegistrationMode.Approved && RegistrationMode != UserRegistrationMode.PreApproved)
throw new NotSupportedException();
MockUser user = this.awaitingApproval.FirstOrDefault (u => u.Username == username);
if (user == null)
return;
this.awaitingApproval.Remove (user);
this.users.Add (user);
}
public void RejectRegistration (string username)
{
if (username == null)
throw new ArgumentNullException ("username");
if (RegistrationMode != UserRegistrationMode.Approved && RegistrationMode != UserRegistrationMode.PreApproved)
throw new NotSupportedException();
this.awaitingApproval.RemoveAll (m => m.Username == username);
}
public bool UserExists (string username)
{
if (username == null)
throw new ArgumentNullException ("username");
username = username.Trim().ToLower();
return users.Concat (awaitingApproval).Any (u => u.Username.Trim().ToLower() == username);
}
public LoginResult Login (string username, string password)
{
if (username == null)
throw new ArgumentNullException ("username");
username = username.Trim().ToLower();
if (this.bans.Any (b => !b.IsExpired && b.Username != null && b.Username.Trim().ToLower() == username))
return new LoginResult (0, LoginResultState.FailedBanned);
LoginResultState state = LoginResultState.Success;
MockUser user = users.FirstOrDefault (u => u.Username.Trim().ToLower() == username);
if (user != null)
{
if (password == null)
state = LoginResultState.FailedPassword;
else if (password.Trim().ToLower() != user.Password.Trim().ToLower())
state = LoginResultState.FailedPassword;
}
else
{
if (password != null)
state = LoginResultState.FailedUsernameAndPassword;
}
return new LoginResult ((user != null) ? user.UserId : Interlocked.Decrement (ref nextGuestId), state);
}
public RegisterResult Register (string username, string password)
{
if (RegistrationMode != UserRegistrationMode.Normal && RegistrationMode != UserRegistrationMode.Approved && RegistrationMode != UserRegistrationMode.PreApproved)
return RegisterResult.FailedUnsupported;
if (username == null)
throw new ArgumentNullException ("username");
RegisterResult state = RegisterResult.FailedUnknown;
if (username.Trim() == String.Empty)
state = RegisterResult.FailedUsername;
else if (UserExists (username))
state = RegisterResult.FailedUsernameInUse;
else
{
state = RegisterResult.Success;
int userId = ((users.Any()) ? users.Max (u => u.UserId) : 0) + 1;
if (RegistrationMode != UserRegistrationMode.Approved)
this.users.Add (new MockUser (userId, username, password));
else
this.awaitingApproval.Add (new MockUser (userId, username, password));
}
return state;
}
public IEnumerable<IUser> GetUsers()
{
return this.users.Cast<IUser>();
}
public IEnumerable<BanInfo> GetBans()
{
lock (this.bans)
return this.bans.ToList();
}
public void AddBan (BanInfo ban)
{
if (ban == null)
throw new ArgumentNullException ("ban");
lock (this.bans)
this.bans.Add (ban);
OnBansChanged();
}
public void RemoveBan (BanInfo ban)
{
if (ban == null)
throw new ArgumentNullException ("ban");
lock (this.bans)
this.bans.Remove (ban);
OnBansChanged();
}
private readonly HashSet<BanInfo> bans = new HashSet<BanInfo>();
private readonly List<MockUser> awaitingApproval = new List<MockUser>();
private readonly List<MockUser> users = new List<MockUser>();
private int nextGuestId;
private void OnBansChanged()
{
var changed = BansChanged;
if (changed != null)
changed (this, EventArgs.Empty);
}
}
}
| |
// 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 ShiftLeftLogicalUInt1616()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalUInt1616
{
private struct TestStruct
{
public Vector256<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalUInt1616 testClass)
{
var result = Avx2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector256<UInt16> _clsVar;
private Vector256<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalUInt1616()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalUInt1616()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt1616();
var result = Avx2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt16>(Vector256<UInt16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Numerics;
using GUI.Types.Renderer;
using GUI.Utils;
using OpenTK.Graphics.OpenGL;
using ValveResourceFormat.ResourceTypes;
using ValveResourceFormat.Serialization;
namespace GUI.Types.ParticleRenderer.Renderers
{
internal class RenderTrails : IParticleRenderer
{
private readonly Shader shader;
private readonly int quadVao;
private readonly int glTexture;
private readonly Texture.SpritesheetData spriteSheetData;
private readonly float animationRate = 0.1f;
private readonly bool additive;
private readonly float overbrightFactor = 1;
private readonly long orientationType;
private readonly float finalTextureScaleU = 1f;
private readonly float finalTextureScaleV = 1f;
private readonly float maxLength = 2000f;
private readonly float lengthFadeInTime;
public RenderTrails(IKeyValueCollection keyValues, VrfGuiContext vrfGuiContext)
{
shader = vrfGuiContext.ShaderLoader.LoadShader("vrf.particle.trail", new Dictionary<string, bool>());
// The same quad is reused for all particles
quadVao = SetupQuadBuffer();
if (keyValues.ContainsKey("m_hTexture"))
{
var textureSetup = LoadTexture(keyValues.GetProperty<string>("m_hTexture"), vrfGuiContext);
glTexture = textureSetup.TextureIndex;
spriteSheetData = textureSetup.TextureData?.GetSpriteSheetData();
}
else
{
glTexture = vrfGuiContext.MaterialLoader.GetErrorTexture();
}
additive = keyValues.GetProperty<bool>("m_bAdditive");
if (keyValues.ContainsKey("m_flOverbrightFactor"))
{
overbrightFactor = keyValues.GetFloatProperty("m_flOverbrightFactor");
}
if (keyValues.ContainsKey("m_nOrientationType"))
{
orientationType = keyValues.GetIntegerProperty("m_nOrientationType");
}
if (keyValues.ContainsKey("m_flAnimationRate"))
{
animationRate = keyValues.GetFloatProperty("m_flAnimationRate");
}
if (keyValues.ContainsKey("m_flFinalTextureScaleU"))
{
finalTextureScaleU = keyValues.GetFloatProperty("m_flFinalTextureScaleU");
}
if (keyValues.ContainsKey("m_flFinalTextureScaleV"))
{
finalTextureScaleV = keyValues.GetFloatProperty("m_flFinalTextureScaleV");
}
if (keyValues.ContainsKey("m_flMaxLength"))
{
maxLength = keyValues.GetFloatProperty("m_flMaxLength");
}
if (keyValues.ContainsKey("m_flLengthFadeInTime"))
{
lengthFadeInTime = keyValues.GetFloatProperty("m_flLengthFadeInTime");
}
}
private int SetupQuadBuffer()
{
GL.UseProgram(shader.Program);
// Create and bind VAO
var vao = GL.GenVertexArray();
GL.BindVertexArray(vao);
var vbo = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
var vertices = new[]
{
-1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw);
GL.EnableVertexAttribArray(0);
var positionAttributeLocation = GL.GetAttribLocation(shader.Program, "aVertexPosition");
GL.VertexAttribPointer(positionAttributeLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
GL.BindVertexArray(0); // Unbind VAO
return vao;
}
private static (int TextureIndex, Texture TextureData) LoadTexture(string textureName, VrfGuiContext vrfGuiContext)
{
var textureResource = vrfGuiContext.LoadFileByAnyMeansNecessary(textureName + "_c");
if (textureResource == null)
{
return (vrfGuiContext.MaterialLoader.GetErrorTexture(), null);
}
return (vrfGuiContext.MaterialLoader.LoadTexture(textureName), (Texture)textureResource.DataBlock);
}
public void Render(ParticleBag particleBag, Matrix4x4 viewProjectionMatrix, Matrix4x4 modelViewMatrix)
{
var particles = particleBag.LiveParticles;
GL.Enable(EnableCap.Blend);
GL.UseProgram(shader.Program);
if (additive)
{
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.One);
}
else
{
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
}
GL.BindVertexArray(quadVao);
GL.EnableVertexAttribArray(0);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, glTexture);
GL.Uniform1(shader.GetUniformLocation("uTexture"), 0); // set texture unit 0 as uTexture uniform
var otkProjection = viewProjectionMatrix.ToOpenTK();
GL.UniformMatrix4(shader.GetUniformLocation("uProjectionViewMatrix"), false, ref otkProjection);
// TODO: This formula is a guess but still seems too bright compared to valve particles
GL.Uniform1(shader.GetUniformLocation("uOverbrightFactor"), overbrightFactor);
var modelMatrixLocation = shader.GetUniformLocation("uModelMatrix");
var colorLocation = shader.GetUniformLocation("uColor");
var alphaLocation = shader.GetUniformLocation("uAlpha");
var uvOffsetLocation = shader.GetUniformLocation("uUvOffset");
var uvScaleLocation = shader.GetUniformLocation("uUvScale");
// Create billboarding rotation (always facing camera)
Matrix4x4.Decompose(modelViewMatrix, out _, out Quaternion modelViewRotation, out _);
modelViewRotation = Quaternion.Inverse(modelViewRotation);
var billboardMatrix = Matrix4x4.CreateFromQuaternion(modelViewRotation);
for (int i = 0; i < particles.Length; ++i)
{
var position = new Vector3(particles[i].Position.X, particles[i].Position.Y, particles[i].Position.Z);
var previousPosition = new Vector3(particles[i].PositionPrevious.X, particles[i].PositionPrevious.Y, particles[i].PositionPrevious.Z);
var difference = previousPosition - position;
var direction = Vector3.Normalize(difference);
var midPoint = position + (0.5f * difference);
// Trail width = radius
// Trail length = distance between current and previous times trail length divided by 2 (because the base particle is 2 wide)
var length = Math.Min(maxLength, particles[i].TrailLength * difference.Length() / 2f);
var t = 1 - (particles[i].Lifetime / particles[i].ConstantLifetime);
var animatedLength = t >= lengthFadeInTime
? length
: t * length / lengthFadeInTime;
var scaleMatrix = Matrix4x4.CreateScale(particles[i].Radius, animatedLength, 1);
// Center the particle at the midpoint between the two points
var translationMatrix = Matrix4x4.CreateTranslation(Vector3.UnitY * animatedLength);
// Calculate rotation matrix
var axis = Vector3.Normalize(Vector3.Cross(Vector3.UnitY, direction));
var angle = (float)Math.Acos(direction.Y);
var rotationMatrix = Matrix4x4.CreateFromAxisAngle(axis, angle);
var modelMatrix =
orientationType == 0 ? Matrix4x4.Multiply(scaleMatrix, Matrix4x4.Multiply(translationMatrix, rotationMatrix))
: particles[i].GetTransformationMatrix();
// Position/Radius uniform
var otkModelMatrix = modelMatrix.ToOpenTK();
GL.UniformMatrix4(modelMatrixLocation, false, ref otkModelMatrix);
if (spriteSheetData != null && spriteSheetData.Sequences.Length > 0 && spriteSheetData.Sequences[0].Frames.Length > 0)
{
var sequence = spriteSheetData.Sequences[0];
var particleTime = particles[i].ConstantLifetime - particles[i].Lifetime;
var frame = particleTime * sequence.FramesPerSecond * animationRate;
var currentFrame = sequence.Frames[(int)Math.Floor(frame) % sequence.Frames.Length];
// Lerp frame coords and size
var subFrameTime = frame % 1.0f;
var offset = (currentFrame.StartMins * (1 - subFrameTime)) + (currentFrame.EndMins * subFrameTime);
var scale = ((currentFrame.StartMaxs - currentFrame.StartMins) * (1 - subFrameTime))
+ ((currentFrame.EndMaxs - currentFrame.EndMins) * subFrameTime);
GL.Uniform2(uvOffsetLocation, offset.X, offset.Y);
GL.Uniform2(uvScaleLocation, scale.X * finalTextureScaleU, scale.Y * finalTextureScaleV);
}
else
{
GL.Uniform2(uvOffsetLocation, 1f, 1f);
GL.Uniform2(uvScaleLocation, finalTextureScaleU, finalTextureScaleV);
}
// Color uniform
GL.Uniform3(colorLocation, particles[i].Color.X, particles[i].Color.Y, particles[i].Color.Z);
GL.Uniform1(alphaLocation, particles[i].Alpha * particles[i].AlphaAlternate);
GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
}
GL.BindVertexArray(0);
GL.UseProgram(0);
if (additive)
{
GL.BlendEquation(BlendEquationMode.FuncAdd);
}
GL.Disable(EnableCap.Blend);
}
}
}
| |
// 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.Runtime;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.Reflection.Core.NonPortable;
using Internal.IntrinsicSupport;
using EEType = Internal.Runtime.EEType;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
// Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both
// IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details.
public abstract partial class Array : ICollection, IEnumerable, IList, IStructuralComparable, IStructuralEquatable, ICloneable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
internal Array() { }
// CS0649: Field '{blah}' is never assigned to, and will always have its default value
#pragma warning disable 649
// This field should be the first field in Array as the runtime/compilers depend on it
[NonSerialized]
private int _numComponents;
#pragma warning restore
#if BIT64
private const int POINTER_SIZE = 8;
#else
private const int POINTER_SIZE = 4;
#endif
// Header + m_pEEType + _numComponents (with an optional padding)
private const int SZARRAY_BASE_SIZE = POINTER_SIZE + POINTER_SIZE + POINTER_SIZE;
public int Length
{
get
{
// NOTE: The compiler has assumptions about the implementation of this method.
// Changing the implementation here (or even deleting this) will NOT have the desired impact
return _numComponents;
}
}
internal bool IsSzArray
{
get
{
return this.EETypePtr.BaseSize == SZARRAY_BASE_SIZE;
}
}
// This is the classlib-provided "get array eetype" function that will be invoked whenever the runtime
// needs to know the base type of an array.
[RuntimeExport("GetSystemArrayEEType")]
private static unsafe EEType* GetSystemArrayEEType()
{
return EETypePtr.EETypePtrOf<Array>().ToPointer();
}
public static Array CreateInstance(Type elementType, int length)
{
if ((object)elementType == null)
throw new ArgumentNullException(nameof(elementType));
return CreateSzArray(elementType, length);
}
public static unsafe Array CreateInstance(Type elementType, int length1, int length2)
{
if ((object)elementType == null)
throw new ArgumentNullException(nameof(elementType));
if (length1 < 0)
throw new ArgumentOutOfRangeException(nameof(length1));
if (length2 < 0)
throw new ArgumentOutOfRangeException(nameof(length2));
Type arrayType = GetArrayTypeFromElementType(elementType, true, 2);
int* pLengths = stackalloc int[2];
pLengths[0] = length1;
pLengths[1] = length2;
return NewMultiDimArray(arrayType.TypeHandle.ToEETypePtr(), pLengths, 2);
}
public static unsafe Array CreateInstance(Type elementType, int length1, int length2, int length3)
{
if ((object)elementType == null)
throw new ArgumentNullException(nameof(elementType));
if (length1 < 0)
throw new ArgumentOutOfRangeException(nameof(length1));
if (length2 < 0)
throw new ArgumentOutOfRangeException(nameof(length2));
if (length3 < 0)
throw new ArgumentOutOfRangeException(nameof(length3));
Type arrayType = GetArrayTypeFromElementType(elementType, true, 3);
int* pLengths = stackalloc int[3];
pLengths[0] = length1;
pLengths[1] = length2;
pLengths[2] = length3;
return NewMultiDimArray(arrayType.TypeHandle.ToEETypePtr(), pLengths, 3);
}
public static Array CreateInstance(Type elementType, params int[] lengths)
{
if ((object)elementType == null)
throw new ArgumentNullException(nameof(elementType));
if (lengths == null)
throw new ArgumentNullException(nameof(lengths));
if (lengths.Length == 0)
throw new ArgumentException(SR.Arg_NeedAtLeast1Rank);
if (lengths.Length == 1)
{
int length = lengths[0];
return CreateSzArray(elementType, length);
}
else
{
return CreateMultiDimArray(elementType, lengths, null);
}
}
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
{
if (elementType == null)
throw new ArgumentNullException(nameof(elementType));
if (lengths == null)
throw new ArgumentNullException(nameof(lengths));
if (lowerBounds == null)
throw new ArgumentNullException(nameof(lowerBounds));
if (lengths.Length != lowerBounds.Length)
throw new ArgumentException(SR.Arg_RanksAndBounds);
if (lengths.Length == 0)
throw new ArgumentException(SR.Arg_NeedAtLeast1Rank);
return CreateMultiDimArray(elementType, lengths, lowerBounds);
}
private static Array CreateSzArray(Type elementType, int length)
{
// Though our callers already validated length once, this parameter is passed via arrays, so we must check it again
// in case a malicious caller modified the array after the check.
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
Type arrayType = GetArrayTypeFromElementType(elementType, false, 1);
return RuntimeImports.RhNewArray(arrayType.TypeHandle.ToEETypePtr(), length);
}
private static Array CreateMultiDimArray(Type elementType, int[] lengths, int[] lowerBounds)
{
Debug.Assert(lengths != null);
Debug.Assert(lowerBounds == null || lowerBounds.Length == lengths.Length);
for (int i = 0; i < lengths.Length; i++)
{
if (lengths[i] < 0)
throw new ArgumentOutOfRangeException("lengths[" + i + "]", SR.ArgumentOutOfRange_NeedNonNegNum);
}
int rank = lengths.Length;
Type arrayType = GetArrayTypeFromElementType(elementType, true, rank);
return RuntimeAugments.NewMultiDimArray(arrayType.TypeHandle, lengths, lowerBounds);
}
private static Type GetArrayTypeFromElementType(Type elementType, bool multiDim, int rank)
{
elementType = elementType.UnderlyingSystemType;
ValidateElementType(elementType);
if (multiDim)
return elementType.MakeArrayType(rank);
else
return elementType.MakeArrayType();
}
private static void ValidateElementType(Type elementType)
{
if (!elementType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(elementType));
while (elementType.IsArray)
{
elementType = elementType.GetElementType();
}
if (elementType.IsByRef || elementType.IsByRefLike)
throw new NotSupportedException(SR.NotSupported_ByRefLikeArray);
if (elementType.Equals(CommonRuntimeTypes.Void))
throw new NotSupportedException(SR.NotSupported_VoidArray);
if (elementType.ContainsGenericParameters)
throw new NotSupportedException(SR.NotSupported_OpenType);
}
public void Initialize()
{
// Project N port note: On the desktop, this api is a nop unless the array element type is a value type with
// an explicit nullary constructor. Such a type cannot be expressed in C# so Project N does not support this.
// The ILC toolchain fails the build if it encounters such a type.
return;
}
[StructLayout(LayoutKind.Sequential)]
private class RawData
{
public IntPtr Count; // Array._numComponents padded to IntPtr
public byte Data;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ref byte GetRawSzArrayData()
{
Debug.Assert(IsSzArray);
return ref Unsafe.As<RawData>(this).Data;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ref byte GetRawArrayData()
{
return ref Unsafe.Add(ref Unsafe.As<RawData>(this).Data, (int)(EETypePtr.BaseSize - SZARRAY_BASE_SIZE));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetRawMultiDimArrayBounds()
{
Debug.Assert(!IsSzArray);
return ref Unsafe.AddByteOffset(ref _numComponents, POINTER_SIZE);
}
// Copies length elements from sourceArray, starting at sourceIndex, to
// destinationArray, starting at destinationIndex.
//
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
if (!RuntimeImports.TryArrayCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
CopyImpl(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false);
}
// Provides a strong exception guarantee - either it succeeds, or
// it throws an exception with no side effects. The arrays must be
// compatible array types based on the array element type - this
// method does not support casting, boxing, or primitive widening.
// It will up-cast, assuming the array types are correct.
public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
if (!RuntimeImports.TryArrayCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
CopyImpl(sourceArray, sourceIndex, destinationArray, destinationIndex, length, true);
}
public static void Copy(Array sourceArray, Array destinationArray, int length)
{
if (!RuntimeImports.TryArrayCopy(sourceArray, 0, destinationArray, 0, length))
CopyImpl(sourceArray, 0, destinationArray, 0, length, false);
}
//
// Funnel for all the Array.Copy() overloads. The "reliable" parameter indicates whether the caller for ConstrainedCopy()
// (must leave destination array unchanged on any exception.)
//
private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
if (sourceArray == null)
throw new ArgumentNullException(nameof(sourceArray));
if (destinationArray == null)
throw new ArgumentNullException(nameof(destinationArray));
int sourceRank = sourceArray.Rank;
int destinationRank = destinationArray.Rank;
if (sourceRank != destinationRank)
throw new RankException(SR.Rank_MultiDimNotSupported);
if ((sourceIndex < 0) || (destinationIndex < 0) || (length < 0))
throw new ArgumentOutOfRangeException();
if ((length > sourceArray.Length) || length > destinationArray.Length)
throw new ArgumentException();
if ((length > sourceArray.Length - sourceIndex) || (length > destinationArray.Length - destinationIndex))
throw new ArgumentException();
EETypePtr sourceElementEEType = sourceArray.ElementEEType;
EETypePtr destinationElementEEType = destinationArray.ElementEEType;
if (!destinationElementEEType.IsValueType && !destinationElementEEType.IsPointer)
{
if (!sourceElementEEType.IsValueType && !sourceElementEEType.IsPointer)
{
CopyImplGcRefArray(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable);
}
else if (RuntimeImports.AreTypesAssignable(sourceElementEEType, destinationElementEEType))
{
CopyImplValueTypeArrayToReferenceArray(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable);
}
else
{
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
}
else
{
if (RuntimeImports.AreTypesEquivalent(sourceElementEEType, destinationElementEEType))
{
if (sourceElementEEType.HasPointers)
{
CopyImplValueTypeArrayWithInnerGcRefs(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable);
}
else
{
CopyImplValueTypeArrayNoInnerGcRefs(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
}
}
else if (sourceElementEEType.IsPointer && destinationElementEEType.IsPointer)
{
// CLR compat note: CLR only allows Array.Copy between pointee types that would be assignable
// to using array covariance rules (so int*[] can be copied to uint*[], but not to float*[]).
// This is rather weird since e.g. we don't allow casting int*[] to uint*[] otherwise.
// Instead of trying to replicate the behavior, we're choosing to be simply more permissive here.
CopyImplValueTypeArrayNoInnerGcRefs(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
}
else if (IsSourceElementABaseClassOrInterfaceOfDestinationValueType(sourceElementEEType, destinationElementEEType))
{
CopyImplReferenceArrayToValueTypeArray(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable);
}
else if (sourceElementEEType.IsPrimitive && destinationElementEEType.IsPrimitive)
{
// The only case remaining is that primitive types could have a widening conversion between the source element type and the destination
// If a widening conversion does not exist we are going to throw an ArrayTypeMismatchException from it.
CopyImplPrimitiveTypeWithWidening(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable);
}
else
{
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
}
}
private static bool IsSourceElementABaseClassOrInterfaceOfDestinationValueType(EETypePtr sourceElementEEType, EETypePtr destinationElementEEType)
{
if (sourceElementEEType.IsValueType || sourceElementEEType.IsPointer)
return false;
// It may look like we're passing the arguments to AreTypesAssignable in the wrong order but we're not. The source array is an interface or Object array, the destination
// array is a value type array. Our job is to check if the destination value type implements the interface - which is what this call to AreTypesAssignable does.
// The copy loop still checks each element to make sure it actually is the correct valuetype.
if (!RuntimeImports.AreTypesAssignable(destinationElementEEType, sourceElementEEType))
return false;
return true;
}
//
// Array.CopyImpl case: Gc-ref array to gc-ref array copy.
//
private static unsafe void CopyImplGcRefArray(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
// For mismatched array types, the desktop Array.Copy has a policy that determines whether to throw an ArrayTypeMismatch without any attempt to copy
// or to throw an InvalidCastException in the middle of a copy. This code replicates that policy.
EETypePtr sourceElementEEType = sourceArray.ElementEEType;
EETypePtr destinationElementEEType = destinationArray.ElementEEType;
Debug.Assert(!sourceElementEEType.IsValueType && !sourceElementEEType.IsPointer);
Debug.Assert(!destinationElementEEType.IsValueType && !destinationElementEEType.IsPointer);
bool attemptCopy = RuntimeImports.AreTypesAssignable(sourceElementEEType, destinationElementEEType);
bool mustCastCheckEachElement = !attemptCopy;
if (reliable)
{
if (mustCastCheckEachElement)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy);
}
else
{
attemptCopy = attemptCopy || RuntimeImports.AreTypesAssignable(destinationElementEEType, sourceElementEEType);
// If either array is an interface array, we allow the attempt to copy even if the other element type does not statically implement the interface.
// We don't have an "IsInterface" property in EETypePtr so we instead check for a null BaseType. The only the other EEType with a null BaseType is
// System.Object but if that were the case, we would already have passed one of the AreTypesAssignable checks above.
attemptCopy = attemptCopy || sourceElementEEType.BaseType.IsNull;
attemptCopy = attemptCopy || destinationElementEEType.BaseType.IsNull;
if (!attemptCopy)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
bool reverseCopy = ((object)sourceArray == (object)destinationArray) && (sourceIndex < destinationIndex);
ref object refDestinationArray = ref Unsafe.As<byte, object>(ref destinationArray.GetRawArrayData());
ref object refSourceArray = ref Unsafe.As<byte, object>(ref sourceArray.GetRawArrayData());
if (reverseCopy)
{
sourceIndex += length - 1;
destinationIndex += length - 1;
for (int i = 0; i < length; i++)
{
object value = Unsafe.Add(ref refSourceArray, sourceIndex - i);
if (mustCastCheckEachElement && value != null && RuntimeImports.IsInstanceOf(value, destinationElementEEType) == null)
throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement);
Unsafe.Add(ref refDestinationArray, destinationIndex - i) = value;
}
}
else
{
for (int i = 0; i < length; i++)
{
object value = Unsafe.Add(ref refSourceArray, sourceIndex + i);
if (mustCastCheckEachElement && value != null && RuntimeImports.IsInstanceOf(value, destinationElementEEType) == null)
throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement);
Unsafe.Add(ref refDestinationArray, destinationIndex + i) = value;
}
}
}
//
// Array.CopyImpl case: Value-type array to Object[] or interface array copy.
//
private static unsafe void CopyImplValueTypeArrayToReferenceArray(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
Debug.Assert(sourceArray.ElementEEType.IsValueType || sourceArray.ElementEEType.IsPointer);
Debug.Assert(!destinationArray.ElementEEType.IsValueType && !destinationArray.ElementEEType.IsPointer);
// Caller has already validated this.
Debug.Assert(RuntimeImports.AreTypesAssignable(sourceArray.ElementEEType, destinationArray.ElementEEType));
if (reliable)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy);
EETypePtr sourceElementEEType = sourceArray.ElementEEType;
nuint sourceElementSize = sourceArray.ElementSize;
fixed (byte* pSourceArray = &sourceArray.GetRawArrayData())
{
byte* pElement = pSourceArray + (nuint)sourceIndex * sourceElementSize;
ref object refDestinationArray = ref Unsafe.As<byte, object>(ref destinationArray.GetRawArrayData());
for (int i = 0; i < length; i++)
{
Object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pElement);
Unsafe.Add(ref refDestinationArray, destinationIndex + i) = boxedValue;
pElement += sourceElementSize;
}
}
}
//
// Array.CopyImpl case: Object[] or interface array to value-type array copy.
//
private static unsafe void CopyImplReferenceArrayToValueTypeArray(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
Debug.Assert(!sourceArray.ElementEEType.IsValueType && !sourceArray.ElementEEType.IsPointer);
Debug.Assert(destinationArray.ElementEEType.IsValueType || destinationArray.ElementEEType.IsPointer);
if (reliable)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
EETypePtr destinationElementEEType = destinationArray.ElementEEType;
nuint destinationElementSize = destinationArray.ElementSize;
bool isNullable = destinationElementEEType.IsNullable;
fixed (byte* pDestinationArray = &destinationArray.GetRawArrayData())
{
ref object refSourceArray = ref Unsafe.As<byte, object>(ref sourceArray.GetRawArrayData());
byte* pElement = pDestinationArray + (nuint)destinationIndex * destinationElementSize;
for (int i = 0; i < length; i++)
{
Object boxedValue = Unsafe.Add(ref refSourceArray, sourceIndex + i);
if (boxedValue == null)
{
if (!isNullable)
throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement);
}
else
{
EETypePtr eeType = boxedValue.EETypePtr;
if (!(RuntimeImports.AreTypesAssignable(eeType, destinationElementEEType)))
throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement);
}
RuntimeImports.RhUnbox(boxedValue, pElement, destinationElementEEType);
pElement += destinationElementSize;
}
}
}
//
// Array.CopyImpl case: Value-type array with embedded gc-references.
//
private static unsafe void CopyImplValueTypeArrayWithInnerGcRefs(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
Debug.Assert(RuntimeImports.AreTypesEquivalent(sourceArray.EETypePtr, destinationArray.EETypePtr));
Debug.Assert(sourceArray.ElementEEType.IsValueType);
EETypePtr sourceElementEEType = sourceArray.EETypePtr.ArrayElementType;
bool reverseCopy = ((object)sourceArray == (object)destinationArray) && (sourceIndex < destinationIndex);
// Copy scenario: ValueType-array to value-type array with embedded gc-refs.
object[] boxedElements = null;
if (reliable)
{
boxedElements = new object[length];
reverseCopy = false;
}
fixed (byte* pDstArray = &destinationArray.GetRawArrayData(), pSrcArray = &sourceArray.GetRawArrayData())
{
nuint cbElementSize = sourceArray.ElementSize;
byte* pSourceElement = pSrcArray + (nuint)sourceIndex * cbElementSize;
byte* pDestinationElement = pDstArray + (nuint)destinationIndex * cbElementSize;
if (reverseCopy)
{
pSourceElement += (nuint)length * cbElementSize;
pDestinationElement += (nuint)length * cbElementSize;
}
for (int i = 0; i < length; i++)
{
if (reverseCopy)
{
pSourceElement -= cbElementSize;
pDestinationElement -= cbElementSize;
}
object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pSourceElement);
if (reliable)
boxedElements[i] = boxedValue;
else
RuntimeImports.RhUnbox(boxedValue, pDestinationElement, sourceElementEEType);
if (!reverseCopy)
{
pSourceElement += cbElementSize;
pDestinationElement += cbElementSize;
}
}
}
if (reliable)
{
for (int i = 0; i < length; i++)
destinationArray.SetValue(boxedElements[i], destinationIndex + i);
}
}
//
// Array.CopyImpl case: Value-type array without embedded gc-references.
//
internal static unsafe void CopyImplValueTypeArrayNoInnerGcRefs(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Debug.Assert((sourceArray.ElementEEType.IsValueType && !sourceArray.ElementEEType.HasPointers) ||
sourceArray.ElementEEType.IsPointer);
Debug.Assert((destinationArray.ElementEEType.IsValueType && !destinationArray.ElementEEType.HasPointers) ||
destinationArray.ElementEEType.IsPointer);
// Copy scenario: ValueType-array to value-type array with no embedded gc-refs.
nuint elementSize = sourceArray.ElementSize;
fixed (byte* pSrcArray = &sourceArray.GetRawArrayData(), pDstArray = &destinationArray.GetRawArrayData())
{
byte* pSrcElements = pSrcArray + (nuint)sourceIndex * elementSize;
byte* pDstElements = pDstArray + (nuint)destinationIndex * elementSize;
nuint cbCopy = elementSize * (nuint)length;
Buffer.Memmove(pDstElements, pSrcElements, cbCopy);
}
}
//
// Array.CopyImpl case: Primitive types that have a widening conversion
//
private static unsafe void CopyImplPrimitiveTypeWithWidening(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable)
{
EETypePtr sourceElementEEType = sourceArray.ElementEEType;
EETypePtr destinationElementEEType = destinationArray.ElementEEType;
Debug.Assert(sourceElementEEType.IsPrimitive && destinationElementEEType.IsPrimitive); // Caller has already validated this.
RuntimeImports.RhCorElementType sourceElementType = sourceElementEEType.CorElementType;
RuntimeImports.RhCorElementType destElementType = destinationElementEEType.CorElementType;
nuint srcElementSize = sourceArray.ElementSize;
nuint destElementSize = destinationArray.ElementSize;
if ((sourceElementEEType.IsEnum || destinationElementEEType.IsEnum) && sourceElementType != destElementType)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
if (reliable)
{
// ContrainedCopy() cannot even widen - it can only copy same type or enum to its exact integral subtype.
if (sourceElementType != destElementType)
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy);
}
fixed (byte* pSrcArray = &sourceArray.GetRawArrayData(), pDstArray = &destinationArray.GetRawArrayData())
{
byte* srcData = pSrcArray + (nuint)sourceIndex * srcElementSize;
byte* data = pDstArray + (nuint)destinationIndex * destElementSize;
if (sourceElementType == destElementType)
{
// Multidim arrays and enum->int copies can still reach this path.
Buffer.Memmove(dest: data, src: srcData, len: (nuint)length * srcElementSize);
return;
}
ulong dummyElementForZeroLengthCopies = 0;
// If the element types aren't identical and the length is zero, we're still obliged to check the types for widening compatibility.
// We do this by forcing the loop below to copy one dummy element.
if (length == 0)
{
srcData = (byte*)&dummyElementForZeroLengthCopies;
data = (byte*)&dummyElementForZeroLengthCopies;
length = 1;
}
for (int i = 0; i < length; i++, srcData += srcElementSize, data += destElementSize)
{
// We pretty much have to do some fancy datatype mangling every time here, for
// converting w/ sign extension and floating point conversions.
switch (sourceElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
{
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = *(byte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(byte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
*(short*)data = *(byte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
*(int*)data = *(byte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
*(long*)data = *(byte*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
}
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
*(short*)data = *(sbyte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
*(int*)data = *(sbyte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
*(long*)data = *(sbyte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = *(sbyte*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(sbyte*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = *(ushort*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(ushort*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
*(ushort*)data = *(ushort*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
*(uint*)data = *(ushort*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
*(ulong*)data = *(ushort*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
*(int*)data = *(short*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
*(long*)data = *(short*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = *(short*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(short*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
*(long*)data = *(int*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = (float)*(int*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(int*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
*(long*)data = *(uint*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = (float)*(uint*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(uint*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
*(float*)data = (float)*(long*)srcData;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = (double)*(long*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
//*(float*) data = (float) *(Ulong*)srcData;
long srcValToFloat = *(long*)srcData;
float f = (float)srcValToFloat;
if (srcValToFloat < 0)
f += 4294967296.0f * 4294967296.0f; // This is 2^64
*(float*)data = f;
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
//*(double*) data = (double) *(Ulong*)srcData;
long srcValToDouble = *(long*)srcData;
double d = (double)srcValToDouble;
if (srcValToDouble < 0)
d += 4294967296.0 * 4294967296.0; // This is 2^64
*(double*)data = d;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
switch (destElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
*(double*)data = *(float*)srcData;
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
break;
default:
throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType);
}
}
}
}
public static void Clear(Array array, int index, int length)
{
if (!RuntimeImports.TryArrayClear(array, index, length))
ReportClearErrors(array, index, length);
}
private static unsafe void ReportClearErrors(Array array, int index, int length)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0 || index > array.Length || length < 0 || length > array.Length)
throw new IndexOutOfRangeException();
if (length > (array.Length - index))
throw new IndexOutOfRangeException();
// The above checks should have covered all the reasons why Clear would fail.
Debug.Assert(false);
}
// We impose limits on maximum array length in each dimension to allow efficient
// implementation of advanced range check elimination in future.
// Keep in sync with vm\gcscan.cpp and HashHelpers.MaxPrimeArrayLength.
internal const int MaxArrayLength = 0X7FEFFFFF;
internal const int MaxByteArrayLength = MaxArrayLength;
public int GetLength(int dimension)
{
int length = GetUpperBound(dimension) + 1;
// We don't support non-zero lower bounds so don't incur the cost of obtaining it.
Debug.Assert(GetLowerBound(dimension) == 0);
return length;
}
public int Rank
{
get
{
return this.EETypePtr.ArrayRank;
}
}
// Allocate new multidimensional array of given dimensions. Assumes that that pLengths is immutable.
internal static unsafe Array NewMultiDimArray(EETypePtr eeType, int* pLengths, int rank)
{
Debug.Assert(eeType.IsArray && !eeType.IsSzArray);
Debug.Assert(rank == eeType.ArrayRank);
// Code below assumes 0 lower bounds. MdArray of rank 1 with zero lower bounds should never be allocated.
// The runtime always allocates an SzArray for those:
// * newobj instance void int32[0...]::.ctor(int32)" actually gives you int[]
// * int[] is castable to int[*] to make it mostly transparent
// The callers need to check for this.
Debug.Assert(rank != 1);
ulong totalLength = 1;
bool maxArrayDimensionLengthOverflow = false;
for (int i = 0; i < rank; i++)
{
int length = pLengths[i];
if (length < 0)
throw new OverflowException();
if (length > MaxArrayLength)
maxArrayDimensionLengthOverflow = true;
totalLength = totalLength * (ulong)length;
if (totalLength > Int32.MaxValue)
throw new OutOfMemoryException(); // "Array dimensions exceeded supported range."
}
// Throw this exception only after everything else was validated for backward compatibility.
if (maxArrayDimensionLengthOverflow)
throw new OutOfMemoryException(); // "Array dimensions exceeded supported range."
Array ret = RuntimeImports.RhNewArray(eeType, (int)totalLength);
ref int bounds = ref ret.GetRawMultiDimArrayBounds();
for (int i = 0; i < rank; i++)
{
Unsafe.Add(ref bounds, i) = pLengths[i];
}
return ret;
}
// Wraps an IComparer inside an IComparer<Object>.
private sealed class ComparerAsComparerT : IComparer<Object>
{
public ComparerAsComparerT(IComparer comparer)
{
_comparer = (comparer == null) ? Comparer.Default : comparer;
}
public int Compare(Object x, Object y)
{
return _comparer.Compare(x, y);
}
private IComparer _comparer;
}
public static T[] Empty<T>()
{
return EmptyArray<T>.Value;
}
private static class EmptyArray<T>
{
internal static readonly T[] Value = new T[0];
}
public int GetLowerBound(int dimension)
{
if (!IsSzArray)
{
int rank = Rank;
if ((uint)dimension >= rank)
throw new IndexOutOfRangeException();
return Unsafe.Add(ref GetRawMultiDimArrayBounds(), rank + dimension);
}
if (dimension != 0)
throw new IndexOutOfRangeException();
return 0;
}
public int GetUpperBound(int dimension)
{
if (!IsSzArray)
{
int rank = Rank;
if ((uint)dimension >= rank)
throw new IndexOutOfRangeException();
ref int bounds = ref GetRawMultiDimArrayBounds();
int length = Unsafe.Add(ref bounds, dimension);
int lowerBound = Unsafe.Add(ref bounds, rank + dimension);
return length + lowerBound - 1;
}
if (dimension != 0)
throw new IndexOutOfRangeException();
return Length - 1;
}
public unsafe Object GetValue(int index)
{
if (!IsSzArray)
{
if (Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
return GetValue(&index, 1);
}
if ((uint)index >= (uint)Length)
throw new IndexOutOfRangeException();
if (ElementEEType.IsPointer)
throw new NotSupportedException(SR.NotSupported_Type);
return GetValueWithFlattenedIndex_NoErrorCheck(index);
}
public unsafe Object GetValue(int index1, int index2)
{
if (Rank != 2)
throw new ArgumentException(SR.Arg_Need2DArray);
int* pIndices = stackalloc int[2];
pIndices[0] = index1;
pIndices[1] = index2;
return GetValue(pIndices, 2);
}
public unsafe Object GetValue(int index1, int index2, int index3)
{
if (Rank != 3)
throw new ArgumentException(SR.Arg_Need3DArray);
int* pIndices = stackalloc int[3];
pIndices[0] = index1;
pIndices[1] = index2;
pIndices[2] = index3;
return GetValue(pIndices, 3);
}
public unsafe Object GetValue(params int[] indices)
{
if (indices == null)
throw new ArgumentNullException(nameof(indices));
int length = indices.Length;
if (IsSzArray && length == 1)
return GetValue(indices[0]);
if (Rank != length)
throw new ArgumentException(SR.Arg_RankIndices);
Debug.Assert(length > 0);
fixed (int* pIndices = &indices[0])
return GetValue(pIndices, length);
}
private unsafe Object GetValue(int* pIndices, int rank)
{
Debug.Assert(Rank == rank);
Debug.Assert(!IsSzArray);
ref int bounds = ref GetRawMultiDimArrayBounds();
int flattenedIndex = 0;
for (int i = 0; i < rank; i++)
{
int index = pIndices[i] - Unsafe.Add(ref bounds, rank + i);
int length = Unsafe.Add(ref bounds, i);
if ((uint)index >= (uint)length)
throw new IndexOutOfRangeException();
flattenedIndex = (length * flattenedIndex) + index;
}
if ((uint)flattenedIndex >= (uint)Length)
throw new IndexOutOfRangeException();
if (ElementEEType.IsPointer)
throw new NotSupportedException(SR.NotSupported_Type);
return GetValueWithFlattenedIndex_NoErrorCheck(flattenedIndex);
}
private Object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex)
{
ref byte element = ref Unsafe.AddByteOffset(ref GetRawArrayData(), (nuint)flattenedIndex * ElementSize);
EETypePtr pElementEEType = ElementEEType;
if (pElementEEType.IsValueType)
{
return RuntimeImports.RhBox(pElementEEType, ref element);
}
else
{
Debug.Assert(!pElementEEType.IsPointer);
return Unsafe.As<byte, object>(ref element);
}
}
public unsafe void SetValue(Object value, int index)
{
if (!IsSzArray)
{
if (Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
SetValue(value, &index, 1);
return;
}
EETypePtr pElementEEType = ElementEEType;
if (pElementEEType.IsValueType)
{
if ((uint)index >= (uint)Length)
throw new IndexOutOfRangeException();
// Unlike most callers of InvokeUtils.ChangeType(), Array.SetValue() does *not* permit conversion from a primitive to an Enum.
if (value != null && !(value.EETypePtr == pElementEEType) && pElementEEType.IsEnum)
throw new InvalidCastException(SR.Format(SR.Arg_ObjObjEx, value.GetType(), Type.GetTypeFromHandle(new RuntimeTypeHandle(pElementEEType))));
value = InvokeUtils.CheckArgument(value, pElementEEType, InvokeUtils.CheckArgumentSemantics.ArraySet, binderBundle: null);
Debug.Assert(value == null || RuntimeImports.AreTypesAssignable(value.EETypePtr, pElementEEType));
ref byte element = ref Unsafe.AddByteOffset(ref GetRawArrayData(), (nuint)index * ElementSize);
RuntimeImports.RhUnbox(value, ref element, pElementEEType);
}
else if (pElementEEType.IsPointer)
{
throw new NotSupportedException(SR.NotSupported_Type);
}
else
{
object[] objArray = this as object[];
try
{
objArray[index] = value;
}
catch (ArrayTypeMismatchException)
{
throw new InvalidCastException(SR.InvalidCast_StoreArrayElement);
}
}
}
public unsafe void SetValue(Object value, int index1, int index2)
{
if (Rank != 2)
throw new ArgumentException(SR.Arg_Need2DArray);
int* pIndices = stackalloc int[2];
pIndices[0] = index1;
pIndices[1] = index2;
SetValue(value, pIndices, 2);
}
public unsafe void SetValue(Object value, int index1, int index2, int index3)
{
if (Rank != 3)
throw new ArgumentException(SR.Arg_Need3DArray);
int* pIndices = stackalloc int[3];
pIndices[0] = index1;
pIndices[1] = index2;
pIndices[2] = index3;
SetValue(value, pIndices, 3);
}
public unsafe void SetValue(Object value, params int[] indices)
{
if (indices == null)
throw new ArgumentNullException(nameof(indices));
int length = indices.Length;
if (IsSzArray && length == 1)
{
SetValue(value, indices[0]);
return;
}
if (Rank != length)
throw new ArgumentException(SR.Arg_RankIndices);
Debug.Assert(length > 0);
fixed (int* pIndices = &indices[0])
{
SetValue(value, pIndices, length);
return;
}
}
private unsafe void SetValue(Object value, int* pIndices, int rank)
{
Debug.Assert(Rank == rank);
Debug.Assert(!IsSzArray);
ref int bounds = ref GetRawMultiDimArrayBounds();
int flattenedIndex = 0;
for (int i = 0; i < rank; i++)
{
int index = pIndices[i] - Unsafe.Add(ref bounds, rank + i);
int length = Unsafe.Add(ref bounds, i);
if ((uint)index >= (uint)length)
throw new IndexOutOfRangeException();
flattenedIndex = (length * flattenedIndex) + index;
}
if ((uint)flattenedIndex >= (uint)Length)
throw new IndexOutOfRangeException();
ref byte element = ref Unsafe.AddByteOffset(ref GetRawArrayData(), (nuint)flattenedIndex * ElementSize);
EETypePtr pElementEEType = ElementEEType;
if (pElementEEType.IsValueType)
{
// Unlike most callers of InvokeUtils.ChangeType(), Array.SetValue() does *not* permit conversion from a primitive to an Enum.
if (value != null && !(value.EETypePtr == pElementEEType) && pElementEEType.IsEnum)
throw new InvalidCastException(SR.Format(SR.Arg_ObjObjEx, value.GetType(), Type.GetTypeFromHandle(new RuntimeTypeHandle(pElementEEType))));
value = InvokeUtils.CheckArgument(value, pElementEEType, InvokeUtils.CheckArgumentSemantics.ArraySet, binderBundle: null);
Debug.Assert(value == null || RuntimeImports.AreTypesAssignable(value.EETypePtr, pElementEEType));
RuntimeImports.RhUnbox(value, ref element, pElementEEType);
}
else if (pElementEEType.IsPointer)
{
throw new NotSupportedException(SR.NotSupported_Type);
}
else
{
try
{
RuntimeImports.RhCheckArrayStore(this, value);
}
catch (ArrayTypeMismatchException)
{
throw new InvalidCastException(SR.InvalidCast_StoreArrayElement);
}
Unsafe.As<byte, Object>(ref element) = value;
}
}
internal EETypePtr ElementEEType
{
get
{
return this.EETypePtr.ArrayElementType;
}
}
private sealed partial class ArrayEnumerator : IEnumerator, ICloneable
{
public Object Current
{
get
{
if (_index < 0) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_index >= _endIndex) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (_array.ElementEEType.IsPointer) throw new NotSupportedException(SR.NotSupported_Type);
return _array.GetValueWithFlattenedIndex_NoErrorCheck(_index);
}
}
}
//
// Return storage size of an individual element in bytes.
//
internal nuint ElementSize
{
get
{
return EETypePtr.ComponentSize;
}
}
private static int IndexOfImpl<T>(T[] array, T value, int startIndex, int count)
{
// See comment in EqualityComparerHelpers.GetComparerForReferenceTypesOnly for details
EqualityComparer<T> comparer = EqualityComparerHelpers.GetComparerForReferenceTypesOnly<T>();
int endIndex = startIndex + count;
if (comparer != null)
{
for (int i = startIndex; i < endIndex; i++)
{
if (comparer.Equals(array[i], value))
return i;
}
}
else
{
for (int i = startIndex; i < endIndex; i++)
{
if (EqualityComparerHelpers.StructOnlyEquals<T>(array[i], value))
return i;
}
}
return -1;
}
private static int LastIndexOfImpl<T>(T[] array, T value, int startIndex, int count)
{
// See comment in EqualityComparerHelpers.GetComparerForReferenceTypesOnly for details
EqualityComparer<T> comparer = EqualityComparerHelpers.GetComparerForReferenceTypesOnly<T>();
int endIndex = startIndex - count + 1;
if (comparer != null)
{
for (int i = startIndex; i >= endIndex; i--)
{
if (comparer.Equals(array[i], value))
return i;
}
}
else
{
for (int i = startIndex; i >= endIndex; i--)
{
if (EqualityComparerHelpers.StructOnlyEquals<T>(array[i], value))
return i;
}
}
return -1;
}
static void SortImpl(Array keys, Array items, int index, int length, IComparer comparer)
{
IComparer<Object> comparerT = new ComparerAsComparerT(comparer);
Object[] objKeys = keys as Object[];
Object[] objItems = items as Object[];
// Unfortunately, on Project N, we don't have the ability to specialize ArraySortHelper<> on demand
// for value types. Rather than incur a boxing cost on every compare and every swap (and maintain a separate introsort algorithm
// just for this), box them all, sort them as an Object[] array and unbox them back.
// Check if either of the arrays need to be copied.
if (objKeys == null)
{
objKeys = new Object[index + length];
Array.CopyImplValueTypeArrayToReferenceArray(keys, index, objKeys, index, length, reliable: false);
}
if (objItems == null && items != null)
{
objItems = new Object[index + length];
Array.CopyImplValueTypeArrayToReferenceArray(items, index, objItems, index, length, reliable: false);
}
Sort<Object, Object>(objKeys, objItems, index, length, comparerT);
// If either array was copied, copy it back into the original
if (objKeys != keys)
{
Array.CopyImplReferenceArrayToValueTypeArray(objKeys, index, keys, index, length, reliable: false);
}
if (objItems != items)
{
Array.CopyImplReferenceArrayToValueTypeArray(objItems, index, items, index, length, reliable: false);
}
}
}
internal class ArrayEnumeratorBase
{
protected int _index;
protected int _endIndex;
internal ArrayEnumeratorBase()
{
_index = -1;
}
public bool MoveNext()
{
if (_index < _endIndex)
{
_index++;
return (_index < _endIndex);
}
return false;
}
public void Dispose()
{
}
}
//
// Note: the declared base type and interface list also determines what Reflection returns from TypeInfo.BaseType and TypeInfo.ImplementedInterfaces for array types.
// This also means the class must be declared "public" so that the framework can reflect on it.
//
public class Array<T> : Array, IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyList<T>
{
public new IEnumerator<T> GetEnumerator()
{
// get length so we don't have to call the Length property again in ArrayEnumerator constructor
// and avoid more checking there too.
int length = this.Length;
return length == 0 ? ArrayEnumerator.Empty : new ArrayEnumerator(Unsafe.As<T[]>(this), length);
}
public int Count
{
get
{
return this.Length;
}
}
//
// Fun fact:
//
// ((int[])a).IsReadOnly returns false.
// ((IList<int>)a).IsReadOnly returns true.
//
public new bool IsReadOnly
{
get
{
return true;
}
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
T[] array = Unsafe.As<T[]>(this);
return Array.IndexOf(array, item, 0, array.Length) >= 0;
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(Unsafe.As<T[]>(this), 0, array, arrayIndex, this.Length);
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public T this[int index]
{
get
{
try
{
return Unsafe.As<T[]>(this)[index];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
}
set
{
try
{
Unsafe.As<T[]>(this)[index] = value;
}
catch (IndexOutOfRangeException)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
}
}
public int IndexOf(T item)
{
T[] array = Unsafe.As<T[]>(this);
return Array.IndexOf(array, item, 0, array.Length);
}
public void Insert(int index, T item)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
private sealed class ArrayEnumerator : ArrayEnumeratorBase, IEnumerator<T>, ICloneable
{
private T[] _array;
// Passing -1 for endIndex so that MoveNext always returns false without mutating _index
internal static readonly ArrayEnumerator Empty = new ArrayEnumerator(null, -1);
internal ArrayEnumerator(T[] array, int endIndex)
{
_array = array;
_endIndex = endIndex;
}
public T Current
{
get
{
if (_index < 0 || _index >= _endIndex)
throw new InvalidOperationException();
return _array[_index];
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
void IEnumerator.Reset()
{
_index = -1;
}
public object Clone()
{
return MemberwiseClone();
}
}
}
public class MDArray
{
public const int MinRank = 1;
public const int MaxRank = 32;
}
}
| |
// 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 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Insights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AutoscaleSettingsOperations operations.
/// </summary>
internal partial class AutoscaleSettingsOperations : Microsoft.Rest.IServiceOperations<InsightsManagementClient>, IAutoscaleSettingsOperations
{
/// <summary>
/// Initializes a new instance of the AutoscaleSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AutoscaleSettingsOperations(InsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the InsightsManagementClient
/// </summary>
public InsightsManagementClient Client { get; private set; }
/// <summary>
/// Lists the autoscale settings for a resource group
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </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<AutoscaleSettingResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<AutoscaleSettingResource> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<AutoscaleSettingResource>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
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");
}
string apiVersion = "2015-04-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", 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.insights/autoscalesettings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
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<AutoscaleSettingResource>>();
_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<AutoscaleSettingResource>>(_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>
/// Creates or updates an autoscale setting.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='autoscaleSettingName'>
/// The autoscale setting name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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<AutoscaleSettingResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string autoscaleSettingName, AutoscaleSettingResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (autoscaleSettingName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "autoscaleSettingName");
}
if (parameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("autoscaleSettingName", autoscaleSettingName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.insights/autoscalesettings/{autoscaleSettingName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{autoscaleSettingName}", System.Uri.EscapeDataString(autoscaleSettingName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
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("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
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<AutoscaleSettingResource>();
_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<AutoscaleSettingResource>(_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);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AutoscaleSettingResource>(_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>
/// Deletes and autoscale setting
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='autoscaleSettingName'>
/// The autoscale setting name.
/// </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.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> DeleteWithHttpMessagesAsync(string resourceGroupName, string autoscaleSettingName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (autoscaleSettingName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "autoscaleSettingName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("autoscaleSettingName", autoscaleSettingName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.insights/autoscalesettings/{autoscaleSettingName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{autoscaleSettingName}", System.Uri.EscapeDataString(autoscaleSettingName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
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("DELETE");
_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 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new 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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an autoscale setting
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='autoscaleSettingName'>
/// The autoscale setting name.
/// </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<AutoscaleSettingResource>> GetWithHttpMessagesAsync(string resourceGroupName, string autoscaleSettingName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (autoscaleSettingName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "autoscaleSettingName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("resourceGroupName", resourceGroupName);
tracingParameters.Add("autoscaleSettingName", autoscaleSettingName);
tracingParameters.Add("apiVersion", apiVersion);
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.insights/autoscalesettings/{autoscaleSettingName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{autoscaleSettingName}", System.Uri.EscapeDataString(autoscaleSettingName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
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<AutoscaleSettingResource>();
_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<AutoscaleSettingResource>(_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 autoscale settings for a resource group
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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<AutoscaleSettingResource>>> ListByResourceGroupNextWithHttpMessagesAsync(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, "ListByResourceGroupNext", 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<AutoscaleSettingResource>>();
_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<AutoscaleSettingResource>>(_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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml.Schema
{
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using Microsoft.Xml;
using Microsoft.Xml.XPath;
#pragma warning disable 618
internal sealed class DtdValidator : BaseValidator
{
//required by ParseValue
private class NamespaceManager : XmlNamespaceManager
{
public override string LookupNamespace(string prefix) { return prefix; }
}
private static NamespaceManager s_namespaceManager = new NamespaceManager();
private const int STACK_INCREMENT = 10;
private HWStack _validationStack; // validaton contexts
private Hashtable _attPresence;
private XmlQualifiedName _name = XmlQualifiedName.Empty;
private Hashtable _IDs;
private IdRefNode _idRefListHead;
private bool _processIdentityConstraints;
internal DtdValidator(XmlValidatingReaderImpl reader, IValidationEventHandling eventHandling, bool processIdentityConstraints) : base(reader, null, eventHandling)
{
_processIdentityConstraints = processIdentityConstraints;
Init();
}
private void Init()
{
Debug.Assert(reader != null);
_validationStack = new HWStack(STACK_INCREMENT);
textValue = new StringBuilder();
_name = XmlQualifiedName.Empty;
_attPresence = new Hashtable();
schemaInfo = new SchemaInfo();
checkDatatype = false;
Push(_name);
}
public override void Validate()
{
if (schemaInfo.SchemaType == SchemaType.DTD)
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
ValidateElement();
if (reader.IsEmptyElement)
{
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (MeetsStandAloneConstraint())
{
ValidateWhitespace();
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
ValidatePIComment();
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
ValidateText();
break;
case XmlNodeType.EntityReference:
if (!GenEntity(new XmlQualifiedName(reader.LocalName, reader.Prefix)))
{
ValidateText();
}
break;
case XmlNodeType.EndElement:
ValidateEndElement();
break;
}
}
else
{
if (reader.Depth == 0 &&
reader.NodeType == XmlNodeType.Element)
{
SendValidationEvent(ResXml.Xml_NoDTDPresent, _name.ToString(), XmlSeverityType.Warning);
}
}
}
private bool MeetsStandAloneConstraint()
{
if (reader.StandAlone && // VC 1 - iv
context.ElementDecl != null &&
context.ElementDecl.IsDeclaredInExternal &&
context.ElementDecl.ContentValidator.ContentType == XmlSchemaContentType.ElementOnly)
{
SendValidationEvent(ResXml.Sch_StandAlone);
return false;
}
return true;
}
private void ValidatePIComment()
{
// When validating with a dtd, empty elements should be lexically empty.
if (context.NeedValidateChildren)
{
if (context.ElementDecl.ContentValidator == ContentValidator.Empty)
{
SendValidationEvent(ResXml.Sch_InvalidPIComment);
}
}
}
private void ValidateElement()
{
elementName.Init(reader.LocalName, reader.Prefix);
if ((reader.Depth == 0) &&
(!schemaInfo.DocTypeName.IsEmpty) &&
(!schemaInfo.DocTypeName.Equals(elementName)))
{ //VC 1
SendValidationEvent(ResXml.Sch_RootMatchDocType);
}
else
{
ValidateChildElement();
}
ProcessElement();
}
private void ValidateChildElement()
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
if (context.NeedValidateChildren)
{ //i think i can get away with removing this if cond since won't make this call for documentelement
int errorCode = 0;
context.ElementDecl.ContentValidator.ValidateElement(elementName, context, out errorCode);
if (errorCode < 0)
{
XmlSchemaValidator.ElementValidationError(elementName, context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
}
private void ValidateStartElement()
{
if (context.ElementDecl != null)
{
Reader.SchemaTypeObject = context.ElementDecl.SchemaType;
if (Reader.IsEmptyElement && context.ElementDecl.DefaultValueTyped != null)
{
Reader.TypedValueObject = context.ElementDecl.DefaultValueTyped;
context.IsNill = true; // reusing IsNill - what is this flag later used for??
}
if (context.ElementDecl.HasRequiredAttribute)
{
_attPresence.Clear();
}
}
if (Reader.MoveToFirstAttribute())
{
do
{
try
{
reader.SchemaTypeObject = null;
SchemaAttDef attnDef = context.ElementDecl.GetAttDef(new XmlQualifiedName(reader.LocalName, reader.Prefix));
if (attnDef != null)
{
if (context.ElementDecl != null && context.ElementDecl.HasRequiredAttribute)
{
_attPresence.Add(attnDef.Name, attnDef);
}
Reader.SchemaTypeObject = attnDef.SchemaType;
if (attnDef.Datatype != null && !reader.IsDefault)
{ //Since XmlTextReader adds default attributes, do not check again
// set typed value
CheckValue(Reader.Value, attnDef);
}
}
else
{
SendValidationEvent(ResXml.Sch_UndeclaredAttribute, reader.Name);
}
}
catch (XmlSchemaException e)
{
e.SetSource(Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
} while (Reader.MoveToNextAttribute());
Reader.MoveToElement();
}
}
private void ValidateEndStartElement()
{
if (context.ElementDecl.HasRequiredAttribute)
{
try
{
context.ElementDecl.CheckAttributes(_attPresence, Reader.StandAlone);
}
catch (XmlSchemaException e)
{
e.SetSource(Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
}
if (context.ElementDecl.Datatype != null)
{
checkDatatype = true;
hasSibling = false;
textString = string.Empty;
textValue.Length = 0;
}
}
private void ProcessElement()
{
SchemaElementDecl elementDecl = schemaInfo.GetElementDecl(elementName);
Push(elementName);
if (elementDecl != null)
{
context.ElementDecl = elementDecl;
ValidateStartElement();
ValidateEndStartElement();
context.NeedValidateChildren = true;
elementDecl.ContentValidator.InitValidation(context);
}
else
{
SendValidationEvent(ResXml.Sch_UndeclaredElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
context.ElementDecl = null;
}
}
public override void CompleteValidation()
{
if (schemaInfo.SchemaType == SchemaType.DTD)
{
do
{
ValidateEndElement();
} while (Pop());
CheckForwardRefs();
}
}
private void ValidateEndElement()
{
if (context.ElementDecl != null)
{
if (context.NeedValidateChildren)
{
if (!context.ElementDecl.ContentValidator.CompleteValidation(context))
{
XmlSchemaValidator.CompleteValidationError(context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
if (checkDatatype)
{
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
CheckValue(stringValue, null);
checkDatatype = false;
textValue.Length = 0; // cleanup
textString = string.Empty;
}
}
Pop();
}
public override bool PreserveWhitespace
{
get { return context.ElementDecl != null ? context.ElementDecl.ContentValidator.PreserveWhitespace : false; }
}
private void ProcessTokenizedType(
XmlTokenizedType ttype,
string name
)
{
switch (ttype)
{
case XmlTokenizedType.ID:
if (_processIdentityConstraints)
{
if (FindId(name) != null)
{
SendValidationEvent(ResXml.Sch_DupId, name);
}
else
{
AddID(name, context.LocalName);
}
}
break;
case XmlTokenizedType.IDREF:
if (_processIdentityConstraints)
{
object p = FindId(name);
if (p == null)
{ // add it to linked list to check it later
_idRefListHead = new IdRefNode(_idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
}
break;
case XmlTokenizedType.ENTITY:
ProcessEntity(schemaInfo, name, this, EventHandler, Reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
break;
default:
break;
}
}
//check the contents of this attribute to ensure it is valid according to the specified attribute type.
private void CheckValue(string value, SchemaAttDef attdef)
{
try
{
reader.TypedValueObject = null;
bool isAttn = attdef != null;
XmlSchemaDatatype dtype = isAttn ? attdef.Datatype : context.ElementDecl.Datatype;
if (dtype == null)
{
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA)
{
value = value.Trim();
}
object typedValue = dtype.ParseValue(value, NameTable, s_namespaceManager);
reader.TypedValueObject = typedValue;
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY || ttype == XmlTokenizedType.ID || ttype == XmlTokenizedType.IDREF)
{
if (dtype.Variety == XmlSchemaDatatypeVariety.List)
{
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i)
{
ProcessTokenizedType(dtype.TokenizedType, ss[i]);
}
}
else
{
ProcessTokenizedType(dtype.TokenizedType, (string)typedValue);
}
}
SchemaDeclBase decl = isAttn ? (SchemaDeclBase)attdef : (SchemaDeclBase)context.ElementDecl;
if (decl.Values != null && !decl.CheckEnumeration(typedValue))
{
if (dtype.TokenizedType == XmlTokenizedType.NOTATION)
{
SendValidationEvent(ResXml.Sch_NotationValue, typedValue.ToString());
}
else
{
SendValidationEvent(ResXml.Sch_EnumerationValue, typedValue.ToString());
}
}
if (!decl.CheckValue(typedValue))
{
if (isAttn)
{
SendValidationEvent(ResXml.Sch_FixedAttributeValue, attdef.Name.ToString());
}
else
{
SendValidationEvent(ResXml.Sch_FixedElementValue, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
catch (XmlSchemaException)
{
if (attdef != null)
{
SendValidationEvent(ResXml.Sch_AttributeValueDataType, attdef.Name.ToString());
}
else
{
SendValidationEvent(ResXml.Sch_ElementValueDataType, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
internal void AddID(string name, object node)
{
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
if (_IDs == null)
{
_IDs = new Hashtable();
}
_IDs.Add(name, node);
}
public override object FindId(string name)
{
return _IDs == null ? null : _IDs[name];
}
private bool GenEntity(XmlQualifiedName qname)
{
string n = qname.Name;
if (n[0] == '#')
{ // char entity reference
return false;
}
else if (SchemaEntity.IsPredefinedEntity(n))
{
return false;
}
else
{
SchemaEntity en = GetEntity(qname, false);
if (en == null)
{
// well-formness error, see xml spec [68]
throw new XmlException(ResXml.Xml_UndeclaredEntity, n);
}
if (!en.NData.IsEmpty)
{
// well-formness error, see xml spec [68]
throw new XmlException(ResXml.Xml_UnparsedEntityRef, n);
}
if (reader.StandAlone && en.DeclaredInExternal)
{
SendValidationEvent(ResXml.Sch_StandAlone);
}
return true;
}
}
private SchemaEntity GetEntity(XmlQualifiedName qname, bool fParameterEntity)
{
SchemaEntity entity;
if (fParameterEntity)
{
if (schemaInfo.ParameterEntities.TryGetValue(qname, out entity))
{
return entity;
}
}
else
{
if (schemaInfo.GeneralEntities.TryGetValue(qname, out entity))
{
return entity;
}
}
return null;
}
private void CheckForwardRefs()
{
IdRefNode next = _idRefListHead;
while (next != null)
{
if (FindId(next.Id) == null)
{
SendValidationEvent(new XmlSchemaException(ResXml.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos));
}
IdRefNode ptr = next.Next;
next.Next = null; // unhook each object so it is cleaned up by Garbage Collector
next = ptr;
}
// not needed any more.
_idRefListHead = null;
}
private void Push(XmlQualifiedName elementName)
{
context = (ValidationState)_validationStack.Push();
if (context == null)
{
context = new ValidationState();
_validationStack.AddToTop(context);
}
context.LocalName = elementName.Name;
context.Namespace = elementName.Namespace;
context.HasMatched = false;
context.IsNill = false;
context.NeedValidateChildren = false;
}
private bool Pop()
{
if (_validationStack.Length > 1)
{
_validationStack.Pop();
context = (ValidationState)_validationStack.Peek();
return true;
}
return false;
}
public static void SetDefaultTypedValue(
SchemaAttDef attdef,
IDtdParserAdapter readerAdapter
)
{
try
{
string value = attdef.DefaultValueExpanded;
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null)
{
return; // no reason to check
}
if (dtype.TokenizedType != XmlTokenizedType.CDATA)
{
value = value.Trim();
}
attdef.DefaultValueTyped = dtype.ParseValue(value, readerAdapter.NameTable, readerAdapter.NamespaceResolver);
}
#if DEBUG && disabled
catch (XmlSchemaException ex) {
Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, ex.Message);
#else
catch (Exception)
{
#endif
IValidationEventHandling eventHandling = ((IDtdParserAdapterWithValidation)readerAdapter).ValidationEventHandling;
if (eventHandling != null)
{
XmlSchemaException e = new XmlSchemaException(ResXml.Sch_AttributeDefaultDataType, attdef.Name.ToString());
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
public static void CheckDefaultValue(
SchemaAttDef attdef,
SchemaInfo sinfo,
IValidationEventHandling eventHandling,
string baseUriStr
)
{
try
{
if (baseUriStr == null)
{
baseUriStr = string.Empty;
}
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null)
{
return; // no reason to check
}
object typedValue = attdef.DefaultValueTyped;
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY)
{
if (dtype.Variety == XmlSchemaDatatypeVariety.List)
{
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i)
{
ProcessEntity(sinfo, ss[i], eventHandling, baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
}
}
else
{
ProcessEntity(sinfo, (string)typedValue, eventHandling, baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
}
}
else if (ttype == XmlTokenizedType.ENUMERATION)
{
if (!attdef.CheckEnumeration(typedValue))
{
if (eventHandling != null)
{
XmlSchemaException e = new XmlSchemaException(ResXml.Sch_EnumerationValue, typedValue.ToString(), baseUriStr, attdef.ValueLineNumber, attdef.ValueLinePosition);
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
}
#if DEBUG && disabled
catch (XmlSchemaException ex) {
Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, ex.Message);
#else
catch (Exception)
{
#endif
if (eventHandling != null)
{
XmlSchemaException e = new XmlSchemaException(ResXml.Sch_AttributeDefaultDataType, attdef.Name.ToString());
eventHandling.SendEvent(e, XmlSeverityType.Error);
}
}
}
}
#pragma warning restore 618
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using MethodAttributes = System.Reflection.MethodAttributes;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class TypeHelpers
{
internal const BindingFlags MemberBindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
internal static void AppendTypeMembers(
this Type type,
ArrayBuilder<MemberAndDeclarationInfo> includedMembers,
Predicate<MemberInfo> predicate,
Type declaredType,
DkmClrAppDomain appDomain,
bool includeInherited,
bool hideNonPublic,
bool isProxyType)
{
Debug.Assert(!type.IsInterface);
var memberLocation = DeclarationInfo.FromSubTypeOfDeclaredType;
var previousDeclarationMap = includeInherited ? new Dictionary<string, DeclarationInfo>() : null;
int inheritanceLevel = 0;
while (!type.IsObject())
{
if (type.Equals(declaredType))
{
Debug.Assert(memberLocation == DeclarationInfo.FromSubTypeOfDeclaredType);
memberLocation = DeclarationInfo.FromDeclaredTypeOrBase;
}
// Get the state from DebuggerBrowsableAttributes for the members of the current type.
var browsableState = DkmClrType.Create(appDomain, type).GetDebuggerBrowsableAttributeState();
// Hide non-public members if hideNonPublic is specified (intended to reflect the
// DkmInspectionContext's DkmEvaluationFlags), and the type is from an assembly
// with no symbols.
var hideNonPublicBehavior = DeclarationInfo.None;
if (hideNonPublic)
{
var moduleInstance = appDomain.FindClrModuleInstance(type.Module.ModuleVersionId);
if (moduleInstance == null || moduleInstance.Module == null)
{
// Synthetic module or no symbols loaded.
hideNonPublicBehavior = DeclarationInfo.HideNonPublic;
}
}
foreach (var member in type.GetMembers(MemberBindingFlags))
{
// The native EE shows proxy members regardless of accessibility if they have a
// DebuggerBrowsable attribute of any value. Match that behaviour here.
if (!isProxyType || browsableState == null || !browsableState.ContainsKey(member.Name))
{
if (!predicate(member))
{
continue;
}
}
var memberName = member.Name;
// This represents information about the immediately preceding (more derived)
// declaration with the same name as the current member.
var previousDeclaration = DeclarationInfo.None;
var memberNameAlreadySeen = false;
if (includeInherited)
{
memberNameAlreadySeen = previousDeclarationMap.TryGetValue(memberName, out previousDeclaration);
if (memberNameAlreadySeen)
{
// There was a name conflict, so we'll need to include the declaring
// type of the member to disambiguate.
previousDeclaration |= DeclarationInfo.IncludeTypeInMemberName;
}
// Update previous member with name hiding (casting) and declared location information for next time.
previousDeclarationMap[memberName] =
(previousDeclaration & ~(DeclarationInfo.RequiresExplicitCast |
DeclarationInfo.FromSubTypeOfDeclaredType)) |
member.AccessingBaseMemberWithSameNameRequiresExplicitCast() |
memberLocation;
}
Debug.Assert(memberNameAlreadySeen != (previousDeclaration == DeclarationInfo.None));
// Decide whether to include this member in the list of members to display.
if (!memberNameAlreadySeen || previousDeclaration.IsSet(DeclarationInfo.RequiresExplicitCast))
{
DkmClrDebuggerBrowsableAttributeState? browsableStateValue = null;
if (browsableState != null)
{
DkmClrDebuggerBrowsableAttributeState value;
if (browsableState.TryGetValue(memberName, out value))
{
browsableStateValue = value;
}
}
if (memberLocation.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the current type is a sub-type of the declared type, then
// we always need to insert a cast to access the member
previousDeclaration |= DeclarationInfo.RequiresExplicitCast;
}
else if (previousDeclaration.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the immediately preceding member (less derived) was
// declared on a sub-type of the declared type, then we'll
// ignore the casting bit. Accessing a member through the
// declared type is the same as casting to that type, so
// the cast would be redundant.
previousDeclaration &= ~DeclarationInfo.RequiresExplicitCast;
}
previousDeclaration |= hideNonPublicBehavior;
includedMembers.Add(new MemberAndDeclarationInfo(member, browsableStateValue, previousDeclaration, inheritanceLevel));
}
}
if (!includeInherited)
{
break;
}
type = type.BaseType;
inheritanceLevel++;
}
includedMembers.Sort(MemberAndDeclarationInfo.Comparer);
}
private static DeclarationInfo AccessingBaseMemberWithSameNameRequiresExplicitCast(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return DeclarationInfo.RequiresExplicitCast;
case MemberTypes.Property:
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if ((getMethod != null) &&
(!getMethod.IsVirtual || ((getMethod.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot)))
{
return DeclarationInfo.RequiresExplicitCast;
}
return DeclarationInfo.None;
default:
throw ExceptionUtilities.UnexpectedValue(member.MemberType);
}
}
internal static bool IsVisibleMember(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return GetNonIndexerGetMethod((PropertyInfo)member) != null;
}
return false;
}
/// <summary>
/// Returns true if the member is public or protected.
/// </summary>
internal static bool IsPublic(this MemberInfo member)
{
// Matches native EE which includes protected members.
switch (member.MemberType)
{
case MemberTypes.Field:
{
var field = (FieldInfo)member;
var attributes = field.Attributes;
return ((attributes & System.Reflection.FieldAttributes.Public) == System.Reflection.FieldAttributes.Public) ||
((attributes & System.Reflection.FieldAttributes.Family) == System.Reflection.FieldAttributes.Family);
}
case MemberTypes.Property:
{
// Native EE uses the accessibility of the property rather than getter
// so "public object P { private get; set; }" is treated as public.
// Instead, we drop properties if the getter is inaccessible.
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if (getMethod == null)
{
return false;
}
var attributes = getMethod.Attributes;
return ((attributes & System.Reflection.MethodAttributes.Public) == System.Reflection.MethodAttributes.Public) ||
((attributes & System.Reflection.MethodAttributes.Family) == System.Reflection.MethodAttributes.Family);
}
default:
return false;
}
}
private static MethodInfo GetNonIndexerGetMethod(PropertyInfo property)
{
return (property.GetIndexParameters().Length == 0) ?
property.GetGetMethod(nonPublic: true) :
null;
}
internal static bool IsBoolean(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Boolean;
}
internal static bool IsCharacter(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Char;
}
internal static bool IsDecimal(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Decimal;
}
internal static bool IsDateTime(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.DateTime;
}
internal static bool IsObject(this Type type)
{
bool result = type.IsClass && (type.BaseType == null) && !type.IsPointer;
Debug.Assert(result == type.IsMscorlibType("System", "Object"));
return result;
}
internal static bool IsValueType(this Type type)
{
return type.IsMscorlibType("System", "ValueType");
}
internal static bool IsString(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.String;
}
internal static bool IsVoid(this Type type)
{
return type.IsMscorlibType("System", "Void") && !type.IsGenericType;
}
internal static bool IsIEnumerable(this Type type)
{
return type.IsMscorlibType("System.Collections", "IEnumerable");
}
internal static bool IsIEnumerableOfT(this Type type)
{
return type.IsMscorlibType("System.Collections.Generic", "IEnumerable`1");
}
internal static bool IsTypeVariables(this Type type)
{
return type.IsType(null, "<>c__TypeVariables");
}
internal static bool IsComObject(this Type type)
{
return type.IsType("System", "__ComObject");
}
internal static bool IsDynamicProperty(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicProperty");
}
internal static bool IsDynamicDebugViewEmptyException(this Type type)
{
return type.IsType("Microsoft.CSharp.RuntimeBinder", "DynamicDebugViewEmptyException");
}
internal static bool IsIDynamicMetaObjectProvider(this Type type)
{
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsType("System.Dynamic", "IDynamicMetaObjectProvider"))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns type argument if the type is
/// Nullable<T>, otherwise null.
/// </summary>
internal static Type GetNullableTypeArgument(this Type type)
{
if (type.IsMscorlibType("System", "Nullable`1"))
{
var typeArgs = type.GetGenericArguments();
if (typeArgs.Length == 1)
{
return typeArgs[0];
}
}
return null;
}
internal static bool IsNullable(this Type type)
{
return type.GetNullableTypeArgument() != null;
}
internal static DkmClrValue GetFieldValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Field, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, Type nullableTypeArg, DkmInspectionContext inspectionContext)
{
var valueType = value.Type.GetLmrType();
if (valueType.Equals(nullableTypeArg))
{
return value;
}
return value.GetNullableValue(inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(value.Type.GetLmrType().IsNullable());
var hasValue = value.GetFieldValue(InternalWellKnownMemberNames.NullableHasValue, inspectionContext);
if (object.Equals(hasValue.HostObjectValue, false))
{
return null;
}
return value.GetFieldValue(InternalWellKnownMemberNames.NullableValue, inspectionContext);
}
internal const int TupleFieldRestPosition = 8;
private const string TupleTypeNamePrefix = "ValueTuple`";
private const string TupleFieldItemNamePrefix = "Item";
internal const string TupleFieldRestName = "Rest";
// See NamedTypeSymbol.IsTupleCompatible.
internal static bool IsTupleCompatible(this Type type, out int cardinality)
{
if (type.IsGenericType &&
AreNamesEqual(type.Namespace, "System") &&
type.Name.StartsWith(TupleTypeNamePrefix, StringComparison.Ordinal))
{
var typeArguments = type.GetGenericArguments();
int n = typeArguments.Length;
if ((n > 0) && (n <= TupleFieldRestPosition))
{
if (!AreNamesEqual(type.Name, TupleTypeNamePrefix + n))
{
cardinality = 0;
return false;
}
if (n < TupleFieldRestPosition)
{
cardinality = n;
return true;
}
var restType = typeArguments[n - 1];
int restCardinality;
if (restType.IsTupleCompatible(out restCardinality))
{
cardinality = n - 1 + restCardinality;
return true;
}
}
}
cardinality = 0;
return false;
}
// Returns cardinality if tuple type, otherwise 0.
internal static int GetTupleCardinalityIfAny(this Type type)
{
int cardinality;
type.IsTupleCompatible(out cardinality);
return cardinality;
}
internal static FieldInfo GetTupleField(this Type type, string name)
{
return type.GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
}
internal static string GetTupleFieldName(int index)
{
Debug.Assert(index >= 0);
return TupleFieldItemNamePrefix + (index + 1);
}
internal static bool TryGetTupleFieldValues(this DkmClrValue tuple, int cardinality, ArrayBuilder<string> values, DkmInspectionContext inspectionContext)
{
while (true)
{
var type = tuple.Type.GetLmrType();
int n = Math.Min(cardinality, TupleFieldRestPosition - 1);
for (int index = 0; index < n; index++)
{
var fieldName = GetTupleFieldName(index);
var fieldInfo = type.GetTupleField(fieldName);
if (fieldInfo == null)
{
return false;
}
var value = tuple.GetFieldValue(fieldName, inspectionContext);
var str = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
values.Add(str);
}
cardinality -= n;
if (cardinality == 0)
{
return true;
}
var restInfo = type.GetTupleField(TypeHelpers.TupleFieldRestName);
if (restInfo == null)
{
return false;
}
tuple = tuple.GetFieldValue(TupleFieldRestName, inspectionContext);
}
}
internal static Type GetBaseTypeOrNull(this Type underlyingType, DkmClrAppDomain appDomain, out DkmClrType type)
{
Debug.Assert((underlyingType.BaseType != null) || underlyingType.IsPointer || underlyingType.IsArray, "BaseType should only return null if the underlyingType is a pointer or array.");
underlyingType = underlyingType.BaseType;
type = (underlyingType != null) ? DkmClrType.Create(appDomain, underlyingType) : null;
return underlyingType;
}
/// <summary>
/// Get the first attribute from <see cref="DkmClrType.GetEvalAttributes"/> (including inherited attributes)
/// that is of type T, as well as the type that it targeted.
/// </summary>
internal static bool TryGetEvalAttribute<T>(this DkmClrType type, out DkmClrType attributeTarget, out T evalAttribute)
where T : DkmClrEvalAttribute
{
attributeTarget = null;
evalAttribute = null;
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
evalAttribute = attribute as T;
if (evalAttribute != null)
{
attributeTarget = type;
return true;
}
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
return false;
}
/// <summary>
/// Returns the set of DebuggerBrowsableAttribute state for the
/// members of the type, indexed by member name, or null if there
/// are no DebuggerBrowsableAttributes on members of the type.
/// </summary>
private static Dictionary<string, DkmClrDebuggerBrowsableAttributeState> GetDebuggerBrowsableAttributeState(this DkmClrType type)
{
Dictionary<string, DkmClrDebuggerBrowsableAttributeState> result = null;
foreach (var attribute in type.GetEvalAttributes())
{
var browsableAttribute = attribute as DkmClrDebuggerBrowsableAttribute;
if (browsableAttribute == null)
{
continue;
}
if (result == null)
{
result = new Dictionary<string, DkmClrDebuggerBrowsableAttributeState>();
}
result.Add(browsableAttribute.TargetMember, browsableAttribute.State);
}
return result;
}
/// <summary>
/// Extracts information from the first <see cref="DebuggerDisplayAttribute"/> on the runtime type of <paramref name="value"/>, if there is one.
/// </summary>
internal static bool TryGetDebuggerDisplayInfo(this DkmClrValue value, out DebuggerDisplayInfo displayInfo)
{
displayInfo = default(DebuggerDisplayInfo);
// The native EE does not consider DebuggerDisplayAttribute
// on null or error instances.
if (value.IsError() || value.IsNull)
{
return false;
}
var clrType = value.Type;
DkmClrType attributeTarget;
DkmClrDebuggerDisplayAttribute attribute;
if (clrType.TryGetEvalAttribute(out attributeTarget, out attribute)) // First, as in dev12.
{
displayInfo = new DebuggerDisplayInfo(attributeTarget, attribute);
return true;
}
return false;
}
/// <summary>
/// Returns the array of <see cref="DkmCustomUIVisualizerInfo"/> objects of the type from its <see cref="DkmClrDebuggerVisualizerAttribute"/> attributes,
/// or null if the type has no [DebuggerVisualizer] attributes associated with it.
/// </summary>
internal static DkmCustomUIVisualizerInfo[] GetDebuggerCustomUIVisualizerInfo(this DkmClrType type)
{
var builder = ArrayBuilder<DkmCustomUIVisualizerInfo>.GetInstance();
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
var visualizerAttribute = attribute as DkmClrDebuggerVisualizerAttribute;
if (visualizerAttribute == null)
{
continue;
}
builder.Add(DkmCustomUIVisualizerInfo.Create((uint)builder.Count,
visualizerAttribute.VisualizerDescription,
visualizerAttribute.VisualizerDescription,
// ClrCustomVisualizerVSHost is a registry entry that specifies the CLSID of the
// IDebugCustomViewer class that will be instantiated to display the custom visualizer.
"ClrCustomVisualizerVSHost",
visualizerAttribute.UISideVisualizerTypeName,
visualizerAttribute.UISideVisualizerAssemblyName,
visualizerAttribute.UISideVisualizerAssemblyLocation,
visualizerAttribute.DebuggeeSideVisualizerTypeName,
visualizerAttribute.DebuggeeSideVisualizerAssemblyName));
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
var result = (builder.Count > 0) ? builder.ToArray() : null;
builder.Free();
return result;
}
internal static DkmClrType GetProxyType(this DkmClrType type)
{
// CONSIDER: If needed, we could probably compute a new DynamicAttribute for
// the proxy type based on the DynamicAttribute of the argument.
DkmClrType attributeTarget;
DkmClrDebuggerTypeProxyAttribute attribute;
if (type.TryGetEvalAttribute(out attributeTarget, out attribute))
{
var targetedType = attributeTarget.GetLmrType();
var proxyType = attribute.ProxyType;
var underlyingProxy = proxyType.GetLmrType();
if (underlyingProxy.IsGenericType && targetedType.IsGenericType)
{
var typeArgs = targetedType.GetGenericArguments();
// Drop the proxy type if the arity does not match.
if (typeArgs.Length != underlyingProxy.GetGenericArguments().Length)
{
return null;
}
// Substitute target type arguments for proxy type arguments.
var constructedProxy = underlyingProxy.Substitute(underlyingProxy, typeArgs);
proxyType = DkmClrType.Create(type.AppDomain, constructedProxy);
}
return proxyType;
}
return null;
}
/// <summary>
/// Substitute references to type parameters from 'typeDef'
/// with type arguments from 'typeArgs' in type 'type'.
/// </summary>
internal static Type Substitute(this Type type, Type typeDef, Type[] typeArgs)
{
Debug.Assert(typeDef.IsGenericTypeDefinition);
Debug.Assert(typeDef.GetGenericArguments().Length == typeArgs.Length);
if (type.IsGenericType)
{
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var t in type.GetGenericArguments())
{
builder.Add(t.Substitute(typeDef, typeArgs));
}
var typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition.MakeGenericType(builder.ToArrayAndFree());
}
else if (type.IsArray)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
var n = type.GetArrayRank();
return (n == 1) ? elementType.MakeArrayType() : elementType.MakeArrayType(n);
}
else if (type.IsPointer)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
return elementType.MakePointerType();
}
else if (type.IsGenericParameter)
{
if (type.DeclaringType.Equals(typeDef))
{
var ordinal = type.GenericParameterPosition;
return typeArgs[ordinal];
}
}
return type;
}
// Returns the IEnumerable interface implemented by the given type,
// preferring System.Collections.Generic.IEnumerable<T> over
// System.Collections.IEnumerable. If there are multiple implementations
// of IEnumerable<T> on base and derived types, the implementation on
// the most derived type is returned. If there are multiple implementations
// of IEnumerable<T> on the same type, it is undefined which is returned.
internal static Type GetIEnumerableImplementationIfAny(this Type type)
{
var t = type;
do
{
foreach (var @interface in t.GetInterfacesOnType())
{
if (@interface.IsIEnumerableOfT())
{
// Return the first implementation of IEnumerable<T>.
return @interface;
}
}
t = t.BaseType;
} while (t != null);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsIEnumerable())
{
return @interface;
}
}
return null;
}
internal static bool IsEmptyResultsViewException(this Type type)
{
return type.IsType("System.Linq", "SystemCore_EnumerableDebugViewEmptyException");
}
internal static bool IsOrInheritsFrom(this Type type, Type baseType)
{
Debug.Assert(type != null);
Debug.Assert(baseType != null);
Debug.Assert(!baseType.IsInterface);
if (type.IsInterface)
{
return false;
}
do
{
if (type.Equals(baseType))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
private static bool IsMscorlib(this Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0;
}
private static bool IsMscorlibType(this Type type, string @namespace, string name)
{
// Ignore IsMscorlib for now since type.Assembly returns
// System.Runtime.dll for some types in mscorlib.dll.
// TODO: Re-enable commented out check.
return type.IsType(@namespace, name) /*&& type.Assembly.IsMscorlib()*/;
}
internal static bool IsOrInheritsFrom(this Type type, string @namespace, string name)
{
do
{
if (type.IsType(@namespace, name))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
internal static bool IsType(this Type type, string @namespace, string name)
{
Debug.Assert((@namespace == null) || (@namespace.Length > 0)); // Type.Namespace is null not empty.
Debug.Assert(!string.IsNullOrEmpty(name));
return AreNamesEqual(type.Namespace, @namespace) &&
AreNamesEqual(type.Name, name);
}
private static bool AreNamesEqual(string nameA, string nameB)
{
return string.Equals(nameA, nameB, StringComparison.Ordinal);
}
internal static MemberInfo GetOriginalDefinition(this MemberInfo member)
{
var declaringType = member.DeclaringType;
if (!declaringType.IsGenericType)
{
return member;
}
var declaringTypeOriginalDefinition = declaringType.GetGenericTypeDefinition();
if (declaringType.Equals(declaringTypeOriginalDefinition))
{
return member;
}
foreach (var candidate in declaringTypeOriginalDefinition.GetMember(member.Name, MemberBindingFlags))
{
var memberType = candidate.MemberType;
if (memberType != member.MemberType) continue;
switch (memberType)
{
case MemberTypes.Field:
return candidate;
case MemberTypes.Property:
Debug.Assert(((PropertyInfo)member).GetIndexParameters().Length == 0);
if (((PropertyInfo)candidate).GetIndexParameters().Length == 0)
{
return candidate;
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(memberType);
}
}
throw ExceptionUtilities.Unreachable;
}
internal static Type GetInterfaceListEntry(this Type interfaceType, Type declaration)
{
Debug.Assert(interfaceType.IsInterface);
if (!interfaceType.IsGenericType || !declaration.IsGenericType)
{
return interfaceType;
}
var index = Array.IndexOf(declaration.GetInterfacesOnType(), interfaceType);
Debug.Assert(index >= 0);
var result = declaration.GetGenericTypeDefinition().GetInterfacesOnType()[index];
Debug.Assert(interfaceType.GetGenericTypeDefinition().Equals(result.GetGenericTypeDefinition()));
return result;
}
internal static MemberAndDeclarationInfo GetMemberByName(this DkmClrType type, string name)
{
var members = type.GetLmrType().GetMember(name, TypeHelpers.MemberBindingFlags);
Debug.Assert(members.Length == 1);
return new MemberAndDeclarationInfo(members[0], browsableState: null, info: DeclarationInfo.None, inheritanceLevel: 0);
}
}
}
| |
using System.Collections.Generic;
using UnityEngine;
namespace Xft
{
public class Spline
{
public int Granularity = 20;
private List<SplineControlPoint> mControlPoints = new List<SplineControlPoint>();
private List<SplineControlPoint> mSegments = new List<SplineControlPoint>();
public SplineControlPoint AddControlPoint(Vector3 pos, Vector3 up)
{
SplineControlPoint item = new SplineControlPoint();
item.Init(this);
item.Position = pos;
item.Normal = up;
this.mControlPoints.Add(item);
item.ControlPointIndex = this.mControlPoints.Count - 1;
return item;
}
public static Vector3 CatmulRom(Vector3 T0, Vector3 P0, Vector3 P1, Vector3 T1, float f)
{
double num = -0.5;
double num2 = 1.5;
double num3 = -1.5;
double num4 = 0.5;
double num5 = -2.5;
double num6 = 2.0;
double num7 = -0.5;
double num8 = -0.5;
double num9 = 0.5;
double num10 = num * T0.x + num2 * P0.x + num3 * P1.x + num4 * T1.x;
double num11 = T0.x + num5 * P0.x + num6 * P1.x + num7 * T1.x;
double num12 = num8 * T0.x + num9 * P1.x;
double x = P0.x;
double num14 = num * T0.y + num2 * P0.y + num3 * P1.y + num4 * T1.y;
double num15 = T0.y + num5 * P0.y + num6 * P1.y + num7 * T1.y;
double num16 = num8 * T0.y + num9 * P1.y;
double y = P0.y;
double num18 = num * T0.z + num2 * P0.z + num3 * P1.z + num4 * T1.z;
double num19 = T0.z + num5 * P0.z + num6 * P1.z + num7 * T1.z;
double num20 = num8 * T0.z + num9 * P1.z;
double z = P0.z;
float num22 = (float) (((num10 * f + num11) * f + num12) * f + x);
float num23 = (float) (((num14 * f + num15) * f + num16) * f + y);
return new Vector3(num22, num23, (float) (((num18 * f + num19) * f + num20) * f + z));
}
public void Clear()
{
this.mControlPoints.Clear();
}
public Vector3 InterpolateByLen(float tl)
{
float num;
return this.LenToSegment(tl, out num).Interpolate(num);
}
public Vector3 InterpolateNormalByLen(float tl)
{
float num;
return this.LenToSegment(tl, out num).InterpolateNormal(num);
}
public SplineControlPoint LenToSegment(float t, out float localF)
{
SplineControlPoint point = null;
t = Mathf.Clamp01(t);
float num = t * this.mSegments[this.mSegments.Count - 1].Dist;
int num2 = 0;
num2 = 0;
while (num2 < this.mSegments.Count)
{
if (this.mSegments[num2].Dist >= num)
{
point = this.mSegments[num2];
break;
}
num2++;
}
if (num2 == 0)
{
localF = 0f;
return point;
}
float num3 = 0f;
int num4 = point.SegmentIndex - 1;
SplineControlPoint point2 = this.mSegments[num4];
num3 = point.Dist - point2.Dist;
localF = (num - point2.Dist) / num3;
return point2;
}
public SplineControlPoint NextControlPoint(SplineControlPoint controlpoint)
{
if (this.mControlPoints.Count == 0)
{
return null;
}
int num = controlpoint.ControlPointIndex + 1;
if (num >= this.mControlPoints.Count)
{
return null;
}
return this.mControlPoints[num];
}
public Vector3 NextNormal(SplineControlPoint controlpoint)
{
SplineControlPoint point = this.NextControlPoint(controlpoint);
if (point != null)
{
return point.Normal;
}
return controlpoint.Normal;
}
public Vector3 NextPosition(SplineControlPoint controlpoint)
{
SplineControlPoint point = this.NextControlPoint(controlpoint);
if (point != null)
{
return point.Position;
}
return controlpoint.Position;
}
public SplineControlPoint PreviousControlPoint(SplineControlPoint controlpoint)
{
if (this.mControlPoints.Count == 0)
{
return null;
}
int num = controlpoint.ControlPointIndex - 1;
if (num < 0)
{
return null;
}
return this.mControlPoints[num];
}
public Vector3 PreviousNormal(SplineControlPoint controlpoint)
{
SplineControlPoint point = this.PreviousControlPoint(controlpoint);
if (point != null)
{
return point.Normal;
}
return controlpoint.Normal;
}
public Vector3 PreviousPosition(SplineControlPoint controlpoint)
{
SplineControlPoint point = this.PreviousControlPoint(controlpoint);
if (point != null)
{
return point.Position;
}
return controlpoint.Position;
}
private void RefreshDistance()
{
if (this.mSegments.Count >= 1)
{
this.mSegments[0].Dist = 0f;
for (int i = 1; i < this.mSegments.Count; i++)
{
Vector3 vector = this.mSegments[i].Position - this.mSegments[i - 1].Position;
float magnitude = vector.magnitude;
this.mSegments[i].Dist = this.mSegments[i - 1].Dist + magnitude;
}
}
}
public void RefreshSpline()
{
this.mSegments.Clear();
for (int i = 0; i < this.mControlPoints.Count; i++)
{
if (this.mControlPoints[i].IsValid)
{
this.mSegments.Add(this.mControlPoints[i]);
this.mControlPoints[i].SegmentIndex = this.mSegments.Count - 1;
}
}
this.RefreshDistance();
}
public List<SplineControlPoint> ControlPoints
{
get
{
return this.mControlPoints;
}
}
public SplineControlPoint this[int index]
{
get
{
if (index > -1 && index < this.mSegments.Count)
{
return this.mSegments[index];
}
return null;
}
}
public List<SplineControlPoint> Segments
{
get
{
return this.mSegments;
}
}
}
}
| |
using System;
namespace Glimpse.Core.Extensibility
{
/// <summary>
/// An abstract base class which provides <see cref="ILogger"/> implementations with message formatting abilities.
/// </summary>
public abstract class LoggerBase : ILogger
{
/// <summary>
/// Log message at Trace level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Trace(string message);
/// <summary>
/// Log message at Debug level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Debug(string message);
/// <summary>
/// Log message at Info level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Info(string message);
/// <summary>
/// Log message at Warn level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Warn(string message);
/// <summary>
/// Log message at Error level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Error(string message);
/// <summary>
/// Log message at Fatal level.
/// </summary>
/// <param name="message">The message.</param>
public abstract void Fatal(string message);
/// <summary>
/// Log message at Trace level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Trace(string message, Exception exception);
/// <summary>
/// Log message at Debug level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Debug(string message, Exception exception);
/// <summary>
/// Log message at Info level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Info(string message, Exception exception);
/// <summary>
/// Log message at Warn level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Warn(string message, Exception exception);
/// <summary>
/// Log message at Error level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Error(string message, Exception exception);
/// <summary>
/// Log message at Fatal level.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public abstract void Fatal(string message, Exception exception);
/// <summary>
/// Log message at Trace level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Trace(string messageFormat, params object[] args)
{
Trace(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Debug level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Debug(string messageFormat, params object[] args)
{
Debug(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Info level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Info(string messageFormat, params object[] args)
{
Info(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Warn level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Warn(string messageFormat, params object[] args)
{
Warn(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Error level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Error(string messageFormat, params object[] args)
{
Error(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Fatal level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="args">The args.</param>
public void Fatal(string messageFormat, params object[] args)
{
Fatal(string.Format(messageFormat, args));
}
/// <summary>
/// Log message at Trace level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Trace(string messageFormat, Exception exception, params object[] args)
{
Trace(string.Format(messageFormat, args), exception);
}
/// <summary>
/// Log message at Debug level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Debug(string messageFormat, Exception exception, params object[] args)
{
Debug(string.Format(messageFormat, args), exception);
}
/// <summary>
/// Log message at Info level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Info(string messageFormat, Exception exception, params object[] args)
{
Info(string.Format(messageFormat, args), exception);
}
/// <summary>
/// Log message at Warn level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Warn(string messageFormat, Exception exception, params object[] args)
{
Warn(string.Format(messageFormat, args), exception);
}
/// <summary>
/// Log message at Error level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Error(string messageFormat, Exception exception, params object[] args)
{
Error(string.Format(messageFormat, args), exception);
}
/// <summary>
/// Log message at Fatal level.
/// </summary>
/// <param name="messageFormat">The message format.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">The args.</param>
public void Fatal(string messageFormat, Exception exception, params object[] args)
{
Fatal(string.Format(messageFormat, args), exception);
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using NUnit.Framework;
namespace MindTouch.Deki.Tests {
[TestFixture]
public class TitleTests {
#region WithUserFriendlyName
[Test]
public void WithUserFriendlyName_child_subpage_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_spaces_in_child_subpage_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("sister brother");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("sister_brother", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_child_subpage_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_spaces_in_child_subpage_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("sister brother");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/sister_brother", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_user_prefixed_subpage_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("user:child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/user:child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_user_prefixed_subpage_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("user:child");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_slash_in_chid_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("brother/sister");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/brother//sister", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_trailing_slash_in_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("child/");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
[ExpectedException(ExceptionType = typeof(ArgumentException), ExpectedMessage = "resulting title object is invalid: parent///child\r\nParameter name: name")]
public void WithUserFriendlyName_leading_slash_in_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("/child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_unknown_prefixed_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("unknown:child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("unknown:child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_double_slash_in_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("brother//sister");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("brother////sister", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_leading_underscore_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("_child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_trailing_underscore_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("child_");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_leading_underscore_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("_child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_trailing_underscore_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("child_");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_leading_space_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName(" child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_trailing_space_child_page_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = title.WithUserFriendlyName("child ");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_leading_space_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName(" child");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
[Test]
public void WithUserFriendlyName_trailing_space_child_page_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = title.WithUserFriendlyName("child ");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/child", title.AsUnprefixedDbPath());
}
#endregion
#region FromUIUsername
[Test]
public void FromUIUsername_simple_name() {
Title title = Title.FromUIUsername("bob");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("bob", title.AsUnprefixedDbPath());
}
[Test]
public void FromUIUsername_name_with_slash() {
Title title = Title.FromUIUsername("bob/alex");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("bob//alex", title.AsUnprefixedDbPath());
}
[Test]
public void FromUIUsername_name_with_talk_namespace() {
Title title = Title.FromUIUsername("talk:bob");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("talk:bob", title.AsUnprefixedDbPath());
}
[Test]
public void FromUIUsername_name_with_spaces() {
Title title = Title.FromUIUsername("talk:john doe");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("talk:john_doe", title.AsUnprefixedDbPath());
}
[Test]
[ExpectedException(ExceptionType = typeof(ArgumentException), ExpectedMessage = "username is empty\r\nParameter name: username")]
public void FromUIUsername_missing_name() {
Title title = Title.FromUIUsername("");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("", title.AsUnprefixedDbPath());
}
#endregion
#region GetParent
[Test]
public void GetParent_UserNamespace() {
Title title = Title.FromPrefixedDbPath("user:foo/bar", null);
Assert.AreEqual(Title.FromPrefixedDbPath("user:foo", null), title.GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent().GetParent());
}
[Test]
public void GetParent_TemplateNamespace() {
Title title = Title.FromPrefixedDbPath("template:foo/bar", null);
Assert.AreEqual(Title.FromPrefixedDbPath("template:foo", null), title.GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent().GetParent());
}
[Test]
public void GetParent_SpecialNamespace() {
Title title = Title.FromPrefixedDbPath("special:foo/bar", null);
Assert.AreEqual(Title.FromPrefixedDbPath("special:foo", null), title.GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("special:", null), title.GetParent().GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent().GetParent().GetParent());
}
[Test]
[Ignore] // TODO (steveb): re-enable once Title bug relating to Help:/Project: pages is fixed
public void GetParent_ProjectNamesapce() {
Title title = Title.FromPrefixedDbPath("project:foo", null);
Assert.AreEqual(Title.FromPrefixedDbPath("project:", null), title.GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent().GetParent());
}
[Test]
[Ignore] // TODO (steveb): re-enable once Title bug relating to Help:/Project: pages is fixed
public void GetParent_HelpNamesapce() {
Title title = Title.FromPrefixedDbPath("help:foo", null);
Assert.AreEqual(Title.FromPrefixedDbPath("help:", null), title.GetParent());
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent().GetParent());
}
[Test]
public void GetParent_MainNamesapce() {
Title title = Title.FromPrefixedDbPath("main:foo", null);
Assert.AreEqual(Title.FromPrefixedDbPath("", null), title.GetParent());
Assert.AreEqual(null, title.GetParent().GetParent());
}
#endregion
#region FromUriPath
[Test]
public void FromUriPath_page_subpage_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = Title.FromUIUri(title, "page");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("page", title.AsUnprefixedDbPath());
}
[Test]
public void FromUriPath_page_subpage_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = Title.FromUIUri(title, "page");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("page", title.AsUnprefixedDbPath());
}
[Test]
public void FromUriPath_user_prefixed_subpage_of_parent_page() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = Title.FromUIUri(title, "user:page");
Assert.AreEqual(NS.USER, title.Namespace);
Assert.AreEqual("page", title.AsUnprefixedDbPath());
}
[Test]
public void FromUriPath_relative_subpage_of_homepage() {
Title title = Title.FromPrefixedDbPath("", null);
title = Title.FromUIUri(title, "./page");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("page", title.AsUnprefixedDbPath());
}
[Test]
public void FromUriPath_relative_subpage_of_parentpage() {
Title title = Title.FromPrefixedDbPath("parent", null);
title = Title.FromUIUri(title, "./page");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/page", title.AsUnprefixedDbPath());
}
[Test]
public void FromUriPath_relative_subsubpage_of_parentpage() {
Title title = Title.FromPrefixedDbPath("parent/subpage", null);
title = Title.FromUIUri(title, "../page");
Assert.AreEqual(NS.MAIN, title.Namespace);
Assert.AreEqual("parent/page", title.AsUnprefixedDbPath());
}
#endregion
#region AsFront
[Test]
public void AsFront_main() {
Title title = Title.FromPrefixedDbPath("page", null);
Assert.AreEqual("page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_main_talk() {
Title title = Title.FromPrefixedDbPath("talk:page", null);
Assert.AreEqual("page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_user() {
Title title = Title.FromPrefixedDbPath("user:page", null);
Assert.AreEqual("User:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("User_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_user_talk() {
Title title = Title.FromPrefixedDbPath("user_talk:page", null);
Assert.AreEqual("User:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("User_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_project() {
Title title = Title.FromPrefixedDbPath("project:page", null);
Assert.AreEqual("Project:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Project_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_project_talk() {
Title title = Title.FromPrefixedDbPath("project_talk:page", null);
Assert.AreEqual("Project:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Project_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_template() {
Title title = Title.FromPrefixedDbPath("template:page", null);
Assert.AreEqual("Template:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Template_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_template_talk() {
Title title = Title.FromPrefixedDbPath("template_talk:page", null);
Assert.AreEqual("Template:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Template_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_help() {
Title title = Title.FromPrefixedDbPath("help:page", null);
Assert.AreEqual("Help:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Help_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_help_talk() {
Title title = Title.FromPrefixedDbPath("help_talk:page", null);
Assert.AreEqual("Help:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Help_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_special() {
Title title = Title.FromPrefixedDbPath("special:page", null);
Assert.AreEqual("Special:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Special_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_special_talk() {
Title title = Title.FromPrefixedDbPath("special_talk:page", null);
Assert.AreEqual("Special:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual("Special_talk:page", title.AsTalk().AsPrefixedDbPath());
}
[Test]
public void AsFront_admin() {
Title title = Title.FromPrefixedDbPath("Admin:page", null);
Assert.AreEqual("Admin:page", title.AsFront().AsPrefixedDbPath());
Assert.AreEqual(null, title.AsTalk());
}
#endregion
#region Rename
[Test]
public void Rename_OneSegment() {
Assert.AreEqual("bar", Title.FromPrefixedDbPath("foo", null)
.Rename("bar", null)
.AsPrefixedDbPath());
Assert.AreEqual("Special:bar", Title.FromPrefixedDbPath("Special:foo", null)
.Rename("bar", null)
.AsPrefixedDbPath());
Assert.AreEqual("Template:bar", Title.FromPrefixedDbPath("Template:foo", null)
.Rename("bar", null)
.AsPrefixedDbPath());
Assert.AreEqual("Special:bar", Title.FromPrefixedDbPath("Special:foo", null)
.Rename("special:bar", null)
.AsPrefixedDbPath());
}
[Test]
public void Rename_OneSegmentPrefixed() {
Assert.AreEqual("Special:bar", Title.FromPrefixedDbPath("Special:foo", null)
.Rename("Special:bar", null)
.AsPrefixedDbPath());
}
[Test]
public void Rename_MultiSegment() {
Assert.AreEqual("a/c", Title.FromPrefixedDbPath("a/b", null)
.Rename("c", null)
.AsPrefixedDbPath());
Assert.AreEqual("Special:a/c", Title.FromPrefixedDbPath("Special:a/b", null)
.Rename("c", null)
.AsPrefixedDbPath());
Assert.AreEqual("Special:a/special:c", Title.FromPrefixedDbPath("Special:a/b", null)
.Rename("special:c", null)
.AsPrefixedDbPath());
}
[Test]
public void Rename_CrossNamespaceAttempt() {
Assert.AreEqual("Special:Template:bar", Title.FromPrefixedDbPath("Special:foo", null)
.Rename("Template:bar", null)
.AsPrefixedDbPath());
}
[Test]
[ExpectedException(ExceptionType = typeof(ArgumentException))]
public void Rename_CrossNamespaceAttempt_illegal() {
string s = Title.FromPrefixedDbPath("foo", null)
.Rename("Template:bar", null)
.AsPrefixedDbPath();
}
[Test]
public void Rename_RootPageTitles() {
Title t = null;
t = Title.FromPrefixedDbPath(string.Empty, null);
t = t.Rename(null, "foo");
Assert.IsTrue(t.IsHomepage);
Assert.AreEqual("foo", t.DisplayName);
Assert.AreEqual(string.Empty, t.AsPrefixedDbPath());
t = Title.FromPrefixedDbPath("Special:", null);
t = t.Rename(null, "foo");
Assert.AreEqual("foo", t.DisplayName);
Assert.AreEqual("Special:", t.AsPrefixedDbPath());
t = Title.FromPrefixedDbPath("User:", null);
t = t.Rename(null, "foo");
Assert.AreEqual("foo", t.DisplayName);
Assert.AreEqual("User:", t.AsPrefixedDbPath());
}
[Test]
public void Rename_TitleEncoding() {
// % handling
Title t = TestTitle(Title.FromPrefixedDbPath("A", null), null, "a%b", "a%25b", "a%b");
Assert.IsTrue(t.GetParent().IsHomepage);
// space handling
t = TestTitle(Title.FromPrefixedDbPath("A", null), null, "a b", "a_b", "a b");
// single slash
t = TestTitle(Title.FromPrefixedDbPath("A", null), null, "a/b", "a//b", "a/b");
// double slash
t = TestTitle(Title.FromPrefixedDbPath("A", null), null, "a//b", "a////b", "a//b");
// triple slash
t = TestTitle(Title.FromPrefixedDbPath("A", null), null, "a///b", "a//////b", "a///b");
// %25
TestTitle(Title.FromPrefixedDbPath("A", null), null, "a%25b", "a%25b", "a%25b");
}
[Test]
[Ignore("Displaynames containing characters that change as a result of Xuri.Decode get incorrent renamed path segments")]
public void RenameTitleEncodingWithPercentEncoding() {
// %2f
TestTitle(Title.FromPrefixedDbPath("A", null), null, "a%2fb", "a%2fb", "a%2fb");
// %2b (fails due to %2b being changed to %2B
TestTitle(Title.FromPrefixedDbPath("A", null), null, "a%2bb", "a%2bb", "a%2bb");
}
#endregion
private static Title TestTitle(Title t, string newName, string newDisplayName, string resultPrefixedDbPath, string resultDisplayName) {
t = t.Rename(newName, newDisplayName);
Assert.AreEqual(resultDisplayName, t.DisplayName);
Assert.AreEqual(resultPrefixedDbPath, t.AsPrefixedDbPath());
return t;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using LumiSoft.Net.SIP.Message;
using LumiSoft.Net.SIP.Stack;
using LumiSoft.Net.AUTH;
namespace LumiSoft.Net.SIP.Proxy
{
/// <summary>
/// This class represents B2BUA call.
/// </summary>
public class SIP_B2BUA_Call
{
private SIP_B2BUA m_pOwner = null;
private DateTime m_StartTime;
private SIP_Dialog m_pCaller = null;
private SIP_Dialog m_pCallee = null;
private string m_CallID = "";
private bool m_IsTerminated = false;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="owner">Owner B2BUA server.</param>
/// <param name="caller">Caller side dialog.</param>
/// <param name="callee">Callee side dialog.</param>
internal SIP_B2BUA_Call(SIP_B2BUA owner,SIP_Dialog caller,SIP_Dialog callee)
{
m_pOwner = owner;
m_pCaller = caller;
m_pCallee = callee;
m_StartTime = DateTime.Now;
m_CallID = Guid.NewGuid().ToString().Replace("-","");
//m_pCaller.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCaller_RequestReceived);
//m_pCaller.Terminated += new EventHandler(m_pCaller_Terminated);
//m_pCallee.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCallee_RequestReceived);
//m_pCallee.Terminated += new EventHandler(m_pCallee_Terminated);
}
#region Events Handling
#region method m_pCaller_RequestReceived
/// <summary>
/// Is called when caller sends new request.
/// </summary>
/// <param name="e">Event data.</param>
private void m_pCaller_RequestReceived(SIP_RequestReceivedEventArgs e)
{
// TODO: If we get UPDATE, but callee won't support it ? generate INVITE instead ?
/*
SIP_Request request = m_pCallee.CreateRequest(e.Request.RequestLine.Method);
CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"});
// Remove our Authentication header if it's there.
foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){
try{
Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method);
if(m_pOwner.Stack.Realm == digest.Realm){
request.ProxyAuthorization.Remove(header);
}
}
catch{
// We don't care errors here. This can happen if remote server xxx auth method here and
// we don't know how to parse it, so we leave it as is.
}
}
SIP_ClientTransaction clientTransaction = m_pCallee.CreateTransaction(request);
clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCallee_ResponseReceived);
clientTransaction.Tag = e.ServerTransaction;
clientTransaction.Start();*/
}
#endregion
#region method m_pCaller_Terminated
/// <summary>
/// This method is called when caller dialog has terminated, normally this happens
/// when dialog gets BYE request.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCaller_Terminated(object sender,EventArgs e)
{
Terminate();
}
#endregion
#region method m_pCallee_ResponseReceived
/// <summary>
/// This method is called when callee dialog client transaction receives response.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCallee_ResponseReceived(object sender,SIP_ResponseReceivedEventArgs e)
{
SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction)e.ClientTransaction.Tag;
//SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase);
//CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"});
//serverTransaction.SendResponse(response);
}
#endregion
#region method m_pCallee_RequestReceived
/// <summary>
/// Is called when callee sends new request.
/// </summary>
/// <param name="e">Event data.</param>
private void m_pCallee_RequestReceived(SIP_RequestReceivedEventArgs e)
{ /*
SIP_Request request = m_pCaller.CreateRequest(e.Request.RequestLine.Method);
CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"});
// Remove our Authentication header if it's there.
foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){
try{
Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method);
if(m_pOwner.Stack.Realm == digest.Realm){
request.ProxyAuthorization.Remove(header);
}
}
catch{
// We don't care errors here. This can happen if remote server xxx auth method here and
// we don't know how to parse it, so we leave it as is.
}
}
SIP_ClientTransaction clientTransaction = m_pCaller.CreateTransaction(request);
clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCaller_ResponseReceived);
clientTransaction.Tag = e.ServerTransaction;
clientTransaction.Start();*/
}
#endregion
#region method m_pCalee_Terminated
/// <summary>
/// This method is called when callee dialog has terminated, normally this happens
/// when dialog gets BYE request.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCallee_Terminated(object sender,EventArgs e)
{
Terminate();
}
#endregion
#region method m_pCaller_ResponseReceived
/// <summary>
/// This method is called when caller dialog client transaction receives response.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCaller_ResponseReceived(object sender,SIP_ResponseReceivedEventArgs e)
{
SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction)e.ClientTransaction.Tag;
//SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase);
//CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"});
//serverTransaction.SendResponse(response);
}
#endregion
#endregion
#region method Terminate
/// <summary>
/// Terminates call.
/// </summary>
public void Terminate()
{
if(m_IsTerminated){
return;
}
m_IsTerminated = true;
m_pOwner.RemoveCall(this);
if(m_pCaller != null){
//m_pCaller.Terminate();
m_pCaller.Dispose();
m_pCaller = null;
}
if(m_pCallee != null){
//m_pCallee.Terminate();
m_pCallee.Dispose();
m_pCallee = null;
}
m_pOwner.OnCallTerminated(this);
}
#endregion
#region method CallTransfer
/*
/// <summary>
/// Transfers call to specified recipient.
/// </summary>
/// <param name="to">Address where to transfer call.</param>
public void CallTransfer(string to)
{
throw new NotImplementedException();
}*/
#endregion
#region method CopyMessage
/// <summary>
/// Copies header fileds from 1 message to antother.
/// </summary>
/// <param name="source">Source message.</param>
/// <param name="destination">Destination message.</param>
/// <param name="exceptHeaders">Header fields not to copy.</param>
private void CopyMessage(SIP_Message source,SIP_Message destination,string[] exceptHeaders)
{
foreach(SIP_HeaderField headerField in source.Header){
bool copy = true;
foreach(string h in exceptHeaders){
if(h.ToLower() == headerField.Name.ToLower()){
copy = false;
break;
}
}
if(copy){
destination.Header.Add(headerField.Name,headerField.Value);
}
}
destination.Data = source.Data;
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets call start time.
/// </summary>
public DateTime StartTime
{
get{ return m_StartTime; }
}
/// <summary>
/// Gets current call ID.
/// </summary>
public string CallID
{
get{ return m_CallID; }
}
/// <summary>
/// Gets caller SIP dialog.
/// </summary>
public SIP_Dialog CallerDialog
{
get{ return m_pCaller; }
}
/// <summary>
/// Gets callee SIP dialog.
/// </summary>
public SIP_Dialog CalleeDialog
{
get{ return m_pCallee; }
}
/// <summary>
/// Gets if call has timed out and needs to be terminated.
/// </summary>
public bool IsTimedOut
{
// TODO:
get{ return false; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderedHashRepartitionEnumerator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator handles the actual coordination among partitions required to
/// accomplish the repartitioning operation, as explained above. In addition to that,
/// it tracks order keys so that order preservation can flow through the enumerator.
/// </summary>
/// <typeparam name="TInputOutput">The kind of elements.</typeparam>
/// <typeparam name="THashKey">The key used to distribute elements.</typeparam>
/// <typeparam name="TOrderKey">The kind of keys found in the source.</typeparam>
internal class OrderedHashRepartitionEnumerator<TInputOutput, THashKey, TOrderKey> : QueryOperatorEnumerator<Pair, TOrderKey>
{
private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet.
private readonly int _partitionCount; // The number of partitions.
private readonly int _partitionIndex; // Our unique partition index.
private readonly Func<TInputOutput, THashKey> _keySelector; // A key-selector function.
private readonly HashRepartitionStream<TInputOutput, THashKey, TOrderKey> _repartitionStream; // A repartitioning stream.
private readonly ListChunk<Pair>[][] _valueExchangeMatrix; // Matrix to do inter-task communication of values.
private readonly ListChunk<TOrderKey>[][] _keyExchangeMatrix; // Matrix to do inter-task communication of order keys.
private readonly QueryOperatorEnumerator<TInputOutput, TOrderKey> _source; // The immediate source of data.
private CountdownEvent _barrier; // Used to signal and wait for repartitions to complete.
private readonly CancellationToken _cancellationToken; // A token for canceling the process.
private Mutables _mutables; // Mutable fields for this enumerator.
class Mutables
{
internal int _currentBufferIndex; // Current buffer index.
internal ListChunk<Pair> _currentBuffer; // The buffer we're currently enumerating.
internal ListChunk<TOrderKey> _currentKeyBuffer; // The buffer we're currently enumerating.
internal int _currentIndex; // Current index into the buffer.
internal Mutables()
{
_currentBufferIndex = ENUMERATION_NOT_STARTED;
}
}
//---------------------------------------------------------------------------------------
// Creates a new repartitioning enumerator.
//
// Arguments:
// source - the data stream from which to pull elements
// useOrdinalOrderPreservation - whether order preservation is required
// partitionCount - total number of partitions
// partitionIndex - this operator's unique partition index
// repartitionStream - the stream object to use for partition selection
// barrier - a latch used to signal task completion
// buffers - a set of buffers for inter-task communication
//
internal OrderedHashRepartitionEnumerator(
QueryOperatorEnumerator<TInputOutput, TOrderKey> source, int partitionCount, int partitionIndex,
Func<TInputOutput, THashKey> keySelector, OrderedHashRepartitionStream<TInputOutput, THashKey, TOrderKey> repartitionStream, CountdownEvent barrier,
ListChunk<Pair>[][] valueExchangeMatrix, ListChunk<TOrderKey>[][] keyExchangeMatrix, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired));
Debug.Assert(repartitionStream != null);
Debug.Assert(barrier != null);
Debug.Assert(valueExchangeMatrix != null);
Debug.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(partitionCount > 0 && valueExchangeMatrix[0].Length == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount);
_source = source;
_partitionCount = partitionCount;
_partitionIndex = partitionIndex;
_keySelector = keySelector;
_repartitionStream = repartitionStream;
_barrier = barrier;
_valueExchangeMatrix = valueExchangeMatrix;
_keyExchangeMatrix = keyExchangeMatrix;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Retrieves the next element from this partition. All repartitioning operators across
// all partitions cooperate in a barrier-style algorithm. The first time an element is
// requested, the repartitioning operator will enter the 1st phase: during this phase, it
// scans its entire input and compute the destination partition for each element. During
// the 2nd phase, each partition scans the elements found by all other partitions for
// it, and yield this to callers. The only synchronization required is the barrier itself
// -- all other parts of this algorithm are synchronization-free.
//
// Notes: One rather large penalty that this algorithm incurs is higher memory usage and a
// larger time-to-first-element latency, at least compared with our old implementation; this
// happens because all input elements must be fetched before we can produce a single output
// element. In many cases this isn't too terrible: e.g. a GroupBy requires this to occur
// anyway, so having the repartitioning operator do so isn't complicating matters much at all.
//
internal override bool MoveNext(ref Pair currentElement, ref TOrderKey currentKey)
{
if (_partitionCount == 1)
{
TInputOutput current = default(TInputOutput);
// If there's only one partition, no need to do any sort of exchanges.
if (_source.MoveNext(ref current, ref currentKey))
{
currentElement = new Pair(
current, _keySelector == null ? default(THashKey) : _keySelector(current));
return true;
}
return false;
}
Mutables mutables = _mutables;
if (mutables == null)
mutables = _mutables = new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
if (mutables._currentBufferIndex == ENUMERATION_NOT_STARTED)
{
EnumerateAndRedistributeElements();
Debug.Assert(mutables._currentBufferIndex != ENUMERATION_NOT_STARTED);
}
// Once we've enumerated our contents, we can then go back and walk the buffers that belong
// to the current partition. This is phase two. Note that we slyly move on to the first step
// of phase two before actually waiting for other partitions. That's because we can enumerate
// the buffer we wrote to above, as already noted.
while (mutables._currentBufferIndex < _partitionCount)
{
// If the queue is non-null and still has elements, yield them.
if (mutables._currentBuffer != null)
{
Debug.Assert(mutables._currentKeyBuffer != null);
if (++mutables._currentIndex < mutables._currentBuffer.Count)
{
// Return the current element.
currentElement = mutables._currentBuffer._chunk[mutables._currentIndex];
Debug.Assert(mutables._currentKeyBuffer != null, "expected same # of buffers/key-buffers");
currentKey = mutables._currentKeyBuffer._chunk[mutables._currentIndex];
return true;
}
else
{
// If the chunk is empty, advance to the next one (if any).
mutables._currentIndex = ENUMERATION_NOT_STARTED;
mutables._currentBuffer = mutables._currentBuffer.Next;
mutables._currentKeyBuffer = mutables._currentKeyBuffer.Next;
Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count > 0);
Debug.Assert((mutables._currentBuffer == null) == (mutables._currentKeyBuffer == null));
Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count == mutables._currentKeyBuffer.Count);
continue; // Go back around and invoke this same logic.
}
}
// We're done with the current partition. Slightly different logic depending on whether
// we're on our own buffer or one that somebody else found for us.
if (mutables._currentBufferIndex == _partitionIndex)
{
// We now need to wait at the barrier, in case some other threads aren't done.
// Once we wake up, we reset our index and will increment it immediately after.
_barrier.Wait(_cancellationToken);
mutables._currentBufferIndex = ENUMERATION_NOT_STARTED;
}
// Advance to the next buffer.
mutables._currentBufferIndex++;
mutables._currentIndex = ENUMERATION_NOT_STARTED;
if (mutables._currentBufferIndex == _partitionIndex)
{
// Skip our current buffer (since we already enumerated it).
mutables._currentBufferIndex++;
}
// Assuming we're within bounds, retrieve the next buffer object.
if (mutables._currentBufferIndex < _partitionCount)
{
mutables._currentBuffer = _valueExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
mutables._currentKeyBuffer = _keyExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
}
}
// We're done. No more buffers to enumerate.
return false;
}
//---------------------------------------------------------------------------------------
// Called when this enumerator is first enumerated; it must walk through the source
// and redistribute elements to their slot in the exchange matrix.
//
private void EnumerateAndRedistributeElements()
{
Mutables mutables = _mutables;
Debug.Assert(mutables != null);
ListChunk<Pair>[] privateBuffers = new ListChunk<Pair>[_partitionCount];
ListChunk<TOrderKey>[] privateKeyBuffers = new ListChunk<TOrderKey>[_partitionCount];
TInputOutput element = default(TInputOutput);
TOrderKey key = default(TOrderKey);
int loopCount = 0;
while (_source.MoveNext(ref element, ref key))
{
if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Calculate the element's destination partition index, placing it into the
// appropriate buffer from which partitions will later enumerate.
int destinationIndex;
THashKey elementHashKey = default(THashKey);
if (_keySelector != null)
{
elementHashKey = _keySelector(element);
destinationIndex = _repartitionStream.GetHashCode(elementHashKey) % _partitionCount;
}
else
{
Debug.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired));
destinationIndex = _repartitionStream.GetHashCode(element) % _partitionCount;
}
Debug.Assert(0 <= destinationIndex && destinationIndex < _partitionCount,
"destination partition outside of the legal range of partitions");
// Get the buffer for the destination partition, lazily allocating if needed. We maintain
// this list in our own private cache so that we avoid accessing shared memory locations
// too much. In the original implementation, we'd access the buffer in the matrix ([N,M],
// where N is the current partition and M is the destination), but some rudimentary
// performance profiling indicates copying at the end performs better.
ListChunk<Pair> buffer = privateBuffers[destinationIndex];
ListChunk<TOrderKey> keyBuffer = privateKeyBuffers[destinationIndex];
if (buffer == null)
{
const int INITIAL_PRIVATE_BUFFER_SIZE = 128;
Debug.Assert(keyBuffer == null);
privateBuffers[destinationIndex] = buffer = new ListChunk<Pair>(INITIAL_PRIVATE_BUFFER_SIZE);
privateKeyBuffers[destinationIndex] = keyBuffer = new ListChunk<TOrderKey>(INITIAL_PRIVATE_BUFFER_SIZE);
}
buffer.Add(new Pair(element, elementHashKey));
keyBuffer.Add(key);
}
// Copy the local buffers to the shared space and then signal to other threads that
// we are done. We can then immediately move on to enumerating the elements we found
// for the current partition before waiting at the barrier. If we found a lot, we will
// hopefully never have to physically wait.
for (int i = 0; i < _partitionCount; i++)
{
_valueExchangeMatrix[_partitionIndex][i] = privateBuffers[i];
_keyExchangeMatrix[_partitionIndex][i] = privateKeyBuffers[i];
}
_barrier.Signal();
// Begin at our own buffer.
mutables._currentBufferIndex = _partitionIndex;
mutables._currentBuffer = privateBuffers[_partitionIndex];
mutables._currentKeyBuffer = privateKeyBuffers[_partitionIndex];
mutables._currentIndex = ENUMERATION_NOT_STARTED;
}
protected override void Dispose(bool disposing)
{
if (_barrier != null)
{
// Since this enumerator is being disposed, we will decrement the barrier,
// in case other enumerators will wait on the barrier.
if (_mutables == null || (_mutables._currentBufferIndex == ENUMERATION_NOT_STARTED))
{
_barrier.Signal();
_barrier = null;
}
_source.Dispose();
}
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Newtonsoft.Json;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Net.Http;
using EZOper.TechTester.CnaSptAppSI.Models;
namespace EZOper.TechTester.CnaSptAppSI.Services
{
public class TTTSwipeToRefresh_PostListFragment : Android.Support.V4.App.ListFragment
{
bool loading;
PostListAdapter adapter;
public static TTTSwipeToRefresh_PostListFragment Instantiate (string forumID, string forumName)
{
return new TTTSwipeToRefresh_PostListFragment {
ForumID = forumID,
ForumName = forumName
};
}
public string ForumID {
get;
private set;
}
public string ForumName {
get;
private set;
}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
}
public override void OnAttach (Activity activity)
{
base.OnAttach (activity);
adapter = new PostListAdapter (activity);
FetchItems ();
}
public async Task FetchItems (int pageID = 0, bool clear = false)
{
const string Url = "http://forums.xamarin.com/api/v1/discussions/category.json?CategoryIdentifier=";
if (loading)
return;
loading = true;
var client = new HttpClient ();
//client.DefaultRequestHeaders.Host = "forums.xamarin.com";
try {
var json = await client.GetStringAsync (Url + ForumID);
var forum = JsonConvert.DeserializeObject<Forum> (json);
if (clear)
adapter.ClearData ();
adapter.FeedData (forum.Discussions.OrderByDescending (d => d.DateInserted));
} catch (Exception e) {
Android.Util.Log.Error ("FetchItems", e.ToString ());
}
if (pageID == 0)
ListAdapter = adapter;
loading = false;
}
class PostListAdapter : BaseAdapter
{
List<Discussion> discussions = new List<Discussion> ();
Drawable noFacePicture;
Activity context;
ConcurrentDictionary<string, Task<byte[]>> faceCache = new ConcurrentDictionary<string, Task<byte[]>> ();
public PostListAdapter (Activity context)
{
this.context = context;
this.noFacePicture = new ColorDrawable (Color.White);
}
public void ClearData ()
{
discussions.Clear ();
NotifyDataSetChanged ();
}
public void FeedData (IEnumerable<Discussion> newData)
{
discussions.AddRange (newData);
NotifyDataSetChanged ();
}
public Discussion GetDiscussionAtPosition (int position)
{
return discussions [position];
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
var view = EnsureView (convertView);
var item = discussions [position];
var version = Interlocked.Increment (ref view.VersionNumber);
var title = view.FindViewById<TextView> (Resource.Id.PostTitle);
var body = view.FindViewById<TextView> (Resource.Id.PostText);
var time = view.FindViewById<TextView> (Resource.Id.PostTime);
var timeSecondary = view.FindViewById<TextView> (Resource.Id.PostTimeSecondary);
var avatar = view.FindViewById<ImageView> (Resource.Id.PostAvatar);
var author = view.FindViewById<TextView> (Resource.Id.AuthorName);
body.Text = PrepareBody (item.Body);
title.Text = item.Name.Length > 2 && char.IsLower (item.Name[0]) ?
char.ToUpper (item.Name[0]) + item.Name.Substring (1) : item.Name;
author.Text = item.FirstName;
string timeFirst, timeSecond;
PrepareTime (item, out timeFirst, out timeSecond);
time.Text = timeFirst;
timeSecondary.Text = timeSecond;
avatar.SetImageDrawable (noFacePicture);
FetchAvatar (item.FirstPhoto, view, version);
return view;
}
DiscussionView EnsureView (View convertView)
{
DiscussionView view = convertView as DiscussionView;
if (view == null)
view = new DiscussionView (context);
return view;
}
string PrepareBody (string input)
{
return input.Replace ("\r\n", " ");
}
void PrepareTime (Discussion discussion, out string timeFirst, out string timeSecond)
{
DateTime now = DateTime.UtcNow;
var referenceTime = discussion.DateInserted;
var diff = now - referenceTime;
if (diff < TimeSpan.FromDays (3)) {
timeFirst = string.Empty;
if (diff < TimeSpan.FromMinutes (1))
timeFirst = ((int)diff.TotalSeconds) + " sec";
else if (diff < TimeSpan.FromHours (1))
timeFirst = ((int)diff.TotalMinutes) + " min";
else if (diff < TimeSpan.FromDays (1))
timeFirst = ((int)diff.TotalHours) + " hours";
else
timeFirst = ((int)diff.TotalDays) + " days";
timeSecond = "ago";
} else {
timeFirst = referenceTime.ToString ("MMM d");
timeSecond = referenceTime.ToString ("yyyy");
}
}
void FetchAvatar (string url, DiscussionView view, long version)
{
var data = faceCache.GetOrAdd (url, u => Task.Run (() => {
u = ResizeUrl (u);
var client = new WebClient ();
try {
return client.DownloadData (u);
} catch {
return null;
}
}));
if (data.IsCompleted && data.Result != null) {
var avatar = view.FindViewById<ImageView> (Resource.Id.PostAvatar);
var bmp = BitmapFactory.DecodeByteArray (data.Result, 0, data.Result.Length);
bmp = ResizeBitmap (bmp);
avatar.SetImageDrawable (new TTTSwipeToRefresh_VignetteDrawable (bmp, withEffect: false));
} else {
data.ContinueWith (t => {
if (t.Result != null && view.VersionNumber == version) {
var bmp = BitmapFactory.DecodeByteArray (data.Result, 0, data.Result.Length);
bmp = ResizeBitmap (bmp);
context.RunOnUiThread (() => {
if (view.VersionNumber == version) {
var avatar = view.FindViewById<ImageView> (Resource.Id.PostAvatar);
avatar.SetImageDrawable (new TTTSwipeToRefresh_VignetteDrawable (bmp, withEffect: false));
}
});
}
});
}
}
string ResizeUrl (string inputUrl)
{
var uri = new Uri (inputUrl);
if (uri.Host != "www.gravatar.com")
return inputUrl;
return inputUrl.Replace ("&size=130", string.Empty)
+ "&size="
+ TypedValue.ApplyDimension (ComplexUnitType.Dip, 48, context.Resources.DisplayMetrics);
}
Bitmap ResizeBitmap (Bitmap inputBitmap)
{
var size = (int)TypedValue.ApplyDimension (ComplexUnitType.Dip, 48, context.Resources.DisplayMetrics);
return Bitmap.CreateScaledBitmap (inputBitmap, size, size, true);
}
public override long GetItemId (int position)
{
return long.Parse (discussions[position].DiscussionID);
}
public override Java.Lang.Object GetItem (int position)
{
return new Java.Lang.String (discussions[position].Name);
}
public override int Count {
get {
return discussions == null ? 0 : discussions.Count;
}
}
public override int ViewTypeCount {
get {
return 1;
}
}
}
class DiscussionView : FrameLayout
{
public DiscussionView (Context ctx) : base (ctx)
{
var inflater = ctx.GetSystemService (Context.LayoutInflaterService).JavaCast<LayoutInflater> ();
inflater.Inflate (Resource.Layout.TTTSwipeToRefresh_PostItem, this, true);
}
public long VersionNumber;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.