context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Runtime.InteropServices;
public static class Program
{
public static void Main()
{
var s =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), null,
typeof(StaticClass).GetMethod("Run"));
s("in", "in99");
var s2 =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), null,
typeof(StaticClass).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
s2("in", "in99");
var s3 =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), null,
typeof(StaticGenericClass<string>).GetMethod("Run"));
s3("in", "in99");
var s4 =
(Action<string, string, string>)
Delegate.CreateDelegate(typeof(Action<string, string, string>), null,
typeof(StaticGenericClass<string>).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
s4("in", "in2", "in99");
var s5 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), null,
typeof(StaticClass).GetMethod("RunOutput"));
Console.WriteLine(s5("in", "in99"));
var s6 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), null,
typeof(StaticClass).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(s6("in", "in99"));
var s7 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), null,
typeof(StaticGenericClass<string>).GetMethod("RunOutput"));
Console.WriteLine(s7("in", "in99"));
var s8 =
(Func<string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string, string>), null,
typeof(StaticGenericClass<string>).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(s8("in", "in2", "in99"));
var d =
(Action<NonGenericClass, string, string>)
Delegate.CreateDelegate(typeof(Action<NonGenericClass, string, string>), null,
typeof(NonGenericClass).GetMethod("Run"));
d(new NonGenericClass(1), "in", "in99");
d(null, "in", "in99");
var d_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new NonGenericClass(1),
typeof(NonGenericClass).GetMethod("Run"));
d_("in", "in99");
var d2 =
(Action<NonGenericClass, string, string>)
Delegate.CreateDelegate(typeof(Action<NonGenericClass, string, string>), null,
typeof(NonGenericClass).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d2(new NonGenericClass(1), "in", "in99");
d2(null, "in", "in99");
var d2_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new NonGenericClass(1),
typeof(NonGenericClass).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d2_("in", "in99");
var d3 =
(Action<GenericClass<string>, string, string>)
Delegate.CreateDelegate(typeof(Action<GenericClass<string>, string, string>), null,
typeof(GenericClass<string>).GetMethod("Run"));
d3(new GenericClass<string>(1), "in", "in99");
d3(null, "in", "in99");
var d3_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new GenericClass<string>(1),
typeof(GenericClass<string>).GetMethod("Run"));
d3_("in", "in99");
var d4 =
(Action<GenericClass<string>, string, string, string>)
Delegate.CreateDelegate(typeof(Action<GenericClass<string>, string, string, string>), null,
typeof(GenericClass<string>).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d4(new GenericClass<string>(1), "in", "in2", "in99");
d4(null, "in", "in2", "in99");
var d4_ =
(Action<string, string, string>)
Delegate.CreateDelegate(typeof(Action<string, string, string>), new GenericClass<string>(1),
typeof(GenericClass<string>).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d4_("in", "in2", "in99");
var d5 =
(Func<NonGenericClass, string, string, string>)
Delegate.CreateDelegate(typeof(Func<NonGenericClass, string, string, string>), null,
typeof(NonGenericClass).GetMethod("RunOutput"));
Console.WriteLine(d5(new NonGenericClass(1), "in", "in99"));
Console.WriteLine(d5(null, "in", "in99"));
var d5_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new NonGenericClass(1),
typeof(NonGenericClass).GetMethod("RunOutput"));
Console.WriteLine(d5_("in", "in99"));
var d6 =
(Func<NonGenericClass, string, string, string>)
Delegate.CreateDelegate(typeof(Func<NonGenericClass, string, string, string>), null,
typeof(NonGenericClass).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d6(new NonGenericClass(1), "in", "in99"));
Console.WriteLine(d6(null, "in", "in99"));
var d6_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new NonGenericClass(1),
typeof(NonGenericClass).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d6_("in", "in99"));
var d7 =
(Func<GenericClass<string>, string, string, string>)
Delegate.CreateDelegate(typeof(Func<GenericClass<string>, string, string, string>), null,
typeof(GenericClass<string>).GetMethod("RunOutput"));
Console.WriteLine(d7(new GenericClass<string>(1), "in", "in99"));
Console.WriteLine(d7(null, "in", "in99"));
var d7_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new GenericClass<string>(1),
typeof(GenericClass<string>).GetMethod("RunOutput"));
Console.WriteLine(d7_("in", "in99"));
var d8 =
(Func<GenericClass<string>, string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<GenericClass<string>, string, string, string, string>), null,
typeof(GenericClass<string>).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d8(new GenericClass<string>(1), "in", "in2", "in99"));
Console.WriteLine(d8(null, "in", "in2", "in99"));
var d8_ =
(Func<string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string, string>), new GenericClass<string>(1),
typeof(GenericClass<string>).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d8_("in", "in2", "in99"));
var d9 =
(Action<IInterface, string, string>)
Delegate.CreateDelegate(typeof(Action<IInterface, string, string>), null,
typeof(IInterface).GetMethod("Run"));
d9(new NonGenericClassImplementor(1), "in", "in99");
d9(new GenericClassImplementor<string>(2), "in", "in99");
var d9_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new NonGenericClassImplementor(1),
typeof(IInterface).GetMethod("Run"));
d9_("in", "in99");
var d9_2 =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new GenericClassImplementor<string>(2),
typeof(IInterface).GetMethod("Run"));
d9_2("in", "in99");
//Looks like .Net doesn't support unbinded delegate for generic interface methods.
/*var d10 =
(Action<IInterface, string, string>)
Delegate.CreateDelegate(typeof(Action<IInterface, string, string>), null,
typeof(IInterface).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d10(new NonGenericClassImplementor(1), "in", "in99");
d10(new GenericClassImplementor<string>(2), "in", "in99");*/
var d10_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new NonGenericClassImplementor(1),
typeof(IInterface).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d10_("in", "in99");
var d10_2 =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new GenericClassImplementor<string>(2),
typeof(IInterface).GetMethod("RunGeneric").MakeGenericMethod(typeof(string)));
d10_2("in", "in99");
var d11 =
(Action<IGenericInterface<string>, string, string>)
Delegate.CreateDelegate(typeof(Action<IGenericInterface<string>, string, string>), null,
typeof(IGenericInterface<string>).GetMethod("Run"));
d11(new NonGenericClassImplementor(1), "in", "in99");
d11(new GenericClassImplementor<string>(2), "in", "in99");
var d11_ =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new NonGenericClassImplementor(1),
typeof(IGenericInterface<string>).GetMethod("Run"));
d11_("in", "in99");
var d11_2 =
(Action<string, string>)
Delegate.CreateDelegate(typeof(Action<string, string>), new GenericClassImplementor<string>(2),
typeof(IGenericInterface<string>).GetMethod("Run"));
d11_2("in", "in99");
/*var d12 =
(Action<IGenericInterface<string>, string, string, string>)
Delegate.CreateDelegate(typeof(Action<IGenericInterface<string>, string, string, string>), null,
typeof(IGenericInterface<string>).GetMethod("RunGeneric2").MakeGenericMethod(typeof(string)));
d12(new NonGenericClassImplementor(1), "in", "in2", "in99");
d12(new GenericClassImplementor<string>(2), "in", "in2", "in99");*/
var d12_ =
(Action<string, string, string>)
Delegate.CreateDelegate(typeof(Action<string, string, string>), new NonGenericClassImplementor(1),
typeof(IGenericInterface<string>).GetMethod("RunGeneric2").MakeGenericMethod(typeof(string)));
d12_("in", "in2", "in99");
var d12_2 =
(Action<string, string, string>)
Delegate.CreateDelegate(typeof(Action<string, string, string>), new GenericClassImplementor<string>(2),
typeof(IGenericInterface<string>).GetMethod("RunGeneric2").MakeGenericMethod(typeof(string)));
d12_2("in", "in2", "in99");
var d13 =
(Func<IInterface, string, string, string>)
Delegate.CreateDelegate(typeof(Func<IInterface, string, string, string>), null,
typeof(IInterface).GetMethod("RunOutput"));
Console.WriteLine(d13(new NonGenericClassImplementor(1), "in", "in99"));
Console.WriteLine(d13(new GenericClassImplementor<string>(2), "in", "in99"));
var d13_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new NonGenericClassImplementor(1),
typeof(IInterface).GetMethod("RunOutput"));
Console.WriteLine(d13_("in", "in99"));
var d13_2 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new GenericClassImplementor<string>(2),
typeof(IInterface).GetMethod("RunOutput"));
Console.WriteLine(d13_2("in", "in99"));
/*var d14 =
(Func<IInterface, string, string, string>)
Delegate.CreateDelegate(typeof(Func<IInterface, string, string, string>), null,
typeof(IInterface).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d14(new NonGenericClassImplementor(1), "in", "in99"));
Console.WriteLine(d14(new GenericClassImplementor<string>(2), "in", "in99"));*/
var d14_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new NonGenericClassImplementor(1),
typeof(IInterface).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d14_("in", "in99"));
var d14_2 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new GenericClassImplementor<string>(1),
typeof(IInterface).GetMethod("RunOutputGeneric").MakeGenericMethod(typeof(string)));
Console.WriteLine(d14_2("in", "in99"));
var d15 =
(Func<IGenericInterface<string>, string, string, string>)
Delegate.CreateDelegate(typeof(Func<IGenericInterface<string>, string, string, string>), null,
typeof(IGenericInterface<string>).GetMethod("RunOutput"));
Console.WriteLine(d15(new NonGenericClassImplementor(1), "in", "in99"));
Console.WriteLine(d15(new GenericClassImplementor<string>(2), "in", "in99"));
var d15_ =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new NonGenericClassImplementor(1),
typeof(IGenericInterface<string>).GetMethod("RunOutput"));
Console.WriteLine(d15_("in", "in99"));
var d15_2 =
(Func<string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string>), new GenericClassImplementor<string>(2),
typeof(IGenericInterface<string>).GetMethod("RunOutput"));
Console.WriteLine(d15_2("in", "in99"));
/*var d16 =
(Func<IGenericInterface<string>, string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<IGenericInterface<string>, string, string, string, string>), null,
typeof(IGenericInterface<string>).GetMethod("RunOutputGeneric2").MakeGenericMethod(typeof(string)));
Console.WriteLine(d16(new NonGenericClassImplementor(1), "in", "in2", "in99"));
Console.WriteLine(d16(new GenericClassImplementor<string>(2), "in", "in2", "in99"));*/
var d16_ =
(Func<string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string, string>), new NonGenericClassImplementor(1),
typeof(IGenericInterface<string>).GetMethod("RunOutputGeneric2").MakeGenericMethod(typeof(string)));
Console.WriteLine(d16_("in", "in2", "in99"));
var d16_2 =
(Func<string, string, string, string>)
Delegate.CreateDelegate(typeof(Func<string, string, string, string>), new GenericClassImplementor<string>(2),
typeof(IGenericInterface<string>).GetMethod("RunOutputGeneric2").MakeGenericMethod(typeof(string)));
Console.WriteLine(d16_2("in", "in2", "in99"));
}
}
public static class StaticClass
{
public static void Run(string input, string input2)
{
Console.WriteLine("Static class, Non-Generic; Input: " + input);
}
public static void RunGeneric<T>(T input, string input2)
{
Console.WriteLine("Static class, Non-Generic; Input: " + input);
}
public static string RunOutput(string input, string input2)
{
Console.WriteLine("Static class, Non-Generic; Input: " + input);
return "output1";
}
public static string RunOutputGeneric<T>(T input, string input2)
{
Console.WriteLine("Static class, Non-Generic; Input: " + input);
return "output2";
}
}
public class NonGenericClass
{
public int _value;
public NonGenericClass(int value)
{
_value = value;
}
public void Run(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Non-Generic, this==null; Input: " + input);
}
}
public void RunGeneric<T>(T input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input);
}
}
public string RunOutput(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Non-Generic, this==null; Input: " + input);
}
return "output1";
}
public string RunOutputGeneric<T>(T input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input);
}
return "output2";
}
}
public static class StaticGenericClass<T>
{
public static void Run(string input, string input2)
{
Console.WriteLine(
"Static generic class, Non-Generic; Input: " + input);
}
public static void RunGeneric<T2>(T input, T2 input2, string input3)
{
Console.WriteLine("Static generic class, Generic; Input: " + input + "; Input2: " + input2);
}
public static string RunOutput(string input, string input2)
{
Console.WriteLine("Static generic class, Non-Generic; Input: " + input);
return "output3";
}
public static string RunOutputGeneric<T2>(T input, T2 input2, string input3)
{
Console.WriteLine("Static generic class, Generic; Input: " + input + "; Input2: " + input2);
return "output4";
}
}
public class GenericClass<T>
{
public int _value;
public GenericClass(int value)
{
_value = value;
}
public void Run(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Non-Generic, this==null; Input: " + input);
}
}
public void RunGeneric<T2>(T input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
}
public string RunOutput(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Non-Generic, this==null; Input: " + input);
}
return "output3";
}
public string RunOutputGeneric<T2>(T input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
return "output4";
}
}
public interface IInterface
{
void Run(string input, string input2);
void RunGeneric<T>(T input, string input2);
string RunOutput(string input, string input2);
string RunOutputGeneric<T>(T input, string input2);
}
public interface IGenericInterface<T>
{
void Run(string input, string input2);
void RunGeneric2<T2>(T input, T2 input2, string input3);
string RunOutput(string input, string input2);
string RunOutputGeneric2<T2>(T input, T2 input2, string input3);
}
public class NonGenericClassImplementor : IInterface, IGenericInterface<string>
{
public int _value;
public NonGenericClassImplementor(int value)
{
_value = value;
}
public void Run(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Non-Generic, this==null; Input: " + input);
}
}
public void RunGeneric<T>(T input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input);
}
}
public void RunGeneric2<T2>(string input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
}
public string RunOutput(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Non-Generic, this==null; Input: " + input);
}
return "99";
}
public string RunOutputGeneric<T>(T input, string input2)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input);
}
return "100";
}
public string RunOutputGeneric2<T2>(string input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Non-Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Non-Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
return "101";
}
}
public class GenericClassImplementor<T> : IGenericInterface<T>, IInterface
{
public int _value;
public GenericClassImplementor(int value)
{
_value = value;
}
public void Run(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Non-Generic, this==null; Input: " + input);
}
}
public void RunGeneric2<T2>(T input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
}
public void RunGeneric<T>(T input, string input2)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input);
}
}
public string RunOutput(string input, string input2)
{
if (this != null)
{
Console.WriteLine("Generic class, Non-Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Non-Generic, this==null; Input: " + input);
}
return "110";
}
public string RunOutputGeneric2<T2>(T input, T2 input2, string input3)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input + "; Input2: " + input2);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input + "; Input2: " + input2);
}
return "111";
}
public string RunOutputGeneric<T>(T input, string input3)
{
if (this != null)
{
Console.WriteLine("Generic class, Generic, this: " + _value + "; Input: " + input);
}
else
{
Console.WriteLine("Generic class, Generic, this==null " + input);
}
return "112";
}
}
| |
// StrangeCRC.cs - computes a crc used in the bziplib
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace TvdbLib.SharpZipLib.Checksums
{
/// <summary>
/// Bzip2 checksum algorithm
/// </summary>
public class StrangeCRC : IChecksum
{
readonly static uint[] crc32Table = {
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
int globalCrc;
/// <summary>
/// Initialise a default instance of <see cref="StrangeCRC"></see>
/// </summary>
public StrangeCRC()
{
Reset();
}
/// <summary>
/// Reset the state of Crc.
/// </summary>
public void Reset()
{
globalCrc = -1;
}
/// <summary>
/// Get the current Crc value.
/// </summary>
public long Value {
get {
return ~globalCrc;
}
}
/// <summary>
/// Update the Crc value.
/// </summary>
/// <param name="value">data update is based on</param>
public void Update(int value)
{
int temp = (globalCrc >> 24) ^ value;
if (temp < 0) {
temp = 256 + temp;
}
globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp]));
}
/// <summary>
/// Update Crc based on a block of data
/// </summary>
/// <param name="buffer">The buffer containing data to update the crc with.</param>
public void Update(byte[] buffer)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Update Crc based on a portion of a block of data
/// </summary>
/// <param name="buffer">block of data</param>
/// <param name="offset">index of first byte to use</param>
/// <param name="count">number of bytes to use</param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if ( offset < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "cannot be less than zero");
#endif
}
if ( count < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "cannot be less than zero");
#endif
}
if ( offset + count > buffer.Length )
{
throw new ArgumentOutOfRangeException("count");
}
for (int i = 0; i < count; ++i) {
Update(buffer[offset++]);
}
}
}
}
| |
public class Yahtzee {
public static int Chance(int d1, int d2, int d3, int d4, int d5)
{
int total = 0;
total += d1;
total += d2;
total += d3;
total += d4;
total += d5;
return total;
}
public static int yahtzee(params int[] dice)
{
int[] counts = new int[6];
foreach (int die in dice)
counts[die-1]++;
for (int i = 0; i != 6; i++)
if (counts[i] == 5)
return 50;
return 0;
}
public static int Ones(int d1, int d2, int d3, int d4, int d5) {
int sum = 0;
if (d1 == 1) sum++;
if (d2 == 1) sum++;
if (d3 == 1) sum++;
if (d4 == 1) sum++;
if (d5 == 1)
sum++;
return sum;
}
public static int Twos(int d1, int d2, int d3, int d4, int d5) {
int sum = 0;
if (d1 == 2) sum += 2;
if (d2 == 2) sum += 2;
if (d3 == 2) sum += 2;
if (d4 == 2) sum += 2;
if (d5 == 2) sum += 2;
return sum;
}
public static int Threes(int d1, int d2, int d3, int d4, int d5) {
int s;
s = 0;
if (d1 == 3) s += 3;
if (d2 == 3) s += 3;
if (d3 == 3) s += 3;
if (d4 == 3) s += 3;
if (d5 == 3) s += 3;
return s;
}
protected int[] dice;
public Yahtzee(int d1, int d2, int d3, int d4, int _5)
{
dice = new int[5];
dice[0] = d1;
dice[1] = d2;
dice[2] = d3;
dice[3] = d4;
dice[4] = _5;
}
public int Fours()
{
int sum;
sum = 0;
for (int at = 0; at != 5; at++) {
if (dice[at] == 4) {
sum += 4;
}
}
return sum;
}
public int Fives()
{
int s = 0;
int i;
for (i = 0; i < dice.Length; i++)
if (dice[i] == 5)
s = s + 5;
return s;
}
public int sixes()
{
int sum = 0;
for (int at = 0; at < dice.Length; at++)
if (dice[at] == 6)
sum = sum + 6;
return sum;
}
public static int ScorePair(int d1, int d2, int d3, int d4, int d5)
{
int[] counts = new int[6];
counts[d1-1]++;
counts[d2-1]++;
counts[d3-1]++;
counts[d4-1]++;
counts[d5-1]++;
int at;
for (at = 0; at != 6; at++)
if (counts[6-at-1] == 2)
return (6-at)*2;
return 0;
}
public static int TwoPair(int d1, int d2, int d3, int d4, int d5)
{
int[] counts = new int[6];
counts[d1-1]++;
counts[d2-1]++;
counts[d3-1]++;
counts[d4-1]++;
counts[d5-1]++;
int n = 0;
int score = 0;
for (int i = 0; i < 6; i += 1)
if (counts[6-i-1] == 2) {
n++;
score += (6-i);
}
if (n == 2)
return score * 2;
else
return 0;
}
public static int FourOfAKind(int _1, int _2, int d3, int d4, int d5)
{
int[] tallies;
tallies = new int[6];
tallies[_1-1]++;
tallies[_2-1]++;
tallies[d3-1]++;
tallies[d4-1]++;
tallies[d5-1]++;
for (int i = 0; i < 6; i++)
if (tallies[i] == 4)
return (i+1) * 4;
return 0;
}
public static int ThreeOfAKind(int d1, int d2, int d3, int d4, int d5)
{
int[] t;
t = new int[6];
t[d1-1]++;
t[d2-1]++;
t[d3-1]++;
t[d4-1]++;
t[d5-1]++;
for (int i = 0; i < 6; i++)
if (t[i] == 3)
return (i+1) * 3;
return 0;
}
public static int SmallStraight(int d1, int d2, int d3, int d4, int d5)
{
int[] tallies;
tallies = new int[6];
tallies[d1-1] += 1;
tallies[d2-1] += 1;
tallies[d3-1] += 1;
tallies[d4-1] += 1;
tallies[d5-1] += 1;
if (tallies[0] == 1 &&
tallies[1] == 1 &&
tallies[2] == 1 &&
tallies[3] == 1 &&
tallies[4] == 1)
return 15;
return 0;
}
public static int LargeStraight(int d1, int d2, int d3, int d4, int d5)
{
int[] tallies;
tallies = new int[6];
tallies[d1-1] += 1;
tallies[d2-1] += 1;
tallies[d3-1] += 1;
tallies[d4-1] += 1;
tallies[d5-1] += 1;
if (tallies[1] == 1 &&
tallies[2] == 1 &&
tallies[3] == 1 &&
tallies[4] == 1
&& tallies[5] == 1)
return 20;
return 0;
}
public static int FullHouse(int d1, int d2, int d3, int d4, int d5)
{
int[] tallies;
bool _2 = false;
int i;
int _2_at = 0;
bool _3 = false;
int _3_at = 0;
tallies = new int[6];
tallies[d1-1] += 1;
tallies[d2-1] += 1;
tallies[d3-1] += 1;
tallies[d4-1] += 1;
tallies[d5-1] += 1;
for (i = 0; i != 6; i += 1)
if (tallies[i] == 2) {
_2 = true;
_2_at = i+1;
}
for (i = 0; i != 6; i += 1)
if (tallies[i] == 3) {
_3 = true;
_3_at = i+1;
}
if (_2 && _3)
return _2_at * 2 + _3_at * 3;
else
return 0;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Numerics.Hashing;
namespace System.Drawing
{
/// <summary>
/// <para>
/// Stores the location and size of a rectangular region.
/// </para>
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public struct Rectangle : IEquatable<Rectangle>
{
public static readonly Rectangle Empty = new Rectangle();
private int x; // Do not rename (binary serialization)
private int y; // Do not rename (binary serialization)
private int width; // Do not rename (binary serialization)
private int height; // Do not rename (binary serialization)
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Rectangle'/>
/// class with the specified location and size.
/// </para>
/// </summary>
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <summary>
/// <para>
/// Initializes a new instance of the Rectangle class with the specified location
/// and size.
/// </para>
/// </summary>
public Rectangle(Point location, Size size)
{
x = location.X;
y = location.Y;
width = size.Width;
height = size.Height;
}
/// <summary>
/// Creates a new <see cref='System.Drawing.Rectangle'/> with
/// the specified location and size.
/// </summary>
public static Rectangle FromLTRB(int left, int top, int right, int bottom) =>
new Rectangle(left, top, unchecked(right - left), unchecked(bottom - top));
/// <summary>
/// <para>
/// Gets or sets the coordinates of the
/// upper-left corner of the rectangular region represented by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
[Browsable(false)]
public Point Location
{
get { return new Point(X, Y); }
set
{
X = value.X;
Y = value.Y;
}
}
/// <summary>
/// Gets or sets the size of this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
[Browsable(false)]
public Size Size
{
get { return new Size(Width, Height); }
set
{
Width = value.Width;
Height = value.Height;
}
}
/// <summary>
/// Gets or sets the x-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int X
{
get { return x; }
set { x = value; }
}
/// <summary>
/// Gets or sets the y-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Y
{
get { return y; }
set { y = value; }
}
/// <summary>
/// Gets or sets the width of the rectangular
/// region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Width
{
get { return width; }
set { width = value; }
}
/// <summary>
/// Gets or sets the width of the rectangular
/// region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Height
{
get { return height; }
set { height = value; }
}
/// <summary>
/// <para>
/// Gets the x-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
[Browsable(false)]
public int Left => X;
/// <summary>
/// <para>
/// Gets the y-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
[Browsable(false)]
public int Top => Y;
/// <summary>
/// <para>
/// Gets the x-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
[Browsable(false)]
public int Right => unchecked(X + Width);
/// <summary>
/// <para>
/// Gets the y-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
[Browsable(false)]
public int Bottom => unchecked(Y + Height);
/// <summary>
/// <para>
/// Tests whether this <see cref='System.Drawing.Rectangle'/> has a <see cref='System.Drawing.Rectangle.Width'/>
/// or a <see cref='System.Drawing.Rectangle.Height'/> of 0.
/// </para>
/// </summary>
[Browsable(false)]
public bool IsEmpty => height == 0 && width == 0 && x == 0 && y == 0;
/// <summary>
/// <para>
/// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.Rectangle'/> with
/// the same location and size of this Rectangle.
/// </para>
/// </summary>
public override bool Equals(object obj) => obj is Rectangle && Equals((Rectangle)obj);
public bool Equals(Rectangle other) => this == other;
/// <summary>
/// <para>
/// Tests whether two <see cref='System.Drawing.Rectangle'/>
/// objects have equal location and size.
/// </para>
/// </summary>
public static bool operator ==(Rectangle left, Rectangle right) =>
left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height;
/// <summary>
/// <para>
/// Tests whether two <see cref='System.Drawing.Rectangle'/>
/// objects differ in location or size.
/// </para>
/// </summary>
public static bool operator !=(Rectangle left, Rectangle right) => !(left == right);
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a ceiling operation on
/// all the coordinates.
/// </summary>
public static Rectangle Ceiling(RectangleF value)
{
unchecked
{
return new Rectangle(
(int)Math.Ceiling(value.X),
(int)Math.Ceiling(value.Y),
(int)Math.Ceiling(value.Width),
(int)Math.Ceiling(value.Height));
}
}
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a truncate operation on
/// all the coordinates.
/// </summary>
public static Rectangle Truncate(RectangleF value)
{
unchecked
{
return new Rectangle(
(int)value.X,
(int)value.Y,
(int)value.Width,
(int)value.Height);
}
}
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a round operation on
/// all the coordinates.
/// </summary>
public static Rectangle Round(RectangleF value)
{
unchecked
{
return new Rectangle(
(int)Math.Round(value.X),
(int)Math.Round(value.Y),
(int)Math.Round(value.Width),
(int)Math.Round(value.Height));
}
}
/// <summary>
/// <para>
/// Determines if the specified point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
public bool Contains(int x, int y) => X <= x && x < X + Width && Y <= y && y < Y + Height;
/// <summary>
/// <para>
/// Determines if the specified point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
public bool Contains(Point pt) => Contains(pt.X, pt.Y);
/// <summary>
/// <para>
/// Determines if the rectangular region represented by
/// <paramref name="rect"/> is entirely contained within the rectangular region represented by
/// this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
public bool Contains(Rectangle rect) =>
(X <= rect.X) && (rect.X + rect.Width <= X + Width) &&
(Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height);
public override int GetHashCode() =>
HashHelpers.Combine(HashHelpers.Combine(HashHelpers.Combine(X, Y), Width), Height);
/// <summary>
/// <para>
/// Inflates this <see cref='System.Drawing.Rectangle'/>
/// by the specified amount.
/// </para>
/// </summary>
public void Inflate(int width, int height)
{
unchecked
{
X -= width;
Y -= height;
Width += 2 * width;
Height += 2 * height;
}
}
/// <summary>
/// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount.
/// </summary>
public void Inflate(Size size) => Inflate(size.Width, size.Height);
/// <summary>
/// <para>
/// Creates a <see cref='System.Drawing.Rectangle'/>
/// that is inflated by the specified amount.
/// </para>
/// </summary>
public static Rectangle Inflate(Rectangle rect, int x, int y)
{
Rectangle r = rect;
r.Inflate(x, y);
return r;
}
/// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect.
/// </summary>
public void Intersect(Rectangle rect)
{
Rectangle result = Intersect(rect, this);
X = result.X;
Y = result.Y;
Width = result.Width;
Height = result.Height;
}
/// <summary>
/// Creates a rectangle that represents the intersection between a and
/// b. If there is no intersection, null is returned.
/// </summary>
public static Rectangle Intersect(Rectangle a, Rectangle b)
{
int x1 = Math.Max(a.X, b.X);
int x2 = Math.Min(a.X + a.Width, b.X + b.Width);
int y1 = Math.Max(a.Y, b.Y);
int y2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (x2 >= x1 && y2 >= y1)
{
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
return Empty;
}
/// <summary>
/// Determines if this rectangle intersects with rect.
/// </summary>
public bool IntersectsWith(Rectangle rect) =>
(rect.X < X + Width) && (X < rect.X + rect.Width) &&
(rect.Y < Y + Height) && (Y < rect.Y + rect.Height);
/// <summary>
/// <para>
/// Creates a rectangle that represents the union between a and
/// b.
/// </para>
/// </summary>
public static Rectangle Union(Rectangle a, Rectangle b)
{
int x1 = Math.Min(a.X, b.X);
int x2 = Math.Max(a.X + a.Width, b.X + b.Width);
int y1 = Math.Min(a.Y, b.Y);
int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// <para>
/// Adjusts the location of this rectangle by the specified amount.
/// </para>
/// </summary>
public void Offset(Point pos) => Offset(pos.X, pos.Y);
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
public void Offset(int x, int y)
{
unchecked
{
X += x;
Y += y;
}
}
/// <summary>
/// <para>
/// Converts the attributes of this <see cref='System.Drawing.Rectangle'/> to a
/// human readable string.
/// </para>
/// </summary>
public override string ToString() =>
"{X=" + X.ToString() + ",Y=" + Y.ToString() +
",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}";
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Diagnostics;
using Glass.Mapper.Sc.DataMappers;
using NUnit.Framework;
using Sitecore.Data;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldDateTimeMapperFixture : AbstractMapperFixture
{
#region Method - GetField
[Test]
public void GetField_FieldContainsValidDate_ReturnsDateTime()
{
//Assign
string fieldValue = "20120101T010101";
DateTime expected = new DateTime(2012, 01, 01, 01, 01, 01);
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var mapper = new SitecoreFieldDateTimeMapper();
//Act
var result = (DateTime) mapper.GetField(field, null, null);
//Assert
Assert.AreEqual(expected, result);
}
[Test]
public void GetField_FieldContainsValidIsoDate_ReturnsDateTime()
{
//Assign
string fieldValue = "20121101T230000";
DateTime expected = new DateTime(2012, 11, 01, 23, 00, 00);
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var mapper = new SitecoreFieldDateTimeMapper();
//Act
var result = (DateTime)mapper.GetField(field, null, null);
//Assert
Assert.AreEqual(expected, result);
}
#if (SC80 || SC81 || SC82 || SC90)
[Test]
public void SitecoreTimeZoneDemo()
{
//Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("be-NL");
const string isoDateString = "20151013T220000Z";
const string serverDateString = "20120901T010101";
var serverDateTime = Sitecore.DateUtil.IsoDateToServerTimeIsoDate(isoDateString);
var utcDate = Sitecore.DateUtil.IsoDateToUtcIsoDate(isoDateString);
Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(utcDate));
var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString);
Console.WriteLine(isoDate);
Console.WriteLine(Sitecore.DateUtil.ToServerTime(isoDate));
Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(serverDateTime));
// go the other way
Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.Now));
Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.UtcNow));
Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.Now, false, true));
var serverDate = Sitecore.DateUtil.IsoDateToDateTime(serverDateString);
Console.WriteLine(serverDate);
Console.WriteLine(Sitecore.DateUtil.ToServerTime(serverDate));
Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(serverDateString, DateTime.MinValue, false));
var crappyDate = Sitecore.DateUtil.IsoDateToDateTime(serverDateString, DateTime.MinValue, true);
Console.WriteLine(crappyDate);
Console.WriteLine(Sitecore.DateUtil.ToServerTime(serverDate));
Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(isoDateString, DateTime.MinValue, true));
}
[Test]
[Ignore("POC only")]
public void ConvertTimeToServerTime_using_date_lots()
{
const string isoDateString = "20151013T220000Z";
Stopwatch sw = new Stopwatch();
sw.Start();
for (var i = 0; i < 1000000; i++)
{
var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString);
Sitecore.DateUtil.ToServerTime(isoDate);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
[Test]
[Ignore("POC only")]
public void ConvertTimeToServerTime_checking_z_lots()
{
const string isoDateString = "20151013T220000Z";
const string serverDateString = "20120101T010101";
Stopwatch sw = new Stopwatch();
sw.Start();
for (var i = 0; i < 1000000; i++)
{
var currentString = i%2 == 1 ? isoDateString : serverDateString;
DateTime isoDate = Sitecore.DateUtil.IsoDateToDateTime(currentString);
if (currentString.EndsWith("Z", StringComparison.OrdinalIgnoreCase))
{
Sitecore.DateUtil.ToServerTime(isoDate);
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
[Test]
[Ignore("POC only")]
public void ConvertTimeToServerTime_not_checking_z_lots()
{
const string isoDateString = "20151013T220000Z";
Stopwatch sw = new Stopwatch();
sw.Start();
for (var i = 0; i < 1000000; i++)
{
var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString);
Sitecore.DateUtil.ToServerTime(isoDate);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
[Test]
[Ignore("POC only")]
public void ConvertTimeToServerTime_using_string_lots()
{
const string isoDateString = "20151013T220000Z";
Stopwatch sw = new Stopwatch();
sw.Start();
for (var i = 0; i < 1000000; i++)
{
var serverDateTime = Sitecore.DateUtil.IsoDateToServerTimeIsoDate(isoDateString);
Sitecore.DateUtil.IsoDateToDateTime(serverDateTime);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
#endif
#endregion
#region Method - SetField
[Test]
public void SetField_DateTimePassed_SetsFieldValue()
{
//Assign
#if (SC80 || SC81 || SC82 || SC90)
string expected = "20120101T010101Z";
#else
string expected = "20120101T010101";
#endif
DateTime objectValue = new DateTime(2012, 01, 01, 01, 01, 01, DateTimeKind.Utc);
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, string.Empty);
var field = item.Fields[new ID(fieldId)];
var mapper = new SitecoreFieldDateTimeMapper();
item.Editing.BeginEdit();
//Act
mapper.SetField(field, objectValue, null, null);
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_NonDateTimePassed_ExceptionThrown()
{
//Assign
string expected = "20120101T010101Z";
int objectValue = 4;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, string.Empty);
var field = item.Fields[new ID(fieldId)];
var mapper = new SitecoreFieldDateTimeMapper();
item.Editing.BeginEdit();
//Act
Assert.Throws<NotSupportedException>(() =>
{
mapper.SetField(field, objectValue, null, null);
});
//Assert
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Talent.V4.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTenantServiceClientTest
{
[xunit::FactAttribute]
public void CreateTenantRequestObject()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.CreateTenant(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTenantRequestObjectAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.CreateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.CreateTenantAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTenant()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.CreateTenant(request.Parent, request.Tenant);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTenantAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.CreateTenantAsync(request.Parent, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.CreateTenantAsync(request.Parent, request.Tenant, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTenantResourceNames()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.CreateTenant(request.ParentAsProjectName, request.Tenant);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTenantResourceNamesAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
CreateTenantRequest request = new CreateTenantRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Tenant = new Tenant(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTenantRequestObject()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.GetTenant(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTenantRequestObjectAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.GetTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.GetTenantAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTenant()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.GetTenant(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTenantAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.GetTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.GetTenantAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTenantResourceNames()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.GetTenant(request.TenantName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTenantResourceNamesAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
GetTenantRequest request = new GetTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.GetTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.GetTenantAsync(request.TenantName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTenantRequestObject()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new wkt::FieldMask(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.UpdateTenant(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTenantRequestObjectAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new wkt::FieldMask(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.UpdateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.UpdateTenantAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTenant()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new wkt::FieldMask(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant response = client.UpdateTenant(request.Tenant, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTenantAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
UpdateTenantRequest request = new UpdateTenantRequest
{
Tenant = new Tenant(),
UpdateMask = new wkt::FieldMask(),
};
Tenant expectedResponse = new Tenant
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
ExternalId = "external_id9442680e",
};
mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
Tenant responseCallSettings = await client.UpdateTenantAsync(request.Tenant, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tenant responseCancellationToken = await client.UpdateTenantAsync(request.Tenant, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTenantRequestObject()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteTenant(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTenantRequestObjectAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTenantAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTenant()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteTenant(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTenantAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTenantAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTenantResourceNames()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteTenant(request.TenantName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTenantResourceNamesAsync()
{
moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict);
DeleteTenantRequest request = new DeleteTenantRequest
{
TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTenantAsync(request.TenantName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpResponseStreamTest
{
public WinHttpResponseStreamTest()
{
TestControl.ResetAll();
}
[Fact]
public void CanRead_WhenCreated_ReturnsTrue()
{
Stream stream = MakeResponseStream();
bool result = stream.CanRead;
Assert.True(result);
}
[Fact]
public void CanRead_WhenDisposed_ReturnsFalse()
{
Stream stream = MakeResponseStream();
stream.Dispose();
bool result = stream.CanRead;
Assert.False(result);
}
[Fact]
public void CanSeek_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanSeek;
Assert.False(result);
}
[Fact]
public void CanWrite_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanWrite;
Assert.False(result);
}
[Fact]
public void Length_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Length);
}
[Fact]
public void Length_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Length);
}
[Fact]
public void Position_WhenCreatedDoGet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Position);
}
[Fact]
public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Position);
}
[Fact]
public void Position_WhenCreatedDoSet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Position = 0);
}
[Fact]
public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Position = 0);
}
[Fact]
public void Seek_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
}
[Fact]
public void Seek_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin));
}
[Fact]
public void SetLength_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.SetLength(0));
}
[Fact]
public void SetLength_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.SetLength(0));
}
[Fact]
public void Write_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => stream.Write(new byte[1], 0, 1));
}
[Fact]
public void Write_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Write(new byte[1], 0, 1));
}
[Fact]
public void Read_BufferIsNull_ThrowsArgumentNullException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1));
}
[Fact]
public void Read_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[1], -1, 1));
}
[Fact]
public void Read_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[1], 0, -1));
}
[Fact]
public void Read_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentException>(() => stream.Read(new byte[1], int.MaxValue, int.MaxValue));
}
[Fact]
public void Read_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => stream.Read(new byte[1], 0, 1));
}
[Fact]
public void ReadAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { Task t = stream.ReadAsync(new byte[1], -1, 1); });
}
[Fact]
public void ReadAsync_NetworkFails_TaskIsFaultedWithIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorOnCompletion = true;
Task t = stream.ReadAsync(new byte[1], 0, 1);
AggregateException ex = Assert.Throws<AggregateException>(() => t.Wait());
Assert.IsType<IOException>(ex.InnerException);
}
[Fact]
public void ReadAsync_TokenIsAlreadyCanceled_TaskIsCanceled()
{
Stream stream = MakeResponseStream();
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.ReadAsync(new byte[1], 0, 1, cts.Token);
Assert.True(t.IsCanceled);
}
[Fact]
public void ReadAsync_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { Task t = stream.ReadAsync(new byte[1], 0, 1); });
}
[Fact]
public void ReadAsync_PriorReadInProgress_ThrowsInvalidOperationException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.Pause();
Task t1 = stream.ReadAsync(new byte[1], 0, 1);
Assert.Throws<InvalidOperationException>(() => { Task t2 = stream.ReadAsync(new byte[1], 0, 1); });
TestControl.WinHttpReadData.Resume();
t1.Wait();
}
[Fact]
public void Read_NetworkFails_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpReadData.ErrorOnCompletion = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_NoOffsetAndNotEndOfData_FillsBuffer()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
Assert.Equal(buffer.Length, bytesRead);
for (int i = 0; i < buffer.Length; i++)
{
Assert.Equal(testData[i], buffer[i]);
}
}
[Fact]
public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int offset = 5;
int bytesRead = stream.Read(buffer, offset, buffer.Length - offset);
Assert.Equal(buffer.Length - offset, bytesRead);
for (int i = 0; i < offset; i++)
{
Assert.Equal(0, buffer[i]);
}
for (int i = offset; i < buffer.Length; i++)
{
Assert.Equal(testData[i - offset], buffer[i]);
}
}
internal Stream MakeResponseStream()
{
var state = new WinHttpRequestState();
var handle = new FakeSafeWinHttpHandle(true);
handle.Callback = WinHttpRequestCallback.StaticCallbackDelegate;
handle.Context = state.ToIntPtr();
state.RequestHandle = handle;
return new WinHttpResponseStream(state);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS
{
/// <summary>
/// The MessageContent element represents the content of a message:
/// its properties, the recipients, and the attachments.
/// MessageContent = propList MessageChildren
/// </summary>
public class MessageContent : SyntacticalBase
{
/// <summary>
/// A propList value.
/// </summary>
private PropList propList;
/// <summary>
/// Represents children of the Message objects: Recipient and Attachment objects.
/// </summary>
private MessageChildren messageChildren;
/// <summary>
/// Initializes a new instance of the MessageContent class.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
public MessageContent(FastTransferStream stream)
: base(stream)
{
}
/// <summary>
/// Gets the propList.
/// </summary>
public PropList PropList
{
get
{
return this.propList;
}
}
/// <summary>
/// Gets the MessageChildren.
/// </summary>
public MessageChildren MessageChildren
{
get
{
return this.messageChildren;
}
}
/// <summary>
/// Gets a value indicating whether has a rtf body.
/// </summary>
public bool IsRTFFormat
{
get
{
if (this.PropList != null)
{
return this.PropList.HasPropertyTag(0x1009, 0x0102);
}
return false;
}
}
/// <summary>
/// Gets a value indicating whether all subObjects of this are in rtf format.
/// </summary>
public bool IsAllRTFFormat
{
get
{
if (this.PropList != null)
{
bool flag = this.PropList.HasPropertyTag(0x1009, 0x0102);
if (flag)
{
if (this.MessageChildren != null
&& this.MessageChildren.Attachments != null
&& this.MessageChildren.Attachments.Count > 0)
{
foreach (Attachment atta in this.MessageChildren.Attachments)
{
flag = flag && atta.IsRTFFormat;
if (!flag)
{
return false;
}
}
}
}
return flag;
}
return false;
}
}
/// <summary>
/// Gets a value indicating whether is a false message.
/// </summary>
public bool IsFAIMessage
{
get
{
if (this.PropList != null)
{
uint val = (uint)this.PropList.GetPropValue(0x0e07, 0x0003);
// mfFAI 0x00000040 The message is an FAI message.
return 0 != (val & 0x00000040);
}
return false;
}
}
/// <summary>
/// Verify that a stream's current position contains a serialized MessageContent.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
/// <returns>If the stream's current position contains
/// a serialized MessageContent, return true, else false.</returns>
public static bool Verify(FastTransferStream stream)
{
return PropList.Verify(stream);
}
/// <summary>
/// Get the corresponding AbstractFastTransferStream.
/// </summary>
/// <returns>The corresponding AbstractFastTransferStream.</returns>
public AbstractFastTransferStream GetAbstractFastTransferStream()
{
AbstractFastTransferStream abstractFastTransferStream = new AbstractFastTransferStream
{
StreamType = FastTransferStreamType.MessageContent
};
AbstractMessageContent abstractMessageContent = new AbstractMessageContent();
if (this.PropList != null && this.PropList.PropValues.Count > 0)
{
// Check the propList of MessageContent if one PropValue is a PtypString value,
// the StringPropertiesInUnicode of the AbstractMessageContent is true.
for (int i = 0; i < this.PropList.PropValues.Count; i++)
{
PropValue p = this.PropList.PropValues[i];
if (p.PropType == 0x1f)
{
abstractMessageContent.StringPropertiesInUnicode = true;
break;
}
}
for (int i = 0; i < this.PropList.PropValues.Count; i++)
{
PropValue p = this.PropList.PropValues[i];
// If server stored the string using Unicode, the code page property type should be 0x84B0, which specifies the Unicode (1200) code page, specified in section 2.2.4.1.1.1.
if (p.PropType == 0x84b0)
{
abstractMessageContent.StringPropertiesInUnicodeCodePage = true;
break;
}
}
for (int i = 0; i < this.PropList.PropValues.Count; i++)
{
PropValue p = this.PropList.PropValues[i];
// If server supports other formats (not Unicode), the PropType should not be 0X84b0, which specifies the Unicode (1200) code page, specified in section 2.2.4.1.1.1.
if (p.PropType - 0x8000 >= 0 && p.PropType != 0x84b0)
{
abstractMessageContent.StringPropertiesInOtherCodePage = true;
break;
}
}
}
else if (this.MessageChildren != null)
{
// Check the propList of MessageContent if one PropValue is a PtypString value,
// the StringPropertiesInUnicode of the AbstractMessageContent is true.
foreach (Recipient rec in this.MessageChildren.Recipients)
{
if (rec.PropList.HasPropertyType(0x1f))
{
abstractMessageContent.StringPropertiesInUnicode = true;
break;
}
// If server stored the string using Unicode, the code page property type should be 0x84B0, which specifies the Unicode (1200) code page, specified in section 2.2.4.1.1.1.
if (rec.PropList.HasPropertyType(0x84b0))
{
abstractMessageContent.StringPropertiesInUnicodeCodePage = true;
break;
}
for (int i = 0; i < rec.PropList.PropValues.Count; i++)
{
// If server supports other formats (not Unicode), the PropType should not be 0X84b0, which specifies the Unicode (1200) code page, specified in section 2.2.4.1.1.1.
if (rec.PropList.PropValues[i].PropType - 0x8000 >= 0 && rec.PropList.PropValues[i].PropType != 0x84b0)
{
abstractMessageContent.StringPropertiesInOtherCodePage = true;
break;
}
}
}
}
else
{
abstractMessageContent.StringPropertiesInUnicode = false;
}
if (this.MessageChildren != null)
{
// If MessageChildren contains attachments check whether attachments Preceded By PidTagFXDelProp.
if (this.MessageChildren.Attachments != null && this.MessageChildren.Attachments.Count > 0)
{
abstractMessageContent.AbsMessageChildren.AttachmentPrecededByPidTagFXDelProp
= this.MessageChildren.FXDelPropsBeforeAttachment != null
&& this.MessageChildren.FXDelPropsBeforeAttachment.Count > 0;
}
if (this.MessageChildren.Recipients != null && this.MessageChildren.Recipients.Count > 0)
{
abstractMessageContent.AbsMessageChildren.RecipientPrecededByPidTagFXDelProp
= this.MessageChildren.FXDelPropsBeforeRecipient != null
&& this.MessageChildren.FXDelPropsBeforeRecipient.Count > 0;
}
}
abstractFastTransferStream.AbstractMessageContent = abstractMessageContent;
return abstractFastTransferStream;
}
/// <summary>
/// Deserialize fields from a FastTransferStream.
/// </summary>
/// <param name="stream">A FastTransferStream.</param>
public override void Deserialize(FastTransferStream stream)
{
this.propList = new PropList(stream);
this.messageChildren = new MessageChildren(stream);
}
}
}
| |
// 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 CompareGreaterThanUnorderedScalarSingle()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanUnorderedScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanComparisonOpTest__CompareGreaterThanUnorderedScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private BooleanComparisonOpTest__DataTable<Single> _dataTable;
static BooleanComparisonOpTest__CompareGreaterThanUnorderedScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public BooleanComparisonOpTest__CompareGreaterThanUnorderedScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new BooleanComparisonOpTest__DataTable<Single>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareGreaterThanUnorderedScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareGreaterThanUnorderedScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareGreaterThanUnorderedScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
var result = Sse.CompareGreaterThanUnorderedScalar(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareGreaterThanUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanUnorderedScalarSingle();
var result = Sse.CompareGreaterThanUnorderedScalar(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse.CompareGreaterThanUnorderedScalar(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
if ((left[0] > right[0]) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareGreaterThanUnorderedScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using StateCorrelations;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AppendOnlyLog
{
public delegate IReadOnlyList<KeyValuePair<TSagaId, TOutput>>
MapOutputs<TSagaId, TSagaData, TOutput>(IReadOnlyDictionary<TSagaId, TSagaData> sagasById);
public class Program
{
private static IO IO<TInput>(TInput input)
=> Create.IO(input);
private static IO Load<TId, TDoc>(
IEnumerable<TId> ids,
out Lazy<IReadOnlyDictionary<TId, TDoc>> output)
=> Create.IO(
new BatchLoad<TId, TDoc>(ids),
out output);
private static IO Commit<TData>(TData data)
=> IO(new Commit<TData>(data));
private static IO IO<TInput, TOutput>(TInput input, out Lazy<TOutput> output)
=> Create.IO(input, out output);
static IEnumerable<IO> HandleEvents<TSagaId, TSagaData, TOutput>(
IEnumerable<KeyValuePair<TypeContract, Transition<TSagaData>>> stateTransitionsByEvent,
Func<TSagaData, TSagaId> sagaId,
Func<TSagaData> newSagaData,
bool replay,
MapOutputs<TSagaId, TSagaData, TOutput> mapOutputs)
{
var consumerName = new ConsumerName<TSagaData>();
var transactionId = Guid.NewGuid();
var stateTransitionsGroupedByEvents = stateTransitionsByEvent.ToDictionary(
x => x.Key,
x => x.Value);
IReadOnlyList<Event> events;
do
{
yield return IO(
new Offset<TSagaData>(consumerName, replay),
out Lazy<long?> offset);
yield return IO(
new EventFeedBy<TSagaData>(consumerName, offset.Value),
out Lazy<EventFeed> eventFeed);
events = eventFeed.Value.Events;
var eventsBySagaId = GroupEventsBy(
MapEventsToSaga(
events,
stateTransitionsGroupedByEvents,
newSagaData),
sagaId);
yield return Load(
eventsBySagaId.Keys,
out Lazy<IReadOnlyDictionary<TSagaId, Folded<TSagaData>>> savedSagaData);
var foldedSagaData = Fold(
Union(
Create.DictionaryPair(eventsBySagaId, savedSagaData.Value),
newSagaData),
stateTransitionsGroupedByEvents);
yield return Commit(new Transaction<TSagaId, TSagaData, TOutput>(
transactionId,
eventFeed.Value,
foldedSagaData,
mapOutputs));
} while (events != null && events.Any());
}
public static IEnumerable<KeyValuePair<Event, TSagaData>> MapEventsToSaga<TSagaData>(
IEnumerable<Event> events,
IReadOnlyDictionary<TypeContract, Transition<TSagaData>> stateTransitionsByEvent,
Func<TSagaData> getS)
=> events
.Where(e => stateTransitionsByEvent.Any(m => m.Key == TypeContract.From(e.Content)))
.Select(e => new KeyValuePair<Event, TSagaData>(
key: e,
value: stateTransitionsByEvent[TypeContract.From(e.Content)](e.Content, getS())));
public static IReadOnlyDictionary<TSagaId, IEnumerable<Event>> GroupEventsBy<TSagaId, TSagaData>(
IEnumerable<KeyValuePair<Event, TSagaData>> eventToSagaMaps,
Func<TSagaData, TSagaId> sagaIdentity)
=> eventToSagaMaps
.Select(eventToSagaMap => KeyValuePair.Create(
sagaIdentity(eventToSagaMap.Value),
eventToSagaMap.Key))
.GroupBy(eventSagaIdentityKvp => eventSagaIdentityKvp.Key)
.ToDictionary(
x => x.Key,
x => x.Select(e => e.Value));
static IReadOnlyDictionary<TSagaId, Foldable<TSagaId, TSagaData>> Union<TSagaId, TSagaData>(
DictionaryPair<TSagaId, IEnumerable<Event>, Folded<TSagaData>> dictionaryPair,
Func<TSagaData> newState)
{
var eventsBySagaId = dictionaryPair.Left;
var savedSagas = dictionaryPair.Right;
var existingGroup = savedSagas
.Where(saga => eventsBySagaId.ContainsKey(saga.Key))
.Select(saga => new
{
Id = saga.Key,
EventsBySaga = KeyValuePair.Create(saga.Value, eventsBySagaId[saga.Key])
});
var newGroup = eventsBySagaId
.Where(sagaEvents => savedSagas.All(x => !x.Key.Equals(sagaEvents.Key)))
.Select(sagaEvents => new
{
Id = sagaEvents.Key,
EventsBySaga = KeyValuePair.Create(
new Folded<TSagaData> { SagaData = newState() },
eventsBySagaId[sagaEvents.Key])
});
return existingGroup
.Union(newGroup)
.ToDictionary(
x => x.Id,
x => Create.Foldable(x.Id, x.EventsBySaga.Key, x.EventsBySaga.Value));
}
public static IReadOnlyDictionary<TSagaId , Folded<TSagaData>> Fold<TSagaId, TSagaData>(
IReadOnlyDictionary<TSagaId, Foldable<TSagaId, TSagaData>> dictionary,
IReadOnlyDictionary<TypeContract, Transition<TSagaData>> stateTransitionsByEvent)
=> dictionary
.Select(x => KeyValuePair.Create(
x.Key,
FoldEventsToState(
x.Value.Events,
stateTransitionsByEvent,
x.Value.SagaData)))
.ToDictionary(x => x.Key, x => x.Value);
public static Folded<TSagaData> FoldEventsToState<TSagaData>(
IEnumerable<Event> events,
IReadOnlyDictionary<TypeContract, Transition<TSagaData>> stateTransitionsByEvent,
Folded<TSagaData> folded)
{
foreach (var @event in events
.Where(e => e.Offset > folded.OffsetEnd)
.OrderBy(e => e.Offset))
{
var contract = TypeContract.From(@event.Content);
if (stateTransitionsByEvent.TryGetValue(contract, out Transition<TSagaData> transition))
{
try
{
folded.SagaData = transition(@event.Content, folded.SagaData);
folded.OffsetEnd = @event.Offset;
folded.OffsetStart = folded.OffsetStart ?? folded.OffsetEnd;
}
catch
{
folded.ExceptionAtOffset = @event.Offset;
return folded;
}
}
}
return folded;
}
}
struct EventFeed
{
public EventFeed(IReadOnlyList<Event> events, bool replaying)
{
Events = events;
Replaying = replaying;
}
public IReadOnlyList<Event> Events { get; }
public bool Replaying { get; }
}
struct Transaction<TSagaId, TSagaData, TOutput>
{
public Transaction(
Guid transactionId,
EventFeed eventFeed,
IReadOnlyDictionary<TSagaId, Folded<TSagaData>> sagas,
MapOutputs<TSagaId, TSagaData, TOutput> mapOutputs)
{
TransactionId = transactionId;
EventFeed = eventFeed;
Sagas = sagas;
ConsumerName = new ConsumerName<TSagaData>();
Outputs = eventFeed.Replaying
? new List<KeyValuePair<TSagaId, TOutput>>()
: mapOutputs(sagas
.Where(x => !x.Value.ExceptionAtOffset.HasValue)
.ToDictionary(x => x.Key, x => x.Value.SagaData));
}
public Guid TransactionId { get; }
public EventFeed EventFeed { get; }
public IReadOnlyDictionary<TSagaId, Folded<TSagaData>> Sagas { get; }
public ConsumerName<TSagaData> ConsumerName { get; }
public IReadOnlyList<KeyValuePair<TSagaId, TOutput>> Outputs { get; }
}
struct Commit<TData>
{
public Commit(TData data)
{
Data = data;
}
public readonly TData Data;
}
struct BatchLoad<TId, TDoc>
{
public BatchLoad(IEnumerable<TId> ids)
{
Ids = ids;
}
public readonly IEnumerable<TId> Ids;
}
struct EventFeedBy<TSagaData>
{
public readonly long Offset;
public readonly ConsumerName<TSagaData> ConsumerName;
public EventFeedBy(ConsumerName<TSagaData> consumerName, long? offset)
{
ConsumerName = consumerName;
Offset = offset ?? 0;
}
}
struct ConsumerName<TSagaData>
{ }
struct Offset<TSagaData>
{
public Offset(ConsumerName<TSagaData> name, bool replay)
{
ConsumerName = name;
Replay = replay;
}
public readonly ConsumerName<TSagaData> ConsumerName;
public readonly bool Replay;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
public class TripleSlashCommentModel
{
private const string idSelector = @"((?![0-9])[\w_])+[\w\(\)\.\{\}\[\]\|\*\^~#@!`,_<>:]*";
private static Regex CommentIdRegex = new Regex(@"^(?<type>N|T|M|P|F|E|Overload):(?<id>" + idSelector + ")$", RegexOptions.Compiled);
private static Regex LineBreakRegex = new Regex(@"\r?\n", RegexOptions.Compiled);
private static Regex CodeElementRegex = new Regex(@"<code[^>]*>([\s\S]*?)</code>", RegexOptions.Compiled);
private readonly ITripleSlashCommentParserContext _context;
public string Summary { get; private set; }
public string Remarks { get; private set; }
public string Returns { get; private set; }
public List<ExceptionInfo> Exceptions { get; private set; }
public List<LinkInfo> Sees { get; private set; }
public List<LinkInfo> SeeAlsos { get; private set; }
public List<string> Examples { get; private set; }
public Dictionary<string, string> Parameters { get; private set; }
public Dictionary<string, string> TypeParameters { get; private set; }
public bool IsInheritDoc { get; private set; }
private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
// Transform triple slash comment
XDocument doc = TripleSlashCommentTransformer.Transform(xml, language);
_context = context;
if (!context.PreserveRawInlineComments)
{
ResolveSeeCref(doc, context.AddReferenceDelegate);
ResolveSeeAlsoCref(doc, context.AddReferenceDelegate);
}
var nav = doc.CreateNavigator();
Summary = GetSummary(nav, context);
Remarks = GetRemarks(nav, context);
Returns = GetReturns(nav, context);
Exceptions = GetExceptions(nav, context);
Sees = GetSees(nav, context);
SeeAlsos = GetSeeAlsos(nav, context);
Examples = GetExamples(nav, context);
Parameters = GetParameters(nav, context);
TypeParameters = GetTypeParameters(nav, context);
IsInheritDoc = GetIsInheritDoc(nav, context);
}
public static TripleSlashCommentModel CreateModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (string.IsNullOrEmpty(xml)) return null;
// Quick turnaround for badly formed XML comment
if (xml.StartsWith("<!-- Badly formed XML comment ignored for member "))
{
Logger.LogWarning($"Invalid triple slash comment is ignored: {xml}");
return null;
}
try
{
var model = new TripleSlashCommentModel(xml, language, context);
return model;
}
catch (XmlException)
{
return null;
}
}
public void CopyInheritedData(TripleSlashCommentModel src)
{
if (src == null)
throw new ArgumentNullException(nameof(src));
if (Summary == null)
Summary = src.Summary;
if (Remarks == null)
Remarks = src.Remarks;
if (Returns == null)
Returns = src.Returns;
if (Exceptions == null && src.Exceptions != null)
Exceptions = src.Exceptions.Select(e => e.Clone()).ToList();
if (Sees == null && src.Sees != null)
Sees = src.Sees.Select(s => s.Clone()).ToList();
if (SeeAlsos == null && src.SeeAlsos != null)
SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList();
if (Examples == null && src.Examples != null)
Examples = new List<string>(src.Examples);
if (Parameters == null && src.Parameters != null)
Parameters = new Dictionary<string, string>(src.Parameters);
if (TypeParameters == null && src.TypeParameters != null)
TypeParameters = new Dictionary<string, string>(src.TypeParameters);
}
public string GetParameter(string name)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return GetValue(name, Parameters);
}
public string GetTypeParameter(string name)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return GetValue(name, TypeParameters);
}
private static string GetValue(string name, Dictionary<string, string> dictionary)
{
if (dictionary == null) return null;
string description;
if (dictionary.TryGetValue(name, out description))
{
return description;
}
return null;
}
/// <summary>
/// Get summary node out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <example>
/// <code> <see cref="Hello"/></code>
/// </example>
private string GetSummary(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/summary";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get remarks node out from triple slash comments
/// </summary>
/// <remarks>
/// <para>This is a sample of exception node</para>
/// </remarks>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
private string GetRemarks(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/remarks";
return GetSingleNodeValue(nav, selector);
}
private string GetReturns(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/returns";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get exceptions nodes out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <exception cref="XmlException">This is a sample of exception node</exception>
private List<ExceptionInfo> GetExceptions(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/exception";
var result = GetMulitpleCrefInfo(nav, selector).ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `see` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <see cref="SpecIdHelper"/>
/// <see cref="SourceSwitch"/>
private List<LinkInfo> GetSees(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/see").ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `seealso` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <seealso cref="WaitForChangedResult"/>
/// <seealso cref="http://google.com">ABCS</seealso>
private List<LinkInfo> GetSeeAlsos(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/seealso").ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `example` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <example>
/// This sample shows how to call the <see cref="GetExceptions(string, ITripleSlashCommentParserContext)"/> method.
/// <code>
/// class TestClass
/// {
/// static int Main()
/// {
/// return GetExceptions(null, null).Count();
/// }
/// }
/// </code>
/// </example>
private List<string> GetExamples(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
return GetMultipleExampleNodes(nav, "/member/example").ToList();
}
private bool GetIsInheritDoc(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var node = nav.SelectSingleNode("/member/inheritdoc");
if (node == null)
return false;
if (node.HasAttributes)
{
//The Sandcastle implementation of <inheritdoc /> supports two attributes: 'cref' and 'select'.
//These attributes allow changing the source of the inherited doc and controlling what is inherited.
//Until these attributes are supported, ignoring inheritdoc elements with attributes, so as not to misinterpret them.
Logger.LogWarning("Attributes on <inheritdoc /> elements are not supported; inheritdoc element will be ignored.");
return false;
}
return true;
}
private Dictionary<string, string> GetListContent(XPathNavigator navigator, string xpath, string contentType, ITripleSlashCommentParserContext context)
{
var iterator = navigator.Select(xpath);
var result = new Dictionary<string, string>();
if (iterator == null) return result;
foreach (XPathNavigator nav in iterator)
{
string name = nav.GetAttribute("name", string.Empty);
string description = GetXmlValue(nav);
if (!string.IsNullOrEmpty(name))
{
if (result.ContainsKey(name))
{
string path = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path;
Logger.LogWarning($"Duplicate {contentType} '{name}' found in comments, the latter one is ignored.", null, StringExtension.ToDisplayPath(path), context.Source.StartLine.ToString());
}
else
{
result.Add(name, description);
}
}
}
return result;
}
private Dictionary<string, string> GetParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/param", "parameter", context);
}
private Dictionary<string, string> GetTypeParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/typeparam", "type parameter", context);
}
private void ResolveSeeAlsoCref(XNode node, Action<string, string> addReference)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//seealso[@cref]", addReference);
}
private void ResolveSeeCref(XNode node, Action<string, string> addReference)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//see[@cref]", addReference);
}
private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, string> addReference)
{
if (node == null || string.IsNullOrEmpty(nodeSelector)) return;
try
{
var nodes = node.XPathSelectElements(nodeSelector + "[@cref]").ToList();
foreach (var item in nodes)
{
var cref = item.Attribute("cref").Value;
// Strict check is needed as value could be an invalid href,
// e.g. !:Dictionary<TKey, string> when user manually changed the intellisensed generic type
var match = CommentIdRegex.Match(cref);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
// When see and seealso are top level nodes in triple slash comments, do not convert it into xref node
if (item.Parent?.Parent != null)
{
var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(id)}\" data-throw-if-not-resolved=\"false\"></xref>");
item.ReplaceWith(replacement);
}
if (addReference != null)
{
addReference(id, cref);
}
}
else
{
var detailedInfo = new StringBuilder();
if (_context != null && _context.Source != null)
{
if (!string.IsNullOrEmpty(_context.Source.Name))
{
detailedInfo.Append(" for ");
detailedInfo.Append(_context.Source.Name);
}
if (!string.IsNullOrEmpty(_context.Source.Path))
{
detailedInfo.Append(" defined in ");
detailedInfo.Append(_context.Source.Path);
detailedInfo.Append(" Line ");
detailedInfo.Append(_context.Source.StartLine);
}
}
Logger.Log(LogLevel.Warning, $"Invalid cref value \"{cref}\" found in triple-slash-comments{detailedInfo}, ignored.");
}
}
}
catch
{
}
}
private IEnumerable<string> GetMultipleExampleNodes(XPathNavigator navigator, string selector)
{
var iterator = navigator.Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
yield return description;
}
}
private IEnumerable<ExceptionInfo> GetMulitpleCrefInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
string commentId = nav.GetAttribute("cref", string.Empty);
if (!string.IsNullOrEmpty(commentId))
{
// Check if exception type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "T")
{
if (string.IsNullOrEmpty(description)) description = null;
yield return new ExceptionInfo { Description = description, Type = id, CommentId = commentId };
}
}
}
}
}
private IEnumerable<LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string altText = GetXmlValue(nav);
if (string.IsNullOrEmpty(altText)) altText = null;
string commentId = nav.GetAttribute("cref", string.Empty);
string url = nav.GetAttribute("href", string.Empty);
if (!string.IsNullOrEmpty(commentId))
{
// Check if cref type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
yield return new LinkInfo { AltText = altText, LinkId = id, CommentId = commentId, LinkType = LinkType.CRef };
}
}
else if (!string.IsNullOrEmpty(url))
{
yield return new LinkInfo { AltText = altText ?? url, LinkId = url, LinkType = LinkType.HRef };
}
}
}
private string GetSingleNodeValue(XPathNavigator nav, string selector)
{
var node = nav.Clone().SelectSingleNode(selector);
if (node == null)
{
// throw new ArgumentException(selector + " is not found");
return null;
}
else
{
var output = GetXmlValue(node);
return output;
}
}
private string GetXmlValue(XPathNavigator node)
{
// NOTE: use node.InnerXml instead of node.Value, to keep decorative nodes,
// e.g.
// <remarks><para>Value</para></remarks>
// decode InnerXml as it encodes
// IXmlLineInfo.LinePosition starts from 1 and it would ignore '<'
// e.g.
// <summary/> the LinePosition is the column number of 's', so it should be minus 2
var lineInfo = node as IXmlLineInfo;
int column = lineInfo.HasLineInfo() ? lineInfo.LinePosition - 2 : 0;
return NormalizeXml(RemoveLeadingSpaces(node.InnerXml), column);
}
/// <summary>
/// Remove least common whitespces in each line of xml
/// </summary>
/// <param name="xml"></param>
/// <returns>xml after removing least common whitespaces</returns>
private static string RemoveLeadingSpaces(string xml)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
var preIndex = 0;
var leadingSpaces = from line in lines
where !string.IsNullOrWhiteSpace(line)
select line.TakeWhile(char.IsWhiteSpace).Count();
if (leadingSpaces.Any())
{
preIndex = leadingSpaces.Min();
}
if (preIndex == 0)
{
return xml;
}
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
normalized.Add(line.Substring(preIndex));
}
}
return string.Join("\n", normalized);
}
/// <summary>
/// Split xml into lines. Trim meaningless whitespaces.
/// if a line starts with xml node, all leading whitespaces would be trimmed
/// otherwise text node start position always aligns with the start position of its parent line(the last previous line that starts with xml node)
/// Trim newline character for code element.
/// </summary>
/// <param name="xml"></param>
/// <param name="parentIndex">the start position of the last previous line that starts with xml node</param>
/// <returns>normalized xml</returns>
private static string NormalizeXml(string xml, int parentIndex)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
// TO-DO: special logic for TAB case
int index = line.TakeWhile(char.IsWhiteSpace).Count();
if (line[index] == '<')
{
parentIndex = index;
}
normalized.Add(line.Substring(Math.Min(parentIndex, index)));
}
}
// trim newline character for code element
return CodeElementRegex.Replace(
string.Join("\n", normalized),
m =>
{
var group = m.Groups[1];
if (group.ToString() == string.Empty)
{
return m.Value;
}
return m.Value.Replace(group.ToString(), group.ToString().Trim('\n'));
});
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected static SqliteConnection m_Connection;
private static bool m_initialized;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (!m_initialized)
{
m_Connection = new SqliteConnection(connectionString);
//Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString));
m_Connection.Open();
if (storeName != String.Empty)
{
//SqliteConnection newConnection =
// (SqliteConnection)((ICloneable)m_Connection).Clone();
//newConnection.Open();
//Migration m = new Migration(newConnection, Assembly, storeName);
Migration m = new Migration(m_Connection, Assembly, storeName);
m.Update();
//newConnection.Close();
//newConnection.Dispose();
}
m_initialized = true;
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (SqliteCommand cmd = new SqliteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
protected T[] DoQuery(SqliteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd, m_Connection);
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
//CloseCommand(cmd);
return result.ToArray();
}
public virtual T[] Get(string where)
{
using (SqliteCommand cmd = new SqliteCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
using (SqliteCommand cmd = new SqliteCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (SqliteCommand cmd = new SqliteCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
terms.Add("`" + fields[i] + "` = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("delete from {0} where {1}", m_Realm, where);
cmd.CommandText = query;
return ExecuteNonQuery(cmd, m_Connection) > 0;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.EventUserModel
{
using System.Collections;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.HSSF.UserModel;
using System.Collections.Generic;
/// <summary>
/// When working with the EventUserModel, if you want to
/// Process formulas, you need an instance of
/// Workbook to pass to a HSSFWorkbook,
/// to finally give to HSSFFormulaParser,
/// and this will build you stub ones.
/// Since you're working with the EventUserModel, you
/// wouldn't want to Get a full Workbook and
/// HSSFWorkbook, as they would eat too much memory.
/// Instead, you should collect a few key records as they
/// go past, then call this once you have them to build a
/// stub Workbook, and from that a stub
/// HSSFWorkbook, to use with the HSSFFormulaParser.
/// The records you should collect are:
/// ExternSheetRecord
/// BoundSheetRecord
/// You should probably also collect SSTRecord,
/// but it's not required to pass this in.
/// To help, this class includes a HSSFListener wrapper
/// that will do the collecting for you.
/// </summary>
public class EventWorkbookBuilder
{
/// <summary>
/// Wraps up your stub Workbook as a stub HSSFWorkbook, ready for passing to HSSFFormulaParser
/// </summary>
/// <param name="workbook">The stub workbook.</param>
/// <returns></returns>
public static HSSFWorkbook CreateStubHSSFWorkbook(InternalWorkbook workbook)
{
return new StubHSSFWorkbook(workbook);
}
/// <summary>
/// Creates a stub Workbook from the supplied records,
/// suitable for use with the {@link HSSFFormulaParser}
/// </summary>
/// <param name="externs">The ExternSheetRecords in your file</param>
/// <param name="bounds">The BoundSheetRecords in your file</param>
/// <param name="sst">TThe SSTRecord in your file.</param>
/// <returns>A stub Workbook suitable for use with HSSFFormulaParser</returns>
public static InternalWorkbook CreateStubWorkbook(ExternSheetRecord[] externs,
BoundSheetRecord[] bounds, SSTRecord sst)
{
List<Record> wbRecords = new List<Record>();
// Core Workbook records go first
if (bounds != null)
{
for (int i = 0; i < bounds.Length; i++)
{
wbRecords.Add(bounds[i]);
}
}
if (sst != null)
{
wbRecords.Add(sst);
}
// Now we can have the ExternSheetRecords,
// preceded by a SupBookRecord
if (externs != null)
{
wbRecords.Add(SupBookRecord.CreateInternalReferences(
(short)externs.Length));
for (int i = 0; i < externs.Length; i++)
{
wbRecords.Add(externs[i]);
}
}
// Finally we need an EoF record
wbRecords.Add(EOFRecord.instance);
return InternalWorkbook.CreateWorkbook(wbRecords);
}
/// <summary>
/// Creates a stub workbook from the supplied records,
/// suitable for use with the HSSFFormulaParser
/// </summary>
/// <param name="externs">The ExternSheetRecords in your file</param>
/// <param name="bounds">A stub Workbook suitable for use with HSSFFormulaParser</param>
/// <returns>A stub Workbook suitable for use with {@link HSSFFormulaParser}</returns>
public static InternalWorkbook CreateStubWorkbook(ExternSheetRecord[] externs,
BoundSheetRecord[] bounds)
{
return CreateStubWorkbook(externs, bounds, null);
}
/// <summary>
/// A wrapping HSSFListener which will collect
/// BoundSheetRecords and {@link ExternSheetRecord}s as
/// they go past, so you can Create a Stub {@link Workbook} from
/// them once required.
/// </summary>
public class SheetRecordCollectingListener : IHSSFListener
{
private IHSSFListener childListener;
private ArrayList boundSheetRecords = new ArrayList();
private ArrayList externSheetRecords = new ArrayList();
private SSTRecord sstRecord = null;
/// <summary>
/// Initializes a new instance of the <see cref="SheetRecordCollectingListener"/> class.
/// </summary>
/// <param name="childListener">The child listener.</param>
public SheetRecordCollectingListener(IHSSFListener childListener)
{
this.childListener = childListener;
}
/// <summary>
/// Gets the bound sheet records.
/// </summary>
/// <returns></returns>
public BoundSheetRecord[] GetBoundSheetRecords()
{
return (BoundSheetRecord[])boundSheetRecords.ToArray(
typeof(BoundSheetRecord)
);
}
/// <summary>
/// Gets the extern sheet records.
/// </summary>
/// <returns></returns>
public ExternSheetRecord[] GetExternSheetRecords()
{
return (ExternSheetRecord[])externSheetRecords.ToArray(
typeof(ExternSheetRecord)
);
}
/// <summary>
/// Gets the SST record.
/// </summary>
/// <returns></returns>
public SSTRecord GetSSTRecord()
{
return sstRecord;
}
/// <summary>
/// Gets the stub HSSF workbook.
/// </summary>
/// <returns></returns>
public HSSFWorkbook GetStubHSSFWorkbook()
{
return CreateStubHSSFWorkbook(
GetStubWorkbook()
);
}
/// <summary>
/// Gets the stub workbook.
/// </summary>
/// <returns></returns>
public InternalWorkbook GetStubWorkbook()
{
return CreateStubWorkbook(
GetExternSheetRecords(), GetBoundSheetRecords(),
GetSSTRecord()
);
}
/// <summary>
/// Process this record ourselves, and then
/// pass it on to our child listener
/// </summary>
/// <param name="record">The record.</param>
public void ProcessRecord(Record record)
{
// Handle it ourselves
ProcessRecordInternally(record);
// Now pass on to our child
childListener.ProcessRecord(record);
}
/// <summary>
/// Process the record ourselves, but do not
/// pass it on to the child Listener.
/// </summary>
/// <param name="record">The record.</param>
public void ProcessRecordInternally(Record record)
{
if (record is BoundSheetRecord)
{
boundSheetRecords.Add(record);
}
else if (record is ExternSheetRecord)
{
externSheetRecords.Add(record);
}
else if (record is SSTRecord)
{
sstRecord = (SSTRecord)record;
}
}
}
/**
* Let us at the {@link Workbook} constructor on
* {@link HSSFWorkbook}
*/
private class StubHSSFWorkbook : HSSFWorkbook
{
public StubHSSFWorkbook(InternalWorkbook wb)
: base(wb)
{
}
}
}
}
| |
namespace EIDSS.Reports.Parameterized.Veterinary.Situation
{
partial class VetSituationReport
{
#region 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(VetSituationReport));
DevExpress.XtraCharts.XYDiagram xyDiagram1 = new DevExpress.XtraCharts.XYDiagram();
DevExpress.XtraCharts.Series series1 = new DevExpress.XtraCharts.Series();
DevExpress.XtraCharts.SideBySideBarSeriesLabel sideBySideBarSeriesLabel1 = new DevExpress.XtraCharts.SideBySideBarSeriesLabel();
DevExpress.XtraCharts.SideBySideBarSeriesLabel sideBySideBarSeriesLabel2 = new DevExpress.XtraCharts.SideBySideBarSeriesLabel();
DevExpress.XtraCharts.ChartTitle chartTitle1 = new DevExpress.XtraCharts.ChartTitle();
this.vetSituationDataSet1 = new EIDSS.Reports.Parameterized.Veterinary.Situation.VetSituationDataSet();
this.tableHeader = new DevExpress.XtraReports.UI.XRTable();
this.rowHeader1 = new DevExpress.XtraReports.UI.XRTableRow();
this.cell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.cell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellType = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellPerson = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1 = new EIDSS.Reports.Parameterized.Veterinary.Situation.VetSituationDataSetTableAdapters.sp_rep_VET_YearlyVeterinarySituationTableAdapter();
this.xrChart1 = new DevExpress.XtraReports.UI.XRChart();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.vetSituationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrChart1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(xyDiagram1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(series1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// xrTable4
//
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseFont = false;
this.xrTable4.StylePriority.UsePadding = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableHeader});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.PrintOn = DevExpress.XtraReports.UI.PrintOnPages.NotWithReportFooter;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// tableBaseHeader
//
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// vetSituationDataSet1
//
this.vetSituationDataSet1.DataSetName = "VetSituationDataSet";
this.vetSituationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// tableHeader
//
this.tableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableHeader, "tableHeader");
this.tableHeader.Name = "tableHeader";
this.tableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.rowHeader1});
this.tableHeader.StylePriority.UseBorders = false;
this.tableHeader.StylePriority.UseFont = false;
this.tableHeader.StylePriority.UseTextAlignment = false;
//
// rowHeader1
//
this.rowHeader1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cell1,
this.xrTableCell1,
this.cell4,
this.xrTableCell2,
this.cell5,
this.xrTableCell5,
this.cell6,
this.xrTableCell6,
this.cellType,
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell10,
this.xrTableCell4,
this.cellPerson});
resources.ApplyResources(this.rowHeader1, "rowHeader1");
this.rowHeader1.Name = "rowHeader1";
this.rowHeader1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.rowHeader1.StylePriority.UseFont = false;
this.rowHeader1.StylePriority.UsePadding = false;
this.rowHeader1.StylePriority.UseTextAlignment = false;
//
// cell1
//
resources.ApplyResources(this.cell1, "cell1");
this.cell1.Name = "cell1";
this.cell1.StylePriority.UseFont = false;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
//
// cell4
//
resources.ApplyResources(this.cell4, "cell4");
this.cell4.Name = "cell4";
this.cell4.StylePriority.UseFont = false;
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
//
// cell5
//
resources.ApplyResources(this.cell5, "cell5");
this.cell5.Name = "cell5";
this.cell5.StylePriority.UseFont = false;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseFont = false;
//
// cell6
//
resources.ApplyResources(this.cell6, "cell6");
this.cell6.Name = "cell6";
this.cell6.StylePriority.UseFont = false;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseFont = false;
//
// cellType
//
resources.ApplyResources(this.cellType, "cellType");
this.cellType.Name = "cellType";
this.cellType.StylePriority.UseFont = false;
this.cellType.StylePriority.UseTextAlignment = false;
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseFont = false;
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
//
// cellPerson
//
resources.ApplyResources(this.cellPerson, "cellPerson");
this.cellPerson.Name = "cellPerson";
this.cellPerson.StylePriority.UseFont = false;
this.cellPerson.StylePriority.UseTextAlignment = false;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.DataAdapter = this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1;
this.DetailReport.DataMember = "spRepVetYearlyVeterinarySituation";
this.DetailReport.DataSource = this.vetSituationDataSet1;
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.xrTableCell9,
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell13,
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrTableRow1.StylePriority.UseBorders = false;
this.xrTableRow1.StylePriority.UseFont = false;
this.xrTableRow1.StylePriority.UsePadding = false;
this.xrTableRow1.StylePriority.UseTextAlignment = false;
//
// xrTableCell3
//
this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Disease")});
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
//
// xrTableCell9
//
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jan")});
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseFont = false;
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Feb")});
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Mar")});
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Apr")});
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.May")});
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jun")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseFont = false;
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Jul")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseFont = false;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Aug")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.StylePriority.UseTextAlignment = false;
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Sep")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseFont = false;
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Oct")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseFont = false;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Nov")});
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
//
// xrTableCell21
//
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Dec")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseFont = false;
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetYearlyVeterinarySituation.Total")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
//
// sp_rep_VET_YearlyVeterinarySituationTableAdapter1
//
this.sp_rep_VET_YearlyVeterinarySituationTableAdapter1.ClearBeforeFill = true;
//
// xrChart1
//
resources.ApplyResources(this.xrChart1, "xrChart1");
this.xrChart1.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
xyDiagram1.AxisX.Label.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
xyDiagram1.AxisX.MinorCount = 1;
xyDiagram1.AxisX.Title.Text = resources.GetString("resource.Text");
xyDiagram1.AxisX.Title.Visibility = DevExpress.Utils.DefaultBoolean.True;
xyDiagram1.AxisX.VisibleInPanesSerializable = "-1";
xyDiagram1.AxisY.DateTimeScaleOptions.AutoGrid = false;
xyDiagram1.AxisY.NumericScaleOptions.AutoGrid = false;
xyDiagram1.AxisY.Tickmarks.MinorVisible = false;
xyDiagram1.AxisY.Title.Text = resources.GetString("resource.Text1");
xyDiagram1.AxisY.Title.Visibility = DevExpress.Utils.DefaultBoolean.True;
xyDiagram1.AxisY.VisibleInPanesSerializable = "-1";
this.xrChart1.Diagram = xyDiagram1;
this.xrChart1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
this.xrChart1.Name = "xrChart1";
series1.ArgumentDataMember = "Disease";
series1.DataSource = this.vetSituationDataSet1.spRepVetYearlyVeterinarySituation;
sideBySideBarSeriesLabel1.LineVisibility = DevExpress.Utils.DefaultBoolean.True;
series1.Label = sideBySideBarSeriesLabel1;
series1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.False;
resources.ApplyResources(series1, "series1");
series1.ValueDataMembersSerializable = "Total";
this.xrChart1.SeriesSerializable = new DevExpress.XtraCharts.Series[] {
series1};
sideBySideBarSeriesLabel2.LineVisibility = DevExpress.Utils.DefaultBoolean.True;
this.xrChart1.SeriesTemplate.Label = sideBySideBarSeriesLabel2;
this.xrChart1.StylePriority.UseBorders = false;
resources.ApplyResources(chartTitle1, "chartTitle1");
this.xrChart1.Titles.AddRange(new DevExpress.XtraCharts.ChartTitle[] {
chartTitle1});
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrChart1});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// VetSituationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport,
this.ReportFooter});
this.Version = "15.1";
this.Controls.SetChildIndex(this.ReportFooter, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.vetSituationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(xyDiagram1)).EndInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(series1)).EndInit();
((System.ComponentModel.ISupportInitialize)(sideBySideBarSeriesLabel2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrChart1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableHeader;
private DevExpress.XtraReports.UI.XRTableRow rowHeader1;
private DevExpress.XtraReports.UI.XRTableCell cell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell cell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell cell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell cell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell cellType;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell cellPerson;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private VetSituationDataSetTableAdapters.sp_rep_VET_YearlyVeterinarySituationTableAdapter sp_rep_VET_YearlyVeterinarySituationTableAdapter1;
private VetSituationDataSet vetSituationDataSet1;
private DevExpress.XtraReports.UI.XRChart xrChart1;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
}
}
| |
//
// Tuples.cs
//
// Authors:
// Zoltan Varga (vargaz@gmail.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2009 Novell
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace System
{
public partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
{
public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
this.item6 = item6;
this.item7 = item7;
this.rest = rest;
if (!(rest is ITuple))
throw new ArgumentException ("rest", "The last element of an eight element tuple must be a Tuple.");
}
}
interface ITuple
{
string ToString ();
}
/* The rest is generated by the script at the bottom */
[Serializable]
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
public Tuple (T1 item1)
{
this.item1 = item1;
}
public T1 Item1 {
get { return item1; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
return comparer.Compare (item1, t.item1);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
return comparer.GetHashCode (item1);
}
string ITuple.ToString ()
{
return String.Format ("{0}", item1);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
public Tuple (T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
return comparer.Compare (item2, t.item2);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}", item1, item2);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
public Tuple (T1 item1, T2 item2, T3 item3)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
return comparer.Compare (item3, t.item3);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item3);
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}", item1, item2, item3);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
T4 item4;
public Tuple (T1 item1, T2 item2, T3 item3, T4 item4)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
public T4 Item4 {
get { return item4; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
res = comparer.Compare (item3, t.item3);
if (res != 0) return res;
return comparer.Compare (item4, t.item4);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3) &&
comparer.Equals (item4, t.item4);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0, h1;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h1 = comparer.GetHashCode (item3);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item4);
h0 = (h0 << 5) + h0 ^ h1;
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}, {3}", item1, item2, item3, item4);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
T4 item4;
T5 item5;
public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
public T4 Item4 {
get { return item4; }
}
public T5 Item5 {
get { return item5; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
res = comparer.Compare (item3, t.item3);
if (res != 0) return res;
res = comparer.Compare (item4, t.item4);
if (res != 0) return res;
return comparer.Compare (item5, t.item5);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3) &&
comparer.Equals (item4, t.item4) &&
comparer.Equals (item5, t.item5);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0, h1;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h1 = comparer.GetHashCode (item3);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item4);
h0 = (h0 << 5) + h0 ^ h1;
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item5);
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}, {3}, {4}", item1, item2, item3, item4, item5);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
T4 item4;
T5 item5;
T6 item6;
public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
this.item6 = item6;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
public T4 Item4 {
get { return item4; }
}
public T5 Item5 {
get { return item5; }
}
public T6 Item6 {
get { return item6; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
res = comparer.Compare (item3, t.item3);
if (res != 0) return res;
res = comparer.Compare (item4, t.item4);
if (res != 0) return res;
res = comparer.Compare (item5, t.item5);
if (res != 0) return res;
return comparer.Compare (item6, t.item6);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3) &&
comparer.Equals (item4, t.item4) &&
comparer.Equals (item5, t.item5) &&
comparer.Equals (item6, t.item6);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0, h1;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h1 = comparer.GetHashCode (item3);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item4);
h0 = (h0 << 5) + h0 ^ h1;
h1 = comparer.GetHashCode (item5);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item6);
h0 = (h0 << 5) + h0 ^ h1;
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}, {3}, {4}, {5}", item1, item2, item3, item4, item5, item6);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
T4 item4;
T5 item5;
T6 item6;
T7 item7;
public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
this.item6 = item6;
this.item7 = item7;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
public T4 Item4 {
get { return item4; }
}
public T5 Item5 {
get { return item5; }
}
public T6 Item6 {
get { return item6; }
}
public T7 Item7 {
get { return item7; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
res = comparer.Compare (item3, t.item3);
if (res != 0) return res;
res = comparer.Compare (item4, t.item4);
if (res != 0) return res;
res = comparer.Compare (item5, t.item5);
if (res != 0) return res;
res = comparer.Compare (item6, t.item6);
if (res != 0) return res;
return comparer.Compare (item7, t.item7);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3) &&
comparer.Equals (item4, t.item4) &&
comparer.Equals (item5, t.item5) &&
comparer.Equals (item6, t.item6) &&
comparer.Equals (item7, t.item7);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0, h1;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h1 = comparer.GetHashCode (item3);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item4);
h0 = (h0 << 5) + h0 ^ h1;
h1 = comparer.GetHashCode (item5);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item6);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item7);
h0 = (h0 << 5) + h0 ^ h1;
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}, {3}, {4}, {5}, {6}", item1, item2, item3, item4, item5, item6, item7);
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
[Serializable]
public partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
T1 item1;
T2 item2;
T3 item3;
T4 item4;
T5 item5;
T6 item6;
T7 item7;
TRest rest;
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
public T3 Item3 {
get { return item3; }
}
public T4 Item4 {
get { return item4; }
}
public T5 Item5 {
get { return item5; }
}
public T6 Item6 {
get { return item6; }
}
public T7 Item7 {
get { return item7; }
}
public TRest Rest {
get { return rest; }
}
int IComparable.CompareTo (object obj)
{
return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);
}
int IStructuralComparable.CompareTo (object other, IComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (t == null) {
if (other == null) return 1;
throw new ArgumentException ("other");
}
int res = comparer.Compare (item1, t.item1);
if (res != 0) return res;
res = comparer.Compare (item2, t.item2);
if (res != 0) return res;
res = comparer.Compare (item3, t.item3);
if (res != 0) return res;
res = comparer.Compare (item4, t.item4);
if (res != 0) return res;
res = comparer.Compare (item5, t.item5);
if (res != 0) return res;
res = comparer.Compare (item6, t.item6);
if (res != 0) return res;
res = comparer.Compare (item7, t.item7);
if (res != 0) return res;
return comparer.Compare (rest, t.rest);
}
public override bool Equals (object obj)
{
return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);
}
bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
{
var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (t == null)
return false;
return comparer.Equals (item1, t.item1) &&
comparer.Equals (item2, t.item2) &&
comparer.Equals (item3, t.item3) &&
comparer.Equals (item4, t.item4) &&
comparer.Equals (item5, t.item5) &&
comparer.Equals (item6, t.item6) &&
comparer.Equals (item7, t.item7) &&
comparer.Equals (rest, t.rest);
}
public override int GetHashCode ()
{
return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);
}
int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
{
int h0, h1, h2;
h0 = comparer.GetHashCode (item1);
h0 = (h0 << 5) + h0 ^ comparer.GetHashCode (item2);
h1 = comparer.GetHashCode (item3);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item4);
h0 = (h0 << 5) + h0 ^ h1;
h1 = comparer.GetHashCode (item5);
h1 = (h1 << 5) + h1 ^ comparer.GetHashCode (item6);
h2 = comparer.GetHashCode (item7);
h2 = (h2 << 5) + h2 ^ comparer.GetHashCode (rest);
h1 = (h1 << 5) + h1 ^ h2;
h0 = (h0 << 5) + h0 ^ h1;
return h0;
}
string ITuple.ToString ()
{
return String.Format ("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", item1, item2, item3, item4, item5, item6, item7, ((ITuple)rest).ToString ());
}
public override string ToString ()
{
return "(" + ((ITuple) this).ToString () + ")";
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.InteropServices;
// ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
namespace _4PosBackOffice.NET
{
internal partial class frmZeroiseCD : System.Windows.Forms.Form
{
public event ExportStartedEventHandler ExportStarted;
public delegate void ExportStartedEventHandler(DatabaseExport.DatabaseExportEnum ExportingFormat);
public event ExportErrorEventHandler ExportError;
public delegate void ExportErrorEventHandler(ref ErrObject myError, DatabaseExport.DatabaseExportEnum ExportingFormat);
public event ExportCompleteEventHandler ExportComplete;
public delegate void ExportCompleteEventHandler(bool Success, DatabaseExport.DatabaseExportEnum ExportingFormat);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int GetQueueStatus(int qsFlags);
//As ADODB.Recordset
ADODB.Recordset rs;
string sql;
short gSection;
const short sec_Payment = 0;
const short sec_Debit = 1;
const short sec_Credit = 2;
//Public Enum DatabaseExportEnum
// [CSV] = 0
// [HTML] = 1
// [Excel] = 2
//End Enum
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2492;
//Zeroise|Checked
if (modRecordSet.rsLang.RecordCount){My.MyProject.Forms.frmZeroise.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;My.MyProject.Forms.frmZeroise.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2494;
//Please Click start to zeroise all stock|Checked
if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2490;
//Password|Checked
if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2496;
//Start|Checked
if (modRecordSet.rsLang.RecordCount){cmdStart.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdStart.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmZeroiseCD.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void frmZeroiseCD_Load(System.Object eventSender, System.EventArgs eventArgs)
{
loadLanguage();
//If App.PrevInstance = True Then End
//If openConnection() = True Then
//ExportToCSV
//Else: MsgBox "Connection to database was not successful"
//End If
}
private void cmdStart_Click(System.Object eventSender, System.EventArgs eventArgs)
{
//If mdbFile.Text <> "" Then
string dtDate = null;
string dtMonth = null;
string stPass = null;
//Construct password...........
if (Strings.Len(DateAndTime.Day(DateAndTime.Today)) == 1)
dtDate = "0" + Conversion.Str(DateAndTime.Day(DateAndTime.Today));
else
dtDate = Strings.Trim(Conversion.Str(DateAndTime.Day(DateAndTime.Today)));
if (Strings.Len(DateAndTime.Month(DateAndTime.Today)) == 1)
dtMonth = "0" + Conversion.Str(DateAndTime.Month(DateAndTime.Today));
else
dtMonth = Strings.Trim(Conversion.Str(DateAndTime.Month(DateAndTime.Today)));
//Create password
stPass = dtDate + "##" + dtMonth;
stPass = Strings.Replace(stPass, " ", "");
if (Strings.Trim(txtPassword.Text) == stPass) {
// ZeroiseStock
//Trim(mdbFile.Text)
if (modRecordSet.openConnection() == true) {
ExportToCSV();
} else {
Interaction.MsgBox("Connection to database was not successful");
}
} else {
Interaction.MsgBox("Incorrect password was entered!!!", MsgBoxStyle.Exclamation, "Incorrect Passwords");
}
//Else
//MsgBox "Upload your database before you continue", vbOKOnly, "Customers"
//End If
}
public bool ShowOpen1()
{
bool functionReturnValue = false;
string strPath_DB1 = null;
string Extention = null;
// ERROR: Not supported in C#: OnErrorStatement
var _with1 = CommonDialog1Open;
//.CancelError = True
_with1.Title = "Upload Database";
_with1.FileName = "";
_with1.Filter = "Access File (*.mdb)|*.mdb|Access (*.mdb)|*.mdb|";
_with1.FilterIndex = 0;
_with1.ShowDialog();
strPath_DB1 = _with1.FileName;
if (!string.IsNullOrEmpty(strPath_DB1)) {
mdbFile.Text = strPath_DB1;
functionReturnValue = true;
} else {
functionReturnValue = false;
}
return functionReturnValue;
Extracter:
if (MsgBoxResult.Cancel) {
return functionReturnValue;
}
Interaction.MsgBox(Err().Description);
return functionReturnValue;
}
private void Command1_Click(System.Object eventSender, System.EventArgs eventArgs)
{
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
if (ShowOpen1() == true) {
} else {
return;
}
}
public string FilePath {
get {
string functionReturnValue = null;
short x = 0;
string temp = null;
string strPath_DB1 = null;
strPath_DB1 = (Strings.Trim(mdbFile.Text));
functionReturnValue = mdbFile.Text;
temp = functionReturnValue;
x = Strings.InStrRev(temp, "\\");
functionReturnValue = Strings.Mid(temp, 1, x - 1);
functionReturnValue = functionReturnValue + "\\";
return functionReturnValue;
}
set {
short x = 0;
string temp = null;
FilePath = mdbFile.Text;
temp = FilePath;
x = Strings.InStrRev(temp, "\\");
FilePath = Strings.Mid(temp, 1, x - 1);
FilePath = FilePath + "\\";
}
}
private int DoEventsEx()
{
int functionReturnValue = 0;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = GetQueueStatus(0x80 | 0x1 | 0x4 | 0x20 | 0x10);
if (functionReturnValue != 0) {
System.Windows.Forms.Application.DoEvents();
}
return functionReturnValue;
}
public void ExportToCSV(bool PrintHeader = true)
{
ADODB.Recordset rsz = default(ADODB.Recordset);
//Dim rs As Recordset
//Dim i As Long
//Dim TotalRecords As Long
//Dim ErrorOccured As Boolean
//Dim NumberOfFields As Integer
//Const Quote As String = """" 'Faster then Chr$(34)
//Dim sql As String
//Dim fso As New FileSystemObject
//
// cmdStart.Enabled = False
// cmdExit.Enabled = False
// txtPassword.Enabled = False
//Dim ptbl As String
// Dim t_day As String
// Dim t_Mon As String
//
// If Len(Trim(Str(Day(Date)))) = 1 Then t_day = "0" & Trim(Day(Date)) Else t_day = Day(Date)
// If Len(Trim(Str(Month(Date)))) = 1 Then t_Mon = "0" & Trim(Month(Date)) Else t_Mon = Str(Month(Date))
//
//
// ExportFilePath = serverPath & "4POSProd" & Trim(Year(Date)) & Trim(t_Mon) & Trim(t_day)
// If fso.FileExists(ExportFilePath & ".csv") Then fso.DeleteFile (ExportFilePath & ".csv")
// Set rs = getRS("SELECT CustomerID, Customer_InvoiceName, Customer_DepartmentName, Customer_FirstName, Customer_Surname, Customer_PhysicalAddress, Customer_PostalAddress, Customer_Telephone, Customer_Current as CurrentBalance,Customer_30Days as 30Days, Customer_60Days as 60days, Customer_90Days as 90Days, Customer_120Days as 120Days,Customer_150Days as 150Days FROM Customer")
// prgBar.Max = rs.RecordCount
// If rs.RecordCount > 0 Then
// Open ExportFilePath & ".csv" For Output As #1
// With getRS("SELECT CustomerID, Customer_InvoiceName, Customer_DepartmentName, Customer_FirstName, Customer_Surname, Customer_PhysicalAddress, Customer_PostalAddress, Customer_Telephone, Customer_Current as CurrentBalance,Customer_30Days as 30Days, Customer_60Days as 60days, Customer_90Days as 90Days, Customer_120Days as 120Days,Customer_150Days as 150Days FROM Customer")
// rs.MoveFirst
// NumberOfFields = rs.Fields.Count - 1
// If PrintHeader Then
// For i = 0 To NumberOfFields - 1 'Now add the field names
// Print #1, rs.Fields(i).Name & ","; 'similar to the ones below
// Next i
// Print #1, rs.Fields(NumberOfFields).Name
// End If
// Do While Not rs.EOF
// prgBar = prgBar + 1
// On Error Resume Next
// TotalRecords = TotalRecords + 1
//
// For i = 0 To NumberOfFields 'If there is an emty field,
// If (IsNull(rs.Fields(i))) Then 'add a , to indicate it is
// Print #1, ","; 'empty
// Else
// If i = NumberOfFields Then
// Print #1, Quote & Trim$(CStr(rs.Fields(i))) & Quote;
// Else
// Print #1, Quote & Trim$(CStr(rs.Fields(i))) & Quote & ",";
// End If
// End If 'Putting data under "" will not
// Next i 'confuse the reader of the file
// DoEventsEx 'between Dhaka, Bangladesh as two
// Print #1, 'fields or as one field.
// rs.moveNext'
// Loop
// End With
// Close #1
// MsgBox "Customer details were successfully exported to : " & FilePath & "" & "4POSProd" & Trim(Year(Date)) & Trim(t_Mon) & Trim(t_day) & ".csv", vbOKOnly, "Customers"
// DoEvents
// DoEvents
// MsgBox "Now Zeroising...", vbOKOnly, "Customers"
cmdStart.Enabled = false;
cmdExit.Enabled = false;
txtPassword.Enabled = false;
rsz = modRecordSet.getRS(ref "SELECT CustomerID FROM Customer");
if (rsz.RecordCount > 0) {
while (!rsz.EOF) {
System.Windows.Forms.Application.DoEvents();
cmdProcess_Click(ref (rsz("CustomerID")));
System.Windows.Forms.Application.DoEvents();
rsz.moveNext();
}
Interaction.MsgBox("Completed", MsgBoxStyle.OkOnly, "Customers");
} else {
Interaction.MsgBox("No Customers!", MsgBoxStyle.OkOnly, "Customers");
}
//cmdStart.Enabled = True
//cmdExit.Enabled = True
this.Close();
//End If
System.Windows.Forms.Cursor.Current = Cursors.Default;
//rs.Close
//cnnDB.Close
//Set cnnDB = Nothing
//closeConnection
}
private void frmZeroiseCD_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
this.Close();
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void cmdProcess_Click(ref object cID)
{
decimal amount = default(decimal);
string txtAmountText = null;
string txtNarrativeText = null;
string txtNotesText = null;
ADODB.Recordset rsCus = default(ADODB.Recordset);
string cSQL = null;
string sql = null;
string sql1 = null;
ADODB.Recordset rs = default(ADODB.Recordset);
string id = null;
decimal days120 = default(decimal);
decimal days60 = default(decimal);
decimal current = default(decimal);
decimal lAmount = default(decimal);
decimal days30 = default(decimal);
decimal days90 = default(decimal);
decimal days150 = default(decimal);
System.Windows.Forms.Application.DoEvents();
//If txtNarrative.Text = "" Then
// MsgBox "Narrative is a mandarory field", vbExclamation, Me.Caption
// txtNarrative.SetFocus
// Exit Sub
//End If
//If CCur(txtAmount.Text) = 0 Then
// MsgBox "Amount is a mandarory field", vbExclamation, Me.Caption
// txtAmount.SetFocus
// Exit Sub
//End If
cSQL = "SELECT CustomerTransaction.*, TransactionType.TransactionType_Name, IIf([CustomerTransaction_Amount]>0,[CustomerTransaction_Amount],Null) AS debit, IIf([CustomerTransaction_Amount]<0,[CustomerTransaction_Amount],Null) AS credit";
cSQL = cSQL + " FROM CustomerTransaction INNER JOIN TransactionType ON CustomerTransaction.CustomerTransaction_TransactionTypeID = TransactionType.TransactionTypeID";
cSQL = cSQL + " WHERE (((CustomerTransaction.CustomerTransaction_CustomerID)=" + cID + "))";
cSQL = cSQL + " ORDER BY CustomerTransaction.CustomerTransaction_Date DESC;";
rsCus = modRecordSet.getRS(ref cSQL);
if (rsCus.RecordCount < 1)
return;
//rsCus("credit") <> ""
if (Convert.ToDecimal(rsCus("CustomerTransaction_Amount").Value) < 0) {
gSection = 1;
txtNotesText = "Zeroise Debitors Accounts";
txtNarrativeText = "Zeroise Debitors Accounts";
txtAmountText = (rsCus("CustomerTransaction_Amount").Value / -1);
}
//rsCus("debit") <> ""
if (Convert.ToDecimal(rsCus("CustomerTransaction_Amount").Value) > 0) {
gSection = 2;
txtNotesText = "Zeroise Debitors Accounts";
txtNarrativeText = "Zeroise Debitors Accounts";
txtAmountText = (rsCus("CustomerTransaction_Amount"));
}
sql = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )";
switch (gSection) {
case sec_Payment:
sql = sql + "SELECT " + cID + " AS Customer, 3 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(txtNotesText, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(txtAmountText)) + " AS amount, '" + Strings.Replace(txtNarrativeText, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Debit:
sql = sql + "SELECT " + cID + " AS Customer, 4 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(txtNotesText, "'", "''") + "' AS description, " + Convert.ToDecimal(txtAmountText) + " AS amount, '" + Strings.Replace(txtNarrativeText, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Credit:
sql = sql + "SELECT " + cID + " AS Customer, 5 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(txtNotesText, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(txtAmountText)) + " AS amount, '" + Strings.Replace(txtNarrativeText, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
}
modRecordSet.cnnDB.Execute(sql);
rs = modRecordSet.getRS(ref "SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction");
if (rs.BOF | rs.EOF) {
} else {
id = rs.Fields("id").Value;
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_Current) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_30Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_60Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_90Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_120Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_150Days) Is Null));");
rs = modRecordSet.getRS(ref "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " + id + "));");
amount = rs.Fields("CustomerTransaction_Amount").Value;
current = rs.Fields("Customer_Current").Value;
days30 = rs.Fields("Customer_30Days").Value;
days60 = rs.Fields("Customer_60Days").Value;
days90 = rs.Fields("Customer_90Days").Value;
days120 = rs.Fields("Customer_120Days").Value;
days150 = rs.Fields("Customer_150Days").Value;
if (amount < 0) {
days150 = days150 + amount;
if ((days150 < 0)) {
amount = days150;
days150 = 0;
} else {
amount = 0;
}
days120 = days120 + amount;
if ((days120 < 0)) {
amount = days120;
days120 = 0;
} else {
amount = 0;
}
days90 = days90 + amount;
if ((days90 < 0)) {
amount = days90;
days90 = 0;
} else {
amount = 0;
}
days60 = days60 + amount;
if ((days60 < 0)) {
amount = days60;
days60 = 0;
} else {
amount = 0;
}
days30 = days30 + amount;
if ((days30 < 0)) {
amount = days30;
days30 = 0;
} else {
amount = 0;
}
}
current = current + amount;
//cnnDB.Execute "UPDATE Customer SET Customer.Customer_Current = " & current & ", Customer.Customer_30Days = " & days30 & ", Customer.Customer_60Days = " & days60 & ", Customer.Customer_90Days = " & days90 & ", Customer.Customer_120Days = " & days120 & ", Customer.Customer_150Days = 0" & days150 & " WHERE (((Customer.CustomerID)=" & rs("CustomerTransaction_CustomerID") & "));"
modRecordSet.cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " + 0 + ", Customer.Customer_30Days = " + 0 + ", Customer.Customer_60Days = " + 0 + ", Customer.Customer_90Days = " + 0 + ", Customer.Customer_120Days = " + 0 + ", Customer.Customer_150Days = " + 0 + " WHERE (((Customer.CustomerID)=" + rs.Fields("CustomerTransaction_CustomerID").Value + "));");
}
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using System;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;
namespace ArcGISRuntime.Samples.QueryFeatureCountAndExtent
{
[Register("QueryFeatureCountAndExtent")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Query feature count and extent",
category: "Analysis",
description: "Zoom to features matching a query and count the features in the current visible extent.",
instructions: "Use the button to zoom to the extent of the state specified (by abbreviation) in the textbox or use the button to count the features in the current extent.",
tags: new[] { "count", "feature layer", "feature table", "features", "filter", "number", "query" })]
public class QueryFeatureCountAndExtent : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UILabel _resultLabel;
private UIBarButtonItem _countInExtentButton;
private UIBarButtonItem _zoomToQueryButton;
private UIAlertController _unionAlert;
// URL to the feature service.
private readonly Uri _medicareHospitalSpendLayer =
new Uri("https://services1.arcgis.com/4yjifSiIG17X0gW4/arcgis/rest/services/Medicare_Hospital_Spending_per_Patient/FeatureServer/0");
// Feature table to query.
private ServiceFeatureTable _featureTable;
public QueryFeatureCountAndExtent()
{
Title = "Query feature count and extent";
}
private async void Initialize()
{
// Create the map with a basemap.
Map myMap = new Map(BasemapStyle.ArcGISDarkGray);
// Create the feature table from the service URL.
_featureTable = new ServiceFeatureTable(_medicareHospitalSpendLayer);
// Create the feature layer from the table.
FeatureLayer myFeatureLayer = new FeatureLayer(_featureTable);
// Add the feature layer to the map.
myMap.OperationalLayers.Add(myFeatureLayer);
try
{
// Wait for the feature layer to load.
await myFeatureLayer.LoadAsync();
// Set the map initial extent to the extent of the feature layer.
myMap.InitialViewpoint = new Viewpoint(myFeatureLayer.FullExtent);
// Add the map to the MapView.
_myMapView.Map = myMap;
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
private async void ZoomToFeature(string query)
{
// Create the query parameters.
QueryParameters queryStates = new QueryParameters {WhereClause = $"upper(State) LIKE '%{query.ToUpper()}%'"};
try
{
// Get the extent from the query.
Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);
// Return if there is no result (might happen if query is invalid).
if (resultExtent?.SpatialReference == null)
{
return;
}
// Create a viewpoint from the extent.
Viewpoint resultViewpoint = new Viewpoint(resultExtent);
// Zoom to the viewpoint.
await _myMapView.SetViewpointAsync(resultViewpoint);
// Update the UI.
_resultLabel.Text = $"Zoomed to features in {query}";
}
catch (Exception ex)
{
new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
private void ZoomToQuery_Click(object sender, EventArgs e)
{
// Prompt for the type of convex hull to create.
if (_unionAlert == null)
{
_unionAlert = UIAlertController.Create("Query features", "Enter a state abbreviation (e.g. CA)", UIAlertControllerStyle.Alert);
_unionAlert.AddTextField(field => field.Placeholder = "e.g. CA");
_unionAlert.AddAction(UIAlertAction.Create("Submit query", UIAlertActionStyle.Default, action => ZoomToFeature(_unionAlert.TextFields[0].Text)));
_unionAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
}
// Show the alert.
PresentViewController(_unionAlert, true, null);
}
private async void CountFeatures_Click(object sender, EventArgs e)
{
// Get the current visible extent.
Geometry currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry;
// Create the query parameters.
QueryParameters queryCityCount = new QueryParameters
{
Geometry = currentExtent,
// Specify the interpretation of the Geometry query parameters.
SpatialRelationship = SpatialRelationship.Intersects
};
try
{
// Get the count of matching features.
long count = await _featureTable.QueryFeatureCountAsync(queryCityCount);
// Update the UI.
_resultLabel.Text = $"{count} features in extent";
}
catch (Exception ex)
{
new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor};
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_zoomToQueryButton = new UIBarButtonItem();
_zoomToQueryButton.Title = "Zoom to query";
_countInExtentButton = new UIBarButtonItem();
_countInExtentButton.Title = "Count in extent";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
_countInExtentButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_zoomToQueryButton
};
_resultLabel = new UILabel
{
Text = "Press 'Zoom to query' to begin.",
BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
TextColor = UIColor.White,
TextAlignment = UITextAlignment.Center,
TranslatesAutoresizingMaskIntoConstraints = false
};
// Add the views.
View.AddSubviews(_myMapView, toolbar, _resultLabel);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_resultLabel.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_resultLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_resultLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_resultLabel.HeightAnchor.ConstraintEqualTo(40)
});
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_zoomToQueryButton.Clicked += ZoomToQuery_Click;
_countInExtentButton.Clicked += CountFeatures_Click;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_zoomToQueryButton.Clicked -= ZoomToQuery_Click;
_countInExtentButton.Clicked -= CountFeatures_Click;
// Remove the reference to the alert, preventing a memory leak.
_unionAlert = null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Modules.Core;
using ReactNative.Tracing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.UI.Core;
#endif
namespace ReactNative.UIManager
{
/// <summary>
/// This class acts as a buffer for command executed on
/// <see cref="NativeViewHierarchyManager"/>. It exposes similar methods as
/// mentioned classes but instead of executing commands immediately, it
/// enqueues those operations in a queue that is then flushed from
/// <see cref="UIManagerModule"/> once a JavaScript batch of UI operations
/// is finished.
/// </summary>
public class UIViewOperationQueueInstance
{
private const string NonBatchedChoreographerKey = nameof(UIViewOperationQueueInstance) + "_NonBatched";
private static readonly TimeSpan s_frameDuration = TimeSpan.FromTicks(166666);
private static readonly TimeSpan s_minTimeLeftInFrameForNonBatchedOperation = TimeSpan.FromTicks(83333);
private readonly object _gate = new object();
private readonly object _nonBatchedGate = new object();
private readonly double[] _measureBuffer = new double[4];
private readonly NativeViewHierarchyManager _nativeViewHierarchyManager;
private readonly ReactContext _reactContext;
private readonly IReactChoreographer _reactChoreographer;
private readonly IList<Action> _nonBatchedOperations = new List<Action>();
private IList<Action> _operations = new List<Action>();
private IList<Action> _batches = new List<Action>();
/// <summary>
/// Instantiates the <see cref="UIViewOperationQueueInstance"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="nativeViewHierarchyManager">
/// The native view hierarchy manager associated with this instance.
/// </param>
/// <param name="reactChoreographer">
/// The choreographer associated with this instance.
/// </param>
public UIViewOperationQueueInstance(ReactContext reactContext, NativeViewHierarchyManager nativeViewHierarchyManager, IReactChoreographer reactChoreographer)
{
_nativeViewHierarchyManager = nativeViewHierarchyManager;
_reactContext = reactContext;
_reactChoreographer = reactChoreographer;
}
/// <summary>
/// The native view hierarchy manager.
/// </summary>
internal NativeViewHierarchyManager NativeViewHierarchyManager
{
get
{
return _nativeViewHierarchyManager;
}
}
#if WINDOWS_UWP
internal CoreDispatcher Dispatcher
{
get
{
return _nativeViewHierarchyManager.Dispatcher;
}
}
#endif
/// <summary>
/// Checks if the operation queue is empty.
/// </summary>
/// <returns>
/// <b>true</b> if the queue is empty, <b>false</b> otherwise.
/// </returns>
public bool IsEmpty()
{
lock (_gate)
{
return _operations.Count == 0;
}
}
/// <summary>
/// Adds a root view to the hierarchy.
/// </summary>
/// <param name="tag">The root view tag.</param>
/// <param name="rootView">The root view.</param>
/// <param name="themedRootContext">The React context.</param>
public void AddRootView(
int tag,
SizeMonitoringCanvas rootView,
ThemedReactContext themedRootContext)
{
EnqueueOperation(() => _nativeViewHierarchyManager.AddRootView(tag, rootView, themedRootContext));
}
/// <summary>
/// Enqueues an operation to remove the root view.
/// </summary>
/// <param name="rootViewTag">The root view tag.</param>
public void EnqueueRemoveRootView(int rootViewTag)
{
EnqueueOperation(() => _nativeViewHierarchyManager.RemoveRootView(rootViewTag));
}
/// <summary>
/// Refreshes RTL/LTR direction on all root views.
/// </summary>
public void UpdateRootViewNodesDirection()
{
EnqueueOperation(() => _nativeViewHierarchyManager.UpdateRootViewNodesDirection());
}
/// <summary>
/// Enqueues an operation to dispatch a command.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="commandId">The command identifier.</param>
/// <param name="commandArgs">The command arguments.</param>
public void EnqueueDispatchCommand(int tag, int commandId, JArray commandArgs)
{
EnqueueOperation(() => _nativeViewHierarchyManager.DispatchCommand(tag, commandId, commandArgs));
}
/// <summary>
/// Enqueues an operation to update the extra data for a view.
/// </summary>
/// <param name="reactTag">The view tag.</param>
/// <param name="extraData">The extra data.</param>
public void EnqueueUpdateExtraData(int reactTag, object extraData)
{
EnqueueOperation(() => _nativeViewHierarchyManager.UpdateViewExtraData(reactTag, extraData));
}
/// <summary>
/// Enqueues an operation to show a popup menu.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="items">The menu items.</param>
/// <param name="error">Called on error.</param>
/// <param name="success">Called on success.</param>
public void EnqueueShowPopupMenu(int tag, string[] items, ICallback error, ICallback success)
{
EnqueueOperation(() => _nativeViewHierarchyManager.ShowPopupMenu(tag, items, success));
}
/// <summary>
/// Enqueues an operation to execute a UI block.
/// </summary>
/// <param name="block">The UI block.</param>
public void EnqueueUIBlock(IUIBlock block)
{
EnqueueOperation(() => block.Execute(_nativeViewHierarchyManager));
}
/// <summary>
/// Prepends an operation to execute a UI block.
/// </summary>
/// <param name="block">The UI block.</param>
public void PrependUIBlock(IUIBlock block)
{
PrependOperation(() => block.Execute(_nativeViewHierarchyManager));
}
/// <summary>
/// Enqueues an operation to create a view.
/// </summary>
/// <param name="themedContext">The React context.</param>
/// <param name="viewReactTag">The view React tag.</param>
/// <param name="viewClassName">The view class name.</param>
/// <param name="initialProps">The initial props.</param>
public void EnqueueCreateView(
ThemedReactContext themedContext,
int viewReactTag,
string viewClassName,
JObject initialProps)
{
lock (_nonBatchedGate)
{
_nonBatchedOperations.Add(() => _nativeViewHierarchyManager.CreateView(
themedContext,
viewReactTag,
viewClassName,
initialProps));
}
// Dispatch event from non-layout thread to avoid queueing
// main dispatcher callbacks from the layout thread
Task.Run(() => _reactChoreographer.ActivateCallback(NonBatchedChoreographerKey));
}
/// <summary>
/// Enqueue a configure layout animation operation.
/// </summary>
/// <param name="config">The configuration.</param>
/// <param name="success">The success callback.</param>
/// <param name="error">The error callback.</param>
public void EnqueueConfigureLayoutAnimation(JObject config, ICallback success, ICallback error)
{
EnqueueOperation(() => _nativeViewHierarchyManager.ConfigureLayoutAnimation(config, success, error));
}
/// <summary>
/// Enqueues an operation to update the props of a view.
/// </summary>
/// <param name="tag">The view tag.</param>
/// <param name="className">The class name.</param>
/// <param name="props">The props.</param>
public void EnqueueUpdateProps(int tag, string className, JObject props)
{
EnqueueOperation(() =>
_nativeViewHierarchyManager.UpdateProps(tag, props));
}
/// <summary>
/// Enqueues an operation to update the layout of a view.
/// </summary>
/// <param name="parentTag">The parent tag.</param>
/// <param name="tag">The view tag.</param>
/// <param name="dimensions">The dimensions.</param>
public void EnqueueUpdateLayout(
int parentTag,
int tag,
Dimensions dimensions)
{
EnqueueOperation(() => _nativeViewHierarchyManager.UpdateLayout(
parentTag,
tag,
dimensions));
}
/// <summary>
/// Enqueues an operation to manage the children of a view.
/// </summary>
/// <param name="tag">The view to manage.</param>
/// <param name="indexesToRemove">The indices to remove.</param>
/// <param name="viewsToAdd">The views to add.</param>
/// <param name="tagsToDelete">The tags to delete.</param>
public void EnqueueManageChildren(
int tag,
int[] indexesToRemove,
ViewAtIndex[] viewsToAdd,
int[] tagsToDelete)
{
EnqueueOperation(() => _nativeViewHierarchyManager.ManageChildren(
tag,
indexesToRemove,
viewsToAdd,
tagsToDelete));
}
/// <summary>
/// Enqueues an operation to set the children of a view.
/// </summary>
/// <param name="reactTag">The view to manage.</param>
/// <param name="childrenTags">The children tags.</param>
public void EnqueueSetChildren(int reactTag, int[] childrenTags)
{
EnqueueOperation(() => _nativeViewHierarchyManager.SetChildren(
reactTag,
childrenTags));
}
/// <summary>
/// Enqueues an operation to measure the view.
/// </summary>
/// <param name="reactTag">The tag of the view to measure.</param>
/// <param name="callback">The measurement result callback.</param>
public void EnqueueMeasure(int reactTag, ICallback callback)
{
EnqueueOperation(() =>
{
try
{
_nativeViewHierarchyManager.Measure(reactTag, _measureBuffer);
}
catch
{
callback.Invoke();
return;
}
var x = _measureBuffer[0];
var y = _measureBuffer[1];
var width = _measureBuffer[2];
var height = _measureBuffer[3];
callback.Invoke(0, 0, width, height, x, y);
});
}
/// <summary>
/// Enqueues an operation to measure the view relative to the window.
/// </summary>
/// <param name="reactTag">The tag of the view to measure.</param>
/// <param name="callback">The measurement result callback.</param>
public void EnqueueMeasureInWindow(int reactTag, ICallback callback)
{
EnqueueOperation(() =>
{
try
{
_nativeViewHierarchyManager.MeasureInWindow(reactTag, _measureBuffer);
}
catch
{
callback.Invoke();
return;
}
var x = _measureBuffer[0];
var y = _measureBuffer[1];
var width = _measureBuffer[2];
var height = _measureBuffer[3];
callback.Invoke(x, y, width, height);
});
}
/// <summary>
/// Enqueues an operation to find a touch target.
/// </summary>
/// <param name="reactTag">The parent view to search from.</param>
/// <param name="targetX">The x-coordinate of the touch event.</param>
/// <param name="targetY">The y-coordinate of the touch event.</param>
/// <param name="callback">The callback.</param>
public void EnqueueFindTargetForTouch(
int reactTag,
double targetX,
double targetY,
ICallback callback)
{
EnqueueOperation(() =>
{
try
{
_nativeViewHierarchyManager.MeasureInWindow(reactTag, _measureBuffer);
targetX += (double)_measureBuffer[0];
targetY += (double)_measureBuffer[1];
_nativeViewHierarchyManager.Measure(reactTag, _measureBuffer);
}
catch
{
// TODO: catch specific exception?
callback.Invoke();
return;
}
var containerX = (double)_measureBuffer[0];
var containerY = (double)_measureBuffer[1];
var touchTargetReactTag = _nativeViewHierarchyManager.FindTargetForTouch(reactTag, targetX, targetY);
try
{
_nativeViewHierarchyManager.Measure(touchTargetReactTag, _measureBuffer);
}
catch
{
// TODO: catch specific exception?
callback.Invoke();
return;
}
var x = _measureBuffer[0] - containerX;
var y = _measureBuffer[1] - containerY;
var width = _measureBuffer[2];
var height = _measureBuffer[3];
callback.Invoke(touchTargetReactTag, x, y, width, height);
});
}
/// <summary>
/// Called when the host receives the suspend event.
/// </summary>
public void OnSuspend()
{
// Must be called in the context of the dispatcher thread corresponding to this queue
_reactChoreographer.DispatchUICallback -= OnRenderingSafe;
}
/// <summary>
/// Called when the host receives the resume event.
/// </summary>
public void OnResume()
{
// Must be called in the context of the dispatcher thread corresponding to this queue
_reactChoreographer.DispatchUICallback += OnRenderingSafe;
}
/// <summary>
/// Called when the host is shutting down.
/// </summary>
public void OnDestroy()
{
_nativeViewHierarchyManager.DropAllViews();
// Must be called in the context of the dispatcher thread corresponding to this queue
_reactChoreographer.DispatchUICallback -= OnRenderingSafe;
// Don't dispose main choreographer, there's a great chance it will be reused
if (!_reactChoreographer.IsMainChoreographer())
{
(_reactChoreographer as IDisposable).Dispose();
}
}
/// <summary>
/// Dispatches the view updates.
/// </summary>
/// <param name="batchId">The batch identifier.</param>
internal void DispatchViewUpdates(int batchId)
{
var nonBatchedOperations = default(Action[]);
lock (_nonBatchedGate)
{
if (_nonBatchedOperations.Count > 0)
{
nonBatchedOperations = _nonBatchedOperations.ToArray();
_nonBatchedOperations.Clear();
_reactChoreographer.DeactivateCallback(NonBatchedChoreographerKey);
}
}
lock (_gate)
{
var operations = _operations.Count == 0 ? null : _operations;
if (operations != null)
{
_operations = new List<Action>();
}
_batches.Add(() =>
{
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "DispatchUI")
.With("BatchId", batchId)
.Start())
{
if (nonBatchedOperations != null)
{
foreach (var operation in nonBatchedOperations)
{
operation();
}
}
if (operations != null)
{
foreach (var operation in operations)
{
operation();
}
}
_nativeViewHierarchyManager.OnBatchComplete();
}
});
}
// Dispatch event from non-layout thread to avoid queueing
// main dispatcher callbacks from the layout thread
Task.Run(() => _reactChoreographer.ActivateCallback(nameof(UIViewOperationQueueInstance)));
}
private void EnqueueOperation(Action action)
{
lock (_gate)
{
_operations.Add(action);
}
}
private void PrependOperation(Action action)
{
lock (_gate)
{
_operations.Insert(0, action);
}
}
private void OnRenderingSafe(object sender, FrameEventArgs e)
{
try
{
OnRendering(sender, e);
}
catch (Exception ex)
{
_reactContext.HandleException(ex);
}
}
private void OnRendering(object sender, FrameEventArgs e)
{
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "dispatchNonBatchedUIOperations").Start())
{
DispatchPendingNonBatchedOperations(e.FrameTime);
}
lock (_gate)
{
try
{
foreach (var batch in _batches)
{
batch();
}
}
finally
{
_batches.Clear();
_reactChoreographer.DeactivateCallback(nameof(UIViewOperationQueueInstance));
}
}
}
private void DispatchPendingNonBatchedOperations(DateTimeOffset frameTime)
{
while (true)
{
var timeLeftInFrame = frameTime - DateTimeOffset.UtcNow;
if (timeLeftInFrame < s_minTimeLeftInFrameForNonBatchedOperation)
{
break;
}
var nextOperation = default(Action);
lock (_nonBatchedGate)
{
if (_nonBatchedOperations.Count == 0)
{
_reactChoreographer.DeactivateCallback(NonBatchedChoreographerKey);
break;
}
nextOperation = _nonBatchedOperations[0];
_nonBatchedOperations.RemoveAt(0);
}
nextOperation();
}
}
}
}
| |
#region License
/*
* WebSocketSessionManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Timers;
namespace WebSocketSharp.Server
{
/// <summary>
/// Manages the sessions in a Websocket service.
/// </summary>
public class WebSocketSessionManager
{
#region Private Fields
private volatile bool _clean;
private object _forSweep;
private Logger _logger;
private Dictionary<string, IWebSocketSession> _sessions;
private volatile ServerState _state;
private volatile bool _sweeping;
private System.Timers.Timer _sweepTimer;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketSessionManager ()
: this (new Logger ())
{
}
internal WebSocketSessionManager (Logger logger)
{
_logger = logger;
_clean = true;
_forSweep = new object ();
_sessions = new Dictionary<string, IWebSocketSession> ();
_state = ServerState.Ready;
_sync = ((ICollection) _sessions).SyncRoot;
_waitTime = TimeSpan.FromSeconds (1);
setSweepTimer (60000);
}
#endregion
#region Internal Properties
internal ServerState State {
get {
return _state;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the IDs for the active sessions in the Websocket service.
/// </summary>
/// <value>
/// An <c>IEnumerable<string></c> instance that provides an enumerator which
/// supports the iteration over the collection of the IDs for the active sessions.
/// </value>
public IEnumerable<string> ActiveIDs {
get {
foreach (var res in Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime))
if (res.Value)
yield return res.Key;
}
}
/// <summary>
/// Gets the number of the sessions in the Websocket service.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the sessions.
/// </value>
public int Count {
get {
lock (_sync)
return _sessions.Count;
}
}
/// <summary>
/// Gets the IDs for the sessions in the Websocket service.
/// </summary>
/// <value>
/// An <c>IEnumerable<string></c> instance that provides an enumerator which
/// supports the iteration over the collection of the IDs for the sessions.
/// </value>
public IEnumerable<string> IDs {
get {
if (_state == ServerState.ShuttingDown)
return new string[0];
lock (_sync)
return _sessions.Keys.ToList ();
}
}
/// <summary>
/// Gets the IDs for the inactive sessions in the Websocket service.
/// </summary>
/// <value>
/// An <c>IEnumerable<string></c> instance that provides an enumerator which
/// supports the iteration over the collection of the IDs for the inactive sessions.
/// </value>
public IEnumerable<string> InactiveIDs {
get {
foreach (var res in Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime))
if (!res.Value)
yield return res.Key;
}
}
/// <summary>
/// Gets the session with the specified <paramref name="id"/>.
/// </summary>
/// <value>
/// A <see cref="IWebSocketSession"/> instance that provides the access to
/// the information in the session, or <see langword="null"/> if it's not found.
/// </value>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
public IWebSocketSession this[string id] {
get {
IWebSocketSession session;
TryGetSession (id, out session);
return session;
}
}
/// <summary>
/// Gets a value indicating whether the manager cleans up the inactive sessions in
/// the WebSocket service periodically.
/// </summary>
/// <value>
/// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepClean {
get {
return _clean;
}
internal set {
if (!(value ^ _clean))
return;
_clean = value;
if (_state == ServerState.Start)
_sweepTimer.Enabled = value;
}
}
/// <summary>
/// Gets the sessions in the Websocket service.
/// </summary>
/// <value>
/// An <c>IEnumerable<IWebSocketSession></c> instance that provides an enumerator
/// which supports the iteration over the collection of the sessions in the service.
/// </value>
public IEnumerable<IWebSocketSession> Sessions {
get {
if (_state == ServerState.ShuttingDown)
return new IWebSocketSession[0];
lock (_sync)
return _sessions.Values.ToList ();
}
}
/// <summary>
/// Gets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time.
/// </value>
public TimeSpan WaitTime {
get {
return _waitTime;
}
internal set {
if (value == _waitTime)
return;
_waitTime = value;
foreach (var session in Sessions)
session.Context.WebSocket.WaitTime = value;
}
}
#endregion
#region Private Methods
private void broadcast (Opcode opcode, byte[] data, Action completed)
{
var cache = new Dictionary<CompressionMethod, byte[]> ();
try {
Broadcast (opcode, data, cache);
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
cache.Clear ();
}
}
private void broadcast (Opcode opcode, Stream stream, Action completed)
{
var cache = new Dictionary <CompressionMethod, Stream> ();
try {
Broadcast (opcode, stream, cache);
if (completed != null)
completed ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
}
finally {
foreach (var cached in cache.Values)
cached.Dispose ();
cache.Clear ();
}
}
private void broadcastAsync (Opcode opcode, byte[] data, Action completed)
{
ThreadPool.QueueUserWorkItem (state => broadcast (opcode, data, completed));
}
private void broadcastAsync (Opcode opcode, Stream stream, Action completed)
{
ThreadPool.QueueUserWorkItem (state => broadcast (opcode, stream, completed));
}
private static string createID ()
{
return Guid.NewGuid ().ToString ("N");
}
private void setSweepTimer (double interval)
{
_sweepTimer = new System.Timers.Timer (interval);
_sweepTimer.Elapsed += (sender, e) => Sweep ();
}
private bool tryGetSession (string id, out IWebSocketSession session)
{
bool ret;
lock (_sync)
ret = _sessions.TryGetValue (id, out session);
if (!ret)
_logger.Error ("A session with the specified ID isn't found:\n ID: " + id);
return ret;
}
#endregion
#region Internal Methods
internal string Add (IWebSocketSession session)
{
lock (_sync) {
if (_state != ServerState.Start)
return null;
var id = createID ();
_sessions.Add (id, session);
return id;
}
}
internal void Broadcast (
Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache)
{
foreach (var session in Sessions) {
if (_state != ServerState.Start)
break;
session.Context.WebSocket.Send (opcode, data, cache);
}
}
internal void Broadcast (
Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache)
{
foreach (var session in Sessions) {
if (_state != ServerState.Start)
break;
session.Context.WebSocket.Send (opcode, stream, cache);
}
}
internal Dictionary<string, bool> Broadping (byte[] frameAsBytes, TimeSpan timeout)
{
var ret = new Dictionary<string, bool> ();
foreach (var session in Sessions) {
if (_state != ServerState.Start)
break;
ret.Add (session.ID, session.Context.WebSocket.Ping (frameAsBytes, timeout));
}
return ret;
}
internal bool Remove (string id)
{
lock (_sync)
return _sessions.Remove (id);
}
internal void Start ()
{
lock (_sync) {
_sweepTimer.Enabled = _clean;
_state = ServerState.Start;
}
}
internal void Stop (CloseEventArgs e, byte[] frameAsBytes, TimeSpan timeout)
{
lock (_sync) {
_state = ServerState.ShuttingDown;
_sweepTimer.Enabled = false;
foreach (var session in _sessions.Values.ToList ())
session.Context.WebSocket.Close (e, frameAsBytes, timeout);
_state = ServerState.Stop;
}
}
#endregion
#region Public Methods
/// <summary>
/// Sends binary <paramref name="data"/> to every client in the WebSocket service.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
public void Broadcast (byte[] data)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
if (data.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, data, null);
else
broadcast (Opcode.Binary, new MemoryStream (data), null);
}
/// <summary>
/// Sends text <paramref name="data"/> to every client in the WebSocket service.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
public void Broadcast (string data)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
var bytes = Encoding.UTF8.GetBytes (data);
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Text, bytes, null);
else
broadcast (Opcode.Text, new MemoryStream (bytes), null);
}
/// <summary>
/// Sends binary <paramref name="data"/> asynchronously to every client in
/// the WebSocket service.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (byte[] data, Action completed)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
if (data.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Binary, data, completed);
else
broadcastAsync (Opcode.Binary, new MemoryStream (data), completed);
}
/// <summary>
/// Sends text <paramref name="data"/> asynchronously to every client in
/// the WebSocket service.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (string data, Action completed)
{
var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData ();
if (msg != null) {
_logger.Error (msg);
return;
}
var bytes = Encoding.UTF8.GetBytes (data);
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Text, bytes, completed);
else
broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sends binary data from the specified <see cref="Stream"/> asynchronously to
/// every client in the WebSocket service.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> from which contains the binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that represents the number of bytes to send.
/// </param>
/// <param name="completed">
/// An <see cref="Action"/> delegate that references the method(s) called when
/// the send is complete.
/// </param>
public void BroadcastAsync (Stream stream, int length, Action completed)
{
var msg = _state.CheckIfStart () ??
stream.CheckIfCanRead () ??
(length < 1 ? "'length' is less than 1." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
stream.ReadBytesAsync (
length,
data => {
var len = data.Length;
if (len == 0) {
_logger.Error ("The data cannot be read from 'stream'.");
return;
}
if (len < length)
_logger.Warn (
String.Format (
"The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}",
length,
len));
if (len <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, data, completed);
else
broadcast (Opcode.Binary, new MemoryStream (data), completed);
},
ex => _logger.Fatal (ex.ToString ()));
}
/// <summary>
/// Sends a Ping to every client in the WebSocket service.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, bool></c> that contains a collection of pairs of
/// a session ID and a value indicating whether the manager received a Pong from
/// each client in a time.
/// </returns>
public Dictionary<string, bool> Broadping ()
{
var msg = _state.CheckIfStart ();
if (msg != null) {
_logger.Error (msg);
return null;
}
return Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime);
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to every client in
/// the WebSocket service.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, bool></c> that contains a collection of pairs of
/// a session ID and a value indicating whether the manager received a Pong from
/// each client in a time.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that represents the message to send.
/// </param>
public Dictionary<string, bool> Broadping (string message)
{
if (message == null || message.Length == 0)
return Broadping ();
byte[] data = null;
var msg = _state.CheckIfStart () ?? WebSocket.CheckPingParameter (message, out data);
if (msg != null) {
_logger.Error (msg);
return null;
}
return Broadping (WebSocketFrame.CreatePingFrame (data, false).ToByteArray (), _waitTime);
}
/// <summary>
/// Closes the session with the specified <paramref name="id"/>.
/// </summary>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to close.
/// </param>
public void CloseSession (string id)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.Close ();
}
/// <summary>
/// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>,
/// and <paramref name="reason"/>.
/// </summary>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to close.
/// </param>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for the close.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the close.
/// </param>
public void CloseSession (string id, ushort code, string reason)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.Close (code, reason);
}
/// <summary>
/// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>,
/// and <paramref name="reason"/>.
/// </summary>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to close.
/// </param>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
/// indicating the reason for the close.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the close.
/// </param>
public void CloseSession (string id, CloseStatusCode code, string reason)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.Close (code, reason);
}
/// <summary>
/// Sends a Ping to the client on the session with the specified <paramref name="id"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the manager receives a Pong from the client in a time;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
public bool PingTo (string id)
{
IWebSocketSession session;
return TryGetSession (id, out session) && session.Context.WebSocket.Ping ();
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to the client on
/// the session with the specified <paramref name="id"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the manager receives a Pong from the client in a time;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that represents the message to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
public bool PingTo (string message, string id)
{
IWebSocketSession session;
return TryGetSession (id, out session) && session.Context.WebSocket.Ping (message);
}
/// <summary>
/// Sends binary <paramref name="data"/> to the client on the session with
/// the specified <paramref name="id"/>.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
public void SendTo (byte[] data, string id)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.Send (data);
}
/// <summary>
/// Sends text <paramref name="data"/> to the client on the session with
/// the specified <paramref name="id"/>.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
public void SendTo (string data, string id)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.Send (data);
}
/// <summary>
/// Sends binary <paramref name="data"/> asynchronously to the client on
/// the session with the specified <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
public void SendToAsync (byte[] data, string id, Action<bool> completed)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.SendAsync (data, completed);
}
/// <summary>
/// Sends text <paramref name="data"/> asynchronously to the client on
/// the session with the specified <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
public void SendToAsync (string data, string id, Action<bool> completed)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.SendAsync (data, completed);
}
/// <summary>
/// Sends binary data from the specified <see cref="Stream"/> asynchronously to
/// the client on the session with the specified <paramref name="id"/>.
/// </summary>
/// <remarks>
/// This method doesn't wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> from which contains the binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that represents the number of bytes to send.
/// </param>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
public void SendToAsync (Stream stream, int length, string id, Action<bool> completed)
{
IWebSocketSession session;
if (TryGetSession (id, out session))
session.Context.WebSocket.SendAsync (stream, length, completed);
}
/// <summary>
/// Cleans up the inactive sessions in the WebSocket service.
/// </summary>
public void Sweep ()
{
if (_state != ServerState.Start || _sweeping || Count == 0)
return;
lock (_forSweep) {
_sweeping = true;
foreach (var id in InactiveIDs) {
if (_state != ServerState.Start)
break;
lock (_sync) {
IWebSocketSession session;
if (_sessions.TryGetValue (id, out session)) {
var state = session.State;
if (state == WebSocketState.Open)
session.Context.WebSocket.Close (CloseStatusCode.ProtocolError);
else if (state == WebSocketState.Closing)
continue;
else
_sessions.Remove (id);
}
}
}
_sweeping = false;
}
}
/// <summary>
/// Tries to get the session with the specified <paramref name="id"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the session is successfully found; otherwise, <c>false</c>.
/// </returns>
/// <param name="id">
/// A <see cref="string"/> that represents the ID of the session to find.
/// </param>
/// <param name="session">
/// When this method returns, a <see cref="IWebSocketSession"/> instance that
/// provides the access to the information in the session, or <see langword="null"/>
/// if it's not found. This parameter is passed uninitialized.
/// </param>
public bool TryGetSession (string id, out IWebSocketSession session)
{
var msg = _state.CheckIfStart () ?? id.CheckIfValidSessionID ();
if (msg != null) {
_logger.Error (msg);
session = null;
return false;
}
return tryGetSession (id, out session);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.SqlTypes;
using System.Reflection;
using System.Text;
using Microsoft.SqlServer.Server;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class UdtTest2
{
private string _connStr = null;
public UdtTest2()
{
_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { InitialCatalog = DataTestUtility.UdtTestDbName }).ConnectionString;
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_Early()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();
cmd.CommandText = "vicinity"; // select proc
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.Udt);
p.UdtTypeName = "UdtTestDb.dbo.Point";
Point pt = new Point()
{
X = 250,
Y = 250
};
p.Value = pt;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTestUtility.AssertEqualsWithDescription(
(new Point(250, 250)).ToString(), p.Value.ToString(),
"Unexpected Point value.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_Binary()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("vicinity", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.VarBinary, 8);
p.Direction = ParameterDirection.Input;
byte[] value = new byte[8];
value[0] = 0xF0;
value[1] = 0;
value[2] = 0;
value[3] = 0;
value[4] = 0xF0;
value[5] = 0;
value[6] = 0;
value[7] = 0;
p.Value = new SqlBinary(value);
DataTestUtility.AssertThrowsWrapper<SqlException>(
() => cmd.ExecuteReader(),
"Error converting data type varbinary to Point.");
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_Invalid2()
{
string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2");
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();
cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
cmd.ExecuteNonQuery();
cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = spInsertCustomer;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pName = cmd.Parameters.Add("@fname", SqlDbType.NVarChar, 20);
SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
Address addr = Address.Parse("customer whose name is address");
p.UdtTypeName = "UdtTestDb.dbo.Address";
p.Value = addr;
pName.Value = addr;
DataTestUtility.AssertThrowsWrapper<InvalidCastException>(
() => cmd.ExecuteReader(),
"Failed to convert parameter value from a Address to a String.");
}
finally
{
cmd.Transaction.Rollback();
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_Invalid()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("vicinity", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.Udt);
p.UdtTypeName = "UdtTestDb.dbo.Point";
p.Value = 32;
DataTestUtility.AssertThrowsWrapper<ArgumentException>(
() => cmd.ExecuteReader(),
"Specified type is not registered on the target server. System.Int32");
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_TypedNull()
{
string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2_Customer");
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();
cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
cmd.ExecuteNonQuery();
// create proc sp_insert_customer(@name nvarchar(30), @addr Address OUTPUT)
// AS
// insert into customers values (@name, @addr)
cmd.CommandText = "create proc " + spInsertCustomer + " (@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = spInsertCustomer;
cmd.CommandType = CommandType.StoredProcedure;
Address addr = Address.Parse("123 baker st || Redmond");
SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
p.UdtTypeName = "UdtTestDb.dbo.Address";
p.Value = Address.Null;
pName.Value = "john";
cmd.ExecuteNonQuery();
DataTestUtility.AssertEqualsWithDescription(
Address.Null.ToString(), p.Value.ToString(),
"Unexpected parameter value.");
}
finally
{
cmd.Transaction.Rollback();
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_NullInput()
{
string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2_Customer");
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();
cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
cmd.ExecuteNonQuery();
cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = spInsertCustomer;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
p.UdtTypeName = "UdtTestDb.dbo.Address";
p.Value = null;
pName.Value = "john";
string spInsertCustomerNoBrackets = spInsertCustomer;
if (spInsertCustomer.StartsWith("[") && spInsertCustomer.EndsWith("]"))
spInsertCustomerNoBrackets = spInsertCustomer.Substring(1, spInsertCustomer.Length - 2);
string errorMsg = "Procedure or function '" + spInsertCustomerNoBrackets + "' expects parameter '@addr', which was not supplied.";
DataTestUtility.AssertThrowsWrapper<SqlException>(
() => cmd.ExecuteNonQuery(),
errorMsg);
}
finally
{
cmd.Transaction.Rollback();
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_InputOutput()
{
string spInsertCity = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCity");
string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
SqlTransaction tx = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = tx;
// create the table
cmd.CommandText = "create table " + tableName + " (name sysname,location Point)";
cmd.ExecuteNonQuery();
// create sp
cmd.CommandText = "create proc " + spInsertCity + "(@name sysname, @location Point OUTPUT)" + " AS insert into " + tableName + " values (@name, @location)";
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = spInsertCity;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
SqlParameter p = cmd.Parameters.Add("@location", SqlDbType.Udt);
Point pt = new Point(100, 100);
p.UdtTypeName = "Point";
p.Direction = ParameterDirection.InputOutput;
p.Value = pt;
pName.Value = "newcity";
cmd.ExecuteNonQuery();
DataTestUtility.AssertEqualsWithDescription(
"141.4213562373095", ((Point)(p.Value)).Distance().ToString(),
"Unexpected distance value.");
DataTestUtility.AssertEqualsWithDescription(
"141.4213562373095", ((Point)(p.Value)).Distance().ToString(),
"Unexpected distance value after reading out param again.");
cmd.Parameters.Clear();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from " + tableName;
using (SqlDataReader reader = cmd.ExecuteReader())
{
string expectedValue = " newcity, p.X = 100, p.Y = 100, p.Distance() = 141.4213562373095" + Environment.NewLine;
DataTestUtility.AssertEqualsWithDescription(
expectedValue, UdtTestHelpers.DumpReaderString(reader, false),
"Unexpected reader dump string.");
}
}
finally
{
tx.Rollback();
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTFields_WrongType()
{
using (SqlConnection cn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select name,location from cities order by name", cn))
{
cn.Open();
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
DataTestUtility.AssertEqualsWithDescription(
"beaverton", reader.GetValue(0),
"Unexpected reader value.");
DataTestUtility.AssertEqualsWithDescription(
"14.866068747318506", ((Point)reader.GetValue(1)).Distance().ToString(),
"Unexpected distance value.");
reader.Read();
// retrieve the UDT as a string
DataTestUtility.AssertThrowsWrapper<InvalidCastException>(
() => reader.GetString(1),
"Unable to cast object of type 'System.Byte[]' to type 'System.String'.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDT_DataSetFill()
{
using (SqlConnection cn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select * from cities", cn))
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from cities", cn))
{
cn.Open();
cmd.CommandType = CommandType.Text;
adapter.SelectCommand = cmd;
DataSet ds = new DataSet("newset");
adapter.Fill(ds);
DataTestUtility.AssertEqualsWithDescription(
1, ds.Tables.Count,
"Unexpected Tables count.");
DataTestUtility.AssertEqualsWithDescription(
typeof(Point), ds.Tables[0].Columns[1].DataType,
"Unexpected DataType.");
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_DeriveParameters_CheckAutoFixSuccess()
{
// the type and sproc must be commited to the database or this test will deadlock with a schema lock violation
// if you are missing these database entities then you should look for an updated version of the database creation script
string sprocName = "sp_insert_customers";
string typeName = "CustomerAddress";
string customerAddressTypeIncorrectName = $"{DataTestUtility.UdtTestDbName}.dbo.{typeName.Trim('[',']')}";
string customerAddressTypeCorrectedName = $"[dbo].[{typeName.Trim('[',']')}]";
string customerParameterName = "@customers";
Address addr = Address.Parse("123 baker st || Redmond");
DataTable table = new DataTable();
table.Columns.Add();
table.Columns.Add();
table.Rows.Add("john", addr);
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand cmd = new SqlCommand(sprocName, connection, transaction))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
Assert.NotNull(cmd.Parameters);
Assert.Equal(2, cmd.Parameters.Count); // [return_value, table]
SqlParameter p = cmd.Parameters[1];
Assert.Equal(customerParameterName, p.ParameterName);
Assert.Equal(SqlDbType.Structured, p.SqlDbType);
Assert.Equal(customerAddressTypeIncorrectName, p.TypeName); // the 3 part name is incorrect but needs to be maintained for compatibility
p.Value = table;
cmd.ExecuteNonQuery();
Assert.Equal(customerAddressTypeCorrectedName, p.TypeName); // check that the auto fix has been applied correctly
}
finally
{
try
{
transaction.Rollback();
}
catch
{
// ignore rollback failure exceptions to preserve original thrown error in test result
}
}
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void UDTParams_DeriveParameters_CheckAutoFixOverride()
{
// the type and sproc must be commited to the database or this test will deadlock with a schema lock violation
// if you are missing these database entities then you should look for an updated version of the database creation script
string sprocName = "sp_insert_customers";
string typeName = "CustomerAddress";
string customerAddressTypeIncorrectName = $"{DataTestUtility.UdtTestDbName}.dbo.{typeName.Trim('[', ']')}";
string customerAddressTypeCorrectedName = $"[dbo].[{typeName.Trim('[', ']')}]";
string customerParameterName = "@customers";
Address addr = Address.Parse("123 baker st || Redmond");
DataTable table = new DataTable();
table.Columns.Add();
table.Columns.Add();
table.Rows.Add("john", addr);
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand cmd = new SqlCommand(sprocName, connection, transaction))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
Assert.NotNull(cmd.Parameters);
Assert.Equal(2, cmd.Parameters.Count); // [return_value, table]
SqlParameter p = cmd.Parameters[1];
Assert.Equal(customerParameterName, p.ParameterName);
Assert.Equal(SqlDbType.Structured, p.SqlDbType);
Assert.Equal(customerAddressTypeIncorrectName, p.TypeName); // the 3 part name is incorrect but needs to be maintained for compatibility
p.Value = table;
p.TypeName = customerAddressTypeIncorrectName; // force using the incorrect name by manually setting it
Assert.Throws<SqlException>(
() => cmd.ExecuteNonQuery()
);
}
finally
{
try
{
transaction.Rollback();
}
catch
{
// ignore rollback failure exceptions to preserve original thrown error in test result
}
}
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void Reader_PointEarly()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select name, location from cities", conn))
{
conn.Open();
string expectedReaderValues =
"ColumnName[0] = name" + Environment.NewLine +
"DataType[0] = nvarchar" + Environment.NewLine +
"FieldType[0] = System.String" + Environment.NewLine +
"ColumnName[1] = location" + Environment.NewLine +
"DataType[1] = UdtTestDb.dbo.Point" + Environment.NewLine +
"FieldType[1] = Point" + Environment.NewLine +
" redmond, p.X = 3, p.Y = 3, p.Distance() = 5" + Environment.NewLine +
" bellevue, p.X = 6, p.Y = 6, p.Distance() = 10" + Environment.NewLine +
" seattle, p.X = 10, p.Y = 10, p.Distance() = 14.866068747318506" + Environment.NewLine +
" portland, p.X = 20, p.Y = 20, p.Distance() = 25" + Environment.NewLine +
" LA, p.X = 3, p.Y = 3, p.Distance() = 5" + Environment.NewLine +
" SFO, p.X = 6, p.Y = 6, p.Distance() = 10" + Environment.NewLine +
" beaverton, p.X = 10, p.Y = 10, p.Distance() = 14.866068747318506" + Environment.NewLine +
" new york, p.X = 20, p.Y = 20, p.Distance() = 25" + Environment.NewLine +
" yukon, p.X = 20, p.Y = 20, p.Distance() = 32.01562118716424" + Environment.NewLine;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTestUtility.AssertEqualsWithDescription(
expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
"Unexpected reader values.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void Reader_LineEarly()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select * from lines", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
Line l = null;
Point p = null;
int x = 0, y = 0;
double length = 0;
string expectedReaderValues =
"ids (int);pos (UdtTestDb.dbo.Line);";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++)
{
builder.Append(reader.GetName(i) + " (" + reader.GetDataTypeName(i) + ");");
}
DataTestUtility.AssertEqualsWithDescription(
expectedReaderValues, builder.ToString(),
"Unexpected reader values.");
string expectedLineValues =
"1, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
"2, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
"3, IsNull = False, Length = 9.848857801796104" + Environment.NewLine +
"4, IsNull = False, Length = 214.1074496602115" + Environment.NewLine +
"5, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
"6, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
"7, IsNull = False, Length = 9.848857801796104" + Environment.NewLine +
"8, IsNull = False, Length = 214.1074496602115" + Environment.NewLine;
builder = new StringBuilder();
while (reader.Read())
{
builder.Append(reader.GetValue(0).ToString() + ", ");
l = (Line)reader.GetValue(1);
if (!l.IsNull)
{
p = l.Start;
x = p.X;
y = p.Y;
length = l.Length();
}
builder.Append("IsNull = " + l.IsNull + ", ");
builder.Append("Length = " + length);
builder.AppendLine();
}
DataTestUtility.AssertEqualsWithDescription(
expectedLineValues, builder.ToString(),
"Unexpected Line values.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void Reader_PointLate()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select name, location from cities", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
string expectedReaderValues =
"ColumnName[0] = name" + Environment.NewLine +
"DataType[0] = nvarchar" + Environment.NewLine +
"FieldType[0] = System.String" + Environment.NewLine +
"ColumnName[1] = location" + Environment.NewLine +
"DataType[1] = UdtTestDb.dbo.Point" + Environment.NewLine +
"FieldType[1] = Point" + Environment.NewLine +
" redmond, p.X = 3, p.Y = 3, p.Distance() = 5" + Environment.NewLine +
" bellevue, p.X = 6, p.Y = 6, p.Distance() = 10" + Environment.NewLine +
" seattle, p.X = 10, p.Y = 10, p.Distance() = 14.866068747318506" + Environment.NewLine +
" portland, p.X = 20, p.Y = 20, p.Distance() = 25" + Environment.NewLine +
" LA, p.X = 3, p.Y = 3, p.Distance() = 5" + Environment.NewLine +
" SFO, p.X = 6, p.Y = 6, p.Distance() = 10" + Environment.NewLine +
" beaverton, p.X = 10, p.Y = 10, p.Distance() = 14.866068747318506" + Environment.NewLine +
" new york, p.X = 20, p.Y = 20, p.Distance() = 25" + Environment.NewLine +
" yukon, p.X = 20, p.Y = 20, p.Distance() = 32.01562118716424" + Environment.NewLine;
DataTestUtility.AssertEqualsWithDescription(
expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
"Unexpected reader values.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void Reader_CircleLate()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select * from circles", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
string expectedReaderValues =
"ColumnName[0] = num" + Environment.NewLine +
"DataType[0] = int" + Environment.NewLine +
"FieldType[0] = System.Int32" + Environment.NewLine +
"ColumnName[1] = def" + Environment.NewLine +
"DataType[1] = UdtTestDb.dbo.Circle" + Environment.NewLine +
"FieldType[1] = Circle" + Environment.NewLine +
" 1, Center = 1,2" + Environment.NewLine +
" 2, Center = 3,4" + Environment.NewLine +
" 3, Center = 11,23" + Environment.NewLine +
" 4, Center = 444,555" + Environment.NewLine +
" 5, Center = 1,2" + Environment.NewLine +
" 6, Center = 3,4" + Environment.NewLine +
" 7, Center = 11,23" + Environment.NewLine +
" 8, Center = 444,245" + Environment.NewLine;
DataTestUtility.AssertEqualsWithDescription(
expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
"Unexpected reader values.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void TestSchemaTable()
{
using (SqlConnection conn = new SqlConnection(_connStr))
using (SqlCommand cmd = new SqlCommand("select * from lines", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable t = reader.GetSchemaTable();
string expectedSchemaTableValues =
"ids, 0, 4, 10, 255, False, , , , ids, , , System.Int32, True, 8, , , False, False, False, , False, False, System.Data.SqlTypes.SqlInt32, int, , , , , 8, False, " + Environment.NewLine +
"pos, 1, 20, 255, 255, False, , , , pos, , , Line, True, 29, , , False, False, False, , False, False, Line, UdtTestDb.dbo.Line, , , , Line, Shapes, Version=1.2.0.0, Culture=neutral, PublicKeyToken=a3e3aa32e6a16344, 29, False, " + Environment.NewLine;
StringBuilder builder = new StringBuilder();
foreach (DataRow row in t.Rows)
{
foreach (DataColumn col in t.Columns)
builder.Append(row[col] + ", ");
builder.AppendLine();
}
DataTestUtility.AssertEqualsWithDescription(
expectedSchemaTableValues, builder.ToString(),
"Unexpected DataTable values from GetSchemaTable.");
string expectedReaderValues =
"ids1" + Environment.NewLine +
"pos1,2,3,4" + Environment.NewLine +
"ids2" + Environment.NewLine +
"pos3,4,5,6" + Environment.NewLine +
"ids3" + Environment.NewLine +
"pos11,23,15,32" + Environment.NewLine +
"ids4" + Environment.NewLine +
"pos444,555,245,634" + Environment.NewLine +
"ids5" + Environment.NewLine +
"pos1,2,3,4" + Environment.NewLine +
"ids6" + Environment.NewLine +
"pos3,4,5,6" + Environment.NewLine +
"ids7" + Environment.NewLine +
"pos11,23,15,32" + Environment.NewLine +
"ids8" + Environment.NewLine +
"pos444,555,245,634" + Environment.NewLine;
builder = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
builder.Append(reader.GetName(i) + reader.GetValue(i).ToString());
builder.AppendLine();
}
}
DataTestUtility.AssertEqualsWithDescription(
expectedReaderValues, builder.ToString(),
"Unexpected Reader values.");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
public void TestSqlUserDefinedAggregateAttributeMaxByteSize()
{
Func<int, SqlUserDefinedAggregateAttribute> create
= (size) => new SqlUserDefinedAggregateAttribute(Format.UserDefined) { MaxByteSize = size };
SqlUserDefinedAggregateAttribute attribute1 = create(-1);
SqlUserDefinedAggregateAttribute attribute2 = create(0);
SqlUserDefinedAggregateAttribute attribute3 = create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue);
string udtError = SystemDataResourceManager.Instance.SQLUDT_MaxByteSizeValue;
string errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", 8001, udtError)).Message;
DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(
() => create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue + 1),
errorMessage);
errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", -2, udtError)).Message;
DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(
() => create(-2),
errorMessage);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using ManagedBass;
using ManagedBass.Fx;
using osu.Framework.IO;
using System.Threading.Tasks;
using osu.Framework.Audio.Callbacks;
using osu.Framework.Audio.Mixing;
using osu.Framework.Audio.Mixing.Bass;
using osu.Framework.Extensions;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Utils;
namespace osu.Framework.Audio.Track
{
public sealed class TrackBass : Track, IBassAudio, IBassAudioChannel
{
public const int BYTES_PER_SAMPLE = 4;
private AsyncBufferStream? dataStream;
/// <summary>
/// Should this track only be used for preview purposes? This suggests it has not yet been fully loaded.
/// </summary>
public bool Preview { get; private set; }
/// <summary>
/// The handle for this track, if there is one.
/// </summary>
private int activeStream;
/// <summary>
/// The handle for adjusting tempo.
/// </summary>
private int tempoAdjustStream;
/// <summary>
/// This marks if the track is paused, or stopped to the end.
/// </summary>
private bool isPlayed;
/// <summary>
/// The last position that a seek will succeed for.
/// </summary>
private double lastSeekablePosition;
private FileCallbacks? fileCallbacks;
private SyncCallback? stopCallback;
private SyncCallback? endCallback;
private int? stopSync;
private int? endSync;
private volatile bool isLoaded;
public override bool IsLoaded => isLoaded;
private readonly BassRelativeFrequencyHandler relativeFrequencyHandler;
/// <summary>
/// Constructs a new <see cref="TrackBass"/> from provided audio data.
/// </summary>
/// <param name="data">The sample data stream.</param>
/// <param name="quick">If true, the track will not be fully loaded, and should only be used for preview purposes. Defaults to false.</param>
internal TrackBass(Stream data, bool quick = false)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
relativeFrequencyHandler = new BassRelativeFrequencyHandler
{
FrequencyChangedToZero = () => stopInternal(),
FrequencyChangedFromZero = () =>
{
// Do not resume the track if a play wasn't requested at all or has been paused via Stop().
if (!isPlayed) return;
startInternal();
}
};
// todo: support this internally to match the underlying Track implementation (which can support this).
const float tempo_minimum_supported = 0.05f;
AggregateTempo.ValueChanged += t =>
{
if (t.NewValue < tempo_minimum_supported)
throw new ArgumentException($"{nameof(TrackBass)} does not support {nameof(Tempo)} specifications below {tempo_minimum_supported}. Use {nameof(Frequency)} instead.");
};
EnqueueAction(() =>
{
Preview = quick;
activeStream = prepareStream(data, quick);
long byteLength = Bass.ChannelGetLength(activeStream);
// will be -1 in case of an error
double seconds = Bass.ChannelBytes2Seconds(activeStream, byteLength);
bool success = seconds >= 0;
if (success)
{
Length = seconds * 1000;
// Bass does not allow seeking to the end of the track, so the last available position is 1 sample before.
lastSeekablePosition = Bass.ChannelBytes2Seconds(activeStream, byteLength - BYTES_PER_SAMPLE) * 1000;
isLoaded = true;
relativeFrequencyHandler.SetChannel(activeStream);
}
});
InvalidateState();
}
private void setLoopFlag(bool value) => EnqueueAction(() =>
{
if (activeStream != 0)
Bass.ChannelFlags(activeStream, value ? BassFlags.Loop : BassFlags.Default, BassFlags.Loop);
});
private int prepareStream(Stream data, bool quick)
{
//encapsulate incoming stream with async buffer if it isn't already.
dataStream = data as AsyncBufferStream ?? new AsyncBufferStream(data, quick ? 8 : -1);
fileCallbacks = new FileCallbacks(new DataStreamFileProcedures(dataStream));
BassFlags flags = Preview ? 0 : BassFlags.Decode | BassFlags.Prescan;
int stream = Bass.CreateStream(StreamSystem.NoBuffer, flags, fileCallbacks.Callbacks, fileCallbacks.Handle);
bitrate = (int)Math.Round(Bass.ChannelGetAttribute(stream, ChannelAttribute.Bitrate));
if (!Preview)
{
// We assign the BassFlags.Decode streams to the device "bass_nodevice" to prevent them from getting
// cleaned up during a Bass.Free call. This is necessary for seamless switching between audio devices.
// Further, we provide the flag BassFlags.FxFreeSource such that freeing the stream also frees
// all parent decoding streams.
const int bass_nodevice = 0x20000;
Bass.ChannelSetDevice(stream, bass_nodevice);
tempoAdjustStream = BassFx.TempoCreate(stream, BassFlags.Decode | BassFlags.FxFreeSource);
Bass.ChannelSetDevice(tempoAdjustStream, bass_nodevice);
stream = BassFx.ReverseCreate(tempoAdjustStream, 5f, BassFlags.Default | BassFlags.FxFreeSource | BassFlags.Decode);
Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoUseQuickAlgorithm, 1);
Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoOverlapMilliseconds, 4);
Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoSequenceMilliseconds, 30);
}
return stream;
}
/// <summary>
/// Returns whether the playback state is considered to be running or not.
/// This will only return true for <see cref="PlaybackState.Playing"/> and <see cref="PlaybackState.Stalled"/>.
/// </summary>
private static bool isRunningState(PlaybackState state) => state == PlaybackState.Playing || state == PlaybackState.Stalled;
void IBassAudio.UpdateDevice(int deviceIndex)
{
// Bass may leave us in an invalid state after the output device changes (this is true for "No sound" device)
// if the observed state was playing before change, we should force things into a good state.
if (isPlayed)
{
// While on windows, changing to "No sound" changes the playback state correctly,
// on macOS it is left in a playing-but-stalled state. Forcefully stopping first fixes this.
stopInternal();
startInternal();
}
}
private BassAmplitudeProcessor? bassAmplitudeProcessor;
protected override void UpdateState()
{
base.UpdateState();
bool running = isRunningState(bassMixer.ChannelIsActive(this));
// because device validity check isn't done frequently, when switching to "No sound" device,
// there will be a brief time where this track will be stopped, before we resume it manually (see comments in UpdateDevice(int).)
// this makes us appear to be playing, even if we may not be.
isRunning = running || (isPlayed && !hasCompleted);
updateCurrentTime();
bassAmplitudeProcessor?.Update();
}
public override bool IsDummyDevice => false;
public override void Stop()
{
base.Stop();
StopAsync().WaitSafely();
}
public Task StopAsync() => EnqueueAction(() =>
{
stopInternal();
isPlayed = false;
});
private bool stopInternal() => isRunningState(bassMixer.ChannelIsActive(this)) && bassMixer.ChannelPause(this, true);
private int direction;
private void setDirection(bool reverse)
{
direction = reverse ? -1 : 1;
Bass.ChannelSetAttribute(activeStream, ChannelAttribute.ReverseDirection, direction);
}
public override void Start()
{
base.Start();
StartAsync().WaitSafely();
}
public Task StartAsync() => EnqueueAction(() =>
{
if (startInternal())
isPlayed = true;
});
private bool startInternal()
{
// ensure state is correct before starting.
InvalidateState();
// Bass will restart the track if it has reached its end. This behavior isn't desirable so block locally.
if (hasCompleted)
return false;
if (relativeFrequencyHandler.IsFrequencyZero)
return true;
setLoopFlag(Looping);
return bassMixer.ChannelPlay(this);
}
public override bool Looping
{
get => base.Looping;
set
{
base.Looping = value;
setLoopFlag(Looping);
}
}
public override bool Seek(double seek) => SeekAsync(seek).GetResultSafely();
public async Task<bool> SeekAsync(double seek)
{
// At this point the track may not yet be loaded which is indicated by a 0 length.
// In that case we still want to return true, hence the conservative length.
double conservativeLength = Length == 0 ? double.MaxValue : lastSeekablePosition;
double conservativeClamped = Math.Clamp(seek, 0, conservativeLength);
await EnqueueAction(() => seekInternal(seek)).ConfigureAwait(false);
return conservativeClamped == seek;
}
private void seekInternal(double seek)
{
double clamped = Math.Clamp(seek, 0, Length);
if (clamped < Length)
hasCompleted = false;
long pos = Bass.ChannelSeconds2Bytes(activeStream, clamped / 1000d);
if (pos != bassMixer.ChannelGetPosition(this))
bassMixer.ChannelSetPosition(this, pos);
// current time updates are safe to perform from enqueued actions,
// but not always safe to perform from BASS callbacks, since those can sometimes use a separate thread.
// if it's not safe to update immediately here, the next UpdateState() call is guaranteed to update the time safely anyway.
if (CanPerformInline)
updateCurrentTime();
}
private void updateCurrentTime()
{
Debug.Assert(CanPerformInline);
long bytePosition = bassMixer.ChannelGetPosition(this);
Interlocked.Exchange(ref currentTime, Bass.ChannelBytes2Seconds(activeStream, bytePosition) * 1000);
}
private double currentTime;
public override double CurrentTime => currentTime;
private volatile bool isRunning;
public override bool IsRunning => isRunning;
private volatile bool hasCompleted;
public override bool HasCompleted => hasCompleted;
internal override void OnStateChanged()
{
base.OnStateChanged();
if (activeStream == 0)
return;
setDirection(AggregateFrequency.Value < 0);
Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Volume, AggregateVolume.Value);
Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Pan, AggregateBalance.Value);
relativeFrequencyHandler.SetFrequency(AggregateFrequency.Value);
Bass.ChannelSetAttribute(tempoAdjustStream, ChannelAttribute.Tempo, (Math.Abs(AggregateTempo.Value) - 1) * 100);
}
private volatile int bitrate;
public override int? Bitrate => bitrate;
public override ChannelAmplitudes CurrentAmplitudes => (bassAmplitudeProcessor ??= new BassAmplitudeProcessor(this)).CurrentAmplitudes;
private void initializeSyncs()
{
Debug.Assert(stopCallback == null
&& stopSync == null
&& endCallback == null
&& endSync == null);
stopCallback = new SyncCallback((a, b, c, d) => RaiseFailed());
endCallback = new SyncCallback((a, b, c, d) =>
{
if (Looping)
{
// because the sync callback doesn't necessarily fire in the right moment and the transition may not always be smooth,
// do not attempt to seek back to restart point if it is 0, and defer to the channel loop flag instead.
// a mixtime callback was used for this previously, but it is incompatible with mixers
// (as they have a playback buffer, and so a skip forward would be audible).
if (Precision.DefinitelyBigger(RestartPoint, 0, 1))
seekInternal(RestartPoint);
return;
}
hasCompleted = true;
RaiseCompleted();
});
stopSync = bassMixer.ChannelSetSync(this, SyncFlags.Stop, 0, stopCallback.Callback, stopCallback.Handle);
endSync = bassMixer.ChannelSetSync(this, SyncFlags.End, 0, endCallback.Callback, endCallback.Handle);
}
private void cleanUpSyncs()
{
Debug.Assert(stopCallback != null
&& stopSync != null
&& endCallback != null
&& endSync != null);
bassMixer.ChannelRemoveSync(this, stopSync.Value);
bassMixer.ChannelRemoveSync(this, endSync.Value);
stopSync = null;
endSync = null;
stopCallback.Dispose();
stopCallback = null;
endCallback.Dispose();
endCallback = null;
}
#region Mixing
protected override AudioMixer? Mixer
{
get => base.Mixer;
set
{
// While BASS cleans up syncs automatically on mixer change, ManagedBass internally tracks the sync procedures via ChannelReferences, so clean up eagerly for safety.
if (Mixer != null)
cleanUpSyncs();
base.Mixer = value;
// The mixer can be null in this case, if set via Dispose() / bassMixer.StreamFree(this).
if (Mixer != null)
{
// Tracks are always active until they're disposed, so they need to be added to the mix prematurely for operations like Seek() to work immediately.
bassMixer.AddChannelToBassMix(this);
// Syncs are not automatically moved on mixer change, so restore them on the new mixer manually.
initializeSyncs();
}
}
}
private BassAudioMixer bassMixer => (BassAudioMixer)Mixer.AsNonNull();
bool IBassAudioChannel.IsActive => !IsDisposed;
int IBassAudioChannel.Handle => activeStream;
bool IBassAudioChannel.MixerChannelPaused { get; set; } = true;
BassAudioMixer IBassAudioChannel.Mixer => bassMixer;
#endregion
~TrackBass()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (IsDisposed)
return;
if (activeStream != 0)
{
isRunning = false;
bassMixer.StreamFree(this);
}
activeStream = 0;
dataStream?.Dispose();
dataStream = null;
fileCallbacks?.Dispose();
fileCallbacks = null;
stopCallback?.Dispose();
stopCallback = null;
endCallback?.Dispose();
endCallback = null;
base.Dispose(disposing);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using Autofac;
using Rhino.ServiceBus.Actions;
using Rhino.ServiceBus.Config;
using Rhino.ServiceBus.Convertors;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.LoadBalancer;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Msmq;
using Rhino.ServiceBus.Msmq.TransportActions;
using ErrorAction = Rhino.ServiceBus.Msmq.TransportActions.ErrorAction;
using LoadBalancerConfiguration = Rhino.ServiceBus.LoadBalancer.LoadBalancerConfiguration;
using System.Reflection;
namespace Rhino.ServiceBus.Autofac
{
public class AutofacBuilder : IBusContainerBuilder
{
private readonly AbstractRhinoServiceBusConfiguration config;
private readonly IContainer container;
public AutofacBuilder(AbstractRhinoServiceBusConfiguration config, IContainer container)
{
this.config = config;
this.container = container;
config.BuildWith(this);
}
public void WithInterceptor(IConsumerInterceptor interceptor)
{
var builder = new ContainerBuilder();
builder.RegisterModule(new ConsumerInterceptorModule(interceptor));
builder.Update(container);
}
public void RegisterDefaultServices(IEnumerable<Assembly> assemblies)
{
var builder = new ContainerBuilder();
builder.RegisterInstance(container);
builder.RegisterType<AutofacServiceLocator>()
.As<IServiceLocator>()
.SingleInstance();
foreach (var assembly in assemblies)
builder.RegisterAssemblyTypes(assembly)
.AssignableTo<IBusConfigurationAware>()
.As<IBusConfigurationAware>()
.SingleInstance();
builder.RegisterType<DefaultReflection>()
.As<IReflection>()
.SingleInstance();
builder.RegisterType(config.SerializerType)
.As<IMessageSerializer>()
.SingleInstance();
builder.RegisterType<EndpointRouter>()
.As<IEndpointRouter>()
.SingleInstance();
foreach (var module in config.MessageModules)
{
builder.RegisterType(module)
.Named<IMessageModule>(module.FullName)
.As<IMessageModule>()
.SingleInstance();
}
builder.Update(container);
var locator = container.Resolve<IServiceLocator>();
foreach (var busConfigurationAware in container.Resolve<IEnumerable<IBusConfigurationAware>>())
busConfigurationAware.Configure(config, this, locator);
}
public void RegisterBus()
{
var builder = new ContainerBuilder();
var busConfig = (RhinoServiceBusConfiguration)config;
builder.RegisterType<DefaultServiceBus>()
.WithParameter("messageOwners", busConfig.MessageOwners.ToArray())
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterType<CreateLogQueueAction>()
.As<IDeploymentAction>()
.SingleInstance();
builder.RegisterType<CreateQueuesAction>()
.As<IDeploymentAction>()
.SingleInstance();
builder.Update(container);
}
public void RegisterPrimaryLoadBalancer()
{
var builder = new ContainerBuilder();
var loadBalancerConfig = (LoadBalancerConfiguration)config;
builder.RegisterType<MsmqLoadBalancer>()
.WithParameter("endpoint", loadBalancerConfig.Endpoint)
.WithParameter("threadCount", loadBalancerConfig.ThreadCount)
.WithParameter("secondaryLoadBalancer", loadBalancerConfig.Endpoint)
.WithParameter("transactional", loadBalancerConfig.Transactional)
.PropertiesAutowired()
.AsSelf()
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterType<CreateLoadBalancerQueuesAction>()
.As<IDeploymentAction>()
.SingleInstance();
builder.Update(container);
}
public void RegisterSecondaryLoadBalancer()
{
var builder = new ContainerBuilder();
var loadBalancerConfig = (LoadBalancerConfiguration)config;
builder.RegisterType<MsmqSecondaryLoadBalancer>()
.WithParameter("endpoint", loadBalancerConfig.Endpoint)
.WithParameter("primaryLoadBalancer", loadBalancerConfig.PrimaryLoadBalancer)
.WithParameter("threadCount", loadBalancerConfig.ThreadCount)
.WithParameter("transactional", loadBalancerConfig.Transactional)
.PropertiesAutowired()
.As<MsmqLoadBalancer>()
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterType<CreateLoadBalancerQueuesAction>()
.As<IDeploymentAction>()
.SingleInstance();
builder.Update(container);
}
public void RegisterReadyForWork()
{
var builder = new ContainerBuilder();
var loadBalancerConfig = (LoadBalancerConfiguration)config;
builder.RegisterType<MsmqReadyForWorkListener>()
.WithParameter("endpoint", loadBalancerConfig.ReadyForWork)
.WithParameter("threadCount", loadBalancerConfig.ThreadCount)
.WithParameter("transactional", loadBalancerConfig.Transactional)
.AsSelf()
.SingleInstance();
builder.RegisterType<CreateReadyForWorkQueuesAction>()
.As<IDeploymentAction>()
.SingleInstance();
builder.Update(container);
}
public void RegisterLoadBalancerEndpoint(Uri loadBalancerEndpoint)
{
var builder = new ContainerBuilder();
builder.Register(c => new LoadBalancerMessageModule(loadBalancerEndpoint, c.Resolve<IEndpointRouter>()))
.As<IMessageModule>()
.AsSelf()
.SingleInstance();
builder.Update(container);
}
public void RegisterLoggingEndpoint(Uri logEndpoint)
{
var builder = new ContainerBuilder();
builder.Register(c => new MessageLoggingModule(c.Resolve<IEndpointRouter>(), logEndpoint))
.As<IMessageModule>()
.AsSelf()
.SingleInstance();
builder.Update(container);
}
public void RegisterSingleton<T>(Func<T> func)
where T : class
{
T singleton = null;
var builder = new ContainerBuilder();
builder.Register(x => singleton == null ? singleton = func() : singleton)
.As<T>()
.SingleInstance();
builder.Update(container);
}
public void RegisterSingleton<T>(string name, Func<T> func)
where T : class
{
T singleton = null;
var builder = new ContainerBuilder();
builder.Register(x => singleton == null ? singleton = func() : singleton)
.As<T>()
.Named<T>(name)
.SingleInstance();
builder.Update(container);
}
public void RegisterAll<T>(params Type[] excludes)
where T : class { RegisterAll<T>((Predicate<Type>)(x => !x.IsAbstract && !x.IsInterface && typeof(T).IsAssignableFrom(x) && !excludes.Contains(x))); }
public void RegisterAll<T>(Predicate<Type> condition)
where T : class
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(T).Assembly)
.Where(x => condition(x))
.As<T>()
.SingleInstance();
builder.Update(container);
}
public void RegisterSecurity(byte[] key)
{
var builder = new ContainerBuilder();
builder.RegisterType<RijndaelEncryptionService>()
.WithParameter(new NamedParameter("key", key))
.As<IEncryptionService>().SingleInstance();
builder.RegisterType<WireEncryptedStringConvertor>()
.As<IValueConvertor<WireEncryptedString>>()
.SingleInstance();
builder.RegisterType<WireEncryptedMessageConvertor>()
.As<IElementSerializationBehavior>().SingleInstance();
builder.Update(container);
}
public void RegisterNoSecurity()
{
var builder = new ContainerBuilder();
builder.RegisterType<ThrowingWireEncryptedStringConvertor>()
.As<IValueConvertor<WireEncryptedString>>().SingleInstance();
builder.RegisterType<ThrowingWireEncryptedMessageConvertor>()
.As<IElementSerializationBehavior>().SingleInstance();
builder.Update(container);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using static Epos.Utilities.Characters;
namespace Epos.Utilities
{
/// <summary>Provides utility methods for pretty-printing arbitrary object instances.</summary>
public static class DumpExtensions
{
private const string Null = "null";
private const string My = "my";
private const string Underscore = "_";
private const string ToStringMethodName = "ToString";
private static readonly Type[] ToStringParameters = { typeof(IFormatProvider) };
/// <summary>Returns a pretty-print string representation of the specified
/// <paramref name="value"/>.</summary>
/// <param name="value">Value</param>
/// <returns>Pretty-print string representation</returns>
public static string Dump(this object? value) {
// Simple cases:
switch (value) {
case null:
return Null;
case string theString:
return theString;
case double theDoubleValue:
return
Math.Abs(theDoubleValue) < 1.0E-14 ?
"0" :
theDoubleValue.ToString("0.##########", CultureInfo.InvariantCulture);
case DictionaryEntry theEntry:
return
new StringBuilder("{ ")
.Append(theEntry.Key.Dump()).Append(": ")
.Append(theEntry.Value.Dump()).Append(" }")
.ToString();
case Type theTypeToDump:
return theTypeToDump.Dump();
}
Type theType = value!.GetType();
if (theType.IsGenericType && theType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) {
StringBuilder theBuilder =
new StringBuilder("{ ")
.Append(theType.GetProperty("Key").GetValue(value, null).Dump())
.Append(": ")
.Append(theType.GetProperty("Value").GetValue(value, null).Dump())
.Append(" }");
return theBuilder.ToString();
}
// Find ToString() method and call, if available (not with anonymous types!):
MethodInfo? theToStringMethodInfo = GetToStringMethodInfo(theType);
if (theToStringMethodInfo != null && !theType.Name.StartsWith("<>f__Anonymous")) {
if (theToStringMethodInfo.GetParameters().Length == 1) {
return (string) theToStringMethodInfo.Invoke(
value, new object[] { CultureInfo.InvariantCulture }
);
} else {
return (string) theToStringMethodInfo.Invoke(value, null);
}
}
switch (value) {
case IEnumerable theSequence:
return Dump(theSequence.GetEnumerator());
case IEnumerator theEnumerator:
return Dump(theEnumerator);
}
// Only object.ToString() respectively ValueType.ToString() is possible.
// That's not enough.
FieldInfo[] theFieldInfos = theType.GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static
);
var theStringBuilder = new StringBuilder("{ ");
int theFieldInfosLength = theFieldInfos.Length;
for (int theIndex = 0; theIndex < theFieldInfosLength; theIndex++) {
FieldInfo theFieldInfo = theFieldInfos[theIndex];
string theFieldName = theFieldInfo.Name;
if (theFieldName.StartsWith(My, StringComparison.InvariantCulture)) {
theFieldName = theFieldName.Substring(2);
} else if (theFieldName.StartsWith(Underscore, StringComparison.InvariantCulture)) {
theFieldName =
theFieldName.Substring(1, 1).ToUpper(CultureInfo.CurrentCulture) + theFieldName.Substring(2);
} else if (theFieldName.StartsWith("<")) {
// Anonymous type fields:
theFieldName = theFieldName.Substring(1, theFieldName.IndexOf('>') - 1);
} else {
theFieldName =
theFieldName.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + theFieldName.Substring(1);
}
theStringBuilder.Append(theFieldName).Append(" = ").Append(theFieldInfo.GetValue(value).Dump());
if (theIndex < theFieldInfosLength - 1) {
theStringBuilder.Append(", ");
}
}
return theStringBuilder.Append(" }").ToString();
}
/// <summary>Returns a pretty-print string representation of the specified
/// <paramref name="table"/> object.</summary>
/// <param name="table">Table object</param>
/// <param name="tableInfoProvider">Table info provider</param>
/// <returns>Pretty-print string representation of the table</returns>
public static string DumpTableObject<T, TColumn, TRow>(
this T table, TableInfoProvider<TColumn, TRow> tableInfoProvider
) where T : class {
if (table is null) {
throw new ArgumentNullException(nameof(table));
}
if (tableInfoProvider is null) {
throw new ArgumentNullException(nameof(tableInfoProvider));
}
var theResult = new StringBuilder();
List<TextColumn<TColumn>> theColumns = GetTextColumns(tableInfoProvider);
string theSpaces = new string(' ', tableInfoProvider.LeadingSpaces);
theResult.Append(theSpaces);
int theColumnCount = theColumns.Count;
if (theColumns.Any(c => c.Seperator != null)) {
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theColumn = theColumns[theIndex];
ColumnSeperator? theSeperator = theColumn.Seperator;
if (theSeperator != null) {
int theColSpan = theSeperator.ColSpan;
int theWidth;
if (theColSpan == 1) {
theWidth = theColumn.Width;
} else {
theWidth =
theColumns.Skip(theIndex).Take(theColSpan).Sum(c => c.Width) + (theColSpan - 1) * 3;
}
var theCenteredHeader = new StringBuilder(theSeperator.Header);
while (theCenteredHeader.Length < theWidth) {
if (theCenteredHeader.Length % 2 == 0) {
theCenteredHeader.Insert(0, ' ');
} else {
theCenteredHeader.Append(' ');
}
}
theResult.Append(theCenteredHeader);
theIndex += theColSpan - 1;
}
if (theIndex < theColumnCount - 1) {
theResult.Append(" | ");
}
}
theResult
.Append(Lf)
.Append(theSpaces);
}
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theColumn = theColumns[theIndex];
theResult.Append(string.Format(GetAlignmentString(theColumn), theColumn.Header));
if (theIndex < theColumnCount - 1) {
theResult.Append(" | ");
}
}
if (theColumns.Any(c => c.SecondaryHeader != null)) {
theResult
.Append(Lf)
.Append(theSpaces);
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theColumn = theColumns[theIndex];
theResult.Append(string.Format(GetAlignmentString(theColumn), theColumn.SecondaryHeader));
if (theIndex < theColumnCount - 1) {
theResult.Append(" | ");
}
}
}
if (theColumns.Any(c => c.DataType != null)) {
theResult
.Append(Lf)
.Append(theSpaces);
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theColumn = theColumns[theIndex];
theResult.Append(string.Format(GetAlignmentString(theColumn), theColumn.DataType));
if (theIndex < theColumnCount - 1) {
theResult.Append(" | ");
}
}
}
theResult.Append(Lf);
var theSeperatorLine = new StringBuilder();
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
theSeperatorLine.Append('-', theColumns[theIndex].Width);
if (theIndex < theColumnCount - 1) {
theSeperatorLine.Append("-|-");
}
}
theResult
.Append(theSpaces)
.Append(theSeperatorLine)
.Append(Lf);
int theRowCount = theColumns.First().Rows.Count;
string? theEmptyTableText = tableInfoProvider.EmptyTableText;
if (theEmptyTableText != null && theRowCount == 0) {
theResult
.Append(theSpaces)
.Append(theEmptyTableText)
.Append(Lf);
} else {
for (int theRowIndex = 0; theRowIndex < theRowCount; theRowIndex++) {
theResult.Append(theSpaces);
if (theRowIndex == theRowCount - 1) {
// Letzte Zeile
if (tableInfoProvider.HasSumRow) {
theResult
.Append(theSeperatorLine)
.Append(Lf)
.Append(theSpaces);
}
}
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theColumn = theColumns[theIndex];
(string theCellValue, int theColSpan) = theColumn.Rows[theRowIndex];
string theAlignmentString;
if (theColSpan == 1) {
theAlignmentString = GetAlignmentString(theColumn);
} else {
int theWidth =
theColumns.Skip(theIndex).Take(theColSpan).Sum(c => c.Width) + (theColSpan - 1) * 3;
theAlignmentString = $"{{0,-{theWidth}}}";
}
theResult.Append(string.Format(theAlignmentString, theCellValue));
theIndex += theColSpan - 1;
if (theIndex < theColumnCount - 1) {
theResult.Append(" | ");
}
}
theResult.Append(Lf);
}
}
if (tableInfoProvider.HasTrailingSeperatorLine && (theRowCount != 0 || theEmptyTableText != null)) {
theResult
.Append(theSpaces)
.Append(theSeperatorLine)
.Append(Lf);
}
return theResult.ToString();
}
#region Helper methods
private static string Dump(this Type type) {
if (type.IsGenericParameter) {
return type.Name;
}
var theResult = new StringBuilder();
string theFullName;
bool isNullableType = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
if (type.IsNested) {
theResult.Append(type.DeclaringType.Dump()).Append(Type.Delimiter);
theFullName = type.Name;
} else {
theFullName = GetFriendlyName(type);
}
int theGenericArgumentIndex = theFullName.IndexOf('`');
if (theGenericArgumentIndex != -1) {
theFullName = theFullName.Substring(0, theGenericArgumentIndex);
}
if (!isNullableType) {
theResult.Append(theFullName);
}
if (type.IsGenericType) {
if (!isNullableType) {
theResult.Append('<');
}
Type[] theTypeArguments = type.GetGenericArguments();
int theTypeArgumentsLength = theTypeArguments.Length;
for (int theIndex = 0; theIndex < theTypeArgumentsLength; theIndex++) {
Type theTypeArgument = theTypeArguments[theIndex];
theResult.Append(theTypeArgument.Dump());
if (theIndex < theTypeArgumentsLength - 1) {
theResult.Append(", ");
}
}
theResult.Append(!isNullableType ? '>' : '?');
}
return theResult.ToString();
}
private static string GetFriendlyName(Type type) {
if (type == typeof(int)) {
return "int";
} else if (type == typeof(double)) {
return "double";
} else if (type == typeof(bool)) {
return "bool";
} else if (type == typeof(byte)) {
return "byte";
} else if (type == typeof(char)) {
return "char";
} else if (type == typeof(decimal)) {
return "decimal";
} else if (type == typeof(short)) {
return "short";
} else if (type == typeof(long)) {
return "long";
} else if (type == typeof(float)) {
return "float";
} else if (type == typeof(void)) {
return "void";
} else if (type == typeof(string)) {
return "string";
} else if (type == typeof(object)) {
return "object";
} else if (type.FullName == "Epos.Core.Date") {
return "Date";
} else if (type.FullName == "Epos.Core.DateSpan") {
return "DateSpan";
} else if (type.FullName == "Epos.Core.HistoricalState") {
return "HistoricalState";
} else if (type.FullName == "Epos.Core.Rational") {
return "Rational";
} else {
return type.FullName;
}
}
private static string Dump(IEnumerator enumerator) {
StringBuilder theStringBuilder = new StringBuilder().Append('[');
while (enumerator.MoveNext()) {
object theEntry = enumerator.Current;
theStringBuilder.Append(theEntry.Dump());
theStringBuilder.Append(", ");
}
if (theStringBuilder.Length != 1) {
theStringBuilder.Length -= 2;
}
theStringBuilder.Append(']');
return theStringBuilder.ToString();
}
private static MethodInfo? GetToStringMethodInfo(Type type) {
MethodInfo? theResult = null;
Type theSearchType = type;
while (theSearchType != typeof(object) &&
(theResult = theSearchType.GetMethod(
ToStringMethodName,
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance,
null, ToStringParameters, null)
) == null) {
theSearchType = theSearchType.BaseType;
}
if (theResult != null) {
return theResult;
}
theSearchType = type;
while ((theResult =
theSearchType.GetMethod(
ToStringMethodName,
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance,
null, Type.EmptyTypes, null
)) == null) {
theSearchType = theSearchType.BaseType;
}
if (theSearchType != typeof(object) && theSearchType != typeof(ValueType)) {
return theResult;
}
return null;
}
private static string GetAlignmentString<TColumn>(TextColumn<TColumn> column) {
return column.AlignRight ? $"{{0,{column.Width}}}" : $"{{0,-{column.Width}}}";
}
private static List<TextColumn<TColumn>> GetTextColumns<TColumn, TRow>(
TableInfoProvider<TColumn, TRow> tableInfoProvider
) {
var theResult = new List<TextColumn<TColumn>>();
var theColumns = tableInfoProvider.GetColumns();
int theColumnIndex = 0;
foreach (TColumn theColumn in theColumns) {
ColumnInfo theColumnInfo = tableInfoProvider.GetColumnInfo(theColumn, theColumnIndex);
theResult.Add(
new TextColumn<TColumn>(theColumnInfo.Header, theColumnIndex, theColumn, theColumnInfo.AlignRight) {
SecondaryHeader = theColumnInfo.SecondaryHeader,
DataType = theColumnInfo.DataType,
Seperator = theColumnInfo.Seperator
}
);
if ((theColumnInfo.Seperator?.ColSpan ?? int.MaxValue) < 1) {
throw new InvalidOperationException("ColSpan must not be lower than 1.");
}
theColumnIndex++;
}
var theRows = tableInfoProvider.GetRows();
foreach (TRow theRow in theRows) {
int theColumnCount = theResult.Count;
theColumnIndex = 0;
for (int theIndex = 0; theIndex < theColumnCount; theIndex++) {
TextColumn<TColumn> theTextColumn = theResult[theColumnIndex];
var theValue = tableInfoProvider.GetCellValue(theRow, theTextColumn.Column, theIndex);
if (theValue.ColSpan < 1) {
throw new InvalidOperationException("ColSpan must not be lower than 1.");
} else if (theValue.ColSpan > 1) {
int theRemainingColumnCount = theColumnCount - theIndex;
if (theValue.ColSpan > theRemainingColumnCount) {
throw new InvalidOperationException(
$"ColSpan must not be greater than than the remaining column " +
$"count ({theRemainingColumnCount})."
);
}
}
theTextColumn.Rows.Add(theValue);
if (theValue.ColSpan == 1) {
theTextColumn.Width = Math.Max(theTextColumn.Width, theValue.CellValue.Length);
} else {
int theTotalWidth = theTextColumn.Width;
for (int theNextIndex = theIndex + 1; theNextIndex < theIndex + theValue.ColSpan; theNextIndex++) {
TextColumn<TColumn> theNextTextColumn = theResult[theNextIndex];
theNextTextColumn.Rows.Add((string.Empty, 1));
theTotalWidth += theNextTextColumn.Width;
}
while (theTotalWidth < theValue.CellValue.Length) {
for (int theNextIndex = theIndex; theNextIndex < theIndex + theValue.ColSpan; theNextIndex++) {
TextColumn<TColumn> theNextTextColumn = theResult[theNextIndex];
theNextTextColumn.Width++;
theTotalWidth++;
if (theTotalWidth == theValue.CellValue.Length) {
break;
}
}
}
}
theColumnCount -= theValue.ColSpan - 1;
theColumnIndex += theValue.ColSpan;
}
}
return theResult;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace System.Configuration
{
public sealed class ConfigurationProperty
{
internal static readonly ConfigurationValidatorBase s_nonEmptyStringValidator = new StringValidator(1);
private static readonly ConfigurationValidatorBase s_defaultValidatorInstance = new DefaultValidator();
internal static readonly string s_defaultCollectionPropertyName = "";
private TypeConverter _converter;
private volatile bool _isConfigurationElementType;
private volatile bool _isTypeInited;
private ConfigurationPropertyOptions _options;
public ConfigurationProperty(string name, Type type)
{
object defaultValue = null;
ConstructorInit(name, type, ConfigurationPropertyOptions.None, null, null);
if (type == typeof(string))
{
defaultValue = string.Empty;
}
else if (type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(type);
}
SetDefaultValue(defaultValue);
}
public ConfigurationProperty(string name, Type type, object defaultValue)
: this(name, type, defaultValue, ConfigurationPropertyOptions.None)
{ }
public ConfigurationProperty(string name, Type type, object defaultValue, ConfigurationPropertyOptions options)
: this(name, type, defaultValue, null, null, options)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options)
: this(name, type, defaultValue, typeConverter, validator, options, null)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options,
string description)
{
ConstructorInit(name, type, options, validator, typeConverter);
SetDefaultValue(defaultValue);
}
internal ConfigurationProperty(PropertyInfo info)
{
Debug.Assert(info != null, "info != null");
ConfigurationPropertyAttribute propertyAttribute = null;
DescriptionAttribute descriptionAttribute = null;
// For compatibility we read the component model default value attribute. It is only
// used if ConfigurationPropertyAttribute doesn't provide the default value.
DefaultValueAttribute defaultValueAttribute = null;
TypeConverter typeConverter = null;
ConfigurationValidatorBase validator = null;
// Look for relevant attributes
foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
{
if (attribute is TypeConverterAttribute)
{
typeConverter = TypeUtil.CreateInstance<TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName);
}
else if (attribute is ConfigurationPropertyAttribute)
{
propertyAttribute = (ConfigurationPropertyAttribute)attribute;
}
else if (attribute is ConfigurationValidatorAttribute)
{
if (validator != null)
{
// We only allow one validator to be specified on a property.
//
// Consider: introduce a new validator type ( CompositeValidator ) that is a
// list of validators and executes them all
throw new ConfigurationErrorsException(
SR.Format(SR.Validator_multiple_validator_attributes, info.Name));
}
ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
validatorAttribute.SetDeclaringType(info.DeclaringType);
validator = validatorAttribute.ValidatorInstance;
}
else if (attribute is DescriptionAttribute)
{
descriptionAttribute = (DescriptionAttribute)attribute;
}
else if (attribute is DefaultValueAttribute)
{
defaultValueAttribute = (DefaultValueAttribute)attribute;
}
}
Type propertyType = info.PropertyType;
// If the property is a Collection we need to look for the ConfigurationCollectionAttribute for
// additional customization.
if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType))
{
// Look for the ConfigurationCollection attribute on the property itself, fall back
// on the property type.
ConfigurationCollectionAttribute collectionAttribute =
Attribute.GetCustomAttribute(info,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ??
Attribute.GetCustomAttribute(propertyType,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
if (collectionAttribute != null)
{
if (collectionAttribute.AddItemName.IndexOf(',') == -1) AddElementName = collectionAttribute.AddItemName; // string.Contains(char) is .NetCore2.1+ specific
RemoveElementName = collectionAttribute.RemoveItemName;
ClearElementName = collectionAttribute.ClearItemsName;
}
}
// This constructor shouldn't be invoked if the reflection info is not for an actual config property
Debug.Assert(propertyAttribute != null, "attribProperty != null");
ConstructorInit(propertyAttribute.Name,
info.PropertyType,
propertyAttribute.Options,
validator,
typeConverter);
// Figure out the default value
InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute);
// Get the description
if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
Description = descriptionAttribute.Description;
}
public string Name { get; private set; }
public string Description { get; }
internal string ProvidedName { get; private set; }
internal bool IsConfigurationElementType
{
get
{
if (_isTypeInited)
return _isConfigurationElementType;
_isConfigurationElementType = typeof(ConfigurationElement).IsAssignableFrom(Type);
_isTypeInited = true;
return _isConfigurationElementType;
}
}
public Type Type { get; private set; }
public object DefaultValue { get; private set; }
public bool IsRequired => (_options & ConfigurationPropertyOptions.IsRequired) != 0;
public bool IsKey => (_options & ConfigurationPropertyOptions.IsKey) != 0;
public bool IsDefaultCollection => (_options & ConfigurationPropertyOptions.IsDefaultCollection) != 0;
public bool IsTypeStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsTypeStringTransformationRequired) != 0;
public bool IsAssemblyStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsAssemblyStringTransformationRequired) != 0;
public bool IsVersionCheckRequired => (_options & ConfigurationPropertyOptions.IsVersionCheckRequired) != 0;
public TypeConverter Converter
{
get
{
CreateConverter();
return _converter;
}
}
public ConfigurationValidatorBase Validator { get; private set; }
internal string AddElementName { get; }
internal string RemoveElementName { get; }
internal string ClearElementName { get; }
private void ConstructorInit(
string name,
Type type,
ConfigurationPropertyOptions options,
ConfigurationValidatorBase validator,
TypeConverter converter)
{
if (typeof(ConfigurationSection).IsAssignableFrom(type))
{
throw new ConfigurationErrorsException(
SR.Format(SR.Config_properties_may_not_be_derived_from_configuration_section, name));
}
// save the provided name so we can check for default collection names
ProvidedName = name;
if (((options & ConfigurationPropertyOptions.IsDefaultCollection) != 0) && string.IsNullOrEmpty(name))
{
name = s_defaultCollectionPropertyName;
}
else
{
ValidatePropertyName(name);
}
Name = name;
Type = type;
_options = options;
Validator = validator;
_converter = converter;
// Use the default validator if none was supplied
if (Validator == null)
{
Validator = s_defaultValidatorInstance;
}
else
{
// Make sure the supplied validator supports the type of this property
if (!Validator.CanValidate(Type))
throw new ConfigurationErrorsException(SR.Format(SR.Validator_does_not_support_prop_type, Name));
}
}
private void ValidatePropertyName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(SR.String_null_or_empty, nameof(name));
if (BaseConfigurationRecord.IsReservedAttributeName(name))
throw new ArgumentException(SR.Format(SR.Property_name_reserved, name));
}
private void SetDefaultValue(object value)
{
// Validate the default value if any. This should make errors from invalid defaults easier to catch
if (ConfigurationElement.IsNullOrNullProperty(value))
return;
if (!Type.IsInstanceOfType(value))
{
if (!Converter.CanConvertFrom(value.GetType()))
throw new ConfigurationErrorsException(SR.Format(SR.Default_value_wrong_type, Name));
value = Converter.ConvertFrom(value);
}
Validate(value);
DefaultValue = value;
}
private void InitDefaultValueFromTypeInfo(
ConfigurationPropertyAttribute configurationProperty,
DefaultValueAttribute defaultValueAttribute)
{
object defaultValue = configurationProperty.DefaultValue;
// If the ConfigurationPropertyAttribute has no default try the DefaultValueAttribute
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
defaultValue = defaultValueAttribute?.Value;
// Convert the default value from string if necessary
if (defaultValue is string && (Type != typeof(string)))
{
try
{
defaultValue = Converter.ConvertFromInvariantString((string)defaultValue);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(SR.Format(SR.Default_value_conversion_error_from_string,
Name, ex.Message));
}
}
// If we still have no default, use string Empty for string or the default for value types
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
{
if (Type == typeof(string))
{
defaultValue = string.Empty;
}
else if (Type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(Type);
}
}
SetDefaultValue(defaultValue);
}
internal object ConvertFromString(string value)
{
object result;
try
{
result = Converter.ConvertFromInvariantString(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(SR.Format(SR.Top_level_conversion_error_from_string, Name,
ex.Message));
}
return result;
}
internal string ConvertToString(object value)
{
try
{
if (Type == typeof(bool))
{
// The boolean converter will break 1.1 compat for bool
return (bool)value ? "true" : "false";
}
else
{
return Converter.ConvertToInvariantString(value);
}
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
SR.Format(SR.Top_level_conversion_error_to_string, Name, ex.Message));
}
}
internal void Validate(object value)
{
try
{
Validator.Validate(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
SR.Format(SR.Top_level_validation_error, Name, ex.Message), ex);
}
}
private void CreateConverter()
{
if (_converter != null) return;
if (Type.IsEnum)
{
// We use our custom converter for all enums
_converter = new GenericEnumConverter(Type);
}
else if (Type.IsSubclassOf(typeof(ConfigurationElement)))
{
// Type converters aren't allowed on ConfigurationElement
// derived classes.
return;
}
else
{
_converter = TypeDescriptor.GetConverter(Type);
if ((_converter == null) ||
!_converter.CanConvertFrom(typeof(string)) ||
!_converter.CanConvertTo(typeof(string)))
{
// Need to be able to convert to/from string
throw new ConfigurationErrorsException(SR.Format(SR.No_converter, Name, Type.Name));
}
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Configuration;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Serialization;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Serialization.Formatters;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Caching;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Common.DataStructures;
namespace Alachisoft.NCache.Util
{
/// <summary>
/// {^[\t, ]*}internal{[a-z, ]*}class{[A-Z,a-z,\,,\:,\t, ]*$}
/// #if DEBUG\n\1public\2class\3\n#else\n\1internal\2class\3\n#endif
/// Utility class to help with common tasks.
/// </summary>
public class SerializationUtil
{
private static ILogger _ncacheLog;
public static ILogger NCacheLog
{
set
{
_ncacheLog = value;
}
}
static Hashtable _attributeOrder = new Hashtable();
static Hashtable _portibilaty = new Hashtable();
static Hashtable _subTypeHandle = new Hashtable();
public static short UserdefinedArrayTypeHandle = 5000;
/// <summary>
/// Serializes the object using CompactSerialization Framwork.
/// </summary>
/// <param name="graph"></param>
/// <returns></returns>
public static object CompactSerialize(object graph, string cacheContext)
{
if (graph != null && graph is ICompactSerializable)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
stream.Write(NCHeader.Version, 0, NCHeader.Length);
CompactBinaryFormatter.Serialize(stream, graph, cacheContext);
return stream.ToArray();
}
return graph;
}
/// <summary>
/// Serializes the object using CompactSerialization Framwork.
/// </summary>
/// <param name="graph"></param>
/// <returns></returns>
public static object CompactSerialize(Stream stream, object graph, string cacheContext)
{
if (graph != null && graph is ICompactSerializable)
{
byte[] buffer;
stream.Position = 0;
stream.Write(NCHeader.Version, 0, NCHeader.Length);
CompactBinaryFormatter.Serialize(stream, graph, cacheContext, false);
buffer = new byte[stream.Position];
stream.Position = 0;
stream.Read(buffer, 0, buffer.Length);
stream.Position = 0;
return buffer;
}
return graph;
}
/// <summary>
/// Deserializes the byte buffer to an object using CompactSerialization Framwork.
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static object CompactDeserialize(object buffer, string cacheContext)
{
object obj = buffer;
if (buffer != null && buffer is byte[])
{
if (HasHCHeader((byte[])buffer))
{
System.IO.MemoryStream stream = new System.IO.MemoryStream((byte[])buffer);
//Skip the NCHeader.
stream.Position += NCHeader.Length;
obj = CompactBinaryFormatter.Deserialize(stream, cacheContext);
return obj;
}
}
return obj;
}
public static object SafeDeserialize(object serializedObject, string serializationContext, BitSet flag)
{
object deserialized = serializedObject;
try
{
if(!flag.IsBitSet(BitSetConstants.BinaryData))
{
byte[] serializedData = null;
if (serializedObject is byte[])
{
serializedData = (byte[])serializedObject;
}
else if (serializedObject is UserBinaryObject)
{
serializedData = ((UserBinaryObject)serializedObject).GetFullObject();
}
deserialized = CompactBinaryFormatter.FromByteBuffer(serializedData, serializationContext);
}
}
catch (Exception ex)
{
_ncacheLog.Error(ex.ToString());
//Kill the exception; it is possible that object was serialized by Java
//or from any other domain which can not be deserialized by us.
deserialized = serializedObject;
}
return deserialized;
}
public static object SafeSerialize(object serializableObject, SerializationFormat serializer, string serializationContext, ref BitSet flag)
{
if (serializableObject != null)
{
if (serializableObject is byte[])
{
flag.SetBit(BitSetConstants.BinaryData);
return serializableObject;
}
serializableObject = CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext);
}
return serializableObject;
}
/// <summary>
/// Deserializes the byte buffer to an object using CompactSerialization Framwork.
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static object CompactDeserialize(Stream stream, object buffer, string cacheContext)
{
object obj = buffer;
if (buffer != null && buffer is byte[])
{
if (HasHCHeader((byte[])buffer))
{
byte[] tmp = (byte[])buffer;
stream.Position = 0;
stream.Write(tmp, 0, tmp.Length);
stream.Position = 0;
//Skip the NCHeader.
stream.Position += NCHeader.Length;
obj = CompactBinaryFormatter.Deserialize(stream, cacheContext, false);
stream.Position = 0;
return obj;
}
}
return obj;
}
/// <summary>
/// CompactBinarySerialize which takes object abd return byte array
/// </summary>
/// <param name="serializableObject"></param>
/// <param name="serializationContext"></param>
/// <returns></returns>
public static byte[] CompactBinarySerialize(object serializableObject, string serializationContext)
{
return CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext);
}
/// <summary>
/// convert bytes into object
/// </summary>
/// <param name="buffer"></param>
/// <param name="serializationContext"></param>
/// <returns></returns>
public static object CompactBinaryDeserialize(byte[] buffer, string serializationContext)
{
return CompactBinaryFormatter.FromByteBuffer(buffer, serializationContext);
}
/// <summary>
/// Checks whtether the given buffer has NCHeader attached or not.
/// </summary>
/// <param name="serializedBuffer"></param>
/// <returns></returns>
internal static bool HasHCHeader(byte[] serializedBuffer)
{
byte[] header = new byte[5];
if (serializedBuffer.Length >= NCHeader.Length)
{
for (int i = 0; i < NCHeader.Length; i++)
{
header[i] = serializedBuffer[i];
}
return NCHeader.CompareTo(header);
}
return false;
}
/// <summary>
/// Called recursively and iterates through the string at every '_dictionary' occurance until the string ends
/// </summary>
/// <param name="protocolString">String sent by the server</param>
/// <param name="startIndex">start of string</param>
/// <param name="endIndex">sent by the server</param>
/// <returns>complete hashmap as stored in config read by service</returns>
public static Hashtable GetTypeMapFromProtocolString(string protocolString, ref int startIndex, ref int endIndex)
{
endIndex = protocolString.IndexOf('"', startIndex + 1);
Hashtable tbl = new Hashtable(new EqualityComparer());
string token = protocolString.Substring(startIndex, (endIndex) - (startIndex));
if (token == "__dictionary")
{
startIndex = endIndex + 1;
endIndex = protocolString.IndexOf('"', endIndex + 1);
int dicCount = Convert.ToInt32(protocolString.Substring(startIndex, (endIndex) - (startIndex)));
for (int i = 0; i < dicCount; i++)
{
startIndex = endIndex + 1;
endIndex = protocolString.IndexOf('"', endIndex + 1);
string key = protocolString.Substring(startIndex, (endIndex) - (startIndex));
startIndex = endIndex + 1;
endIndex = protocolString.IndexOf('"', endIndex + 1);
string value = protocolString.Substring(startIndex, (endIndex) - (startIndex));
if (value == "__dictionary")
{
tbl[key] = GetTypeMapFromProtocolString(protocolString, ref startIndex, ref endIndex);
}
else
{
tbl[key] = value;
}
}
}
return tbl;
}
public static string GetProtocolStringFromTypeMap(Hashtable typeMap)
{
System.Collections.Stack st = new Stack();
StringBuilder protocolString = new StringBuilder();
protocolString.Append("__dictionary").Append("\"");
protocolString.Append(typeMap.Count).Append("\"");
IDictionaryEnumerator mapDic = typeMap.GetEnumerator();
while (mapDic.MoveNext())
{
if (mapDic.Value is Hashtable)
{
st.Push(mapDic.Value);
st.Push(mapDic.Key);
}
else
{
protocolString.Append(mapDic.Key).Append("\"");
protocolString.Append(mapDic.Value).Append("\"");
}
}
while (st.Count != 0 && st.Count % 2 == 0)
{
protocolString.Append(st.Pop() as string).Append("\"");
protocolString.Append(GetProtocolStringFromTypeMap(st.Pop() as Hashtable));
}
return protocolString.ToString();
}
//Helper method to convert Attrib object to NonComapactField
private static Hashtable GetNonCompactFields(Hashtable nonCompactAttributes)
{
Hashtable nonCompactFieldsTable = new Hashtable();
IDictionaryEnumerator nonCompactIDE= nonCompactAttributes.GetEnumerator();
while (nonCompactIDE.MoveNext())
{
NonCompactField tempNonCompactField = new NonCompactField();
Hashtable tempAttrib = (Hashtable)nonCompactIDE.Value;
tempNonCompactField.ID = (string)tempAttrib["id"];
tempNonCompactField.Name = (string)tempAttrib["name"];
tempNonCompactField.Type = (string)tempAttrib["type"];
nonCompactFieldsTable.Add(tempNonCompactField.ID,tempNonCompactField);
}
return nonCompactFieldsTable;
}
public static Hashtable CheckNonCompactAttrib(Type type, Hashtable compactTypes)
{
string typeName = type.FullName;
IEnumerator ieOuter = compactTypes.GetEnumerator();
while (ieOuter.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry)ieOuter.Current;
Hashtable hshTable = (Hashtable)entry.Value;
if (hshTable.Contains(typeName))
{
Hashtable hshTypeInfo = (Hashtable)hshTable[typeName];
if (hshTypeInfo.Contains("non-compact-fields"))
return (Hashtable)hshTypeInfo["non-compact-fields"];
}
}
return null;
}
/// <summary>
/// Gets the type, handle info and non-compact fields for the gives types.
/// </summary>
/// <param name="typeInfo"></param>
/// <returns></returns>
public static Hashtable GetCompactTypes(Hashtable portableTypesInfo, bool throwExceptions, string cacheContext)
{
string typeName = "";
short typeHandle = 0;
Assembly asm = null;
Hashtable framework = new Hashtable(new EqualityComparer());
Hashtable typeTable = new Hashtable(new EqualityComparer());
Hashtable porabilaty = new Hashtable(new EqualityComparer());
Hashtable genericInnerClasses = null;
IDictionaryEnumerator ide = portableTypesInfo.GetEnumerator();
while (ide.MoveNext())
{
genericInnerClasses = null;
string assembly = null;
Hashtable portableTypes = (Hashtable)ide.Value;
IDictionaryEnumerator ide4 = portableTypes.GetEnumerator();
while (ide4.MoveNext())
{
Hashtable typeInfo = (Hashtable)ide4.Value;
if (typeInfo.Contains("name") && typeInfo["type"].ToString().Equals("net"))
{
#region [For Generics]
if (typeInfo.Contains("arg-types"))
{
Hashtable nestedGenerics = new Hashtable(new EqualityComparer());
genericInnerClasses = (Hashtable)typeInfo["arg-types"];
Hashtable ht6 = GetGenericComapctTypes(genericInnerClasses, typeInfo, throwExceptions, cacheContext, ref nestedGenerics);
IDictionaryEnumerator ide55 = ht6.GetEnumerator();
while (ide55.MoveNext())
{
try
{
Type nestedType = (Type)ide55.Key;
if (!framework.ContainsKey(nestedType))
{
Hashtable _handleNonCompactFields = new Hashtable(new EqualityComparer());
_handleNonCompactFields.Add("handle", ide55.Value);
if (typeInfo.Contains("non-compact-fields"))
_handleNonCompactFields.Add("non-compact-fields", GetNonCompactFields(typeInfo["non-compact-fields"] as Hashtable));
framework.Add(nestedType,_handleNonCompactFields);
}
}
catch (Exception ex)
{
if (throwExceptions)
throw new Exception("Class Name : " + typeInfo["name"].ToString() + " and Class Id : " + typeInfo["id"].ToString() + "\n" + "ide55.Key" + ide55.Key.ToString());
}
}
IDictionaryEnumerator ide15 = nestedGenerics.GetEnumerator();
while (ide15.MoveNext())
{
try
{
Type nestedConcreteType = (Type)ide15.Key;
if (!framework.ContainsKey(nestedConcreteType))
{
Hashtable _handleNonCompactFields = new Hashtable(new EqualityComparer());
_handleNonCompactFields.Add("handle", ide15.Value);
Hashtable nonCompactAttrib = CheckNonCompactAttrib(nestedConcreteType, portableTypesInfo);
if (nonCompactAttrib!=null)
{
_handleNonCompactFields.Add("non-compact-fields", GetNonCompactFields(nonCompactAttrib));
}
framework.Add(nestedConcreteType, _handleNonCompactFields);
}
}
catch (Exception ex)
{
if (throwExceptions)
throw new Exception("Class Name : " + typeInfo["name"].ToString() + " and Class Id : " + typeInfo["id"].ToString() + "\n" + "ide55.Key" + ide15.Key.ToString());
}
}
nestedGenerics.Clear();
continue;
}
else if (typeInfo.Contains("is-generic") && typeInfo["is-generic"].ToString() == "True")
continue;
#endregion
try
{
assembly = (string)typeInfo["assembly"];
if (assembly != null && assembly.StartsWith("System, "))
{
Type currentType = typeof(SortedDictionary<,>);
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else if (assembly != null && assembly.StartsWith("mscorlib, "))
{
string str = string.Empty;
Type currentType = str.GetType();
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else
asm = Assembly.Load(assembly);
if (asm.FullName != assembly)
throw new Exception("Loaded assembly version is different from the registered version");
}
catch (Exception e)
{
if (throwExceptions && !(e is FileNotFoundException || e is TypeLoadException))
throw new CompactSerializationException(e.Message + "\n GetCompactTypes(" + e.GetType().ToString() + "):" + (string)typeInfo["name"]);
else
{
if (_ncacheLog != null)
_ncacheLog.Error("SerializationUtil.GetCompactTypes", e.Message);
}
continue;
}
}
else
continue;
Type type = null;
if (typeInfo.Contains("name"))
{
typeHandle = Convert.ToInt16((String)ide.Key);
typeName = (string)typeInfo["name"];
bool portable = false;
try
{
portable = Convert.ToBoolean(typeInfo["portable"]);
}
catch (Exception)
{
portable = false;
}
//remove Version number attached
if (portable)
{
string[] typeNameArray = typeName.Split(':');
typeName = typeNameArray[0];
for (int i = 1; i < typeNameArray.Length - 1; i++)
{
typeName += "." + typeNameArray[i];
}
}
try
{
type = null;
type = asm.GetType(typeName);
}
catch (Exception e)
{
type = null;
if (throwExceptions)
throw new CompactSerializationException(e.Message);
}
if (type != null)
{
if (!framework.Contains(type))
{
Hashtable handleNonCompactFields = new Hashtable(new EqualityComparer());
handleNonCompactFields.Add("handle", typeHandle);
if (typeInfo.Contains("non-compact-fields"))
handleNonCompactFields.Add("non-compact-fields", GetNonCompactFields(typeInfo["non-compact-fields"] as Hashtable));
framework.Add(type, handleNonCompactFields);
}
}
else
{
if (throwExceptions)
throw new Exception(typeName + " can not be registered with compact framework");
continue;
}
Hashtable attributeOrder = (Hashtable)typeInfo["attribute"];
Hashtable attributeUnion = null;
Hashtable[] orderedUnion = null;
if (portable)
{
attributeUnion = (Hashtable)portableTypes["Alachisoft.NCache.AttributeUnion"];
orderedUnion = new Hashtable[((Hashtable)(attributeUnion["attribute"])).Count];
//Order AttributeUnion with orderNumber
if (attributeUnion != null && attributeUnion["attribute"] != null)
{
IDictionaryEnumerator union = ((Hashtable)attributeUnion["attribute"]).GetEnumerator();
while (union.MoveNext())
{
Hashtable attribute = (Hashtable)union.Value;
orderedUnion[Convert.ToInt32(attribute["order"]) - 1] = (Hashtable)attribute;
}
}
}
#region New Ordering
// Order of 0 means skip, -1 means it comes after EOF
if (attributeOrder != null && attributeOrder.Count > 0 && portable)
{
string[][] temp = new string[2][];
//Attribute Name
temp[0] = new string[orderedUnion.Length];
//Order Number
temp[1] = new string[orderedUnion.Length];
//Create a List of attributes of a class
Hashtable[] attributearray = new Hashtable[attributeOrder.Values.Count];
attributeOrder.Values.CopyTo(attributearray, 0);
ArrayList attributeList = new ArrayList();
attributeList.AddRange(attributearray);
int count = 0;
Hashtable toRemove = null;
while (count < orderedUnion.Length)
{
string attrib = (string)((Hashtable)orderedUnion[count])["order"];
//Serach for mapped-to in attributeList
foreach (Hashtable attribute in attributeList)
{
if ((attrib) == (string)attribute["order"])
{
temp[0][count] = (string)attribute["name"];
temp[1][count] = Convert.ToString(count + 1);
toRemove = attribute;
break;
}
}
if (toRemove != null)
{
attributeList.Remove(toRemove);
toRemove = null;
}
if (temp[0][count] == null)
{
temp[0][count] = "skip.attribute";
temp[1][count] = "0";
}
count++;
}
//Add in all thats left of attributeList as after EOF
if (attributeList != null && attributeList.Count > 0)
{
string[][] temporary = new string[2][];
temporary = (string[][])temp.Clone();
temp[0] = new string[((Hashtable)attributeUnion["attribute"]).Count + attributeList.Count];
temp[1] = new string[((Hashtable)attributeUnion["attribute"]).Count + attributeList.Count];
for (int i = 0; i < temporary[0].Length; i++)
{
temp[0][i] = temporary[0][i];
temp[1][i] = temporary[1][i];
}
for (int i = temporary[0].Length; i < temporary[0].Length + attributeList.Count; i++)
{
temp[0][i] = (string)((Hashtable)(attributeList[i - temporary[0].Length]))["name"];
temp[1][i] = "-1";
}
}
if (CheckAlreadyRegistered(portable, cacheContext, (string)ide.Key, type, typeName))
continue;
typeTable.Add(typeName, temp);
_attributeOrder[cacheContext] = typeTable;
if (!porabilaty.Contains(Convert.ToInt16(ide.Key)))
{
porabilaty.Add(Convert.ToInt16(ide.Key), portable);
_portibilaty[cacheContext] = porabilaty;
}
PopulateSubHandle(portable, cacheContext, (string)ide.Key, (string)typeInfo["handle-id"], type);
}
else
{
if (CheckAlreadyRegistered(portable, cacheContext, (string)ide.Key, type, typeName))
continue;
typeTable.Add(typeName, null);
_attributeOrder[cacheContext] = typeTable;
if (!porabilaty.Contains(Convert.ToInt16(ide.Key)))
{
porabilaty.Add(Convert.ToInt16(ide.Key), portable);
_portibilaty[cacheContext] = porabilaty;
}
PopulateSubHandle(portable, cacheContext, (string)ide.Key, (string)typeInfo["handle-id"], type);
}
#endregion
}
}
}
// framework Contains all Types registered to cache and its typeHandle as shown by config
return framework;
}
private static Hashtable GetGenericComapctTypes(Hashtable genericInnerClasses, Hashtable typeInfo, bool throwExceptions, string cacheContext, ref Hashtable nestedGenerics)
{
if (genericInnerClasses != null)
{
Hashtable htGenTypes = new Hashtable(new EqualityComparer());
bool isNotAsseblyFound = false;
IDictionaryEnumerator ide11 = genericInnerClasses.GetEnumerator();
while (ide11.MoveNext())
{
Hashtable retNestedTypes = GetNestedGenericCompactTypes((Hashtable)ide11.Value, throwExceptions, cacheContext, ref nestedGenerics);
int argTypeNo = htGenTypes.Count + 1;
if (retNestedTypes.Count > 0)
{
Hashtable[] htArr = new Hashtable[retNestedTypes.Count];
for (int i = 0; i < retNestedTypes.Count; i++)
{
htArr[i] = new Hashtable(new EqualityComparer());
}
retNestedTypes.Values.CopyTo(htArr, 0);
Hashtable htArgType = null;
if (retNestedTypes.Count > 1)
{
htArgType = htArr[0];
for (int i = 1; i < htArr.Length; i++)
{
htArgType = GetArgumentTypesCombination(htArgType, htArr[i], i - 1, argTypeNo);
}
IDictionaryEnumerator ide99 = htArgType.GetEnumerator();
while (ide99.MoveNext())
{
htGenTypes.Add((string)ide99.Key, (System.Collections.Queue)ide99.Value);
}
}
else
{
htArgType = htArr[0];
IDictionaryEnumerator ide12 = htArgType.GetEnumerator();
while (ide12.MoveNext())
{
System.Collections.Queue q = new System.Collections.Queue();
q.Enqueue(new TypeHandlePair((Type)ide12.Key, (short)ide12.Value));
htGenTypes.Add(argTypeNo.ToString(), q);
argTypeNo++;
}
}
}
}
genericInnerClasses = htGenTypes;
Assembly asm = null;
string exceptionMsg = null;
try
{
string assembly = (string)typeInfo["assembly"];
if (assembly != null && assembly.StartsWith("System, "))
{
Type currentType = typeof(System.Collections.Generic.SortedDictionary<,>);
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else if (assembly != null && assembly.StartsWith("mscorlib, "))
{
string str = String.Empty;
Type currentType = str.GetType();
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else
asm = Assembly.Load(assembly);
if (asm.FullName != assembly)
throw new Exception("Loaded assembly version is different from the registered version");
}
catch (Exception e)
{
if (throwExceptions && !(e is FileNotFoundException || e is TypeLoadException))
throw new CompactSerializationException(e.Message + "\n GetCompactTypes(" + e.GetType().ToString() + "):" + (string)typeInfo["name"]);
else
{
if (_ncacheLog != null)
_ncacheLog.Error("SerializationUtil.GetCompactTypes", e.Message);
isNotAsseblyFound = true;
exceptionMsg = e.ToString();
}
}
Type type = null;
short typeHandle;
string typeName = "";
if (typeInfo.Contains("name"))
{
string str = typeInfo["id"].ToString();
typeHandle = Convert.ToInt16(str);
typeName = (string)typeInfo["name"];
try
{
if(asm!=null)
type = asm.GetType(typeName);
}
catch (Exception e)
{
type = null;
if (throwExceptions)
throw new CompactSerializationException(e.Message);
}
if (type != null)
{
if (!typeInfo.Contains("arg-types") && !genericInnerClasses.Contains(type))
genericInnerClasses.Add(type, typeHandle);
else if (typeInfo.Contains("arg-types")) //in case of generics
{
genericInnerClasses = AdjustGenericTypes(type, genericInnerClasses, typeHandle, ref nestedGenerics, throwExceptions);
}
}
else
{
if(isNotAsseblyFound)
if (_ncacheLog != null)
_ncacheLog.Error("SerializationUtil.GetCompactTypes", exceptionMsg);
isNotAsseblyFound = false;
}
}
}
return genericInnerClasses;
}
public static Hashtable GetNestedGenericCompactTypes(Hashtable portableTypesInfo, bool throwExceptions, string cacheContext, ref Hashtable nestedGenerics)
{
string typeName = "";
short typeHandle = 0;
Assembly asm = null;
Hashtable framework = new Hashtable(new EqualityComparer());
Hashtable genericInnerClasses = null;
IDictionaryEnumerator ide = portableTypesInfo.GetEnumerator();
while (ide.MoveNext())
{
genericInnerClasses = null;
string assembly = null;
Hashtable portableTypes = (Hashtable)ide.Value;
IDictionaryEnumerator ide4 = portableTypes.GetEnumerator();
while (ide4.MoveNext())
{
Hashtable typeInfo = (Hashtable)ide4.Value;
if (typeInfo.Contains("name") && typeInfo["type"].ToString().Equals("net"))
{
if (typeInfo.Contains("arg-types"))
{
genericInnerClasses = (Hashtable)typeInfo["arg-types"];
if (genericInnerClasses != null)
{
Hashtable htGenTypes = new Hashtable(new EqualityComparer());
IDictionaryEnumerator ide11 = genericInnerClasses.GetEnumerator();
while (ide11.MoveNext())
{
Hashtable retNestedTypes = GetNestedGenericCompactTypes((Hashtable)ide11.Value, throwExceptions, cacheContext, ref nestedGenerics);
int argTypeNo = htGenTypes.Count + 1;
if (retNestedTypes.Count > 0)
{
Hashtable[] htArr = new Hashtable[retNestedTypes.Count];
for (int i = 0; i < retNestedTypes.Count; i++)
{
htArr[i] = new Hashtable(new EqualityComparer());
}
retNestedTypes.Values.CopyTo(htArr, 0);
Hashtable htArgType = null;
if (retNestedTypes.Count > 1)
{
htArgType = htArr[0];
for (int i = 1; i < htArr.Length; i++)
{
htArgType = GetArgumentTypesCombination(htArgType, htArr[i], i - 1, argTypeNo);
}
IDictionaryEnumerator ide99 = htArgType.GetEnumerator();
while (ide99.MoveNext())
{
htGenTypes.Add((string)ide99.Key, (System.Collections.Queue)ide99.Value);
}
}
else
{
htArgType = htArr[0];
IDictionaryEnumerator ide12 = htArgType.GetEnumerator();
while (ide12.MoveNext())
{
System.Collections.Queue q = new System.Collections.Queue();
q.Enqueue(new TypeHandlePair((Type)ide12.Key, (short)ide12.Value));
htGenTypes.Add(argTypeNo.ToString(), q);
argTypeNo++;
}
}
}
}
genericInnerClasses = htGenTypes;
}
}
try
{
assembly = (string)typeInfo["assembly"];
if (assembly != null && assembly.StartsWith("System, "))
{
Type currentType = typeof(System.Collections.Generic.SortedDictionary<,>);
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else if (assembly != null && assembly.StartsWith("mscorlib, "))
{
string str = String.Empty;
Type currentType = str.GetType();
assembly = currentType.Assembly.FullName;
asm = currentType.Assembly;
}
else
asm = Assembly.Load(assembly);
if (asm.FullName != assembly)
throw new Exception("Loaded assembly version is different from the registered version");
}
catch (Exception e)
{
if (throwExceptions && !(e is FileNotFoundException || e is TypeLoadException))
throw new CompactSerializationException(e.Message + "\n GetCompactTypes(" + e.GetType().ToString() + "):" + (string)typeInfo["name"]);
else
{
if(_ncacheLog != null)
_ncacheLog.Error("SerializationUtil.GetCompactTypes", e.Message);
}
continue;
}
}
else
continue;
Type type = null;
if (typeInfo.Contains("name"))
{
typeHandle = Convert.ToInt16((String)ide.Key);
typeName = (string)typeInfo["name"];
try
{
type = null;
type = asm.GetType(typeName);
}
catch (Exception e)
{
type = null;
if (throwExceptions)
throw new CompactSerializationException(e.Message);
}
if (type != null)
{
if (!typeInfo.Contains("arg-types") && !framework.Contains(type))
{
Hashtable ht = new Hashtable(new EqualityComparer());
ht.Add(type, typeHandle);
int argNum = framework.Count + 1;
framework.Add(argNum.ToString(), ht);
}
else if (typeInfo.Contains("arg-types")) //in case of generics
{
Hashtable resultantGenerics = AdjustGenericTypes(type, genericInnerClasses, typeHandle, ref nestedGenerics, throwExceptions);
int argNum = framework.Count + 1;
framework.Add(argNum.ToString(), resultantGenerics);
}
}
else
{
if (throwExceptions)
throw new Exception(typeName + " can not be registered with compact framework");
continue;
}
}
}
}
return framework;
}
private static Hashtable GetArgumentTypesCombination(Hashtable htArgType1, Hashtable htArgType2, int indx, int argTypeNo)
{
Hashtable htAll = new Hashtable(new EqualityComparer());
if (indx != 0)
{
IDictionaryEnumerator ide3 = htArgType2.GetEnumerator();
while (ide3.MoveNext())
{
IDictionaryEnumerator ide2 = htArgType1.GetEnumerator();
while (ide2.MoveNext())
{
System.Collections.Queue q = (System.Collections.Queue)((System.Collections.Queue)ide2.Value).Clone();
q.Enqueue(new TypeHandlePair((Type)ide3.Key, (short)ide3.Value));
htAll.Add(argTypeNo.ToString(), q);
argTypeNo++;
}
}
}
else
{
IDictionaryEnumerator ide = htArgType1.GetEnumerator();
while (ide.MoveNext())
{
IDictionaryEnumerator ide2 = htArgType2.GetEnumerator();
while (ide2.MoveNext())
{
Hashtable ht3 = new Hashtable(new EqualityComparer());
System.Collections.Queue q = new System.Collections.Queue();
q.Enqueue(new TypeHandlePair((Type)ide.Key, (short)ide.Value));
q.Enqueue(new TypeHandlePair((Type)ide2.Key, (short)ide2.Value));
htAll.Add(argTypeNo.ToString(), q);
argTypeNo++;
}
}
}
return htAll;
}
public struct TypeHandlePair
{
public Type _type;
public short _handle;
public TypeHandlePair(Type type, short handle)
{
this._type = type;
this._handle = handle;
}
}
private static Hashtable AdjustGenericTypes(Type genericType, Hashtable genInnerTypes, short genTypeHandle, ref Hashtable nestedGenerics, bool throwExceptions)
{
Hashtable genNestedTypes = new Hashtable(new EqualityComparer());
if (genInnerTypes != null)
{
IDictionaryEnumerator ide1 = genInnerTypes.GetEnumerator();
while (ide1.MoveNext())
{
System.Collections.Queue genConcreteTypes = (System.Collections.Queue)ide1.Value;
IEnumerator ide = genConcreteTypes.GetEnumerator();
int genArgsCount = genericType.GetGenericArguments().Length;
Type[] parms = new Type[genArgsCount];
SortedList sortedTypes = new SortedList(genArgsCount);
int index = 0;
short typeHandle = 0;
while (ide.MoveNext())
{
TypeHandlePair thp = (TypeHandlePair)ide.Current;
if (!genNestedTypes.Contains((Type)thp._type) && CheckForBuiltinSurrogate((Type)thp._type))
{
if (!nestedGenerics.Contains((Type)thp._type))
nestedGenerics.Add((Type)thp._type, (short)thp._handle);
}
if (typeof(Dictionary<,>) == genericType && index == 0)
{
Type typ = typeof(Dictionary<,>);
if (!nestedGenerics.Contains(typ))
nestedGenerics.Add(typ, genTypeHandle);
}
if (typeof(List<>).Equals(genericType) && index == 0)
{
Type typ = typeof(List<>);
if (!nestedGenerics.Contains(typ))
nestedGenerics.Add(typ, genTypeHandle);
}
if (index == 0 || ((Type)thp._type).IsGenericType)
{
typeHandle = (short)((short)thp._handle - 1);
index++;
}
sortedTypes.Add((short)thp._handle, (Type)thp._type);
}
for (int indx = 0; indx < sortedTypes.Count; indx++)
{
if (indx < parms.Length)
parms[indx] = (Type)sortedTypes.GetByIndex(indx);
}
Type genType = null;
try
{
genType = genericType.MakeGenericType(parms);
}
catch (Exception ex)
{
if (throwExceptions)
{
string data = "param count : " + parms.Length.ToString() + "\n\n";
for (int i = 0; i < parms.Length; i++)
{
data += " FullName Arg " + i + " : " + ((Type)parms[i]).FullName;
data += " Name Arg " + i + " : " + ((Type)parms[i]).Name + "\n";
}
throw new Exception(genericType.FullName + " can not be registered with compact framework ( ex.Message : " + ex.Message + " ) ex.Tostring() : " + ex.ToString() + "Data:" + data);
}
}
if ( genType != null && !genNestedTypes.Contains(genType))
{
typeHandle = GetUniqueHandle(genNestedTypes, nestedGenerics, sortedTypes);
genNestedTypes.Add(genType, typeHandle);
}
}
}
return genNestedTypes;
}
private static short GetUniqueHandle(Hashtable genNestedTypes, Hashtable concreteNested, SortedList sortedTypes)
{
short handle = 5000;
bool uniqueHandle = true;
IDictionaryEnumerator ideArgTypes = sortedTypes.GetEnumerator();
while (ideArgTypes.MoveNext())
{
uniqueHandle = true;
handle = (short)((short)ideArgTypes.Key - 1);
IDictionaryEnumerator ideGeneric = genNestedTypes.GetEnumerator();
while (ideGeneric.MoveNext())
{
if ((short)ideGeneric.Value == handle)
{
uniqueHandle = false;
break;
}
}
IDictionaryEnumerator ideConcrete = concreteNested.GetEnumerator();
while (ideConcrete.MoveNext())
{
if ((short)ideConcrete.Value == handle)
{
uniqueHandle = false;
break;
}
}
if (uniqueHandle)
break;
}
return handle;
}
private static bool CheckForBuiltinSurrogate(Type type)
{
if (!type.IsPrimitive && type != typeof(DateTime) && type != typeof(DateTime[]) && type != typeof(ArrayList) && type != typeof(ArrayList[]) && type != typeof(Hashtable) && type != typeof(Hashtable[]) && type != typeof(String) && type != typeof(String[])
&& type != typeof(Byte[]) && type != typeof(SByte[]) && type != typeof(Char[]) && type != typeof(Boolean[]) && type != typeof(Int16[]) && type != typeof(Int32[]) && type != typeof(Int64[]) && type != typeof(Single[]) && type != typeof(Double[])
&& type != typeof(Decimal) && type != typeof(Decimal[]) && type != typeof(UInt16[]) && type != typeof(UInt32[]) && type != typeof(UInt64[]) && type != typeof(Guid) && type != typeof(Guid[]) && type != typeof(TimeSpan) && type != typeof(TimeSpan[]))
return true;
return false;
}
private static bool IsDotnetBuiltinType(string typeName)
{
bool isBuiltinType = false;
try
{
Type type = Type.GetType(typeName);
if (type.IsPrimitive)
isBuiltinType = true;
else
{
switch (type.FullName)
{
case "System.DateTime":
isBuiltinType = true;
break;
case "System.DateTime[]":
isBuiltinType = true;
break;
case "System.Collections.ArrayList":
isBuiltinType = true;
break;
case "System.Collections.ArrayList[]":
isBuiltinType = true;
break;
case "System.Collections.Hashtable":
isBuiltinType = true;
break;
case "System.Collections.Hashtable[]":
isBuiltinType = true;
break;
case "System.String":
isBuiltinType = true;
break;
case "System.String[]":
isBuiltinType = true;
break;
case "System.Collections.Generic.List`1":
isBuiltinType = true;
break;
case "System.Collections.Generic.Dictionary`2":
isBuiltinType = true;
break;
}
}
}
catch (Exception)
{ }
return isBuiltinType;
}
private static bool CheckAlreadyRegistered(bool portable, string cacheContext, string handle, Type type, string typeName)
{
if (portable)
{
if (_subTypeHandle.Contains(cacheContext))
if (((Hashtable)_subTypeHandle[cacheContext]).Contains(handle))
if (((Hashtable)((Hashtable)_subTypeHandle[cacheContext])[handle]).Contains(type))
return true;
}
else
{
if (_attributeOrder.Contains(cacheContext))
if (((Hashtable)_attributeOrder[cacheContext]).Contains(typeName))
return true;
}
return false;
}
public static void PopulateSubHandle(bool portable, string cacheContext, string handle, string subHandle, Type type)
{
if (portable)
{
if (!_subTypeHandle.Contains(cacheContext))
_subTypeHandle[cacheContext] = new Hashtable();
if (!((Hashtable)_subTypeHandle[cacheContext]).Contains(handle))
((Hashtable)_subTypeHandle[cacheContext]).Add(handle, new Hashtable(new EqualityComparer()));
if (!((Hashtable)((Hashtable)_subTypeHandle[cacheContext])[handle]).Contains(type))
((Hashtable)((Hashtable)_subTypeHandle[cacheContext])[handle]).Add(type, subHandle);
else
throw new ArgumentException("Sub-Handle '" + subHandle + "' already present in " + cacheContext + " in class " + type.Name + " with Handle " + handle);
}
}
/// <summary>
/// Retruns back all registered Types w.r.t a cache, is only called at cache initialization
/// </summary>
/// <param name="cacheContext">Cache Name</param>
/// <returns>Retruns back all registered Types w.r.t a cache</returns>
public static Hashtable GetAttributeOrder(string cacheContext)
{
return (Hashtable)_attributeOrder[cacheContext];
}
public static bool GetPortibilaty(short handle, string cacheContext)
{
if (_portibilaty != null && _portibilaty.Contains(cacheContext) && ((Hashtable)_portibilaty[cacheContext]).Contains(handle))
return (bool)((Hashtable)_portibilaty[cacheContext])[handle];
else
return false;
}
public static short GetSubTypeHandle(string cacheContext, string handle, Type type)
{
if (_subTypeHandle == null)
return 0;
if (!(((Hashtable)_subTypeHandle).Contains(cacheContext)))
return 0;
if (!(((Hashtable)_subTypeHandle[cacheContext]).Contains(handle)))
return 0;
return Convert.ToInt16((string)((Hashtable)((Hashtable)_subTypeHandle[cacheContext])[handle])[type]);
}
internal static void CompactSerialize(CacheEntry entry, string cacheContext, bool compressionEnable, long compressionThreshold)
{
throw new NotImplementedException();
}
public static object SafeSerializeInProc(object serializableObject, string serializationContext, ref BitSet flag, SerializationFormat serializationFormat, ref long size, UserObjectType userObjectType, bool seralize ,bool isCustomAttributeBaseSerialzed = false)
{
if (seralize)
return SafeSerializeOutProc(serializableObject, serializationContext, ref flag, seralize, serializationFormat, ref size, userObjectType, isCustomAttributeBaseSerialzed);
object serializableObjectUnser = serializableObject;
if (size <= 0)
{
Type type = serializableObject.GetType();
if (typeof(byte[]).Equals(type) && flag != null)
{
flag.SetBit(BitSetConstants.BinaryData);
size = serializableObject is byte[] ? ((byte[])serializableObject).Length : 0;
return serializableObject;
}
serializableObject = CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext);
size = serializableObject is byte[] ? ((byte[])serializableObject).Length : 0;
}
return serializableObjectUnser;
}
public static object SafeSerializeOutProc(object serializableObject, string serializationContext, ref BitSet flag, bool isSerializationEnabled, SerializationFormat serializationFormat, ref long size, UserObjectType userObjectType, bool isCustomAttributeBaseSerialzed = false)
{
if (serializableObject != null && isSerializationEnabled)
{
Type type = serializableObject.GetType();
if (typeof(byte[]).Equals(type) && flag != null)
{
flag.SetBit(BitSetConstants.BinaryData);
size = serializableObject is byte[] ? ((byte[])serializableObject).Length : 0;
return serializableObject;
}
serializableObject = CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext);
size = serializableObject is byte[] ? ((byte[])serializableObject).Length : 0;
}
return serializableObject;
}
public static T SafeDeserializeInProc<T>(object serializedObject, string serializationContext, BitSet flag, UserObjectType userObjectType, bool serailze)
{
if (serailze)
return SafeDeserializeOutProc<T>(serializedObject, serializationContext, flag, serailze, userObjectType);
return (T)serializedObject;
}
public static T SafeDeserializeOutProc<T>(object serializedObject, string serializationContext, BitSet flag, bool isSerializationEnabled, UserObjectType userObjectType)
{
object deserialized = serializedObject;
if (serializedObject is byte[] && isSerializationEnabled)
{
if (flag != null && flag.IsBitSet(BitSetConstants.BinaryData))
{
return (T)serializedObject;
}
deserialized = CompactBinaryFormatter.FromByteBuffer((byte[])serializedObject, serializationContext);
}
return (T)deserialized;
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using dnlib.Threading;
using dnlib.IO;
#if THREAD_SAFE
using ThreadSafe = dnlib.Threading.Collections;
#else
using ThreadSafe = System.Collections.Generic;
#endif
namespace dnlib.DotNet {
/// <summary>
/// A custom attribute
/// </summary>
public sealed class CustomAttribute : ICustomAttribute {
ICustomAttributeType ctor;
byte[] rawData;
readonly ThreadSafe.IList<CAArgument> arguments;
readonly ThreadSafe.IList<CANamedArgument> namedArguments;
IBinaryReader blobReader;
/// <summary>
/// Gets/sets the custom attribute constructor
/// </summary>
public ICustomAttributeType Constructor {
get { return ctor; }
set { ctor = value; }
}
/// <summary>
/// Gets the attribute type
/// </summary>
public ITypeDefOrRef AttributeType {
get {
var cat = ctor;
return cat == null ? null : cat.DeclaringType;
}
}
/// <summary>
/// Gets the full name of the attribute type
/// </summary>
public string TypeFullName {
get {
var mrCtor = ctor as MemberRef;
if (mrCtor != null)
return mrCtor.GetDeclaringTypeFullName() ?? string.Empty;
var mdCtor = ctor as MethodDef;
if (mdCtor != null) {
var declType = mdCtor.DeclaringType;
if (declType != null)
return declType.FullName;
}
return string.Empty;
}
}
/// <summary>
/// <c>true</c> if the raw custom attribute blob hasn't been parsed
/// </summary>
public bool IsRawBlob {
get { return rawData != null; }
}
/// <summary>
/// Gets the raw custom attribute blob or <c>null</c> if the CA was successfully parsed.
/// </summary>
public byte[] RawData {
get { return rawData; }
}
/// <summary>
/// Gets all constructor arguments
/// </summary>
public ThreadSafe.IList<CAArgument> ConstructorArguments {
get { return arguments; }
}
/// <summary>
/// <c>true</c> if <see cref="ConstructorArguments"/> is not empty
/// </summary>
public bool HasConstructorArguments {
get { return arguments.Count > 0; }
}
/// <summary>
/// Gets all named arguments (field and property values)
/// </summary>
public ThreadSafe.IList<CANamedArgument> NamedArguments {
get { return namedArguments; }
}
/// <summary>
/// <c>true</c> if <see cref="NamedArguments"/> is not empty
/// </summary>
public bool HasNamedArguments {
get { return namedArguments.Count > 0; }
}
/// <summary>
/// Gets all <see cref="CANamedArgument"/>s that are field arguments
/// </summary>
public IEnumerable<CANamedArgument> Fields {
get {
foreach (var namedArg in namedArguments.GetSafeEnumerable()) {
if (namedArg.IsField)
yield return namedArg;
}
}
}
/// <summary>
/// Gets all <see cref="CANamedArgument"/>s that are property arguments
/// </summary>
public IEnumerable<CANamedArgument> Properties {
get {
foreach (var namedArg in namedArguments.GetSafeEnumerable()) {
if (namedArg.IsProperty)
yield return namedArg;
}
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="rawData">Raw custom attribute blob</param>
public CustomAttribute(ICustomAttributeType ctor, byte[] rawData)
: this(ctor, null, null, null) {
this.rawData = rawData;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
public CustomAttribute(ICustomAttributeType ctor)
: this(ctor, null, null, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="arguments">Constructor arguments or <c>null</c> if none</param>
public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments)
: this(ctor, arguments, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="namedArguments">Named arguments or <c>null</c> if none</param>
public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CANamedArgument> namedArguments)
: this(ctor, null, namedArguments) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="arguments">Constructor arguments or <c>null</c> if none</param>
/// <param name="namedArguments">Named arguments or <c>null</c> if none</param>
public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments, IEnumerable<CANamedArgument> namedArguments)
: this(ctor, arguments, namedArguments, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="arguments">Constructor arguments or <c>null</c> if none</param>
/// <param name="namedArguments">Named arguments or <c>null</c> if none</param>
/// <param name="blobReader">A reader that returns the original custom attribute blob data</param>
public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments, IEnumerable<CANamedArgument> namedArguments, IBinaryReader blobReader) {
this.ctor = ctor;
this.arguments = arguments == null ? ThreadSafeListCreator.Create<CAArgument>() : ThreadSafeListCreator.Create<CAArgument>(arguments);
this.namedArguments = namedArguments == null ? ThreadSafeListCreator.Create<CANamedArgument>() : ThreadSafeListCreator.Create<CANamedArgument>(namedArguments);
this.blobReader = blobReader;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="ctor">Custom attribute constructor</param>
/// <param name="arguments">Constructor arguments. The list is now owned by this instance.</param>
/// <param name="namedArguments">Named arguments. The list is now owned by this instance.</param>
/// <param name="blobReader">A reader that returns the original custom attribute blob data</param>
internal CustomAttribute(ICustomAttributeType ctor, List<CAArgument> arguments, List<CANamedArgument> namedArguments, IBinaryReader blobReader) {
this.ctor = ctor;
this.arguments = arguments == null ? ThreadSafeListCreator.Create<CAArgument>() : ThreadSafeListCreator.MakeThreadSafe(arguments);
this.namedArguments = namedArguments == null ? ThreadSafeListCreator.Create<CANamedArgument>() : ThreadSafeListCreator.MakeThreadSafe(namedArguments);
this.blobReader = blobReader;
}
/// <summary>
/// Gets the field named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of field</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetField(string name) {
return GetNamedArgument(name, true);
}
/// <summary>
/// Gets the field named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of field</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetField(UTF8String name) {
return GetNamedArgument(name, true);
}
/// <summary>
/// Gets the property named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of property</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetProperty(string name) {
return GetNamedArgument(name, false);
}
/// <summary>
/// Gets the property named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of property</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetProperty(UTF8String name) {
return GetNamedArgument(name, false);
}
/// <summary>
/// Gets the property/field named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of property/field</param>
/// <param name="isField"><c>true</c> if it's a field, <c>false</c> if it's a property</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetNamedArgument(string name, bool isField) {
foreach (var namedArg in namedArguments.GetSafeEnumerable()) {
if (namedArg.IsField == isField && UTF8String.ToSystemStringOrEmpty(namedArg.Name) == name)
return namedArg;
}
return null;
}
/// <summary>
/// Gets the property/field named <paramref name="name"/>
/// </summary>
/// <param name="name">Name of property/field</param>
/// <param name="isField"><c>true</c> if it's a field, <c>false</c> if it's a property</param>
/// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns>
public CANamedArgument GetNamedArgument(UTF8String name, bool isField) {
foreach (var namedArg in namedArguments.GetSafeEnumerable()) {
if (namedArg.IsField == isField && UTF8String.Equals(namedArg.Name, name))
return namedArg;
}
return null;
}
/// <summary>
/// Gets the binary custom attribute data that was used to create this instance.
/// </summary>
/// <returns>Blob of this custom attribute</returns>
public byte[] GetBlob() {
if (rawData != null)
return rawData;
if (blob != null)
return blob;
#if THREAD_SAFE
if (blobReader != null) {
lock (this) {
#endif
if (blobReader != null) {
blob = blobReader.ReadAllBytes();
blobReader.Dispose();
blobReader = null;
return blob;
}
#if THREAD_SAFE
}
}
#endif
if (blob != null)
return blob;
return blob = new byte[0];
}
byte[] blob;
/// <inheritdoc/>
public override string ToString() {
return TypeFullName;
}
}
/// <summary>
/// A custom attribute constructor argument
/// </summary>
public struct CAArgument : ICloneable {
TypeSig type;
object value;
/// <summary>
/// Gets/sets the argument type
/// </summary>
public TypeSig Type {
get { return type; }
set { type = value; }
}
/// <summary>
/// Gets/sets the argument value
/// </summary>
public object Value {
get { return value; }
set { this.value = value; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Argument type</param>
public CAArgument(TypeSig type) {
this.type = type;
this.value = null;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Argument type</param>
/// <param name="value">Argument value</param>
public CAArgument(TypeSig type, object value) {
this.type = type;
this.value = value;
}
object ICloneable.Clone() {
return Clone();
}
/// <summary>
/// Clones this instance and any <see cref="CAArgument"/>s and <see cref="CANamedArgument"/>s
/// referenced from this instance.
/// </summary>
/// <returns></returns>
public CAArgument Clone() {
var value = this.value;
if (value is CAArgument)
value = ((CAArgument)value).Clone();
else if (value is IList<CAArgument>) {
var args = (IList<CAArgument>)value;
var newArgs = ThreadSafeListCreator.Create<CAArgument>(args.Count);
foreach (var arg in args.GetSafeEnumerable())
newArgs.Add(arg.Clone());
value = newArgs;
}
return new CAArgument(type, value);
}
/// <inheritdoc/>
public override string ToString() {
object v = value;
return string.Format("{0} ({1})", v == null ? "null" : v, type);
}
}
/// <summary>
/// A custom attribute field/property argument
/// </summary>
public sealed class CANamedArgument : ICloneable {
bool isField;
TypeSig type;
UTF8String name;
CAArgument argument;
/// <summary>
/// <c>true</c> if it's a field
/// </summary>
public bool IsField {
get { return isField; }
set { isField = value; }
}
/// <summary>
/// <c>true</c> if it's a property
/// </summary>
public bool IsProperty {
get { return !isField; }
set { isField = !value; }
}
/// <summary>
/// Gets/sets the field/property type
/// </summary>
public TypeSig Type {
get { return type; }
set { type = value; }
}
/// <summary>
/// Gets/sets the property/field name
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets/sets the argument
/// </summary>
public CAArgument Argument {
get { return argument; }
set { argument = value; }
}
/// <summary>
/// Gets/sets the argument type
/// </summary>
public TypeSig ArgumentType {
get { return argument.Type; }
set { argument.Type = value; }
}
/// <summary>
/// Gets/sets the argument value
/// </summary>
public object Value {
get { return argument.Value; }
set { argument.Value = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public CANamedArgument() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="isField"><c>true</c> if field, <c>false</c> if property</param>
public CANamedArgument(bool isField) {
this.isField = isField;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="isField"><c>true</c> if field, <c>false</c> if property</param>
/// <param name="type">Field/property type</param>
public CANamedArgument(bool isField, TypeSig type) {
this.isField = isField;
this.type = type;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="isField"><c>true</c> if field, <c>false</c> if property</param>
/// <param name="type">Field/property type</param>
/// <param name="name">Name of field/property</param>
public CANamedArgument(bool isField, TypeSig type, UTF8String name) {
this.isField = isField;
this.type = type;
this.name = name;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="isField"><c>true</c> if field, <c>false</c> if property</param>
/// <param name="type">Field/property type</param>
/// <param name="name">Name of field/property</param>
/// <param name="argument">Field/property argument</param>
public CANamedArgument(bool isField, TypeSig type, UTF8String name, CAArgument argument) {
this.isField = isField;
this.type = type;
this.name = name;
this.argument = argument;
}
object ICloneable.Clone() {
return Clone();
}
/// <summary>
/// Clones this instance and any <see cref="CAArgument"/>s referenced from this instance.
/// </summary>
/// <returns></returns>
public CANamedArgument Clone() {
return new CANamedArgument(isField, type, name, argument.Clone());
}
/// <inheritdoc/>
public override string ToString() {
object v = Value;
return string.Format("({0}) {1} {2} = {3} ({4})", isField ? "field" : "property", type, name, v == null ? "null" : v, ArgumentType);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceFabric
{
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>
/// ClustersOperations operations.
/// </summary>
internal partial class ClustersOperations : IServiceOperations<ServiceFabricManagementClient>, IClustersOperations
{
/// <summary>
/// Initializes a new instance of the ClustersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ClustersOperations(ServiceFabricManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ServiceFabricManagementClient
/// </summary>
public ServiceFabricManagementClient Client { get; private set; }
/// <summary>
/// Update cluster configuration
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='parameters'>
/// The parameters which contains the property value and property name which
/// used to update the cluster configuration
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Cluster>> UpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, ClusterUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Cluster> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, clusterName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get cluster resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorModelException">
/// 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<Cluster>> GetWithHttpMessagesAsync(string resourceGroupName, string clusterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (clusterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "clusterName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("clusterName", clusterName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_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<Cluster>();
_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<Cluster>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create cluster resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='parameters'>
/// Put Request
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Cluster>> CreateWithHttpMessagesAsync(string resourceGroupName, string clusterName, Cluster parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Cluster> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, clusterName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete cluster resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorModelException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string clusterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (clusterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "clusterName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("clusterName", clusterName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List cluster resource by resource group
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Cluster>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Cluster>>();
_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<Cluster>>(_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 cluster resource
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Cluster>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/clusters").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Cluster>>();
_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<Cluster>>(_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>
/// Update cluster configuration
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='parameters'>
/// The parameters which contains the property value and property name which
/// used to update the cluster configuration
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorModelException">
/// 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<Cluster>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, ClusterUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (clusterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "clusterName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("clusterName", clusterName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_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<Cluster>();
_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<Cluster>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create cluster resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the resource belongs or get created
/// </param>
/// <param name='clusterName'>
/// The name of the cluster resource
/// </param>
/// <param name='parameters'>
/// Put Request
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorModelException">
/// 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<Cluster>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string clusterName, Cluster parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (clusterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "clusterName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("clusterName", clusterName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_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<Cluster>();
_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<Cluster>(_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 cluster resource by resource group
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Cluster>>> ListByResourceGroupNextWithHttpMessagesAsync(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, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Cluster>>();
_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<Cluster>>(_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 cluster resource
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Cluster>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Cluster>>();
_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<Cluster>>(_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;
}
}
}
| |
namespace Obscureware.DataFlow.Model
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Implementation;
using Logging;
public abstract class BlockBase : IBlock, INavigableElement
{
private readonly object _initLock = new object();
private ProcessingBlockOptions _options;
public ProcessingBlockOptions Options
{
get { return this._options; }
set
{
bool isInited = this._transformation != null;
if (isInited)
{
throw new InvalidOperationException("Can not change options after block was initialized");
}
this._options = value;
}
}
private TransformManyBlock<DataFlowToken, DataFlowToken> _transformation;
private FlowExceptionManager _flowExceptionManager = new FlowExceptionManager();
// TODO: remove this init and adapt! Better share token with IFlow than create new.
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
protected IDataFlowLogger FlowLogger { get; private set; }
/// <summary>
/// Raised when all tokens have been processed.
/// </summary>
protected event EventHandler OnAllTokensProcessed;
/// <summary>
/// Raised when already terminated token has been passed for further processing. Sanity check.
/// </summary>
protected event EventHandler<TerminatedTokenReceivedEventArgs> OnTerminatedTokenReceived;
protected BlockBase(ProcessingBlockOptions options)
{
this.Options = options;
this.FlowLogger = DataFlowLoggerFactory.Create(this.GetType());
}
protected BlockBase()
{
this.FlowLogger = DataFlowLoggerFactory.Create(this.GetType());
}
private void Init()
{
lock (this._initLock)
{
if (this.Options == null)
{
throw new InvalidOperationException("Options can not be null");
}
if (this._transformation != null)
{
return;
}
var tplOptions = new ExecutionDataflowBlockOptions
{
CancellationToken = this._cancellationTokenSource.Token,
MaxDegreeOfParallelism = this.Options.MaxDegreeOfParallelism
};
this._transformation = new TransformManyBlock<DataFlowToken, DataFlowToken>(o => this.TransformInternal(o), tplOptions);
}
this.EntryPoint = this._transformation;
this.Output = this._transformation;
if (this.Options.TurnOnBroadCast)
{
var broadcastBlock = new BroadcastBlock<DataFlowToken>(o => new DataFlowToken(o), new DataflowBlockOptions
{
CancellationToken = this._cancellationTokenSource.Token
});
this._transformation.LinkTo(broadcastBlock, new DataflowLinkOptions { PropagateCompletion = true });
this.Output = broadcastBlock;
}
// call when the block finishes (all tokens were processed)
var completionSource = new TaskCompletionSource<string>();
this.Output.Completion.ContinueWith(o =>
{
if (o.IsCanceled)
{
completionSource.SetCanceled();
return;
}
if (o.IsFaulted && o.Exception != null)
{
completionSource.SetException(o.Exception);
return;
}
this.OnAllTokensProcessed?.Invoke(this, EventArgs.Empty);
completionSource.SetResult(string.Empty);
});
this.Completion = completionSource.Task;
}
private IEnumerable<DataFlowToken> PrepareResult(IEnumerable<DataFlowToken> result)
{
if (!this.Options.DoResultCheck)
{
return result;
}
var isLastBlock = !this.OutgoingLinks.Any();
var materialized = (result ?? new List<DataFlowToken>()).ToList();
// When last block - return empty result.
// The block finishes only when output queue is empty.
return materialized.Any() && isLastBlock ? Enumerable.Empty<DataFlowToken>() : materialized;
}
private IEnumerable<DataFlowToken> TransformInternal(DataFlowToken token)
{
Stopwatch perfCount = new Stopwatch();
try
{
perfCount.Start();
if (token.HasTerminated)
{
this.OnTerminatedTokenReceived?.Invoke(this, new TerminatedTokenReceivedEventArgs(token));
// just pass token to the next block - ignore processing of current block
// we want to pass for instance to the end block that will process results
return this.PrepareResult(new[] { token });
}
try
{
return this.PrepareResult(this.Transform(token));
}
catch (Exception ex)
{
token.HasTerminated = true;
this.FlowLogger.Error(token, ex);
this._flowExceptionManager.IncrementExceptionCount();
if (this._flowExceptionManager.IsCritical(ex) || this._flowExceptionManager.IsExceptionCountExceeded())
{
this._cancellationTokenSource.Cancel();
throw;
}
return this.PrepareResult(new[] { token });
}
}
finally
{
perfCount.Stop();
PerformanceMonitor.RegisterExecution(this.GetType().Name, perfCount.ElapsedTicks);
}
}
public abstract IEnumerable<DataFlowToken> Transform(DataFlowToken token);
public void Set(FlowExceptionManager flowExceptionManager, CancellationTokenSource cancellationTokenSource)
{
if (flowExceptionManager == null)
{
throw new ArgumentNullException(nameof(flowExceptionManager));
}
if (cancellationTokenSource == null)
{
throw new ArgumentNullException(nameof(cancellationTokenSource));
}
if (this._transformation != null)
{
// cancellation token would be ignored
throw new InvalidOperationException("Can not call Set method after block has been initialized.");
}
this._flowExceptionManager = flowExceptionManager;
this._cancellationTokenSource = cancellationTokenSource;
}
private ITargetBlock<DataFlowToken> _entryPoint;
private ITargetBlock<DataFlowToken> EntryPoint
{
get
{
this.Init();
return this._entryPoint;
}
set
{
this._entryPoint = value;
}
}
private ISourceBlock<DataFlowToken> _output;
private ISourceBlock<DataFlowToken> Output
{
get { this.Init(); return this._output; }
set { this._output = value; }
}
public bool Post(object token)
{
return this.EntryPoint.Post(token as DataFlowToken);
}
public object Receive()
{
return this.Output.Receive();
}
public void Complete()
{
this.EntryPoint.Complete();
}
public void Fault(Exception exception)
{
this.EntryPoint.Fault(exception);
}
public void Link(BlockBase target, bool propagare, Predicate<DataFlowToken> prediate = null)
{
var options = new DataflowLinkOptions
{
PropagateCompletion = propagare
};
if (prediate != null)
{
this.Output.LinkTo(target.EntryPoint, options, prediate);
return;
}
this.Output.LinkTo(target.EntryPoint, options);
}
public Task Completion { get; private set; }
public void OnReceived(ITargetBlock<object> onReceiveBlock)
{
var consumer = onReceiveBlock;
this.Output.LinkTo(consumer, new DataflowLinkOptions { PropagateCompletion = true });
}
public bool IsCompleted
{
get { return this.Completion.IsCompleted; }
}
#region Flow linking functions
public void Accept(IFlowNavigator navigator)
{
navigator.Visit(this);
}
public string ReadableId { get; set; }
private readonly List<ILink> _links = new List<ILink>();
public IEnumerable<ILink> IncommingLinks { get { return this._links.Where(o => o.Target == this); } }
public IEnumerable<ILink> OutgoingLinks { get { return this._links.Where(o => o.Source == this); } }
public void AddLink(ILink link)
{
if (link == null)
{
throw new ArgumentNullException();
}
if (link.Source != this && link.Target != this)
{
throw new ArgumentException("Must be either incoming or outgoing link");
}
this._links.Add(link);
}
#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 OLEDB.Test.ModuleCore;
using System.Collections.Generic;
using System.Xml.Linq;
namespace System.Xml.Tests
{
/// <summary>
/// CXmlDriverParam
/// </summary>
public abstract class CXmlDriverParamRawNodes
{
protected XElement poriginalNode;
protected XElement pvirtualNode;
protected CXmlDriverParamRawNodes pparentParams;
internal CXmlDriverParamRawNodes(XElement originalNode, XElement virtualNode, CXmlDriverParamRawNodes parentParams)
{
this.poriginalNode = originalNode;
this.pvirtualNode = virtualNode;
this.pparentParams = parentParams;
}
// original test module node
public virtual XElement TestModule { get { return null; } }
// original test case node
public virtual XElement TestCase { get { return null; } }
// original test variation node
public virtual XElement Variation { get { return null; } }
// dynamic node which includes all sections combined using Inheritance rules.
public virtual XElement Virtual
{
get
{
// support of delayed building of the Virtual node
if (pvirtualNode == null)
{
pvirtualNode = CXmlDriverEngine.BuildVirtualNode(pparentParams.Virtual, poriginalNode);
}
return pvirtualNode;
}
}
}
internal class CXmlDriverParamRawNodes_TestModule : CXmlDriverParamRawNodes
{
internal CXmlDriverParamRawNodes_TestModule(XElement testModuleNode, XElement virtualNode, CXmlDriverParamRawNodes parentParams) : base(testModuleNode, virtualNode, parentParams) { }
public override XElement TestModule { get { return poriginalNode; } }
}
internal class CXmlDriverParamRawNodes_TestCase : CXmlDriverParamRawNodes
{
internal CXmlDriverParamRawNodes_TestCase(XElement testCaseNode, XElement virtualNode, CXmlDriverParamRawNodes parentParams) : base(testCaseNode, virtualNode, parentParams) { }
public override XElement TestModule { get { return pparentParams.TestModule; } }
public override XElement TestCase { get { return poriginalNode; } }
}
internal class CXmlDriverParamRawNodes_Variation : CXmlDriverParamRawNodes
{
internal CXmlDriverParamRawNodes_Variation(XElement variationNode, XElement virtualNode, CXmlDriverParamRawNodes parentParams) : base(variationNode, virtualNode, parentParams) { }
public override XElement TestModule { get { return pparentParams.TestModule; } }
public override XElement TestCase { get { return pparentParams.TestCase; } }
public override XElement Variation { get { return poriginalNode; } }
}
public class CXmlDriverParam
{
private CXmlDriverParamRawNodes _rawNodes;
private string _defaultSection;
internal CXmlDriverParam(CXmlDriverParamRawNodes rawNodes, string defaultSection)
{
_rawNodes = rawNodes;
_defaultSection = defaultSection;
}
// returns raw nodes
public CXmlDriverParamRawNodes RawNodes
{
get
{
return _rawNodes;
}
}
// returns InnerText from the Data (default section) or null if the given xpath selects nothing
public string SelectValue(string xpath)
{
XNode curNode = DefaultSection;
return SelectValue(xpath, curNode);
}
private string SelectValue(string xpath, XNode curNode)
{
string[] route = xpath.Split('/');
int i = 0;
for (; i < route.Length; i++)
{
if (curNode == null || route[i].StartsWith("@") || curNode.NodeType != XmlNodeType.Element)
{
break;
}
curNode = ((XElement)curNode).Element(route[i]);
}
if (i == route.Length - 1)
{
if (curNode != null)
{
XAttribute attr = ((XElement)curNode).Attribute(route[i].Substring(1));
if (attr != null)
{
return attr.Value;
}
}
}
else if (i == route.Length)
{
if (curNode != null)
{
return ((XElement)curNode).Value;
}
}
return null;
}
// returns InnerText from the given section, or null if the given xpath selects nothing
public string SelectValue(string xpath, string sectionName)
{
XElement sectionNode = GetSection(sectionName);
return SelectValue(xpath, sectionNode);
}
// returns InnerText from the Data (default section),
// throws the CTestFailedException if node doesn't exist.
public string SelectExistingValue(string xpath)
{
string value = SelectValue(xpath);
CError.Compare(value != null, true, "XmlDriver: '" + xpath + "' is not found.");
return value;
}
// returns a value from the given section,
// throws the CTestFailedException if value doesn't exist.
public string SelectExistingValue(string xpath, string sectionName)
{
string value = SelectValue(xpath, sectionName);
CError.Compare(value != null, true, "XmlDriver: '" + xpath + "' is not found in the section '" + sectionName + "'.");
return value;
}
// selects nodes by xpath from the Data (default section)
public IEnumerable<XElement> SelectNodes(string xpath)
{
return DefaultSection.Elements(xpath);
}
// selects nodes by xpath from the given section
public IEnumerable<XElement> SelectNodes(string xpath, string sectionName)
{
XElement sectionNode = GetSection(sectionName);
if (sectionNode == null)
return _rawNodes.Virtual.Elements("*[-1]"); // create a dummy empty XmlNodeList
return sectionNode.Elements(xpath);
}
public string DefaultSectionName { get { return _defaultSection; } set { _defaultSection = value; } }
public XElement DefaultSection
{
get
{
XElement node = GetSection(_defaultSection);
CError.Compare(node != null, true, "XmlDriver: no default section found, defaultSectionName='" + _defaultSection);
return node;
}
}
internal XElement GetSection(string sectionName)
{
XElement node = _rawNodes.Virtual.Element(sectionName);
return node;
}
// returns an attribute from the Virtual node by attribute name
public string GetTopLevelAttributeValue(string attrName)
{
XAttribute attr = _rawNodes.Virtual.Attribute(attrName);
if (attr == null)
return null;
return attr.Value;
}
public string GetTopLevelExistingAttributeValue(string attrName)
{
string value = GetTopLevelAttributeValue(attrName);
CError.Compare(value != null, true, "XmlDriver: '" + attrName + "' attribute is not found.");
return value;
}
// 'inline' implementation without using Virtual node for perf improvement (only for internal use)
internal static string GetTopLevelAttributeValue_Inline(CXmlDriverParamRawNodes param, string attrName)
{
XAttribute attr = null;
if (param.Variation != null)
attr = param.Variation.Attribute(attrName);
if (attr == null && param.TestCase != null)
attr = param.TestCase.Attribute(attrName);
if (attr == null && param.TestModule != null)
attr = param.TestModule.Attribute(attrName);
if (attr == null)
return null;
return attr.Value;
}
}
}
| |
using System;
namespace Versioning
{
public class CountryCodeRecord : Sage_Container, ISageRecord
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.CountryCodeRecord ccr11;
SageDataObject120.CountryCodeRecord ccr12;
SageDataObject130.CountryCodeRecord ccr13;
SageDataObject140.CountryCodeRecord ccr14;
SageDataObject150.CountryCodeRecord ccr15;
SageDataObject160.CountryCodeRecord ccr16;
SageDataObject170.CountryCodeRecord ccr17;
public CountryCodeRecord(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
ccr11 = (SageDataObject110.CountryCodeRecord)inner;
m_fields = new Fields(ccr11.Fields,m_version);
return;
}
case 12: {
ccr12 = (SageDataObject120.CountryCodeRecord)inner;
m_fields = new Fields(ccr12.Fields,m_version);
return;
}
case 13: {
ccr13 = (SageDataObject130.CountryCodeRecord)inner;
m_fields = new Fields(ccr13.Fields,m_version);
return;
}
case 14: {
ccr14 = (SageDataObject140.CountryCodeRecord)inner;
m_fields = new Fields(ccr14.Fields,m_version);
return;
}
case 15: {
ccr15 = (SageDataObject150.CountryCodeRecord)inner;
m_fields = new Fields(ccr15.Fields,m_version);
return;
}
case 16: {
ccr16 = (SageDataObject160.CountryCodeRecord)inner;
m_fields = new Fields(ccr16.Fields,m_version);
return;
}
case 17: {
ccr17 = (SageDataObject170.CountryCodeRecord)inner;
m_fields = new Fields(ccr17.Fields,m_version);
return;
}
default: throw new InvalidOperationException("ver");
}
}
/* Autogenerated with record_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string COUNTRYCODERECORD = "CountryCodeRecord";
public bool AddNew() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.AddNew();
break;
}
case 12: {
ret = ccr12.AddNew();
break;
}
case 13: {
ret = ccr13.AddNew();
break;
}
case 14: {
ret = ccr14.AddNew();
break;
}
case 15: {
ret = ccr15.AddNew();
break;
}
case 16: {
ret = ccr16.AddNew();
break;
}
case 17: {
ret = ccr17.AddNew();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Update() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.Update();
break;
}
case 12: {
ret = ccr12.Update();
break;
}
case 13: {
ret = ccr13.Update();
break;
}
case 14: {
ret = ccr14.Update();
break;
}
case 15: {
ret = ccr15.Update();
break;
}
case 16: {
ret = ccr16.Update();
break;
}
case 17: {
ret = ccr17.Update();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Edit() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.Edit();
break;
}
case 12: {
ret = ccr12.Edit();
break;
}
case 13: {
ret = ccr13.Edit();
break;
}
case 14: {
ret = ccr14.Edit();
break;
}
case 15: {
ret = ccr15.Edit();
break;
}
case 16: {
ret = ccr16.Edit();
break;
}
case 17: {
ret = ccr17.Edit();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Find(bool partial) {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.Find(partial);
break;
}
case 12: {
ret = ccr12.Find(partial);
break;
}
case 13: {
ret = ccr13.Find(partial);
break;
}
case 14: {
ret = ccr14.Find(partial);
break;
}
case 15: {
ret = ccr15.Find(partial);
break;
}
case 16: {
ret = ccr16.Find(partial);
break;
}
case 17: {
ret = ccr17.Find(partial);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MoveFirst() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.MoveFirst();
break;
}
case 12: {
ret = ccr12.MoveFirst();
break;
}
case 13: {
ret = ccr13.MoveFirst();
break;
}
case 14: {
ret = ccr14.MoveFirst();
break;
}
case 15: {
ret = ccr15.MoveFirst();
break;
}
case 16: {
ret = ccr16.MoveFirst();
break;
}
case 17: {
ret = ccr17.MoveFirst();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MoveNext() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.MoveNext();
break;
}
case 12: {
ret = ccr12.MoveNext();
break;
}
case 13: {
ret = ccr13.MoveNext();
break;
}
case 14: {
ret = ccr14.MoveNext();
break;
}
case 15: {
ret = ccr15.MoveNext();
break;
}
case 16: {
ret = ccr16.MoveNext();
break;
}
case 17: {
ret = ccr17.MoveNext();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MoveLast() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.MoveLast();
break;
}
case 12: {
ret = ccr12.MoveLast();
break;
}
case 13: {
ret = ccr13.MoveLast();
break;
}
case 14: {
ret = ccr14.MoveLast();
break;
}
case 15: {
ret = ccr15.MoveLast();
break;
}
case 16: {
ret = ccr16.MoveLast();
break;
}
case 17: {
ret = ccr17.MoveLast();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MovePrev() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.MovePrev();
break;
}
case 12: {
ret = ccr12.MovePrev();
break;
}
case 13: {
ret = ccr13.MovePrev();
break;
}
case 14: {
ret = ccr14.MovePrev();
break;
}
case 15: {
ret = ccr15.MovePrev();
break;
}
case 16: {
ret = ccr16.MovePrev();
break;
}
case 17: {
ret = ccr17.MovePrev();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Remove() {
bool ret;
switch (m_version) {
case 11: {
ret = ccr11.Remove();
break;
}
case 12: {
ret = ccr12.Remove();
break;
}
case 13: {
ret = ccr13.Remove();
break;
}
case 14: {
ret = ccr14.Remove();
break;
}
case 15: {
ret = ccr15.Remove();
break;
}
case 16: {
ret = ccr16.Remove();
break;
}
case 17: {
ret = ccr17.Remove();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public int Count {
get {
int ret;
switch (m_version) {
case 11: {
ret = ccr11.Count;
break;
}
case 12: {
ret = ccr12.Count;
break;
}
case 13: {
ret = ccr13.Count;
break;
}
case 14: {
ret = ccr14.Count;
break;
}
case 15: {
ret = ccr15.Count;
break;
}
case 16: {
ret = ccr16.Count;
break;
}
case 17: {
ret = ccr17.Count;
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
set {
switch (m_version) {
case 11: {
ccr11.Count = value;
break;
}
case 12: {
ccr12.Count = value;
break;
}
case 13: {
ccr13.Count = value;
break;
}
case 14: {
ccr14.Count = value;
break;
}
case 15: {
ccr15.Count = value;
break;
}
case 16: {
ccr16.Count = value;
break;
}
case 17: {
ccr17.Count = value;
break;
}
default: throw new InvalidOperationException("ver");
}
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxres = Google.Api.Gax.ResourceNames;
using sys = System;
using scg = System.Collections.Generic;
using linq = System.Linq;
namespace Google.Cloud.PubSub.V1
{
/// <summary>
/// Resource name for the 'snapshot' resource.
/// </summary>
public sealed partial class SnapshotName : gax::IResourceName, sys::IEquatable<SnapshotName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/snapshots/{snapshot}");
/// <summary>
/// Parses the given snapshot resource name in string form into a new
/// <see cref="SnapshotName"/> instance.
/// </summary>
/// <param name="snapshotName">The snapshot resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns>
public static SnapshotName Parse(string snapshotName)
{
gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName));
gax::TemplatedResourceName resourceName = s_template.ParseName(snapshotName);
return new SnapshotName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given snapshot resource name in string form into a new
/// <see cref="SnapshotName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="snapshotName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="snapshotName">The snapshot resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="SnapshotName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string snapshotName, out SnapshotName result)
{
gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(snapshotName, out resourceName))
{
result = new SnapshotName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="SnapshotName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="snapshotId">The snapshot ID. Must not be <c>null</c>.</param>
public SnapshotName(string projectId, string snapshotId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
SnapshotId = gax::GaxPreconditions.CheckNotNull(snapshotId, nameof(snapshotId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The snapshot ID. Never <c>null</c>.
/// </summary>
public string SnapshotId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, SnapshotId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as SnapshotName);
/// <inheritdoc />
public bool Equals(SnapshotName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(SnapshotName a, SnapshotName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(SnapshotName a, SnapshotName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'subscription' resource.
/// </summary>
public sealed partial class SubscriptionName : gax::IResourceName, sys::IEquatable<SubscriptionName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/subscriptions/{subscription}");
/// <summary>
/// Parses the given subscription resource name in string form into a new
/// <see cref="SubscriptionName"/> instance.
/// </summary>
/// <param name="subscriptionName">The subscription resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SubscriptionName"/> if successful.</returns>
public static SubscriptionName Parse(string subscriptionName)
{
gax::GaxPreconditions.CheckNotNull(subscriptionName, nameof(subscriptionName));
gax::TemplatedResourceName resourceName = s_template.ParseName(subscriptionName);
return new SubscriptionName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given subscription resource name in string form into a new
/// <see cref="SubscriptionName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="subscriptionName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="subscriptionName">The subscription resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="SubscriptionName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string subscriptionName, out SubscriptionName result)
{
gax::GaxPreconditions.CheckNotNull(subscriptionName, nameof(subscriptionName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(subscriptionName, out resourceName))
{
result = new SubscriptionName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="SubscriptionName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="subscriptionId">The subscription ID. Must not be <c>null</c>.</param>
public SubscriptionName(string projectId, string subscriptionId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
SubscriptionId = gax::GaxPreconditions.CheckNotNull(subscriptionId, nameof(subscriptionId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The subscription ID. Never <c>null</c>.
/// </summary>
public string SubscriptionId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, SubscriptionId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as SubscriptionName);
/// <inheritdoc />
public bool Equals(SubscriptionName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(SubscriptionName a, SubscriptionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(SubscriptionName a, SubscriptionName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'topic' resource.
/// </summary>
public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/topics/{topic}");
/// <summary>
/// Parses the given topic resource name in string form into a new
/// <see cref="TopicName"/> instance.
/// </summary>
/// <param name="topicName">The topic resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TopicName"/> if successful.</returns>
public static TopicName Parse(string topicName)
{
gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName));
gax::TemplatedResourceName resourceName = s_template.ParseName(topicName);
return new TopicName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given topic resource name in string form into a new
/// <see cref="TopicName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="topicName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="topicName">The topic resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="TopicName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string topicName, out TopicName result)
{
gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(topicName, out resourceName))
{
result = new TopicName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="TopicName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="topicId">The topic ID. Must not be <c>null</c>.</param>
public TopicName(string projectId, string topicId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
TopicId = gax::GaxPreconditions.CheckNotNull(topicId, nameof(topicId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The topic ID. Never <c>null</c>.
/// </summary>
public string TopicId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, TopicId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as TopicName);
/// <inheritdoc />
public bool Equals(TopicName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(TopicName a, TopicName b) => !(a == b);
}
/// <summary>
/// Resource name which will contain one of a choice of resource names.
/// </summary>
/// <remarks>
/// This resource name will contain one of the following:
/// <list type="bullet">
/// <item><description>TopicName: A resource of type 'topic'.</description></item>
/// <item><description>DeletedTopicNameFixed: A resource of type 'deleted_topic'.</description></item>
/// </list>
/// </remarks>
public sealed partial class TopicNameOneof : gax::IResourceName, sys::IEquatable<TopicNameOneof>
{
/// <summary>
/// The possible contents of <see cref="TopicNameOneof"/>.
/// </summary>
public enum OneofType
{
/// <summary>
/// A resource of an unknown type.
/// </summary>
Unknown = 0,
/// <summary>
/// A resource of type 'topic'.
/// </summary>
TopicName = 1,
/// <summary>
/// A resource of type 'deleted_topic'.
/// </summary>
DeletedTopicNameFixed = 2,
}
/// <summary>
/// Parses a resource name in string form into a new <see cref="TopicNameOneof"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully the resource name must be one of the following:
/// <list type="bullet">
/// <item><description>TopicName: A resource of type 'topic'.</description></item>
/// <item><description>DeletedTopicNameFixed: A resource of type 'deleted_topic'.</description></item>
/// </list>
/// Or an <see cref="gax::UnknownResourceName"/> if <paramref name="allowUnknown"/> is <c>true</c>.
/// </remarks>
/// <param name="name">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnknown">If true, will successfully parse an unknown resource name
/// into an <see cref="gax::UnknownResourceName"/>; otherwise will throw an
/// <see cref="sys::ArgumentException"/> if an unknown resource name is given.</param>
/// <returns>The parsed <see cref="TopicNameOneof"/> if successful.</returns>
public static TopicNameOneof Parse(string name, bool allowUnknown)
{
TopicNameOneof result;
if (TryParse(name, allowUnknown, out result))
{
return result;
}
throw new sys::ArgumentException("Invalid name", nameof(name));
}
/// <summary>
/// Tries to parse a resource name in string form into a new <see cref="TopicNameOneof"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully the resource name must be one of the following:
/// <list type="bullet">
/// <item><description>TopicName: A resource of type 'topic'.</description></item>
/// <item><description>DeletedTopicNameFixed: A resource of type 'deleted_topic'.</description></item>
/// </list>
/// Or an <see cref="gax::UnknownResourceName"/> if <paramref name="allowUnknown"/> is <c>true</c>.
/// </remarks>
/// <param name="name">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnknown">If true, will successfully parse an unknown resource name
/// into an <see cref="gax::UnknownResourceName"/>.</param>
/// <param name="result">When this method returns, the parsed <see cref="TopicNameOneof"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string name, bool allowUnknown, out TopicNameOneof result)
{
gax::GaxPreconditions.CheckNotNull(name, nameof(name));
TopicName topicName;
if (TopicName.TryParse(name, out topicName))
{
result = new TopicNameOneof(OneofType.TopicName, topicName);
return true;
}
DeletedTopicNameFixed deletedTopicNameFixed;
if (DeletedTopicNameFixed.TryParse(name, out deletedTopicNameFixed))
{
result = new TopicNameOneof(OneofType.DeletedTopicNameFixed, deletedTopicNameFixed);
return true;
}
if (allowUnknown)
{
gax::UnknownResourceName unknownResourceName;
if (gax::UnknownResourceName.TryParse(name, out unknownResourceName))
{
result = new TopicNameOneof(OneofType.Unknown, unknownResourceName);
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Construct a new instance of <see cref="TopicNameOneof"/> from the provided <see cref="TopicName"/>
/// </summary>
/// <param name="topicName">The <see cref="TopicName"/> to be contained within
/// the returned <see cref="TopicNameOneof"/>. Must not be <c>null</c>.</param>
/// <returns>A new <see cref="TopicNameOneof"/>, containing <paramref name="topicName"/>.</returns>
public static TopicNameOneof From(TopicName topicName) => new TopicNameOneof(OneofType.TopicName, topicName);
/// <summary>
/// Construct a new instance of <see cref="TopicNameOneof"/> from the provided <see cref="DeletedTopicNameFixed"/>
/// </summary>
/// <param name="deletedTopicNameFixed">The <see cref="DeletedTopicNameFixed"/> to be contained within
/// the returned <see cref="TopicNameOneof"/>. Must not be <c>null</c>.</param>
/// <returns>A new <see cref="TopicNameOneof"/>, containing <paramref name="deletedTopicNameFixed"/>.</returns>
public static TopicNameOneof From(DeletedTopicNameFixed deletedTopicNameFixed) => new TopicNameOneof(OneofType.DeletedTopicNameFixed, deletedTopicNameFixed);
private static bool IsValid(OneofType type, gax::IResourceName name)
{
switch (type)
{
case OneofType.Unknown: return true; // Anything goes with Unknown.
case OneofType.TopicName: return name is TopicName;
case OneofType.DeletedTopicNameFixed: return name is DeletedTopicNameFixed;
default: return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="TopicNameOneof"/> resource name class
/// from a suitable <see cref="gax::IResourceName"/> instance.
/// </summary>
public TopicNameOneof(OneofType type, gax::IResourceName name)
{
Type = gax::GaxPreconditions.CheckEnumValue<OneofType>(type, nameof(type));
Name = gax::GaxPreconditions.CheckNotNull(name, nameof(name));
if (!IsValid(type, name))
{
throw new sys::ArgumentException($"Mismatched OneofType '{type}' and resource name '{name}'");
}
}
/// <summary>
/// The <see cref="OneofType"/> of the Name contained in this instance.
/// </summary>
public OneofType Type { get; }
/// <summary>
/// The <see cref="gax::IResourceName"/> contained in this instance.
/// </summary>
public gax::IResourceName Name { get; }
private T CheckAndReturn<T>(OneofType type)
{
if (Type != type)
{
throw new sys::InvalidOperationException($"Requested type {type}, but this one-of contains type {Type}");
}
return (T)Name;
}
/// <summary>
/// Get the contained <see cref="gax::IResourceName"/> as <see cref="TopicName"/>.
/// </summary>
/// <remarks>
/// An <see cref="sys::InvalidOperationException"/> will be thrown if this does not
/// contain an instance of <see cref="TopicName"/>.
/// </remarks>
public TopicName TopicName => CheckAndReturn<TopicName>(OneofType.TopicName);
/// <summary>
/// Get the contained <see cref="gax::IResourceName"/> as <see cref="DeletedTopicNameFixed"/>.
/// </summary>
/// <remarks>
/// An <see cref="sys::InvalidOperationException"/> will be thrown if this does not
/// contain an instance of <see cref="DeletedTopicNameFixed"/>.
/// </remarks>
public DeletedTopicNameFixed DeletedTopicNameFixed => CheckAndReturn<DeletedTopicNameFixed>(OneofType.DeletedTopicNameFixed);
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Oneof;
/// <inheritdoc />
public override string ToString() => Name.ToString();
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as TopicNameOneof);
/// <inheritdoc />
public bool Equals(TopicNameOneof other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(TopicNameOneof a, TopicNameOneof b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(TopicNameOneof a, TopicNameOneof b) => !(a == b);
}
/// <summary>
/// Resource name to represent the fixed string "_deleted-topic_".
/// </summary>
public sealed partial class DeletedTopicNameFixed : gax::IResourceName, sys::IEquatable<DeletedTopicNameFixed>
{
/// <summary>
/// The fixed string value: "_deleted-topic_".
/// </summary>
public const string FixedValue = "_deleted-topic_";
/// <summary>
/// An instance of <see cref="DeletedTopicNameFixed"/>.
/// </summary>
public static DeletedTopicNameFixed Instance => new DeletedTopicNameFixed();
/// <summary>
/// Parses the given string into a new <see cref="DeletedTopicNameFixed"/> instance.
/// Only succeeds if the string is equal to "_deleted-topic_".
/// </summary>
public static DeletedTopicNameFixed Parse(string deletedTopicNameFixed)
{
DeletedTopicNameFixed result;
if (!TryParse(deletedTopicNameFixed, out result))
{
throw new sys::ArgumentException($"Invalid resource name, must be \"{FixedValue}\"", nameof(deletedTopicNameFixed));
}
return result;
}
/// <summary>
/// Tries to parse the given string into a new <see cref="DeletedTopicNameFixed"/> instance.
/// Only succeeds if the string is equal to "_deleted-topic_".
/// </summary>
public static bool TryParse(string deletedTopicNameFixed, out DeletedTopicNameFixed result)
{
gax::GaxPreconditions.CheckNotNull(deletedTopicNameFixed, nameof(deletedTopicNameFixed));
if (deletedTopicNameFixed == FixedValue)
{
result = Instance;
return true;
}
else
{
result = null;
return false;
}
}
private DeletedTopicNameFixed() { }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Fixed;
/// <inheritdoc />
public override string ToString() => FixedValue;
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as DeletedTopicNameFixed);
/// <inheritdoc />
public bool Equals(DeletedTopicNameFixed other) => other != null;
/// <inheritdoc />
public static bool operator ==(DeletedTopicNameFixed a, DeletedTopicNameFixed b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(DeletedTopicNameFixed a, DeletedTopicNameFixed b) => !(a == b);
}
public partial class AcknowledgeRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class CreateSnapshotRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SnapshotName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SnapshotName SnapshotName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.PubSub.V1.SnapshotName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteSnapshotRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SnapshotName"/>-typed view over the <see cref="Snapshot"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SnapshotName SnapshotAsSnapshotName
{
get { return string.IsNullOrEmpty(Snapshot) ? null : Google.Cloud.PubSub.V1.SnapshotName.Parse(Snapshot); }
set { Snapshot = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteSubscriptionRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class DeleteTopicRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicAsTopicName
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Topic); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class GetSubscriptionRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class GetTopicRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicAsTopicName
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Topic); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class ListSnapshotsRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Project"/> resource name property.
/// </summary>
public gaxres::ProjectName ProjectAsProjectName
{
get { return string.IsNullOrEmpty(Project) ? null : gaxres::ProjectName.Parse(Project); }
set { Project = value != null ? value.ToString() : ""; }
}
}
public partial class ListSubscriptionsRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Project"/> resource name property.
/// </summary>
public gaxres::ProjectName ProjectAsProjectName
{
get { return string.IsNullOrEmpty(Project) ? null : gaxres::ProjectName.Parse(Project); }
set { Project = value != null ? value.ToString() : ""; }
}
}
public partial class ListTopicSubscriptionsRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicAsTopicName
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Topic); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class ListTopicSubscriptionsResponse
{
/// <summary>
/// <see cref="gax::ResourceNameList{SubscriptionName}"/>-typed view over the <see cref="Subscriptions"/> resource name property.
/// </summary>
public gax::ResourceNameList<SubscriptionName> SubscriptionsAsSubscriptionNames =>
new gax::ResourceNameList<SubscriptionName>(Subscriptions,
str => SubscriptionName.Parse(str));
}
public partial class ListTopicsRequest
{
/// <summary>
/// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Project"/> resource name property.
/// </summary>
public gaxres::ProjectName ProjectAsProjectName
{
get { return string.IsNullOrEmpty(Project) ? null : gaxres::ProjectName.Parse(Project); }
set { Project = value != null ? value.ToString() : ""; }
}
}
public partial class ModifyAckDeadlineRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class ModifyPushConfigRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class PublishRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicAsTopicName
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Topic); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class PullRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class SeekRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SnapshotName"/>-typed view over the <see cref="Snapshot"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SnapshotName SnapshotAsSnapshotName
{
get { return string.IsNullOrEmpty(Snapshot) ? null : Google.Cloud.PubSub.V1.SnapshotName.Parse(Snapshot); }
set { Snapshot = value != null ? value.ToString() : ""; }
}
}
public partial class Snapshot
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SnapshotName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SnapshotName SnapshotName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.PubSub.V1.SnapshotName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicAsTopicName
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Topic); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class StreamingPullRequest
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionAsSubscriptionName
{
get { return string.IsNullOrEmpty(Subscription) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Subscription); }
set { Subscription = value != null ? value.ToString() : ""; }
}
}
public partial class Subscription
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.SubscriptionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.SubscriptionName SubscriptionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.PubSub.V1.SubscriptionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicNameOneof"/>-typed view over the <see cref="Topic"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicNameOneof TopicAsTopicNameOneof
{
get { return string.IsNullOrEmpty(Topic) ? null : Google.Cloud.PubSub.V1.TopicNameOneof.Parse(Topic, true); }
set { Topic = value != null ? value.ToString() : ""; }
}
}
public partial class Topic
{
/// <summary>
/// <see cref="Google.Cloud.PubSub.V1.TopicName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.PubSub.V1.TopicName TopicName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.PubSub.V1.TopicName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.KeyVault
{
using System.Threading;
using System.Threading.Tasks;
using Models;
using System.Net.Http;
using Rest.Azure;
using System.Collections.Generic;
using Rest;
using System;
using System.Net;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Client class to perform cryptographic key operations and vault
/// operations against the Key Vault service.
/// </summary>
public partial class KeyVaultClient
{
/// <summary>
/// The authentication callback delegate which is to be implemented by the client code
/// </summary>
/// <param name="authority"> Identifier of the authority, a URL. </param>
/// <param name="resource"> Identifier of the target resource that is the recipient of the requested token, a URL. </param>
/// <param name="scope"> The scope of the authentication request. </param>
/// <returns> access token </returns>
public delegate Task<string> AuthenticationCallback(string authority, string resource, string scope);
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
public KeyVaultClient(AuthenticationCallback authenticationCallback)
: this(new KeyVaultCredential(authenticationCallback))
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
/// <param name='handlers'>Optional. The delegating handlers to add to the http client pipeline.</param>
public KeyVaultClient(AuthenticationCallback authenticationCallback, params DelegatingHandler[] handlers)
: this(new KeyVaultCredential(authenticationCallback), handlers)
{
}
/// <summary>
/// Gets the pending certificate signing request response.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<string>> GetPendingCertificateSigningRequestWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultBaseUrl == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultBaseUrl");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (this.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.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("vaultBaseUrl", vaultBaseUrl);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPendingCertificateSigningRequest", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "certificates/{certificate-name}/pending";
_url = _url.Replace("{vaultBaseUrl}", vaultBaseUrl);
_url = _url.Replace("{certificate-name}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (this.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
_httpRequest.Headers.Add("Accept", "application/pkcs10");
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 KeyVaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
KeyVaultError _errorBody = SafeJsonConvert.DeserializeObject<KeyVaultError>(_responseContent, this.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<string>();
_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)
{
_result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License");you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Util
{
using System;
using System.Collections;
using System.IO;
using System.Reflection;
/**
* Intends to provide support for the very evil index to triplet Issue and
* will likely replace the color constants interface for HSSF 2.0.
* This class Contains static inner class members for representing colors.
* Each color has an index (for the standard palette in Excel (tm) ),
* native (RGB) triplet and string triplet. The string triplet Is as the
* color would be represented by Gnumeric. Having (string) this here Is a bit of a
* collusion of function between HSSF and the HSSFSerializer but I think its
* a reasonable one in this case.
*
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Brian Sanders (bsanders at risklabs dot com) - full default color palette
*/
public class HSSFColor : NPOI.SS.UserModel.IColor
{
private static Hashtable indexHash;
public const short COLOR_NORMAL = 0x7fff;
// TODO make subclass instances immutable
/** Creates a new instance of HSSFColor */
public HSSFColor()
{
}
/**
* this function returns all colors in a hastable. Its not implemented as a
* static member/staticly initialized because that would be dirty in a
* server environment as it Is intended. This means you'll eat the time
* it takes to Create it once per request but you will not hold onto it
* if you have none of those requests.
*
* @return a hashtable containing all colors keyed by <c>int</c> excel-style palette indexes
*/
public static Hashtable GetIndexHash()
{
if (indexHash == null)
{
indexHash = CreateColorsByIndexMap();
}
return indexHash;
}
/**
* This function returns all the Colours, stored in a Hashtable that
* can be edited. No caching is performed. If you don't need to edit
* the table, then call {@link #getIndexHash()} which returns a
* statically cached imuatable map of colours.
*/
public static Hashtable GetMutableIndexHash()
{
return CreateColorsByIndexMap();
}
private static Hashtable CreateColorsByIndexMap()
{
HSSFColor[] colors = GetAllColors();
Hashtable result = new Hashtable(colors.Length * 3 / 2);
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
int index1 = color.Indexed;
if (result.ContainsKey(index1))
{
HSSFColor prevColor = (HSSFColor)result[index1];
throw new InvalidDataException("Dup color index (" + index1
+ ") for colors (" + prevColor.GetType().Name
+ "),(" + color.GetType().Name + ")");
}
result[index1] = color;
}
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
int index2 = GetIndex2(color);
if (index2 == -1)
{
// most colors don't have a second index
continue;
}
//if (result.ContainsKey(index2))
//{
//if (false)
//{ // Many of the second indexes clash
// HSSFColor prevColor = (HSSFColor)result[index2];
// throw new InvalidDataException("Dup color index (" + index2
// + ") for colors (" + prevColor.GetType().Name
// + "),(" + color.GetType().Name + ")");
//}
//}
result[index2] = color;
}
return result;
}
private static int GetIndex2(HSSFColor color)
{
FieldInfo f = color.GetType().GetField("Index2", BindingFlags.Static | BindingFlags.Public);
if (f == null)
{
return -1;
}
short s = (short)f.GetValue(color);
return Convert.ToInt32(s);
}
internal static HSSFColor[] GetAllColors()
{
return new HSSFColor[] {
new Black(), new Brown(), new OliveGreen(), new DarkGreen(),
new DarkTeal(), new DarkBlue(), new Indigo(), new Grey80Percent(),
new Orange(), new DarkYellow(), new Green(), new Teal(), new Blue(),
new BlueGrey(), new Grey50Percent(), new Red(), new LightOrange(), new Lime(),
new SeaGreen(), new Aqua(), new LightBlue(), new Violet(), new Grey40Percent(),
new Pink(), new Gold(), new Yellow(), new BrightGreen(), new Turquoise(),
new DarkRed(), new SkyBlue(), new Plum(), new Grey25Percent(), new Rose(),
new LightYellow(), new LightGreen(), new LightTurquoise(), new PaleBlue(),
new Lavender(), new White(), new CornflowerBlue(), new LemonChiffon(),
new Maroon(), new Orchid(), new Coral(), new RoyalBlue(),
new LightCornflowerBlue(), new Tan(),
};
}
/// <summary>
/// this function returns all colors in a hastable. Its not implemented as a
/// static member/staticly initialized because that would be dirty in a
/// server environment as it Is intended. This means you'll eat the time
/// it takes to Create it once per request but you will not hold onto it
/// if you have none of those requests.
/// </summary>
/// <returns>a hashtable containing all colors keyed by String gnumeric-like triplets</returns>
public static Hashtable GetTripletHash()
{
return CreateColorsByHexStringMap();
}
private static Hashtable CreateColorsByHexStringMap()
{
HSSFColor[] colors = GetAllColors();
Hashtable result = new Hashtable(colors.Length * 3 / 2);
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
String hexString = color.GetHexString();
if (result.ContainsKey(hexString))
{
throw new InvalidDataException("Dup color hexString (" + hexString
+ ") for color (" + color.GetType().Name + ")");
}
result[hexString] = color;
}
return result;
}
/**
* @return index to the standard palette
*/
public virtual short Indexed
{
get
{
return Black.Index;
}
}
public byte[] RGB
{
get { return this.GetTriplet(); }
}
/**
* @return triplet representation like that in Excel
*/
// [Obsolete]
public virtual byte[] GetTriplet()
{
return Black.Triplet;
}
// its a hack but its a good hack
/**
* @return a hex string exactly like a gnumeric triplet
*/
public virtual String GetHexString()
{
return Black.HexString;
}
/**
* Class BLACK
*
*/
public class Black : HSSFColor
{
public const short Index = 0x8;
public static readonly byte[] Triplet = { 0, 0, 0 };
public const string HexString = "0:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BROWN
*
*/
public class Brown : HSSFColor
{
public const short Index = 0x3c;
public static readonly byte[] Triplet = { 153, 51, 0 };
public const string HexString = "9999:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class OLIVE_GREEN
*
*/
public class OliveGreen: HSSFColor
{
public const short Index = 0x3b;
public static readonly byte[] Triplet = { 51, 51, 0 };
public const string HexString = "3333:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_GREEN
*
*/
public class DarkGreen: HSSFColor
{
public const short Index = 0x3a;
public static readonly byte[] Triplet = { 0, 51, 0 };
public const string HexString = "0:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_TEAL
*
*/
public class DarkTeal: HSSFColor
{
public const short Index = 0x38;
public static readonly byte[] Triplet = { 0, 51, 102 };
public const string HexString = "0:3333:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_BLUE
*
*/
public class DarkBlue: HSSFColor
{
public const short Index = 0x12;
public const short Index2 = 0x20;
public static readonly byte[] Triplet = { 0, 0, 128 };
public const string HexString = "0:0:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class INDIGO
*
*/
public class Indigo: HSSFColor
{
public const short Index = 0x3e;
public static readonly byte[] Triplet = { 51, 51, 153 };
public const string HexString = "3333:3333:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_80_PERCENT
*
*/
public class Grey80Percent: HSSFColor
{
public const short Index = 0x3f;
public static readonly byte[] Triplet = { 51, 51, 51 };
public const string HexString = "3333:3333:3333";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_RED
*
*/
public class DarkRed: HSSFColor
{
public const short Index = 0x10;
public const short Index2 = 0x25;
public static readonly byte[] Triplet = { 128, 0, 0 };
public const string HexString = "8080:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ORANGE
*
*/
public class Orange: HSSFColor
{
public const short Index = 0x35;
public static readonly byte[] Triplet = { 255, 102, 0 };
public const string HexString = "FFFF:6666:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_YELLOW
*
*/
public class DarkYellow: HSSFColor
{
public const short Index = 0x13;
public static readonly byte[] Triplet = { 128, 128, 0 };
public const string HexString = "8080:8080:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREEN
*
*/
public class Green: HSSFColor
{
public const short Index = 0x11;
public static readonly byte[] Triplet = { 0, 128, 0 };
public const string HexString = "0:8080:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class TEAL
*
*/
public class Teal: HSSFColor
{
public const short Index = 0x15;
public const short Index2 = 0x26;
public static readonly byte[] Triplet = { 0, 128, 128 };
public const string HexString = "0:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BLUE
*
*/
public class Blue: HSSFColor
{
public const short Index = 0xc;
public const short Index2 = 0x27;
public static readonly byte[] Triplet = { 0, 0, 255 };
public const string HexString = "0:0:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BLUE_GREY
*
*/
public class BlueGrey: HSSFColor
{
public const short Index = 0x36;
public static readonly byte[] Triplet = { 102, 102, 153 };
public const string HexString = "6666:6666:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_50_PERCENT
*
*/
public class Grey50Percent: HSSFColor
{
public const short Index = 0x17;
public static readonly byte[] Triplet = { 128, 128, 128 };
public const string HexString = "8080:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class RED
*
*/
public class Red: HSSFColor
{
public const short Index = 0xa;
public static readonly byte[] Triplet = { 255, 0, 0 };
public const string HexString = "FFFF:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_ORANGE
*
*/
public class LightOrange: HSSFColor
{
public const short Index = 0x34;
public static readonly byte[] Triplet = { 255, 153, 0 };
public const string HexString = "FFFF:9999:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIME
*
*/
public class Lime: HSSFColor
{
public const short Index = 0x32;
public static readonly byte[] Triplet = { 153, 204, 0 };
public const string HexString = "9999:CCCC:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class SEA_GREEN
*
*/
public class SeaGreen: HSSFColor
{
public const short Index = 0x39;
public static readonly byte[] Triplet = { 51, 153, 102 };
public const string HexString = "3333:9999:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class AQUA
*
*/
public class Aqua: HSSFColor
{
public const short Index = 0x31;
public static readonly byte[] Triplet = { 51, 204, 204 };
public const string HexString = "3333:CCCC:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class LightBlue: HSSFColor
{
public const short Index = 0x30;
public static readonly byte[] Triplet = { 51, 102, 255 };
public const string HexString = "3333:6666:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Violet: HSSFColor
{
public const short Index = 0x14;
public const short Index2 = 0x24;
public static readonly byte[] Triplet = { 128, 0, 128 };
public const string HexString = "8080:0:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_40_PERCENT
*
*/
public class Grey40Percent : HSSFColor
{
public const short Index = 0x37;
public static readonly byte[] Triplet = { 150, 150, 150 };
public const string HexString = "9696:9696:9696";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Pink: HSSFColor
{
public const short Index = 0xe;
public const short Index2 = 0x21;
public static readonly byte[] Triplet = { 255, 0, 255 };
public const string HexString = "FFFF:0:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Gold: HSSFColor
{
public const short Index = 0x33;
public static readonly byte[] Triplet = { 255, 204, 0 };
public const string HexString = "FFFF:CCCC:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Yellow: HSSFColor
{
public const short Index = 0xd;
public const short Index2 = 0x22;
public static readonly byte[] Triplet = { 255, 255, 0 };
public const string HexString = "FFFF:FFFF:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class BrightGreen: HSSFColor
{
public const short Index = 0xb;
public const short Index2 = 0x23;
public static readonly byte[] Triplet = { 0, 255, 0 };
public const string HexString = "0:FFFF:0";
public override String GetHexString()
{
return HexString;
}
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
}
/**
* Class TURQUOISE
*
*/
public class Turquoise: HSSFColor
{
public const short Index = 0xf;
public const short Index2 = 0x23;
public static readonly byte[] Triplet = { 0, 255, 255 };
public const string HexString = "0:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class SKY_BLUE
*
*/
public class SkyBlue: HSSFColor
{
public const short Index = 0x28;
public static readonly byte[] Triplet = { 0, 204, 255 };
public const string HexString = "0:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class PLUM
*
*/
public class Plum: HSSFColor
{
public const short Index = 0x3d;
public const short Index2 = 0x19;
public static readonly byte[] Triplet = { 153, 51, 102 };
public const string HexString = "9999:3333:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_25_PERCENT
*
*/
public class Grey25Percent: HSSFColor
{
public const short Index = 0x16;
public static readonly byte[] Triplet = { 192, 192, 192 };
public const string HexString = "C0C0:C0C0:C0C0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ROSE
*
*/
public class Rose: HSSFColor
{
public const short Index = 0x2d;
public static readonly byte[] Triplet = { 255, 153, 204 };
public const string HexString = "FFFF:9999:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class TAN
*
*/
public class Tan: HSSFColor
{
public const short Index = 0x2f;
public static readonly byte[] Triplet = { 255, 204, 153 };
public const string HexString = "FFFF:CCCC:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_YELLOW
*
*/
public class LightYellow: HSSFColor
{
public const short Index = 0x2b;
public static readonly byte[] Triplet = { 255, 255, 153 };
public const string HexString = "FFFF:FFFF:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_GREEN
*
*/
public class LightGreen: HSSFColor
{
public const short Index = 0x2a;
public static readonly byte[] Triplet = { 204, 255, 204 };
public const string HexString = "CCCC:FFFF:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_TURQUOISE
*
*/
public class LightTurquoise: HSSFColor
{
public const short Index = 0x29;
public const short Index2 = 0x1b;
public static readonly byte[] Triplet = { 204, 255, 255 };
public const string HexString = "CCCC:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class PALE_BLUE
*
*/
public class PaleBlue: HSSFColor
{
public const short Index = 0x2c;
public static readonly byte[] Triplet = { 153, 204, 255 };
public const string HexString = "9999:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LAVENDER
*
*/
public class Lavender: HSSFColor
{
public const short Index = 0x2e;
public static readonly byte[] Triplet = { 204, 153, 255 };
public const string HexString = "CCCC:9999:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class WHITE
*
*/
public class White: HSSFColor
{
public const short Index = 0x9;
public static readonly byte[] Triplet = { 255, 255, 255 };
public const string HexString = "FFFF:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class CORNFLOWER_BLUE
*/
public class CornflowerBlue: HSSFColor
{
public const short Index = 0x18;
public static readonly byte[] Triplet = { 153, 153, 255 };
public const string HexString = "9999:9999:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LEMON_CHIFFON
*/
public class LemonChiffon: HSSFColor
{
public const short Index = 0x1a;
public static readonly byte[] Triplet = { 255, 255, 204 };
public const string HexString = "FFFF:FFFF:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class MAROON
*/
public class Maroon: HSSFColor
{
public const short Index = 0x19;
public static readonly byte[] Triplet = { 127, 0, 0 };
public const string HexString = "8000:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ORCHID
*/
public class Orchid: HSSFColor
{
public const short Index = 0x1c;
public static readonly byte[] Triplet = { 102, 0, 102 };
public const string HexString = "6666:0:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class CORAL
*/
public class Coral : HSSFColor
{
public const short Index = 0x1d;
public static readonly byte[] Triplet = { 255, 128, 128 };
public const string HexString = "FFFF:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ROYAL_BLUE
*/
public class RoyalBlue : HSSFColor
{
public const short Index = 0x1e;
public static readonly byte[] Triplet = { 0, 102, 204 };
public const string HexString = "0:6666:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_CORNFLOWER_BLUE
*/
public class LightCornflowerBlue : HSSFColor
{
public const short Index = 0x1f;
public static readonly byte[] Triplet = { 204, 204, 255 };
public const string HexString = "CCCC:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Special Default/Normal/Automatic color.
* <i>Note:</i> This class Is NOT in the default HashTables returned by HSSFColor.
* The index Is a special case which Is interpreted in the various SetXXXColor calls.
*
* @author Jason
*
*/
public class Automatic : HSSFColor
{
private static HSSFColor instance = new Automatic();
public const short Index = 0x40;
public override byte[] GetTriplet()
{
return Black.Triplet;
}
public override String GetHexString()
{
return Black.HexString;
}
public static HSSFColor GetInstance()
{
return instance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Util;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.Android;
using Resource = Android.Resource;
using Trace = System.Diagnostics.Trace;
namespace Xamarin.Forms
{
public static class Forms
{
const int TabletCrossover = 600;
static bool? s_supportsProgress;
static bool? s_isLollipopOrNewer;
public static Context Context { get; internal set; }
public static bool IsInitialized { get; private set; }
internal static bool IsLollipopOrNewer
{
get
{
if (!s_isLollipopOrNewer.HasValue)
s_isLollipopOrNewer = (int)Build.VERSION.SdkInt >= 21;
return s_isLollipopOrNewer.Value;
}
}
internal static bool SupportsProgress
{
get
{
var activity = Context as Activity;
if (!s_supportsProgress.HasValue)
{
int progressCircularId = Context.Resources.GetIdentifier("progress_circular", "id", "android");
if (progressCircularId > 0 && activity != null)
s_supportsProgress = activity.FindViewById(progressCircularId) != null;
else
s_supportsProgress = true;
}
return s_supportsProgress.Value;
}
}
internal static AndroidTitleBarVisibility TitleBarVisibility { get; private set; }
// Provide backwards compat for Forms.Init and AndroidActivity
// Why is bundle a param if never used?
public static void Init(Context activity, Bundle bundle)
{
Assembly resourceAssembly = Assembly.GetCallingAssembly();
SetupInit(activity, resourceAssembly);
}
public static void Init(Context activity, Bundle bundle, Assembly resourceAssembly)
{
SetupInit(activity, resourceAssembly);
}
public static void SetTitleBarVisibility(AndroidTitleBarVisibility visibility)
{
TitleBarVisibility = visibility;
}
public static event EventHandler<ViewInitializedEventArgs> ViewInitialized;
internal static void SendViewInitialized(this VisualElement self, global::Android.Views.View nativeView)
{
EventHandler<ViewInitializedEventArgs> viewInitialized = ViewInitialized;
if (viewInitialized != null)
viewInitialized(self, new ViewInitializedEventArgs { View = self, NativeView = nativeView });
}
static void SetupInit(Context activity, Assembly resourceAssembly)
{
Context = activity;
ResourceManager.Init(resourceAssembly);
// Detect if legacy device and use appropriate accent color
// Hardcoded because could not get color from the theme drawable
var sdkVersion = (int)Build.VERSION.SdkInt;
if (sdkVersion <= 10)
{
// legacy theme button pressed color
Color.Accent = Color.FromHex("#fffeaa0c");
}
else
{
// Holo dark light blue
Color.Accent = Color.FromHex("#ff33b5e5");
}
if (!IsInitialized)
Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c)));
Device.OS = TargetPlatform.Android;
Device.PlatformServices = new AndroidPlatformServices();
// use field and not property to avoid exception in getter
if (Device.info != null)
{
((AndroidDeviceInfo)Device.info).Dispose();
Device.info = null;
}
// probably could be done in a better way
var deviceInfoProvider = activity as IDeviceInfoProvider;
if (deviceInfoProvider != null)
Device.Info = new AndroidDeviceInfo(deviceInfoProvider);
var ticker = Ticker.Default as AndroidTicker;
if (ticker != null)
ticker.Dispose();
Ticker.Default = new AndroidTicker();
if (!IsInitialized)
{
Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute) });
}
int minWidthDp = Context.Resources.Configuration.SmallestScreenWidthDp;
Device.Idiom = minWidthDp >= TabletCrossover ? TargetIdiom.Tablet : TargetIdiom.Phone;
if (ExpressionSearch.Default == null)
ExpressionSearch.Default = new AndroidExpressionSearch();
IsInitialized = true;
}
class AndroidDeviceInfo : DeviceInfo
{
readonly IDeviceInfoProvider _formsActivity;
readonly Size _pixelScreenSize;
readonly double _scalingFactor;
Orientation _previousOrientation = Orientation.Undefined;
public AndroidDeviceInfo(IDeviceInfoProvider formsActivity)
{
_formsActivity = formsActivity;
CheckOrientationChanged(_formsActivity.Resources.Configuration.Orientation);
formsActivity.ConfigurationChanged += ConfigurationChanged;
using (DisplayMetrics display = formsActivity.Resources.DisplayMetrics)
{
_scalingFactor = display.Density;
_pixelScreenSize = new Size(display.WidthPixels, display.HeightPixels);
ScaledScreenSize = new Size(_pixelScreenSize.Width / _scalingFactor, _pixelScreenSize.Width / _scalingFactor);
}
}
public override Size PixelScreenSize
{
get { return _pixelScreenSize; }
}
public override Size ScaledScreenSize { get; }
public override double ScalingFactor
{
get { return _scalingFactor; }
}
protected override void Dispose(bool disposing)
{
_formsActivity.ConfigurationChanged -= ConfigurationChanged;
base.Dispose(disposing);
}
void CheckOrientationChanged(Orientation orientation)
{
if (!_previousOrientation.Equals(orientation))
CurrentOrientation = orientation.ToDeviceOrientation();
_previousOrientation = orientation;
}
void ConfigurationChanged(object sender, EventArgs e)
{
CheckOrientationChanged(_formsActivity.Resources.Configuration.Orientation);
}
}
class AndroidExpressionSearch : ExpressionVisitor, IExpressionSearch
{
List<object> _results;
Type _targetType;
public List<T> FindObjects<T>(Expression expression) where T : class
{
_results = new List<object>();
_targetType = typeof(T);
Visit(expression);
return _results.Select(o => o as T).ToList();
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is ConstantExpression && node.Member is FieldInfo)
{
object container = ((ConstantExpression)node.Expression).Value;
object value = ((FieldInfo)node.Member).GetValue(container);
if (_targetType.IsInstanceOfType(value))
_results.Add(value);
}
return base.VisitMember(node);
}
}
class AndroidPlatformServices : IPlatformServices
{
static readonly MD5CryptoServiceProvider Checksum = new MD5CryptoServiceProvider();
double _buttonDefaultSize;
double _editTextDefaultSize;
double _labelDefaultSize;
double _largeSize;
double _mediumSize;
double _microSize;
double _smallSize;
public void BeginInvokeOnMainThread(Action action)
{
var activity = Context as Activity;
if (activity != null)
activity.RunOnUiThread(action);
}
public Ticker CreateTicker()
{
return new AndroidTicker();
}
public Assembly[] GetAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies();
}
public string GetMD5Hash(string input)
{
byte[] bytes = Checksum.ComputeHash(Encoding.UTF8.GetBytes(input));
var ret = new char[32];
for (var i = 0; i < 16; i++)
{
ret[i * 2] = (char)Hex(bytes[i] >> 4);
ret[i * 2 + 1] = (char)Hex(bytes[i] & 0xf);
}
return new string(ret);
}
public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes)
{
if (_smallSize == 0)
{
_smallSize = ConvertTextAppearanceToSize(Resource.Attribute.TextAppearanceSmall, Resource.Style.TextAppearanceDeviceDefaultSmall, 12);
_mediumSize = ConvertTextAppearanceToSize(Resource.Attribute.TextAppearanceMedium, Resource.Style.TextAppearanceDeviceDefaultMedium, 14);
_largeSize = ConvertTextAppearanceToSize(Resource.Attribute.TextAppearanceLarge, Resource.Style.TextAppearanceDeviceDefaultLarge, 18);
_buttonDefaultSize = ConvertTextAppearanceToSize(Resource.Attribute.TextAppearanceButton, Resource.Style.TextAppearanceDeviceDefaultWidgetButton, 14);
_editTextDefaultSize = ConvertTextAppearanceToSize(Resource.Style.TextAppearanceWidgetEditText, Resource.Style.TextAppearanceDeviceDefaultWidgetEditText, 18);
_labelDefaultSize = _smallSize;
// as decreed by the android docs, ALL HAIL THE ANDROID DOCS, ALL GLORY TO THE DOCS, PRAISE HYPNOTOAD
_microSize = Math.Max(1, _smallSize - (_mediumSize - _smallSize));
}
if (useOldSizes)
{
switch (size)
{
case NamedSize.Default:
if (typeof(Button).IsAssignableFrom(targetElementType))
return _buttonDefaultSize;
if (typeof(Label).IsAssignableFrom(targetElementType))
return _labelDefaultSize;
if (typeof(Editor).IsAssignableFrom(targetElementType) || typeof(Entry).IsAssignableFrom(targetElementType) || typeof(SearchBar).IsAssignableFrom(targetElementType))
return _editTextDefaultSize;
return 14;
case NamedSize.Micro:
return 10;
case NamedSize.Small:
return 12;
case NamedSize.Medium:
return 14;
case NamedSize.Large:
return 18;
default:
throw new ArgumentOutOfRangeException("size");
}
}
switch (size)
{
case NamedSize.Default:
if (typeof(Button).IsAssignableFrom(targetElementType))
return _buttonDefaultSize;
if (typeof(Label).IsAssignableFrom(targetElementType))
return _labelDefaultSize;
if (typeof(Editor).IsAssignableFrom(targetElementType) || typeof(Entry).IsAssignableFrom(targetElementType))
return _editTextDefaultSize;
return _mediumSize;
case NamedSize.Micro:
return _microSize;
case NamedSize.Small:
return _smallSize;
case NamedSize.Medium:
return _mediumSize;
case NamedSize.Large:
return _largeSize;
default:
throw new ArgumentOutOfRangeException("size");
}
}
public async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken))
return await response.Content.ReadAsStreamAsync();
}
public IIsolatedStorageFile GetUserStoreForApplication()
{
return new _IsolatedStorageFile(IsolatedStorageFile.GetUserStoreForApplication());
}
public bool IsInvokeRequired
{
get
{
return Looper.MainLooper != Looper.MyLooper();
}
}
public void OpenUriAction(Uri uri)
{
global::Android.Net.Uri aUri = global::Android.Net.Uri.Parse(uri.ToString());
var intent = new Intent(Intent.ActionView, aUri);
Context.StartActivity(intent);
}
public void StartTimer(TimeSpan interval, Func<bool> callback)
{
Timer timer = null;
TimerCallback onTimeout = o => BeginInvokeOnMainThread(() =>
{
if (callback())
return;
timer.Dispose();
});
timer = new Timer(onTimeout, null, interval, interval);
}
double ConvertTextAppearanceToSize(int themeDefault, int deviceDefault, double defaultValue)
{
double myValue;
if (TryGetTextAppearance(themeDefault, out myValue))
return myValue;
if (TryGetTextAppearance(deviceDefault, out myValue))
return myValue;
return defaultValue;
}
static int Hex(int v)
{
if (v < 10)
return '0' + v;
return 'a' + v - 10;
}
static bool TryGetTextAppearance(int appearance, out double val)
{
val = 0;
try
{
using (var value = new TypedValue())
{
if (Context.Theme.ResolveAttribute(appearance, value, true))
{
var textSizeAttr = new[] { Resource.Attribute.TextSize };
const int indexOfAttrTextSize = 0;
using (TypedArray array = Context.ObtainStyledAttributes(value.Data, textSizeAttr))
{
val = Context.FromPixels(array.GetDimensionPixelSize(indexOfAttrTextSize, -1));
return true;
}
}
}
}
catch (Exception ex)
{
Log.Warning("Xamarin.Forms.Platform.Android.AndroidPlatformServices", "Error retrieving text appearance: {0}", ex);
}
return false;
}
public class _Timer : ITimer
{
readonly Timer _timer;
public _Timer(Timer timer)
{
_timer = timer;
}
public void Change(int dueTime, int period)
{
_timer.Change(dueTime, period);
}
public void Change(long dueTime, long period)
{
_timer.Change(dueTime, period);
}
public void Change(TimeSpan dueTime, TimeSpan period)
{
_timer.Change(dueTime, period);
}
public void Change(uint dueTime, uint period)
{
_timer.Change(dueTime, period);
}
}
public class _IsolatedStorageFile : IIsolatedStorageFile
{
readonly IsolatedStorageFile _isolatedStorageFile;
public _IsolatedStorageFile(IsolatedStorageFile isolatedStorageFile)
{
_isolatedStorageFile = isolatedStorageFile;
}
public Task CreateDirectoryAsync(string path)
{
_isolatedStorageFile.CreateDirectory(path);
return Task.FromResult(true);
}
public Task<bool> GetDirectoryExistsAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.DirectoryExists(path));
}
public Task<bool> GetFileExistsAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.FileExists(path));
}
public Task<DateTimeOffset> GetLastWriteTimeAsync(string path)
{
return Task.FromResult(_isolatedStorageFile.GetLastWriteTime(path));
}
public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access)
{
Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access);
return Task.FromResult(stream);
}
public Task<Stream> OpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share)
{
Stream stream = _isolatedStorageFile.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share);
return Task.FromResult(stream);
}
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.Util;
package com.quantconnect.lean.Lean.Engine.DataFeeds.Enumerators
{
/**
* The FillForwardEnumerator wraps an existing base data enumerator and inserts extra 'base data' instances
* on a specified fill forward resolution
*/
public class FillForwardEnumerator : IEnumerator<BaseData>
{
private DateTime? _delistedTime;
private BaseData _previous;
private boolean _isFillingForward;
private boolean _emittedAuxilliaryData;
private final Duration _dataResolution;
private final boolean _isExtendedMarketHours;
private final DateTime _subscriptionEndTime;
private final IEnumerator<BaseData> _enumerator;
private final IReadOnlyRef<TimeSpan> _fillForwardResolution;
/**
* The exchange used to determine when to insert fill forward data
*/
protected final SecurityExchange Exchange;
/**
* Initializes a new instance of the <see cref="FillForwardEnumerator"/> class that accepts
* a reference to the fill forward resolution, useful if the fill forward resolution is dynamic
* and changing as the enumeration progresses
*/
* @param enumerator The source enumerator to be filled forward
* @param exchange The exchange used to determine when to insert fill forward data
* @param fillForwardResolution The resolution we'd like to receive data on
* @param isExtendedMarketHours True to use the exchange's extended market hours, false to use the regular market hours
* @param subscriptionEndTime The end time of the subscrition, once passing this date the enumerator will stop
* @param dataResolution The source enumerator's data resolution
public FillForwardEnumerator(IEnumerator<BaseData> enumerator,
SecurityExchange exchange,
IReadOnlyRef<TimeSpan> fillForwardResolution,
boolean isExtendedMarketHours,
DateTime subscriptionEndTime,
Duration dataResolution
) {
_subscriptionEndTime = subscriptionEndTime;
Exchange = exchange;
_enumerator = enumerator;
_dataResolution = dataResolution;
_fillForwardResolution = fillForwardResolution;
_isExtendedMarketHours = isExtendedMarketHours;
}
/**
* Gets the element in the collection at the current position of the enumerator.
*/
@returns
* The element in the collection at the current position of the enumerator.
*
public BaseData Current
{
get;
private set;
}
/**
* Gets the current element in the collection.
*/
@returns
* The current element in the collection.
*
* <filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
/**
* Advances the enumerator to the next element of the collection.
*/
@returns
* true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
*
* <exception cref="T:System.InvalidOperationException The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public boolean MoveNext() {
if( _delistedTime.HasValue) {
// don't fill forward after data after the delisted date
if( _previous == null || _previous.EndTime >= _delistedTime.Value) {
return false;
}
}
if( !_emittedAuxilliaryData && Current != null ) {
// only set the _previous if the last item we emitted was NOT auxilliary data,
// since _previous is used for fill forward behavior
_previous = Current;
}
BaseData fillForward;
if( !_isFillingForward) {
// if we're filling forward we don't need to move next since we haven't emitted _enumerator.Current yet
if( !_enumerator.MoveNext()) {
if( _delistedTime.HasValue) {
// don't fill forward delisted data
return false;
}
// check to see if we ran out of data before the end of the subscription
if( _previous == null || _previous.EndTime >= _subscriptionEndTime) {
// we passed the end of subscription, we're finished
return false;
}
// we can fill forward the rest of this subscription if required
endOfSubscription = (Current ?? _previous).Clone(true);
endOfSubscription.Time = _subscriptionEndTime.RoundDown(_dataResolution);
endOfSubscription.EndTime = endOfSubscription.Time + _dataResolution;
if( RequiresFillForwardData(_fillForwardResolution.Value, _previous, endOfSubscription, out fillForward)) {
// don't mark as filling forward so we come back into this block, subscription is done
//_isFillingForward = true;
Current = fillForward;
_emittedAuxilliaryData = false;
return true;
}
// don't emit the last bar if the market isn't considered open!
if( !Exchange.IsOpenDuringBar(endOfSubscription.Time, endOfSubscription.EndTime, _isExtendedMarketHours)) {
return false;
}
Current = endOfSubscription;
_emittedAuxilliaryData = false;
return true;
}
}
underlyingCurrent = _enumerator.Current;
if( _previous == null ) {
// first data point we dutifully emit without modification
Current = underlyingCurrent;
return true;
}
if( underlyingCurrent != null && underlyingCurrent.DataType == MarketDataType.Auxiliary) {
_emittedAuxilliaryData = true;
Current = underlyingCurrent;
delisting = Current as Delisting;
if( delisting != null && delisting.Type == DelistingType.Delisted) {
_delistedTime = delisting.EndTime;
}
return true;
}
_emittedAuxilliaryData = false;
if( RequiresFillForwardData(_fillForwardResolution.Value, _previous, underlyingCurrent, out fillForward)) {
// we require fill forward data because the _enumerator.Current is too far in future
_isFillingForward = true;
Current = fillForward;
return true;
}
_isFillingForward = false;
Current = underlyingCurrent;
return true;
}
/**
* Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
*/
* <filterpriority>2</filterpriority>
public void Dispose() {
_enumerator.Dispose();
}
/**
* Sets the enumerator to its initial position, which is before the first element in the collection.
*/
* <exception cref="T:System.InvalidOperationException The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public void Reset() {
_enumerator.Reset();
}
/**
* Determines whether or not fill forward is required, and if true, will produce the new fill forward data
*/
* @param fillForwardResolution">
* @param previous The last piece of data emitted by this enumerator
* @param next The next piece of data on the source enumerator
* @param fillForward When this function returns true, this will have a non-null value, null when the function returns false
@returns True when a new fill forward piece of data was produced and should be emitted by this enumerator
protected boolean RequiresFillForwardData(TimeSpan fillForwardResolution, BaseData previous, BaseData next, out BaseData fillForward) {
if( next.EndTime < previous.Time) {
throw new IllegalArgumentException( "FillForwardEnumerator received data out of order. Symbol: " + previous.Symbol.ID);
}
// check to see if the gap between previous and next warrants fill forward behavior
if( next.Time - previous.Time <= fillForwardResolution) {
fillForward = null;
return false;
}
// is the bar after previous in market hours?
barAfterPreviousEndTime = previous.EndTime + fillForwardResolution;
if( Exchange.IsOpenDuringBar(previous.EndTime, barAfterPreviousEndTime, _isExtendedMarketHours)) {
// this is the normal case where we had a hole in the middle of the day
fillForward = previous.Clone(true);
fillForward.Time = (previous.Time + fillForwardResolution).RoundDown(fillForwardResolution);
fillForward.EndTime = fillForward.Time + _dataResolution;
return true;
}
// find the next fill forward time after the next market open
nextFillForwardTime = Exchange.Hours.GetNextMarketOpen(previous.EndTime, _isExtendedMarketHours) + fillForwardResolution;
if( _dataResolution == Duration.ofDays( 1 )) {
// special case for daily, we need to emit a midnight bar even though markets are closed
dailyBarEnd = GetNextOpenDateAfter(previous.Time.Date) + Duration.ofDays( 1 );
if( dailyBarEnd < nextFillForwardTime) {
// only emit the midnight bar if it's the next bar to be emitted
nextFillForwardTime = dailyBarEnd;
}
}
if( nextFillForwardTime < next.EndTime) {
// if next is still in the future then we need to emit a fill forward for market open
fillForward = previous.Clone(true);
fillForward.Time = (nextFillForwardTime - _dataResolution).RoundDown(fillForwardResolution);
fillForward.EndTime = fillForward.Time + _dataResolution;
return true;
}
// the next is before the next fill forward time, so do nothing
fillForward = null;
return false;
}
/**
* Finds the next open date that follows the specified date, this functions expects a date, not a date time
*/
private DateTime GetNextOpenDateAfter(DateTime date) {
do
{
date = date + Duration.ofDays( 1 );
}
while (!Exchange.DateIsOpen(date));
return date;
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
using System.Xml;
using System.IO;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaChemHemDao : IChemHemDao
{
AbstractConnection cxn;
public VistaChemHemDao(AbstractConnection cxn)
{
this.cxn = cxn;
}
public IList<ChemHemReport> getChemHemReportsVPR(string fromDate, string toDate)
{
VistaClinicalDao clinicalDao = new VistaClinicalDao(this.cxn);
string results = clinicalDao.getNhinData("lab");
ChemHemReport rpt = new ChemHemReport();
(toLabReportsVPR(results, ref rpt)).CopyTo(rpt.Results, 0);
return new List<ChemHemReport>() { rpt };
}
internal IList<LabResult> toLabReportsVPR(string xml, ref ChemHemReport rpt)
{
IList<LabResult> rpts = new List<LabResult>();
int numRecs = 0;
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
while (reader.Read())
{
if (numRecs > 0)
{
while (!reader.EOF && rpts.Count < numRecs)
{
rpts.Add(readLab(reader, ref rpt));
}
}
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (String.Equals(reader.Name, "labs", StringComparison.CurrentCultureIgnoreCase))
{
if (reader.AttributeCount > 0)
{
string count = reader.GetAttribute("total");
if (!Int32.TryParse(reader.Value, out numRecs))
{
throw new XmlException("Unexpected format - could not determine number of results\r\n" + xml);
}
}
}
break;
case XmlNodeType.EndElement:
if (String.Equals(reader.Name, "labs", StringComparison.CurrentCultureIgnoreCase))
{
continue;
}
if (String.Equals(reader.Name, "results", StringComparison.CurrentCultureIgnoreCase))
{
return rpts;
}
break;
//case XmlNodeType.Comment:
// break;
//case XmlNodeType.Document:
// break;
//case XmlNodeType.Text:
// break;
default:
break;
}
}
}
return rpts;
}
// it appears we're missing local IEN that maps to LabReport.Id
LabResult readLab(XmlReader reader, ref ChemHemReport rpt)
{
LabResult result = new LabResult();
result.Test = new LabTest();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && String.Equals(reader.Name, "lab", StringComparison.CurrentCultureIgnoreCase))
{
break;
}
switch (reader.Name)
{
case "collected":
if (reader.HasAttributes)
{
rpt.Specimen.CollectionDate = reader.GetAttribute("value");
}
break;
case "comment":
result.Comment = reader.GetAttribute("value");
break;
case "facility":
if (reader.HasAttributes)
{
rpt.Facility = new SiteId(reader.GetAttribute("code"), reader.GetAttribute("name"));
}
break;
case "groupName":
if (reader.HasAttributes)
{
rpt.Specimen.AccessionNumber = reader.GetAttribute("value");
}
break;
case "high":
result.Test.HiRef = reader.GetAttribute("value");
break;
case "id":
if (reader.HasAttributes)
{
rpt.Id = reader.GetAttribute("value"); // not the same as old ChemHemRpts ID!!!
}
break;
case "interpretation":
break;
case "labOrderID":
break;
case "localName":
result.Test.ShortName = reader.GetAttribute("value");
break;
case "loinc":
result.Test.Loinc = reader.GetAttribute("value");
break;
case "low":
result.Test.LowRef = reader.GetAttribute("value");
break;
case "orderID":
break;
case "result":
result.Value = reader.GetAttribute("value");
break;
case "resulted":
if (reader.HasAttributes)
{
rpt.Timestamp = reader.GetAttribute("value");
}
break;
case "specimen":
rpt.Specimen.Name = reader.GetAttribute("name");
break;
case "status":
// place to put this?
break;
case "test":
result.Test.Name = reader.GetAttribute("value");
break;
case "type":
// place to put this??
break;
case "units":
result.Test.Units = reader.GetAttribute("value");
break;
case "vuid":
// TBD - where to put this?
break;
}
}
return result;
}
//=========================================================================================
// Chem/Hem DDR + CPRS RPC
//=========================================================================================
public ChemHemReport[] getChemHemReports(string fromDate, string toDate)
{
return getChemHemReports(cxn.Pid, fromDate, toDate);
}
/*
* In order to get the correct results with the correct reports using the DDR calls and RPCs
* available, we are going to use the user specified fromDate but use today as the toDate (like
* CPRS does) and retrieve all the specimens with in that time period. Then, we will find the
* reports, match them up with their specimens and lastly filter those results using our original
* date range
*/
public ChemHemReport[] getChemHemReports(string dfn, string fromDate, string toDate)
{
if (!String.IsNullOrEmpty(toDate) && toDate.IndexOf(".") == -1)
{
toDate += ".235959";
}
IndexedHashtable specimens = getChemHemSpecimens(dfn, fromDate, toDate, "3");
if (specimens == null || specimens.Count == 0)
{
return null;
}
ArrayList lst = new ArrayList();
//string nextDate = VistaTimestamp.fromUtcString(today);
string nextDate = VistaTimestamp.fromUtcString(toDate);
// Due to comment above, we want to loop through "ORWLRR INTERIMG" RPC until we
// get as many reports as the DDR call above told us we would
// TBD - this while statement screams infinite loop (i.e. what happens if we don't get all the
// reports the DDR call above said we would?) Should we put an arbitrarily large stop in here?
// e.g. if count > 1,000,000 then throw an exception that we didn't get what VistA said we should?
int i = 0;
while (lst.Count < specimens.Count)
{
LabSpecimen specimen = (LabSpecimen)specimens.GetValue(i);
// ORWLRR INTERIMG rpc and function below updates nextDate for subsequent calls so LEAVE REF ALONE
string nextDateBefore = nextDate;
ChemHemReport rpt = getChemHemReport(dfn, ref nextDate);
if (rpt != null)
{
if ((rpt.Specimen != null) && (rpt.Specimen.AccessionNumber == specimen.AccessionNumber))
{
i++;
rpt.Id = specimen.Id;
rpt.Facility = specimen.Facility;
rpt.Specimen = specimen;
rpt.Timestamp = specimen.ReportDate;
lst.Add(rpt);
}
}
// if the next date variable was not changed below, it means we are no longer looping through
// the reports so we should go ahead and break out of this loop - should take care of
// infinite loop concerns
if (nextDate.Equals(nextDateBefore))
{
break;
}
}
// At last, filter the reports based on their timestamps
ArrayList filteredList = new ArrayList();
double startDate = Convert.ToDouble(fromDate);
double stopDate = Convert.ToDouble(toDate);
ChemHemReport[] rpts = (ChemHemReport[])lst.ToArray(typeof(ChemHemReport));
foreach (ChemHemReport report in rpts)
{
// if the report doesn't have a timestamp, we will just add it to our list
if(String.IsNullOrEmpty(report.Timestamp))
{
filteredList.Add(report);
continue;
}
double reportTimeStamp = Convert.ToDouble(report.Timestamp);
if (startDate <= reportTimeStamp && reportTimeStamp <= stopDate)
{
filteredList.Add(report);
}
}
return (ChemHemReport[])filteredList.ToArray(typeof(ChemHemReport));
}
internal IndexedHashtable getChemHemSpecimens(string dfn, string fromDate, string toDate, string pieceNum)
{
VistaLabsDao labsDao = new VistaLabsDao(cxn);
string lrdfn = labsDao.getLrDfn(dfn);
if (lrdfn == "")
{
return null;
}
DdrLister query = buildGetChemHemSpecimensQuery(lrdfn, fromDate, toDate, pieceNum);
string[] response = query.execute();
return toChemHemSpecimens(response, ref fromDate, ref toDate);
}
internal DdrLister buildGetChemHemSpecimensQuery(string lrdfn, string fromDate, string toDate, string pieceNum)
{
DateUtils.CheckDateRange(fromDate, toDate);
DdrLister query = new DdrLister(cxn);
query.File = "63.04";
query.Iens = "," + lrdfn + ",";
// E flag note
// .01 - DATE/TIME SPECIMEN TAKEN
// .03 - DATE REPORT COMPLETED
// .05 - SPECIMEN TYPE
// .06 - ACCESSION
// .08 - METHOD OR SITE
// .112 - ACCESSIONING INSTITUTION
query.Fields = ".01;.03;.05E;.06;.08;.112E";
query.Flags = "IP";
query.Xref = "#";
query.Screen = buildChemHemSpecimensScreenParam(fromDate, toDate, pieceNum);
query.Id = "S X=$P(^(0),U,14) I X'= \"\" S Y=$P($G(^DIC(4,X,99)),U,1) D EN^DDIOL(Y)";
return query;
}
internal string buildChemHemSpecimensScreenParam(string fromDate, string toDate, string pieceNum)
{
if (fromDate == "")
{
return "";
}
fromDate = VistaTimestamp.fromUtcFromDate(fromDate);
toDate = VistaTimestamp.fromUtcToDate(toDate);
return "S FD=" + fromDate + ",TD=" + toDate + ",CDT=$P(^(0),U," + pieceNum + ") I CDT>=FD,CDT<TD";
}
internal IndexedHashtable toChemHemSpecimens(string[] response, ref string fromDate, ref string toDate)
{
IndexedHashtable result = new IndexedHashtable(response.Length);
for (int i = 0; i < response.Length; i++)
{
string[] flds = StringUtils.split(response[i], StringUtils.CARET);
LabSpecimen specimen = new LabSpecimen();
specimen.Id = flds[0];
specimen.ReportDate = VistaTimestamp.toUtcString(flds[2]);
specimen.CollectionDate = VistaTimestamp.toUtcString(flds[1]);
if (i == 0)
{
fromDate = specimen.CollectionDate;
}
if (i == response.Length-1)
{
toDate = specimen.CollectionDate;
}
specimen.Name = flds[3];
specimen.AccessionNumber = flds[4];
if (flds.Length > 6)
{
specimen.Site = flds[5];
}
if (flds.Length > 7)
{
specimen.Facility = new SiteId(flds[7], flds[6]);
}
string key = flds[1] + '^' + flds[4];
result.Add(key, specimen);
}
return result;
}
public ChemHemReport getChemHemReport(string dfn, ref string nextDate)
{
MdoQuery request = buildGetChemHemReportRequest(dfn, nextDate);
string response = (string)cxn.query(request);
return toChemHemReport(response, ref nextDate);
}
// Do not check DFN here. This is called by getChemHemReports which checks DFN.
// Also, all this will be replaced by the NHIN RPC.
internal MdoQuery buildGetChemHemReportRequest(string dfn, string nextDate)
{
VistaUtils.CheckRpcParams(dfn);
//if (String.IsNullOrEmpty(nextDate) || !VistaTimestamp.isValid(nextDate))
//{
// throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid 'next' date: " + nextDate);
//}
VistaQuery vq = new VistaQuery("ORWLRR INTERIMG");
vq.addParameter(vq.LITERAL, dfn);
vq.addParameter(vq.LITERAL, nextDate);
vq.addParameter(vq.LITERAL, "1");
vq.addParameter(vq.LITERAL, "1");
return vq;
}
internal ChemHemReport toChemHemReport(string response, ref string nextDate)
{
if (String.IsNullOrEmpty(response))
{
return null;
}
string[] lines = StringUtils.split(response, StringUtils.CRLF);
lines = StringUtils.trimArray(lines);
string[] flds = StringUtils.split(lines[0], StringUtils.CARET);
nextDate = flds[2];
if (flds[1] != "CH")
{
return null;
}
if (lines.Length == 1)
{
return null;
}
int ntests = Convert.ToInt16(flds[0]);
ChemHemReport rpt = new ChemHemReport();
rpt.Id = flds[2] + '^' + flds[5];
rpt.Timestamp = flds[2];
rpt.Specimen = new LabSpecimen();
rpt.Specimen.CollectionDate = VistaTimestamp.toUtcString(flds[2]);
rpt.Specimen.Name = flds[4];
rpt.Specimen.AccessionNumber = flds[5];
rpt.Author = new Author();
rpt.Author.Name = flds[6];
int lineIdx = 1;
for (lineIdx = 1; lineIdx <= ntests; lineIdx++)
{
LabResult lr = new LabResult();
flds = StringUtils.split(lines[lineIdx], StringUtils.CARET);
if (flds.Length < 6)
{
continue;
}
lr.Test = new LabTest();
lr.Test.Id = flds[0];
lr.Test.Name = flds[1];
lr.Value = flds[2].Trim();
lr.BoundaryStatus = flds[3];
lr.Test.Units = flds[4].Trim();
lr.Test.RefRange = flds[5];
// MHV patch - probably no one needs this
lr.LabSiteId = cxn.DataSource.SiteId.Id;
rpt.AddResult(lr);
}
rpt.Comment = "";
while (lineIdx < lines.Length)
{
rpt.Comment += lines[lineIdx++].TrimStart() + "\r\n";
}
return rpt;
}
//=========================================================================================
// Chem/Hem RDV
//=========================================================================================
public ChemHemReport[] getChemHemReports(string fromDate, string toDate, int nrpts)
{
return getChemHemReports(cxn.Pid, fromDate, toDate, nrpts);
}
public ChemHemReport[] getChemHemReports(string dfn, string fromDate, string toDate, int nrpts)
{
MdoQuery request = buildChemHemReportsRequest(dfn, fromDate, toDate, nrpts);
string response = (string)cxn.query(request);
return toChemHemReports(response);
}
internal MdoQuery buildChemHemReportsRequest(string dfn, string fromDate, string toDate, int nrpts)
{
return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nrpts, "OR_CH:CHEM & HEMATOLOGY~CH;ORDV02;3;");
}
internal ChemHemReport[] toChemHemReports(string response)
{
if (response == "")
{
return null;
}
DictionaryHashList lst = new DictionaryHashList();
string[] lines = StringUtils.split(response, StringUtils.CRLF);
lines = StringUtils.trimArray(lines);
ChemHemReport rpt = null;
LabResult rslt = null;
string ts = "";
string facilityTag = "";
string facilityName = "";
for (int i = 0; i < lines.Length; i++)
{
string[] flds = StringUtils.split(lines[i], StringUtils.CARET);
if (!StringUtils.isNumeric(flds[0]))
{
throw new DataMisalignedException("Invalid fldnum: " + flds[0] + " in lines[" + i + "]");
}
int fldnum = Convert.ToInt32(flds[0]);
switch (fldnum)
{
case 1:
string[] parts = StringUtils.split(flds[1], StringUtils.SEMICOLON);
if (parts.Length == 2)
{
facilityTag = parts[1];
facilityName = parts[0];
}
else if (flds[1] != "")
{
facilityTag = cxn.DataSource.SiteId.Id;
facilityName = flds[1];
}
else
{
facilityTag = cxn.DataSource.SiteId.Id;
facilityName = cxn.DataSource.SiteId.Name;
}
break;
case 2:
if (rpt != null)
{
if (StringUtils.isEmpty(rslt.Test.RefRange))
{
if (!StringUtils.isEmpty(rslt.Test.LowRef) &&
!StringUtils.isEmpty(rslt.Test.HiRef))
{
rslt.Test.RefRange = rslt.Test.LowRef + " - " + rslt.Test.HiRef;
}
}
rpt.AddResult(rslt);
}
rslt = new LabResult();
rslt.Test = new LabTest();
ts = VistaTimestamp.toUtcFromRdv(flds[1]);
if (lst[ts] == null)
{
rpt = new ChemHemReport();
rpt.Facility = new SiteId(facilityTag, facilityName);
rpt.Timestamp = ts;
lst.Add(ts, rpt);
}
break;
case 3:
if (flds.Length == 2)
{
rslt.Test.Name = flds[1];
}
break;
case 4:
if (flds.Length == 2)
{
if (null != rslt)
rslt.SpecimenType = flds[1];
}
break;
case 5:
if (flds.Length == 2)
{
rslt.Value = flds[1];
}
break;
case 6:
if (flds.Length == 2)
{
rslt.BoundaryStatus = flds[1];
}
break;
case 7:
if (flds.Length == 2)
{
rslt.Test.Units = flds[1];
}
break;
case 8:
if (flds.Length == 2)
{
rslt.Test.LowRef = flds[1];
}
break;
case 9:
if (flds.Length == 2)
{
rslt.Test.HiRef = flds[1];
}
break;
case 10:
if (flds.Length == 2)
{
rslt.Comment += flds[1] + '\n';
}
break;
}
}
if (rpt != null)
{
if (StringUtils.isEmpty(rslt.Test.RefRange))
{
if (!StringUtils.isEmpty(rslt.Test.LowRef) &&
!StringUtils.isEmpty(rslt.Test.HiRef))
{
rslt.Test.RefRange = rslt.Test.LowRef + " - " + rslt.Test.HiRef;
}
}
rpt.AddResult(rslt);
}
ChemHemReport[] result = new ChemHemReport[lst.Count];
for (int i = 0; i < lst.Count; i++)
{
DictionaryEntry de = lst[i];
result[i] = (ChemHemReport)de.Value;
}
return result;
}
public Dictionary<string, HashSet<string>> getNewChemHemReports(DateTime start)
{
throw new NotImplementedException();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework.Monitoring.Interfaces;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Collects sim statistics which aren't already being collected for the linden viewer's statistics pane
/// </summary>
public class SimExtraStatsCollector : BaseStatsCollector
{
// private long assetsInCache;
// private long texturesInCache;
// private long assetCacheMemoryUsage;
// private long textureCacheMemoryUsage;
// private TimeSpan assetRequestTimeAfterCacheMiss;
// private long blockedMissingTextureRequests;
// private long assetServiceRequestFailures;
// private long inventoryServiceRetrievalFailures;
private volatile float timeDilation;
private volatile float simFps;
private volatile float physicsFps;
private volatile float agentUpdates;
private volatile float rootAgents;
private volatile float childAgents;
private volatile float totalPrims;
private volatile float activePrims;
private volatile float totalFrameTime;
private volatile float netFrameTime;
private volatile float physicsFrameTime;
private volatile float otherFrameTime;
private volatile float imageFrameTime;
private volatile float inPacketsPerSecond;
private volatile float outPacketsPerSecond;
private volatile float unackedBytes;
private volatile float agentFrameTime;
private volatile float pendingDownloads;
private volatile float pendingUploads;
private volatile float activeScripts;
private volatile float spareTime;
private volatile float sleepTime;
private volatile float physicsStep;
private volatile float scriptLinesPerSecond;
private volatile float m_frameDilation;
private volatile float m_usersLoggingIn;
private volatile float m_totalGeoPrims;
private volatile float m_totalMeshes;
private volatile float m_inUseThreads;
// /// <summary>
// /// These statistics are being collected by push rather than pull. Pull would be simpler, but I had the
// /// notion of providing some flow statistics (which pull wouldn't give us). Though admittedly these
// /// haven't yet been implemented...
// /// </summary>
// public long AssetsInCache { get { return assetsInCache; } }
//
// /// <value>
// /// Currently unused
// /// </value>
// public long TexturesInCache { get { return texturesInCache; } }
//
// /// <value>
// /// Currently misleading since we can't currently subtract removed asset memory usage without a performance hit
// /// </value>
// public long AssetCacheMemoryUsage { get { return assetCacheMemoryUsage; } }
//
// /// <value>
// /// Currently unused
// /// </value>
// public long TextureCacheMemoryUsage { get { return textureCacheMemoryUsage; } }
public float TimeDilation { get { return timeDilation; } }
public float SimFps { get { return simFps; } }
public float PhysicsFps { get { return physicsFps; } }
public float AgentUpdates { get { return agentUpdates; } }
public float RootAgents { get { return rootAgents; } }
public float ChildAgents { get { return childAgents; } }
public float TotalPrims { get { return totalPrims; } }
public float ActivePrims { get { return activePrims; } }
public float TotalFrameTime { get { return totalFrameTime; } }
public float NetFrameTime { get { return netFrameTime; } }
public float PhysicsFrameTime { get { return physicsFrameTime; } }
public float OtherFrameTime { get { return otherFrameTime; } }
public float ImageFrameTime { get { return imageFrameTime; } }
public float InPacketsPerSecond { get { return inPacketsPerSecond; } }
public float OutPacketsPerSecond { get { return outPacketsPerSecond; } }
public float UnackedBytes { get { return unackedBytes; } }
public float AgentFrameTime { get { return agentFrameTime; } }
public float PendingDownloads { get { return pendingDownloads; } }
public float PendingUploads { get { return pendingUploads; } }
public float ActiveScripts { get { return activeScripts; } }
public float ScriptLinesPerSecond { get { return scriptLinesPerSecond; } }
// /// <summary>
// /// This is the time it took for the last asset request made in response to a cache miss.
// /// </summary>
// public TimeSpan AssetRequestTimeAfterCacheMiss { get { return assetRequestTimeAfterCacheMiss; } }
//
// /// <summary>
// /// Number of persistent requests for missing textures we have started blocking from clients. To some extent
// /// this is just a temporary statistic to keep this problem in view - the root cause of this lies either
// /// in a mishandling of the reply protocol, related to avatar appearance or may even originate in graphics
// /// driver bugs on clients (though this seems less likely).
// /// </summary>
// public long BlockedMissingTextureRequests { get { return blockedMissingTextureRequests; } }
//
// /// <summary>
// /// Record the number of times that an asset request has failed. Failures are effectively exceptions, such as
// /// request timeouts. If an asset service replies that a particular asset cannot be found, this is not counted
// /// as a failure
// /// </summary>
// public long AssetServiceRequestFailures { get { return assetServiceRequestFailures; } }
/// <summary>
/// Number of known failures to retrieve avatar inventory from the inventory service. This does not
/// cover situations where the inventory service accepts the request but never returns any data, since
/// we do not yet timeout this situation.
/// </summary>
/// <remarks>Commented out because we do not cache inventory at this point</remarks>
// public long InventoryServiceRetrievalFailures { get { return inventoryServiceRetrievalFailures; } }
/// <summary>
/// Retrieve the total frame time (in ms) of the last frame
/// </summary>
//public float TotalFrameTime { get { return totalFrameTime; } }
/// <summary>
/// Retrieve the physics update component (in ms) of the last frame
/// </summary>
//public float PhysicsFrameTime { get { return physicsFrameTime; } }
/// <summary>
/// Retain a dictionary of all packet queues stats reporters
/// </summary>
private IDictionary<UUID, PacketQueueStatsCollector> packetQueueStatsCollectors
= new Dictionary<UUID, PacketQueueStatsCollector>();
// public void AddAsset(AssetBase asset)
// {
// assetsInCache++;
// //assetCacheMemoryUsage += asset.Data.Length;
// }
//
// public void RemoveAsset(UUID uuid)
// {
// assetsInCache--;
// }
//
// public void AddTexture(AssetBase image)
// {
// if (image.Data != null)
// {
// texturesInCache++;
//
// // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates
// textureCacheMemoryUsage += image.Data.Length;
// }
// }
//
// /// <summary>
// /// Signal that the asset cache has been cleared.
// /// </summary>
// public void ClearAssetCacheStatistics()
// {
// assetsInCache = 0;
// assetCacheMemoryUsage = 0;
// texturesInCache = 0;
// textureCacheMemoryUsage = 0;
// }
//
// public void AddAssetRequestTimeAfterCacheMiss(TimeSpan ts)
// {
// assetRequestTimeAfterCacheMiss = ts;
// }
//
// public void AddBlockedMissingTextureRequest()
// {
// blockedMissingTextureRequests++;
// }
//
// public void AddAssetServiceRequestFailure()
// {
// assetServiceRequestFailures++;
// }
// public void AddInventoryServiceRetrievalFailure()
// {
// inventoryServiceRetrievalFailures++;
// }
/// <summary>
/// Register as a packet queue stats provider
/// </summary>
/// <param name="uuid">An agent UUID</param>
/// <param name="provider"></param>
public void RegisterPacketQueueStatsProvider(UUID uuid, IPullStatsProvider provider)
{
lock (packetQueueStatsCollectors)
{
// FIXME: If the region service is providing more than one region, then the child and root agent
// queues are wrongly replacing each other here.
packetQueueStatsCollectors[uuid] = new PacketQueueStatsCollector(provider);
}
}
/// <summary>
/// Deregister a packet queue stats provider
/// </summary>
/// <param name="uuid">An agent UUID</param>
public void DeregisterPacketQueueStatsProvider(UUID uuid)
{
lock (packetQueueStatsCollectors)
{
packetQueueStatsCollectors.Remove(uuid);
}
}
/// <summary>
/// This is the method on which the classic sim stats reporter (which collects stats for
/// client purposes) sends information to listeners.
/// </summary>
/// <param name="pack"></param>
public void ReceiveClassicSimStatsPacket(SimStats stats)
{
// FIXME: SimStats shouldn't allow an arbitrary stat packing order (which is inherited from the original
// SimStatsPacket that was being used).
// For an unknown reason the original designers decided not to
// include the spare MS statistic inside of this class, this is
// located inside the StatsBlock at location 21, thus it is skipped
timeDilation = stats.StatsBlock[0].StatValue;
simFps = stats.StatsBlock[1].StatValue;
physicsFps = stats.StatsBlock[2].StatValue;
agentUpdates = stats.StatsBlock[3].StatValue;
rootAgents = stats.StatsBlock[4].StatValue;
childAgents = stats.StatsBlock[5].StatValue;
totalPrims = stats.StatsBlock[6].StatValue;
activePrims = stats.StatsBlock[7].StatValue;
totalFrameTime = stats.StatsBlock[8].StatValue;
netFrameTime = stats.StatsBlock[9].StatValue;
physicsFrameTime = stats.StatsBlock[10].StatValue;
imageFrameTime = stats.StatsBlock[11].StatValue;
otherFrameTime = stats.StatsBlock[12].StatValue;
inPacketsPerSecond = stats.StatsBlock[13].StatValue;
outPacketsPerSecond = stats.StatsBlock[14].StatValue;
unackedBytes = stats.StatsBlock[15].StatValue;
agentFrameTime = stats.StatsBlock[16].StatValue;
pendingDownloads = stats.StatsBlock[17].StatValue;
pendingUploads = stats.StatsBlock[18].StatValue;
activeScripts = stats.StatsBlock[19].StatValue;
sleepTime = stats.StatsBlock[20].StatValue;
spareTime = stats.StatsBlock[21].StatValue;
physicsStep = stats.StatsBlock[22].StatValue;
scriptLinesPerSecond = stats.ExtraStatsBlock[0].StatValue;
m_frameDilation = stats.ExtraStatsBlock[1].StatValue;
m_usersLoggingIn = stats.ExtraStatsBlock[2].StatValue;
m_totalGeoPrims = stats.ExtraStatsBlock[3].StatValue;
m_totalMeshes = stats.ExtraStatsBlock[4].StatValue;
m_inUseThreads = stats.ExtraStatsBlock[5].StatValue;
}
/// <summary>
/// Report back collected statistical information.
/// </summary>
/// <returns></returns>
public override string Report()
{
StringBuilder sb = new StringBuilder(Environment.NewLine);
// sb.Append("ASSET STATISTICS");
// sb.Append(Environment.NewLine);
/*
sb.Append(
string.Format(
@"Asset cache contains {0,6} non-texture assets using {1,10} K
Texture cache contains {2,6} texture assets using {3,10} K
Latest asset request time after cache miss: {4}s
Blocked client requests for missing textures: {5}
Asset service request failures: {6}"+ Environment.NewLine,
AssetsInCache, Math.Round(AssetCacheMemoryUsage / 1024.0),
TexturesInCache, Math.Round(TextureCacheMemoryUsage / 1024.0),
assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0,
BlockedMissingTextureRequests,
AssetServiceRequestFailures));
*/
/*
sb.Append(
string.Format(
@"Asset cache contains {0,6} assets
Latest asset request time after cache miss: {1}s
Blocked client requests for missing textures: {2}
Asset service request failures: {3}" + Environment.NewLine,
AssetsInCache,
assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0,
BlockedMissingTextureRequests,
AssetServiceRequestFailures));
*/
sb.Append(Environment.NewLine);
sb.Append("CONNECTION STATISTICS");
sb.Append(Environment.NewLine);
List<Stat> stats = StatsManager.GetStatsFromEachContainer("clientstack", "ClientLogoutsDueToNoReceives");
sb.AppendFormat(
"Client logouts due to no data receive timeout: {0}\n\n",
stats != null ? stats.Sum(s => s.Value).ToString() : "unknown");
// sb.Append(Environment.NewLine);
// sb.Append("INVENTORY STATISTICS");
// sb.Append(Environment.NewLine);
// sb.Append(
// string.Format(
// "Initial inventory caching failures: {0}" + Environment.NewLine,
// InventoryServiceRetrievalFailures));
sb.Append(Environment.NewLine);
sb.Append("SAMPLE FRAME STATISTICS");
sb.Append(Environment.NewLine);
sb.Append("Dilatn SimFPS PhyFPS AgntUp RootAg ChldAg Prims AtvPrm AtvScr ScrLPS");
sb.Append(Environment.NewLine);
sb.Append(
string.Format(
"{0,6:0.00} {1,6:0} {2,6:0.0} {3,6:0.0} {4,6:0} {5,6:0} {6,6:0} {7,6:0} {8,6:0} {9,6:0}",
timeDilation, simFps, physicsFps, agentUpdates, rootAgents,
childAgents, totalPrims, activePrims, activeScripts, scriptLinesPerSecond));
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
// There is no script frame time currently because we don't yet collect it
sb.Append("PktsIn PktOut PendDl PendUl UnackB TotlFt NetFt PhysFt OthrFt AgntFt ImgsFt");
sb.Append(Environment.NewLine);
sb.Append(
string.Format(
"{0,6:0} {1,6:0} {2,6:0} {3,6:0} {4,6:0} {5,6:0.0} {6,6:0.0} {7,6:0.0} {8,6:0.0} {9,6:0.0} {10,6:0.0}\n\n",
inPacketsPerSecond, outPacketsPerSecond, pendingDownloads, pendingUploads, unackedBytes, totalFrameTime,
netFrameTime, physicsFrameTime, otherFrameTime, agentFrameTime, imageFrameTime));
/* 20130319 RA: For the moment, disable the dump of 'scene' catagory as they are mostly output by
* the two formatted printouts above.
SortedDictionary<string, SortedDictionary<string, Stat>> sceneStats;
if (StatsManager.TryGetStats("scene", out sceneStats))
{
foreach (KeyValuePair<string, SortedDictionary<string, Stat>> kvp in sceneStats)
{
foreach (Stat stat in kvp.Value.Values)
{
if (stat.Verbosity == StatVerbosity.Info)
{
sb.AppendFormat("{0} ({1}): {2}{3}\n", stat.Name, stat.Container, stat.Value, stat.UnitName);
}
}
}
}
*/
/*
sb.Append(Environment.NewLine);
sb.Append("PACKET QUEUE STATISTICS");
sb.Append(Environment.NewLine);
sb.Append("Agent UUID ");
sb.Append(
string.Format(
" {0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}",
"Send", "In", "Out", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"));
sb.Append(Environment.NewLine);
foreach (UUID key in packetQueueStatsCollectors.Keys)
{
sb.Append(string.Format("{0}: ", key));
sb.Append(packetQueueStatsCollectors[key].Report());
sb.Append(Environment.NewLine);
}
*/
sb.Append(base.Report());
return sb.ToString();
}
/// <summary>
/// Report back collected statistical information as json serialization.
/// </summary>
/// <returns></returns>
public override string XReport(string uptime, string version)
{
return OSDParser.SerializeJsonString(OReport(uptime, version));
}
/// <summary>
/// Report back collected statistical information as an OSDMap
/// </summary>
/// <returns></returns>
public override OSDMap OReport(string uptime, string version)
{
// Get the amount of physical memory, allocated with the instance of this program, in kilobytes;
// the working set is the set of memory pages currently visible to this program in physical RAM
// memory and includes both shared (e.g. system libraries) and private data
double memUsage = Process.GetCurrentProcess().WorkingSet64 / 1024.0;
// Get the number of threads from the system that are currently
// running
int numberThreadsRunning = 0;
foreach (ProcessThread currentThread in
Process.GetCurrentProcess().Threads)
{
// A known issue with the current process .Threads property is
// that it can return null threads, thus don't count those as
// running threads and prevent the program function from failing
if (currentThread != null &&
currentThread.ThreadState == ThreadState.Running)
{
numberThreadsRunning++;
}
}
OSDMap args = new OSDMap(30);
// args["AssetsInCache"] = OSD.FromString (String.Format ("{0:0.##}", AssetsInCache));
// args["TimeAfterCacheMiss"] = OSD.FromString (String.Format ("{0:0.##}",
// assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0));
// args["BlockedMissingTextureRequests"] = OSD.FromString (String.Format ("{0:0.##}",
// BlockedMissingTextureRequests));
// args["AssetServiceRequestFailures"] = OSD.FromString (String.Format ("{0:0.##}",
// AssetServiceRequestFailures));
// args["abnormalClientThreadTerminations"] = OSD.FromString (String.Format ("{0:0.##}",
// abnormalClientThreadTerminations));
// args["InventoryServiceRetrievalFailures"] = OSD.FromString (String.Format ("{0:0.##}",
// InventoryServiceRetrievalFailures));
args["Dilatn"] = OSD.FromString (String.Format ("{0:0.##}", timeDilation));
args["SimFPS"] = OSD.FromString (String.Format ("{0:0.##}", simFps));
args["PhyFPS"] = OSD.FromString (String.Format ("{0:0.##}", physicsFps));
args["AgntUp"] = OSD.FromString (String.Format ("{0:0.##}", agentUpdates));
args["RootAg"] = OSD.FromString (String.Format ("{0:0.##}", rootAgents));
args["ChldAg"] = OSD.FromString (String.Format ("{0:0.##}", childAgents));
args["Prims"] = OSD.FromString (String.Format ("{0:0.##}", totalPrims));
args["AtvPrm"] = OSD.FromString (String.Format ("{0:0.##}", activePrims));
args["AtvScr"] = OSD.FromString (String.Format ("{0:0.##}", activeScripts));
args["ScrLPS"] = OSD.FromString (String.Format ("{0:0.##}", scriptLinesPerSecond));
args["PktsIn"] = OSD.FromString (String.Format ("{0:0.##}", inPacketsPerSecond));
args["PktOut"] = OSD.FromString (String.Format ("{0:0.##}", outPacketsPerSecond));
args["PendDl"] = OSD.FromString (String.Format ("{0:0.##}", pendingDownloads));
args["PendUl"] = OSD.FromString (String.Format ("{0:0.##}", pendingUploads));
args["UnackB"] = OSD.FromString (String.Format ("{0:0.##}", unackedBytes));
args["TotlFt"] = OSD.FromString (String.Format ("{0:0.##}", totalFrameTime));
args["NetFt"] = OSD.FromString (String.Format ("{0:0.##}", netFrameTime));
args["PhysFt"] = OSD.FromString (String.Format ("{0:0.##}", physicsFrameTime));
args["OthrFt"] = OSD.FromString (String.Format ("{0:0.##}", otherFrameTime));
args["AgntFt"] = OSD.FromString (String.Format ("{0:0.##}", agentFrameTime));
args["ImgsFt"] = OSD.FromString (String.Format ("{0:0.##}", imageFrameTime));
args["Memory"] = OSD.FromString (base.XReport (uptime, version));
args["Uptime"] = OSD.FromString (uptime);
args["Version"] = OSD.FromString (version);
args["FrameDilatn"] = OSD.FromString(String.Format("{0:0.##}", m_frameDilation));
args["Logging in Users"] = OSD.FromString(String.Format("{0:0.##}",
m_usersLoggingIn));
args["GeoPrims"] = OSD.FromString(String.Format("{0:0.##}",
m_totalGeoPrims));
args["Mesh Objects"] = OSD.FromString(String.Format("{0:0.##}",
m_totalMeshes));
args["XEngine Thread Count"] = OSD.FromString(String.Format("{0:0.##}",
m_inUseThreads));
args["Util Thread Count"] = OSD.FromString(String.Format("{0:0.##}",
Util.GetSmartThreadPoolInfo().InUseThreads));
args["System Thread Count"] = OSD.FromString(String.Format(
"{0:0.##}", numberThreadsRunning));
args["ProcMem"] = OSD.FromString(String.Format("{0:#,###,###.##}",
memUsage));
return args;
}
}
/// <summary>
/// Pull packet queue stats from packet queues and report
/// </summary>
public class PacketQueueStatsCollector : IStatsCollector
{
private IPullStatsProvider m_statsProvider;
public PacketQueueStatsCollector(IPullStatsProvider provider)
{
m_statsProvider = provider;
}
/// <summary>
/// Report back collected statistical information.
/// </summary>
/// <returns></returns>
public string Report()
{
return m_statsProvider.GetStats();
}
public string XReport(string uptime, string version)
{
return "";
}
public OSDMap OReport(string uptime, string version)
{
OSDMap ret = new OSDMap();
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace Deltatre.Timeline.RectangleTree
{
public class RectangleTree<T>
{
static readonly EqualityComparer<T> Comparer = EqualityComparer<T>.Default;
readonly int MaxEntries;
readonly int MinEntries;
RectangleTreeNode<T> _root;
public RectangleTree(int maxEntries = 9)
{
MaxEntries = Math.Max(4, maxEntries);
MinEntries = (int)Math.Max(2, Math.Ceiling(MaxEntries * 0.4));
Clear();
}
public void Load(IEnumerable<RectangleTreeNode<T>> nnnn)
{
var nodes = nnnn.ToList();
if(nodes.Count < MinEntries)
{
foreach(var n in nodes)
Insert(n);
return;
}
var node = BuildOneLevel(nodes, 0, 0);
if(_root.Children.Count == 0)
_root = node;
else if(_root.Height == node.Height)
SplitRoot(_root, node);
else
{
if(_root.Height < node.Height)
{
var tmpNode = _root;
_root = node;
node = tmpNode;
}
Insert(node, _root.Height - node.Height - 1);
}
}
RectangleTreeNode<T> BuildOneLevel(List<RectangleTreeNode<T>> items, int level, int height)
{
RectangleTreeNode<T> node;
var count = items.Count;
var maxEntries = MaxEntries;
if(count <= maxEntries)
{
node = new RectangleTreeNode<T> { IsLeaf = true, Height = 1 };
node.Children.AddRange(items);
}
else
{
if(level == 0)
{
height = (int)Math.Ceiling(Math.Log(count) / Math.Log(maxEntries));
maxEntries = (int)Math.Ceiling((double)count / Math.Pow(maxEntries, height - 1));
items.Sort(CompareNodesByMinX);
}
node = new RectangleTreeNode<T> { Height = height };
var n1 = (int)(Math.Ceiling((double)count / maxEntries) * Math.Ceiling(Math.Sqrt(maxEntries)));
var n2 = (int)Math.Ceiling((double)count / maxEntries);
var compare = level % 2 != 1
? new Comparison<RectangleTreeNode<T>>(CompareNodesByMinY)
: CompareNodesByMinX;
for(var i = 0; i < count; i += n1)
{
var slice = items.GetSafeRange(i, n1);
slice.Sort(compare);
for(var j = 0; j < slice.Count; j += n2)
{
var childNode = BuildOneLevel(slice.GetSafeRange(j, n2), level + 1, height - 1);
node.Children.Add(childNode);
}
}
}
RefreshEnvelope(node);
return node;
}
public IEnumerable<RectangleTreeNode<T>> Search(Boundary boundary)
{
var node = _root;
if(!boundary.Intersects(node.Boundary))
return Enumerable.Empty<RectangleTreeNode<T>>();
var retval = new List<RectangleTreeNode<T>>();
var nodesToSearch = new Stack<RectangleTreeNode<T>>();
while(node != null)
{
foreach(var child in node.Children)
{
var childEnvelope = child.Boundary;
if(!boundary.Intersects(childEnvelope))
continue;
if(node.IsLeaf) retval.Add(child);
else if(boundary.Contains(childEnvelope)) Collect(child, retval);
else nodesToSearch.Push(child);
}
node = nodesToSearch.TryPop();
}
return retval;
}
public void ForEach(Boundary boundary, Action<RectangleTreeNode<T>> action)
{
foreach(var node in Search(boundary))
action(node);
}
public void ForEach(Rectangle rectangle, Action<RectangleTreeNode<T>> action)
{
foreach(var node in Search(new Boundary(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom)))
action(node);
}
public T FindAt(int x, int y)
{
var result = Search(new Boundary(x, y, x, y)).FirstOrDefault();
return result == null ? default(T) : result.Data;
}
static void Collect(RectangleTreeNode<T> node, List<RectangleTreeNode<T>> result)
{
var nodesToSearch = new Stack<RectangleTreeNode<T>>();
while(node != null)
{
if(node.IsLeaf) result.AddRange(node.Children);
else
{
foreach(var n in node.Children)
nodesToSearch.Push(n);
}
node = nodesToSearch.TryPop();
}
}
public void Clear()
{
_root = new RectangleTreeNode<T> { IsLeaf = true, Height = 1 };
}
public void Insert(RectangleTreeNode<T> item)
{
Insert(item, _root.Height - 1);
}
public void Insert(T data, Boundary bounds)
{
Insert(new RectangleTreeNode<T>(data, bounds));
}
void Insert(RectangleTreeNode<T> item, int level)
{
var envelope = item.Boundary;
var insertPath = new List<RectangleTreeNode<T>>();
// find the best node for accommodating the item, saving all nodes along the path too
var node = ChooseSubtree(envelope, _root, level, insertPath);
// put the item into the node
node.Children.Add(item);
node.Boundary.Extend(envelope);
// split on node overflow; propagate upwards if necessary
while(level >= 0)
{
if(insertPath[level].Children.Count <= MaxEntries) break;
Split(insertPath, level);
level--;
}
// adjust bboxes along the insertion path
AdjutsParentBounds(envelope, insertPath, level);
}
static int CombinedArea(Boundary what, Boundary with)
{
var minX1 = Math.Max(what.Left, with.Left);
var minY1 = Math.Max(what.Top, with.Top);
var maxX2 = Math.Min(what.Right, with.Right);
var maxY2 = Math.Min(what.Bottom, with.Bottom);
return (maxX2 - minX1) * (maxY2 - minY1);
}
static int IntersectionArea(Boundary what, Boundary with)
{
var minX = Math.Max(what.Left, with.Left);
var minY = Math.Max(what.Top, with.Top);
var maxX = Math.Min(what.Right, with.Right);
var maxY = Math.Min(what.Bottom, with.Bottom);
return Math.Max(0, maxX - minX) * Math.Max(0, maxY - minY);
}
static RectangleTreeNode<T> ChooseSubtree(Boundary bbox, RectangleTreeNode<T> node, int level, List<RectangleTreeNode<T>> path)
{
while(true)
{
path.Add(node);
if(node.IsLeaf || path.Count - 1 == level) break;
var minArea = Int32.MaxValue;
var minEnlargement = Int32.MaxValue;
RectangleTreeNode<T> targetNode = null;
for(var i = 0; i < node.Children.Count; i++)
{
var child = node.Children[i];
var area = child.Boundary.Area;
var enlargement = CombinedArea(bbox, child.Boundary) - area;
// choose entry with the least area enlargement
if(enlargement < minEnlargement)
{
minEnlargement = enlargement;
minArea = area < minArea ? area : minArea;
targetNode = child;
}
else if(enlargement == minEnlargement)
{
// otherwise choose one with the smallest area
if(area < minArea)
{
minArea = area;
targetNode = child;
}
}
}
node = targetNode;
}
return node;
}
// split overflowed node into two
void Split(IReadOnlyList<RectangleTreeNode<T>> insertPath, int level)
{
var node = insertPath[level];
var totalCount = node.Children.Count;
ChooseSplitAxis(node, MinEntries, totalCount);
var newNode = new RectangleTreeNode<T> { Height = node.Height };
var splitIndex = ChooseSplitIndex(node, MinEntries, totalCount);
newNode.Children.AddRange(node.Children.GetRange(splitIndex, node.Children.Count - splitIndex));
node.Children.RemoveRange(splitIndex, node.Children.Count - splitIndex);
if(node.IsLeaf) newNode.IsLeaf = true;
RefreshEnvelope(node);
RefreshEnvelope(newNode);
if(level > 0) insertPath[level - 1].Children.Add(newNode);
else SplitRoot(node, newNode);
}
void SplitRoot(RectangleTreeNode<T> node, RectangleTreeNode<T> newNode)
{
// split root node
_root = new RectangleTreeNode<T>
{
Children = { node, newNode },
Height = node.Height + 1
};
RefreshEnvelope(_root);
}
static int ChooseSplitIndex(RectangleTreeNode<T> node, int minEntries, int totalCount)
{
var minOverlap = Int32.MaxValue;
var minArea = Int32.MaxValue;
int index = 0;
for(var i = minEntries; i <= totalCount - minEntries; i++)
{
var bbox1 = SumChildBounds(node, 0, i);
var bbox2 = SumChildBounds(node, i, totalCount);
var overlap = IntersectionArea(bbox1, bbox2);
var area = bbox1.Area + bbox2.Area;
// choose distribution with minimum overlap
if(overlap < minOverlap)
{
minOverlap = overlap;
index = i;
minArea = area < minArea ? area : minArea;
}
else if(overlap == minOverlap)
{
// otherwise choose distribution with minimum area
if(area < minArea)
{
minArea = area;
index = i;
}
}
}
return index;
}
public void Remove(T item, Boundary boundary)
{
var node = _root;
var itemEnvelope = boundary;
var path = new Stack<RectangleTreeNode<T>>();
var indexes = new Stack<int>();
var i = 0;
var goingUp = false;
RectangleTreeNode<T> parent = null;
// depth-first iterative tree traversal
while(node != null || path.Count > 0)
{
if(node == null)
{
// go up
node = path.TryPop();
parent = path.TryPeek();
i = indexes.TryPop();
goingUp = true;
}
if(node != null && node.IsLeaf)
{
// check current node
var index = node.Children.FindIndex(n => Comparer.Equals(item, n.Data));
if(index != -1)
{
// item found, remove the item and condense tree upwards
node.Children.RemoveAt(index);
path.Push(node);
CondenseNodes(path.ToArray());
return;
}
}
if(!goingUp && !node.IsLeaf && node.Boundary.Contains(itemEnvelope))
{
// go down
path.Push(node);
indexes.Push(i);
i = 0;
parent = node;
node = node.Children[0];
}
else if(parent != null)
{
i++;
if(i == parent.Children.Count)
{
// end of list; will go up
node = null;
}
else
{
// go right
node = parent.Children[i];
goingUp = false;
}
}
else node = null; // nothing found
}
}
void CondenseNodes(IList<RectangleTreeNode<T>> path)
{
// go through the path, removing empty nodes and updating bboxes
for(var i = path.Count - 1; i >= 0; i--)
{
if(path[i].Children.Count == 0)
{
if(i == 0)
Clear();
else
{
var siblings = path[i - 1].Children;
siblings.Remove(path[i]);
}
}
else
RefreshEnvelope(path[i]);
}
}
// calculate node's bbox from bboxes of its children
static void RefreshEnvelope(RectangleTreeNode<T> node)
{
node.Boundary = SumChildBounds(node, 0, node.Children.Count);
}
static Boundary SumChildBounds(RectangleTreeNode<T> node, int startIndex, int endIndex)
{
var retval = new Boundary();
for(var i = startIndex; i < endIndex; i++)
retval.Extend(node.Children[i].Boundary);
return retval;
}
static void AdjutsParentBounds(Boundary bbox, List<RectangleTreeNode<T>> path, int level)
{
// adjust bboxes along the given tree path
for(var i = level; i >= 0; i--)
path[i].Boundary.Extend(bbox);
}
// sorts node children by the best axis for split
static void ChooseSplitAxis(RectangleTreeNode<T> node, int m, int M)
{
var xMargin = AllDistMargin(node, m, M, CompareNodesByMinX);
var yMargin = AllDistMargin(node, m, M, CompareNodesByMinY);
// if total distributions margin value is minimal for x, sort by minX,
// otherwise it's already sorted by minY
if(xMargin < yMargin) node.Children.Sort(CompareNodesByMinX);
}
static int CompareNodesByMinX(RectangleTreeNode<T> a, RectangleTreeNode<T> b)
{
return a.Boundary.Left.CompareTo(b.Boundary.Left);
}
static int CompareNodesByMinY(RectangleTreeNode<T> a, RectangleTreeNode<T> b)
{
return a.Boundary.Top.CompareTo(b.Boundary.Top);
}
static int AllDistMargin(RectangleTreeNode<T> node, int m, int M, Comparison<RectangleTreeNode<T>> compare)
{
node.Children.Sort(compare);
var leftBBox = SumChildBounds(node, 0, m);
var rightBBox = SumChildBounds(node, M - m, M);
var margin = leftBBox.Margin + rightBBox.Margin;
for(var i = m; i < M - m; i++)
{
var child = node.Children[i];
leftBBox.Extend(child.Boundary);
margin += leftBBox.Margin;
}
for(var i = M - m - 1; i >= m; i--)
{
var child = node.Children[i];
rightBBox.Extend(child.Boundary);
margin += rightBBox.Margin;
}
return margin;
}
}
}
| |
// 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.CompilerServices;
namespace System.Buffers
{
public readonly partial struct ReadOnlySequence<T>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool TryGetBuffer(SequencePosition start, SequencePosition end, out ReadOnlyMemory<T> data, out SequencePosition next)
{
if (start.GetObject() == null)
{
data = default;
next = default;
return false;
}
int startIndex = start.GetInteger();
int endIndex = end.GetInteger();
SequenceType type = GetSequenceType();
startIndex = GetIndex(startIndex);
endIndex = GetIndex(endIndex);
switch (type)
{
case SequenceType.MemoryList:
var segment = (IMemoryList<T>)start.GetObject();
Memory<T> bufferSegmentMemory = segment.Memory;
int currentEndIndex = bufferSegmentMemory.Length;
if (segment == end.GetObject())
{
currentEndIndex = endIndex;
next = default;
}
else
{
IMemoryList<T> nextSegment = segment.Next;
if (nextSegment == null)
{
if (end.GetObject() != null)
{
ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached();
}
next = default;
}
else
{
next = new SequencePosition(nextSegment, 0);
}
}
data = bufferSegmentMemory.Slice(startIndex, currentEndIndex - startIndex);
return true;
case SequenceType.OwnedMemory:
var ownedMemory = (OwnedMemory<T>)start.GetObject();
if (ownedMemory != end.GetObject())
{
ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached();
}
data = ownedMemory.Memory.Slice(startIndex, endIndex - startIndex);
next = default;
return true;
case SequenceType.Array:
var array = (T[])start.GetObject();
if (array != end.GetObject())
{
ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached();
}
data = new Memory<T>(array, startIndex, endIndex - startIndex);
next = default;
return true;
default:
ThrowHelper.ThrowInvalidOperationException_UnexpectedSegmentType();
next = default;
data = default;
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal SequencePosition Seek(SequencePosition start, SequencePosition end, int count, bool checkEndReachable = true)
{
int startIndex = start.GetInteger();
int endIndex = end.GetInteger();
SequenceType type = GetSequenceType();
startIndex = GetIndex(startIndex);
endIndex = GetIndex(endIndex);
switch (type)
{
case SequenceType.MemoryList:
if (start.GetObject() == end.GetObject() && endIndex - startIndex >= count)
{
return new SequencePosition(start.GetObject(), startIndex + count);
}
return SeekMultiSegment((IMemoryList<byte>)start.GetObject(), startIndex, (IMemoryList<byte>)end.GetObject(), endIndex, count, checkEndReachable);
case SequenceType.OwnedMemory:
case SequenceType.Array:
if (start.GetObject() != end.GetObject())
{
ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached();
}
if (endIndex - startIndex >= count)
{
return new SequencePosition(start.GetObject(), startIndex + count);
}
ThrowHelper.ThrowArgumentOutOfRangeException_CountOutOfRange();
return default;
default:
ThrowHelper.ThrowInvalidOperationException_UnexpectedSegmentType();
return default;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal SequencePosition Seek(SequencePosition start, SequencePosition end, long count, bool checkEndReachable = true)
{
int startIndex = start.GetInteger();
int endIndex = end.GetInteger();
SequenceType type = GetSequenceType();
startIndex = GetIndex(startIndex);
endIndex = GetIndex(endIndex);
switch (type)
{
case SequenceType.MemoryList:
if (start.GetObject() == end.GetObject() && endIndex - startIndex >= count)
{
// end.Index >= count + Index and end.Index is int
return new SequencePosition(start.GetObject(), startIndex + (int)count);
}
return SeekMultiSegment((IMemoryList<byte>)start.GetObject(), startIndex, (IMemoryList<byte>)end.GetObject(), endIndex, count, checkEndReachable);
case SequenceType.OwnedMemory:
case SequenceType.Array:
if (endIndex - startIndex >= count)
{
// end.Index >= count + Index and end.Index is int
return new SequencePosition(start.GetObject(), startIndex + (int)count);
}
ThrowHelper.ThrowArgumentOutOfRangeException_CountOutOfRange();
return default;
default:
ThrowHelper.ThrowInvalidOperationException_UnexpectedSegmentType();
return default;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static SequencePosition SeekMultiSegment(IMemoryList<byte> start, int startIndex, IMemoryList<byte> end, int endPosition, long count, bool checkEndReachable)
{
SequencePosition result = default;
bool foundResult = false;
IMemoryList<byte> current = start;
int currentIndex = startIndex;
while (current != null)
{
// We need to loop up until the end to make sure start and end are connected
// if end is not trusted
if (!foundResult)
{
var isEnd = current == end;
int currentEnd = isEnd ? endPosition : current.Memory.Length;
int currentLength = currentEnd - currentIndex;
// We would prefer to put position in the beginning of next segment
// then past the end of previous one, but only if we are not leaving current buffer
if (currentLength > count ||
(currentLength == count && isEnd))
{
result = new SequencePosition(current, currentIndex + (int)count);
foundResult = true;
if (!checkEndReachable)
{
break;
}
}
count -= currentLength;
}
if (current.Next == null && current != end)
{
ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached();
}
current = current.Next;
currentIndex = 0;
}
if (!foundResult)
{
ThrowHelper.ThrowArgumentOutOfRangeException_CountOutOfRange();
}
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private long GetLength(SequencePosition start, SequencePosition end)
{
int startIndex = start.GetInteger();
int endIndex = end.GetInteger();
SequenceType type = GetSequenceType();
startIndex = GetIndex(startIndex);
endIndex = GetIndex(endIndex);
switch (type)
{
case SequenceType.MemoryList:
return GetLength((IMemoryList<T>)start.GetObject(), startIndex, (IMemoryList<T>)end.GetObject(), endIndex);
case SequenceType.OwnedMemory:
case SequenceType.Array:
return endIndex - startIndex;
default:
ThrowHelper.ThrowInvalidOperationException_UnexpectedSegmentType();
return default;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long GetLength(IMemoryList<T> start, int startIndex, IMemoryList<T> endSegment, int endIndex)
{
if (start == endSegment)
{
return endIndex - startIndex;
}
return (endSegment.RunningIndex - start.Next.RunningIndex) // Length of data in between first and last segment
+ (start.Memory.Length - startIndex) // Length of data in first segment
+ endIndex; // Length of data in last segment
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void BoundsCheck(SequencePosition start, SequencePosition position)
{
int startIndex = start.GetInteger();
int endIndex = position.GetInteger();
SequenceType type = GetSequenceType();
startIndex = GetIndex(startIndex);
endIndex = GetIndex(endIndex);
switch (type)
{
case SequenceType.OwnedMemory:
case SequenceType.Array:
if (endIndex > startIndex)
{
ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange();
}
return;
case SequenceType.MemoryList:
IMemoryList<T> segment = (IMemoryList<T>)position.GetObject();
IMemoryList<T> memoryList = (IMemoryList<T>)start.GetObject();
if (segment.RunningIndex - startIndex > memoryList.RunningIndex - endIndex)
{
ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange();
}
return;
default:
ThrowHelper.ThrowInvalidOperationException_UnexpectedSegmentType();
return;
}
}
internal bool TryGetMemoryList(out IMemoryList<T> startSegment, out int startIndex, out IMemoryList<T> endSegment, out int endIndex)
{
if (Start.GetObject() == null || GetSequenceType() != SequenceType.MemoryList)
{
startSegment = null;
endSegment = null;
startIndex = 0;
endIndex = 0;
return false;
}
startIndex = GetIndex(Start.GetInteger());
endIndex = GetIndex(End.GetInteger());
startSegment = (IMemoryList<T>)Start.GetObject();
endSegment = (IMemoryList<T>)End.GetObject();
return true;
}
internal bool TryGetArray(out ArraySegment<T> array)
{
if (Start.GetObject() == null || GetSequenceType() != SequenceType.Array)
{
array = default;
return false;
}
int startIndex = GetIndex(Start.GetInteger());
array = new ArraySegment<T>((T[])Start.GetObject(), startIndex, GetIndex(End.GetInteger()) - startIndex);
return true;
}
internal bool TryGetOwnedMemory(out OwnedMemory<T> ownedMemory, out int start, out int length)
{
if (Start.GetObject() == null || GetSequenceType() != SequenceType.OwnedMemory)
{
ownedMemory = default;
start = 0;
length = 0;
return false;
}
ownedMemory = (OwnedMemory<T>)Start.GetObject();
start = GetIndex(Start.GetInteger());
length = GetIndex(End.GetInteger()) - start;
return true;
}
internal bool TryGetReadOnlyMemory(out ReadOnlyMemory<T> memory)
{
// Currently ReadOnlyMemory is stored inside single segment of IMemoryList
if (TryGetMemoryList(out IMemoryList<T> startSegment, out int startIndex, out IMemoryList<T> endSegment, out int endIndex) &&
startSegment == endSegment)
{
memory = startSegment.Memory.Slice(startIndex, endIndex - startIndex);
return true;
}
memory = default;
return false;
}
private class ReadOnlySequenceSegment : IMemoryList<T>
{
public Memory<T> Memory { get; set; }
public IMemoryList<T> Next { get; set; }
public long RunningIndex { get; set; }
}
}
}
| |
//#define DEBUG_IO
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Dawn.Net.Sockets;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Enyim.Caching.Memcached
{
[DebuggerDisplay("[ Address: {endpoint}, IsAlive = {IsAlive} ]")]
public partial class PooledSocket : IDisposable
{
private readonly ILogger _logger;
private bool isAlive;
private Socket socket;
private EndPoint endpoint;
private Stream inputStream;
private AsyncSocketHelper helper;
public PooledSocket(EndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout, ILogger logger)
{
_logger = logger;
this.isAlive = true;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// TODO test if we're better off using nagle
//PHP: OPT_TCP_NODELAY
//socket.NoDelay = true;
var timeout = connectionTimeout == TimeSpan.MaxValue
? Timeout.Infinite
: (int)connectionTimeout.TotalMilliseconds;
var rcv = receiveTimeout == TimeSpan.MaxValue
? Timeout.Infinite
: (int)receiveTimeout.TotalMilliseconds;
socket.ReceiveTimeout = rcv;
socket.SendTimeout = rcv;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
ConnectWithTimeout(socket, endpoint, timeout);
this.socket = socket;
this.endpoint = endpoint;
this.inputStream = new BasicNetworkStream(socket);
}
private void ConnectWithTimeout(Socket socket, EndPoint endpoint, int timeout)
{
//var task = socket.ConnectAsync(endpoint);
//if(!task.Wait(timeout))
//{
// using (socket)
// {
// throw new TimeoutException("Could not connect to " + endpoint);
// }
//}
if (endpoint is DnsEndPoint && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var dnsEndPoint = ((DnsEndPoint)endpoint);
var host = dnsEndPoint.Host;
var addresses = Dns.GetHostAddresses(dnsEndPoint.Host);
var address = addresses.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
if (address == null)
{
throw new ArgumentException(String.Format("Could not resolve host '{0}'.", host));
}
_logger.LogDebug($"Resolved '{host}' to '{address}'");
endpoint = new IPEndPoint(address, dnsEndPoint.Port);
}
var completed = new AutoResetEvent(false);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endpoint;
args.Completed += OnConnectCompleted;
args.UserToken = completed;
socket.ConnectAsync(args);
if (!completed.WaitOne(timeout) || !socket.Connected)
{
using (socket)
{
throw new TimeoutException("Could not connect to " + endpoint);
}
}
/*
var mre = new ManualResetEvent(false);
socket.Connect(endpoint, iar =>
{
try { using (iar.AsyncWaitHandle) socket.EndConnect(iar); }
catch { }
mre.Set();
}, null);
if (!mre.WaitOne(timeout) || !socket.Connected)
using (socket)
throw new TimeoutException("Could not connect to " + endpoint);
*/
}
private void OnConnectCompleted(object sender, SocketAsyncEventArgs args)
{
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
handle.Set();
}
public Action<PooledSocket> CleanupCallback { get; set; }
public int Available
{
get { return this.socket.Available; }
}
public void Reset()
{
// discard any buffered data
this.inputStream.Flush();
if (this.helper != null) this.helper.DiscardBuffer();
int available = this.socket.Available;
if (available > 0)
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Socket bound to {0} has {1} unread data! This is probably a bug in the code. InstanceID was {2}.", this.socket.RemoteEndPoint, available, this.InstanceId);
byte[] data = new byte[available];
this.Read(data, 0, available);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(Encoding.ASCII.GetString(data));
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Socket {0} was reset", this.InstanceId);
}
/// <summary>
/// The ID of this instance. Used by the <see cref="T:MemcachedServer"/> to identify the instance in its inner lists.
/// </summary>
public readonly Guid InstanceId = Guid.NewGuid();
public bool IsAlive
{
get { return this.isAlive; }
}
/// <summary>
/// Releases all resources used by this instance and shuts down the inner <see cref="T:Socket"/>. This instance will not be usable anymore.
/// </summary>
/// <remarks>Use the IDisposable.Dispose method if you want to release this instance back into the pool.</remarks>
public void Destroy()
{
this.Dispose(true);
}
~PooledSocket()
{
try { this.Dispose(true); }
catch { }
}
protected void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
try
{
if (socket != null)
try { this.socket.Dispose(); }
catch { }
if (this.inputStream != null)
this.inputStream.Dispose();
this.inputStream = null;
this.socket = null;
this.CleanupCallback = null;
}
catch (Exception e)
{
_logger.LogError(nameof(PooledSocket), e);
}
}
else
{
Action<PooledSocket> cc = this.CleanupCallback;
if (cc != null)
cc(this);
}
}
void IDisposable.Dispose()
{
this.Dispose(false);
}
private void CheckDisposed()
{
if (this.socket == null)
throw new ObjectDisposedException("PooledSocket");
}
/// <summary>
/// Reads the next byte from the server's response.
/// </summary>
/// <remarks>This method blocks and will not return until the value is read.</remarks>
public int ReadByte()
{
this.CheckDisposed();
try
{
return this.inputStream.ReadByte();
}
catch (IOException)
{
this.isAlive = false;
throw;
}
}
public async Task<byte[]> ReadBytesAsync(int count)
{
using (var awaitable = new SocketAwaitable())
{
awaitable.Buffer = new ArraySegment<byte>(new byte[count], 0, count);
await this.socket.ReceiveAsync(awaitable);
return awaitable.Transferred.Array;
}
}
/// <summary>
/// Reads data from the server into the specified buffer.
/// </summary>
/// <param name="buffer">An array of <see cref="T:System.Byte"/> that is the storage location for the received data.</param>
/// <param name="offset">The location in buffer to store the received data.</param>
/// <param name="count">The number of bytes to read.</param>
/// <remarks>This method blocks and will not return until the specified amount of bytes are read.</remarks>
public void Read(byte[] buffer, int offset, int count)
{
this.CheckDisposed();
int read = 0;
int shouldRead = count;
while (read < count)
{
try
{
int currentRead = this.inputStream.Read(buffer, offset, shouldRead);
if (currentRead < 1)
continue;
read += currentRead;
offset += currentRead;
shouldRead -= currentRead;
}
catch (IOException)
{
this.isAlive = false;
throw;
}
}
}
public void Write(byte[] data, int offset, int length)
{
this.CheckDisposed();
SocketError status;
this.socket.Send(data, offset, length, SocketFlags.None, out status);
if (status != SocketError.Success)
{
this.isAlive = false;
ThrowHelper.ThrowSocketWriteError(this.endpoint, status);
}
}
public void Write(IList<ArraySegment<byte>> buffers)
{
this.CheckDisposed();
SocketError status;
#if DEBUG
int total = 0;
for (int i = 0, C = buffers.Count; i < C; i++)
total += buffers[i].Count;
if (this.socket.Send(buffers, SocketFlags.None, out status) != total)
System.Diagnostics.Debugger.Break();
#else
this.socket.Send(buffers, SocketFlags.None, out status);
#endif
if (status != SocketError.Success)
{
this.isAlive = false;
ThrowHelper.ThrowSocketWriteError(this.endpoint, status);
}
}
public async Task WriteSync(IList<ArraySegment<byte>> buffers)
{
using (var awaitable = new SocketAwaitable())
{
awaitable.Arguments.BufferList = buffers;
try
{
await this.socket.SendAsync(awaitable);
}
catch
{
this.isAlive = false;
ThrowHelper.ThrowSocketWriteError(this.endpoint, awaitable.Arguments.SocketError);
}
if (awaitable.Arguments.SocketError != SocketError.Success)
{
this.isAlive = false;
ThrowHelper.ThrowSocketWriteError(this.endpoint, awaitable.Arguments.SocketError);
}
}
}
/// <summary>
/// Receives data asynchronously. Returns true if the IO is pending. Returns false if the socket already failed or the data was available in the buffer.
/// p.Next will only be called if the call completes asynchronously.
/// </summary>
public bool ReceiveAsync(AsyncIOArgs p)
{
this.CheckDisposed();
if (!this.IsAlive)
{
p.Fail = true;
p.Result = null;
return false;
}
if (this.helper == null)
this.helper = new AsyncSocketHelper(this);
return this.helper.Read(p);
}
}
}
#region [ License information ]
/* ************************************************************
*
* Copyright (c) 2010 Attila Kisk? enyim.com
*
* 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
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Threading;
using dnlib.DotNet.MD;
using dnlib.PE;
using dnlib.Threading;
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the Field table
/// </summary>
public abstract class FieldDef : IHasConstant, IHasCustomAttribute, IHasFieldMarshal, IMemberForwarded, IField, ITokenOperand, IMemberDef {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
#if THREAD_SAFE
readonly Lock theLock = Lock.Create();
#endif
/// <inheritdoc/>
public MDToken MDToken {
get { return new MDToken(Table.Field, rid); }
}
/// <inheritdoc/>
public uint Rid {
get { return rid; }
set { rid = value; }
}
/// <inheritdoc/>
public int HasConstantTag {
get { return 0; }
}
/// <inheritdoc/>
public int HasCustomAttributeTag {
get { return 1; }
}
/// <inheritdoc/>
public int HasFieldMarshalTag {
get { return 0; }
}
/// <inheritdoc/>
public int MemberForwardedTag {
get { return 0; }
}
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes == null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() {
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
}
/// <summary>
/// From column Field.Flags
/// </summary>
public FieldAttributes Attributes {
get { return (FieldAttributes)attributes; }
set { attributes = (int)value; }
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column Field.Name
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column Field.Signature
/// </summary>
public CallingConventionSig Signature {
get { return signature; }
set { signature = value; }
}
/// <summary/>
protected CallingConventionSig signature;
/// <summary>
/// Gets/sets the field layout offset
/// </summary>
public uint? FieldOffset {
get {
if (!fieldOffset_isInitialized)
InitializeFieldOffset();
return fieldOffset;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
fieldOffset = value;
fieldOffset_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected uint? fieldOffset;
/// <summary/>
protected bool fieldOffset_isInitialized;
void InitializeFieldOffset() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (fieldOffset_isInitialized)
return;
fieldOffset = GetFieldOffset_NoLock();
fieldOffset_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="fieldOffset"/></summary>
protected virtual uint? GetFieldOffset_NoLock() {
return null;
}
/// <inheritdoc/>
public MarshalType MarshalType {
get {
if (!marshalType_isInitialized)
InitializeMarshalType();
return marshalType;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
marshalType = value;
marshalType_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected MarshalType marshalType;
/// <summary/>
protected bool marshalType_isInitialized;
void InitializeMarshalType() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (marshalType_isInitialized)
return;
marshalType = GetMarshalType_NoLock();
marshalType_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="marshalType"/></summary>
protected virtual MarshalType GetMarshalType_NoLock() {
return null;
}
/// <summary>Reset <see cref="MarshalType"/></summary>
protected void ResetMarshalType() {
marshalType_isInitialized = false;
}
/// <summary>
/// Gets/sets the field RVA
/// </summary>
public RVA RVA {
get {
if (!rva_isInitialized)
InitializeRVA();
return rva;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
rva = value;
rva_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected RVA rva;
/// <summary/>
protected bool rva_isInitialized;
void InitializeRVA() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (rva_isInitialized)
return;
rva = GetRVA_NoLock();
rva_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="rva"/></summary>
protected virtual RVA GetRVA_NoLock() {
return 0;
}
/// <summary>Reset <see cref="RVA"/></summary>
protected void ResetRVA() {
rva_isInitialized = false;
}
/// <summary>
/// Gets/sets the initial value. Be sure to set <see cref="HasFieldRVA"/> to <c>true</c> if
/// you write to this field.
/// </summary>
public byte[] InitialValue {
get {
if (!initialValue_isInitialized)
InitializeInitialValue();
return initialValue;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
initialValue = value;
initialValue_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected byte[] initialValue;
/// <summary/>
protected bool initialValue_isInitialized;
void InitializeInitialValue() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (initialValue_isInitialized)
return;
initialValue = GetInitialValue_NoLock();
initialValue_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="initialValue"/></summary>
protected virtual byte[] GetInitialValue_NoLock() {
return null;
}
/// <summary>Reset <see cref="InitialValue"/></summary>
protected void ResetInitialValue() {
initialValue_isInitialized = false;
}
/// <inheritdoc/>
public ImplMap ImplMap {
get {
if (!implMap_isInitialized)
InitializeImplMap();
return implMap;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
implMap = value;
implMap_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected ImplMap implMap;
/// <summary/>
protected bool implMap_isInitialized;
void InitializeImplMap() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (implMap_isInitialized)
return;
implMap = GetImplMap_NoLock();
implMap_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="implMap"/></summary>
protected virtual ImplMap GetImplMap_NoLock() {
return null;
}
/// <inheritdoc/>
public Constant Constant {
get {
if (!constant_isInitialized)
InitializeConstant();
return constant;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
constant = value;
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected Constant constant;
/// <summary/>
protected bool constant_isInitialized;
void InitializeConstant() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (constant_isInitialized)
return;
constant = GetConstant_NoLock();
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="constant"/></summary>
protected virtual Constant GetConstant_NoLock() {
return null;
}
/// <summary>Reset <see cref="Constant"/></summary>
protected void ResetConstant() {
constant_isInitialized = false;
}
/// <inheritdoc/>
public bool HasCustomAttributes {
get { return CustomAttributes.Count > 0; }
}
/// <inheritdoc/>
public bool HasImplMap {
get { return ImplMap != null; }
}
/// <summary>
/// Gets/sets the declaring type (owner type)
/// </summary>
public TypeDef DeclaringType {
get { return declaringType2; }
set {
var currentDeclaringType = DeclaringType2;
if (currentDeclaringType == value)
return;
if (currentDeclaringType != null)
currentDeclaringType.Fields.Remove(this); // Will set DeclaringType2 = null
if (value != null)
value.Fields.Add(this); // Will set DeclaringType2 = value
}
}
/// <inheritdoc/>
ITypeDefOrRef IMemberRef.DeclaringType {
get { return declaringType2; }
}
/// <summary>
/// Called by <see cref="DeclaringType"/> and should normally not be called by any user
/// code. Use <see cref="DeclaringType"/> instead. Only call this if you must set the
/// declaring type without inserting it in the declaring type's method list.
/// </summary>
public TypeDef DeclaringType2 {
get { return declaringType2; }
set { declaringType2 = value; }
}
/// <summary/>
protected TypeDef declaringType2;
/// <summary>
/// Gets/sets the <see cref="FieldSig"/>
/// </summary>
public FieldSig FieldSig {
get { return signature as FieldSig; }
set { signature = value; }
}
/// <inheritdoc/>
public ModuleDef Module {
get {
var dt = declaringType2;
return dt == null ? null : dt.Module;
}
}
bool IIsTypeOrMethod.IsType {
get { return false; }
}
bool IIsTypeOrMethod.IsMethod {
get { return false; }
}
bool IMemberRef.IsField {
get { return true; }
}
bool IMemberRef.IsTypeSpec {
get { return false; }
}
bool IMemberRef.IsTypeRef {
get { return false; }
}
bool IMemberRef.IsTypeDef {
get { return false; }
}
bool IMemberRef.IsMethodSpec {
get { return false; }
}
bool IMemberRef.IsMethodDef {
get { return false; }
}
bool IMemberRef.IsMemberRef {
get { return false; }
}
bool IMemberRef.IsFieldDef {
get { return true; }
}
bool IMemberRef.IsPropertyDef {
get { return false; }
}
bool IMemberRef.IsEventDef {
get { return false; }
}
bool IMemberRef.IsGenericParam {
get { return false; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldOffset"/> is not <c>null</c>
/// </summary>
public bool HasLayoutInfo {
get { return FieldOffset != null; }
}
/// <summary>
/// <c>true</c> if <see cref="Constant"/> is not <c>null</c>
/// </summary>
public bool HasConstant {
get { return Constant != null; }
}
/// <summary>
/// Gets the constant element type or <see cref="dnlib.DotNet.ElementType.End"/> if there's no constant
/// </summary>
public ElementType ElementType {
get {
var c = Constant;
return c == null ? ElementType.End : c.Type;
}
}
/// <summary>
/// <c>true</c> if <see cref="MarshalType"/> is not <c>null</c>
/// </summary>
public bool HasMarshalType {
get { return MarshalType != null; }
}
/// <summary>
/// Gets/sets the field type
/// </summary>
public TypeSig FieldType {
get { return FieldSig.GetFieldType(); }
set {
var sig = FieldSig;
if (sig != null)
sig.Type = value;
}
}
/// <summary>
/// Modify <see cref="attributes"/> field: <see cref="attributes"/> =
/// (<see cref="attributes"/> & <paramref name="andMask"/>) | <paramref name="orMask"/>.
/// </summary>
/// <param name="andMask">Value to <c>AND</c></param>
/// <param name="orMask">Value to OR</param>
void ModifyAttributes(FieldAttributes andMask, FieldAttributes orMask) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
newVal = (origVal & (int)andMask) | (int)orMask;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
attributes = (attributes & (int)andMask) | (int)orMask;
#endif
}
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, FieldAttributes flags) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
if (set)
newVal = origVal | (int)flags;
else
newVal = origVal & ~(int)flags;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
#endif
}
/// <summary>
/// Gets/sets the field access
/// </summary>
public FieldAttributes Access {
get { return (FieldAttributes)attributes & FieldAttributes.FieldAccessMask; }
set { ModifyAttributes(~FieldAttributes.FieldAccessMask, value & FieldAttributes.FieldAccessMask); }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set
/// </summary>
public bool IsCompilerControlled {
get { return IsPrivateScope; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set
/// </summary>
public bool IsPrivateScope {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.PrivateScope; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Private"/> is set
/// </summary>
public bool IsPrivate {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.FamANDAssem"/> is set
/// </summary>
public bool IsFamilyAndAssembly {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Assembly"/> is set
/// </summary>
public bool IsAssembly {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Family"/> is set
/// </summary>
public bool IsFamily {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.FamORAssem"/> is set
/// </summary>
public bool IsFamilyOrAssembly {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; }
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Public"/> is set
/// </summary>
public bool IsPublic {
get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.Static"/> bit
/// </summary>
public bool IsStatic {
get { return ((FieldAttributes)attributes & FieldAttributes.Static) != 0; }
set { ModifyAttributes(value, FieldAttributes.Static); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.InitOnly"/> bit
/// </summary>
public bool IsInitOnly {
get { return ((FieldAttributes)attributes & FieldAttributes.InitOnly) != 0; }
set { ModifyAttributes(value, FieldAttributes.InitOnly); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.Literal"/> bit
/// </summary>
public bool IsLiteral {
get { return ((FieldAttributes)attributes & FieldAttributes.Literal) != 0; }
set { ModifyAttributes(value, FieldAttributes.Literal); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.NotSerialized"/> bit
/// </summary>
public bool IsNotSerialized {
get { return ((FieldAttributes)attributes & FieldAttributes.NotSerialized) != 0; }
set { ModifyAttributes(value, FieldAttributes.NotSerialized); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.SpecialName"/> bit
/// </summary>
public bool IsSpecialName {
get { return ((FieldAttributes)attributes & FieldAttributes.SpecialName) != 0; }
set { ModifyAttributes(value, FieldAttributes.SpecialName); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.PinvokeImpl"/> bit
/// </summary>
public bool IsPinvokeImpl {
get { return ((FieldAttributes)attributes & FieldAttributes.PinvokeImpl) != 0; }
set { ModifyAttributes(value, FieldAttributes.PinvokeImpl); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.RTSpecialName"/> bit
/// </summary>
public bool IsRuntimeSpecialName {
get { return ((FieldAttributes)attributes & FieldAttributes.RTSpecialName) != 0; }
set { ModifyAttributes(value, FieldAttributes.RTSpecialName); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasFieldMarshal"/> bit
/// </summary>
public bool HasFieldMarshal {
get { return ((FieldAttributes)attributes & FieldAttributes.HasFieldMarshal) != 0; }
set { ModifyAttributes(value, FieldAttributes.HasFieldMarshal); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasDefault"/> bit
/// </summary>
public bool HasDefault {
get { return ((FieldAttributes)attributes & FieldAttributes.HasDefault) != 0; }
set { ModifyAttributes(value, FieldAttributes.HasDefault); }
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasFieldRVA"/> bit
/// </summary>
public bool HasFieldRVA {
get { return ((FieldAttributes)attributes & FieldAttributes.HasFieldRVA) != 0; }
set { ModifyAttributes(value, FieldAttributes.HasFieldRVA); }
}
/// <summary>
/// Returns the full name of this field
/// </summary>
public string FullName {
get {
var dt = declaringType2;
return FullNameCreator.FieldFullName(dt == null ? null : dt.FullName, name, FieldSig);
}
}
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
public uint GetFieldSize() {
uint size;
if (!GetFieldSize(out size))
return 0;
return size;
}
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
public bool GetFieldSize(out uint size) {
return GetFieldSize(declaringType2, FieldSig, out size);
}
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="declaringType">The declaring type of <c>this</c></param>
/// <param name="fieldSig">The field signature of <c>this</c></param>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
protected bool GetFieldSize(TypeDef declaringType, FieldSig fieldSig, out uint size) {
return GetFieldSize(declaringType, fieldSig, GetPointerSize(declaringType), out size);
}
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="declaringType">The declaring type of <c>this</c></param>
/// <param name="fieldSig">The field signature of <c>this</c></param>
/// <param name="ptrSize">Size of a pointer</param>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
protected bool GetFieldSize(TypeDef declaringType, FieldSig fieldSig, int ptrSize, out uint size) {
size = 0;
if (fieldSig == null)
return false;
return GetClassSize(declaringType, fieldSig.Type, ptrSize, out size);
}
bool GetClassSize(TypeDef declaringType, TypeSig ts, int ptrSize, out uint size) {
size = 0;
ts = ts.RemovePinnedAndModifiers();
if (ts == null)
return false;
int size2 = ts.ElementType.GetPrimitiveSize(ptrSize);
if (size2 >= 0) {
size = (uint)size2;
return true;
}
var tdrs = ts as TypeDefOrRefSig;
if (tdrs == null)
return false;
var td = tdrs.TypeDef;
if (td != null)
return TypeDef.GetClassSize(td, out size);
var tr = tdrs.TypeRef;
if (tr != null)
return TypeDef.GetClassSize(tr.Resolve(), out size);
return false;
}
int GetPointerSize(TypeDef declaringType) {
if (declaringType == null)
return 4;
var module = declaringType.Module;
if (module == null)
return 4;
return module.GetPointerSize();
}
/// <inheritdoc/>
public override string ToString() {
return FullName;
}
}
/// <summary>
/// A Field row created by the user and not present in the original .NET file
/// </summary>
public class FieldDefUser : FieldDef {
/// <summary>
/// Default constructor
/// </summary>
public FieldDefUser() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
public FieldDefUser(UTF8String name)
: this(name, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="signature">Signature</param>
public FieldDefUser(UTF8String name, FieldSig signature)
: this(name, signature, 0) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="signature">Signature</param>
/// <param name="attributes">Flags</param>
public FieldDefUser(UTF8String name, FieldSig signature, FieldAttributes attributes) {
this.name = name;
this.signature = signature;
this.attributes = (int)attributes;
}
}
/// <summary>
/// Created from a row in the Field table
/// </summary>
sealed class FieldDefMD : FieldDef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
readonly FieldAttributes origAttributes;
/// <inheritdoc/>
public uint OrigRid {
get { return origRid; }
}
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.MetaData.GetCustomAttributeRidList(Table.Field, origRid);
var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <inheritdoc/>
protected override uint? GetFieldOffset_NoLock() {
return readerModule.TablesStream.ReadFieldLayoutRow2(readerModule.MetaData.GetFieldLayoutRid(origRid));
}
/// <inheritdoc/>
protected override MarshalType GetMarshalType_NoLock() {
return readerModule.ReadMarshalType(Table.Field, origRid, new GenericParamContext(declaringType2));
}
/// <inheritdoc/>
protected override RVA GetRVA_NoLock() {
RVA rva2;
GetFieldRVA_NoLock(out rva2);
return rva2;
}
/// <inheritdoc/>
protected override byte[] GetInitialValue_NoLock() {
RVA rva2;
if (!GetFieldRVA_NoLock(out rva2))
return null;
return ReadInitialValue_NoLock(rva2);
}
/// <inheritdoc/>
protected override ImplMap GetImplMap_NoLock() {
return readerModule.ResolveImplMap(readerModule.MetaData.GetImplMapRid(Table.Field, origRid));
}
/// <inheritdoc/>
protected override Constant GetConstant_NoLock() {
return readerModule.ResolveConstant(readerModule.MetaData.GetConstantRid(Table.Field, origRid));
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>Field</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public FieldDefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule == null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.FieldTable.IsInvalidRID(rid))
throw new BadImageFormatException(string.Format("Field rid {0} does not exist", rid));
#endif
this.origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
uint name;
uint signature = readerModule.TablesStream.ReadFieldRow(origRid, out this.attributes, out name);
this.name = readerModule.StringsStream.ReadNoNull(name);
this.origAttributes = (FieldAttributes)attributes;
this.declaringType2 = readerModule.GetOwnerType(this);
this.signature = readerModule.ReadSignature(signature, new GenericParamContext(declaringType2));
}
internal FieldDefMD InitializeAll() {
MemberMDInitializer.Initialize(CustomAttributes);
MemberMDInitializer.Initialize(Attributes);
MemberMDInitializer.Initialize(Name);
MemberMDInitializer.Initialize(Signature);
MemberMDInitializer.Initialize(FieldOffset);
MemberMDInitializer.Initialize(MarshalType);
MemberMDInitializer.Initialize(RVA);
MemberMDInitializer.Initialize(InitialValue);
MemberMDInitializer.Initialize(ImplMap);
MemberMDInitializer.Initialize(Constant);
MemberMDInitializer.Initialize(DeclaringType);
return this;
}
bool GetFieldRVA_NoLock(out RVA rva) {
if ((origAttributes & FieldAttributes.HasFieldRVA) == 0) {
rva = 0;
return false;
}
return readerModule.TablesStream.ReadFieldRVARow(readerModule.MetaData.GetFieldRVARid(origRid), out rva);
}
byte[] ReadInitialValue_NoLock(RVA rva) {
uint size;
if (!GetFieldSize(declaringType2, signature as FieldSig, out size))
return null;
if (size >= int.MaxValue)
return null;
return readerModule.ReadDataAt(rva, (int)size);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Abstract;
using System.Collections.Generic;
namespace Autofac.Abstract
{
/// <summary>
/// IAutofacServiceLocator
/// </summary>
public interface IAutofacServiceLocator : IServiceLocator
{
/// <summary>
/// Gets the container.
/// </summary>
IContainer Container { get; }
}
/// <summary>
/// AutofacServiceLocator
/// </summary>
[Serializable]
public class AutofacServiceLocator : IAutofacServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration
{
IContainer _container;
AutofacServiceRegistrar _registrar;
readonly Func<IContainer> _containerBuilder;
static AutofacServiceLocator() { ServiceLocatorManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceLocator"/> class.
/// </summary>
public AutofacServiceLocator()
: this(new ContainerBuilder()) { }
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceLocator"/> class.
/// </summary>
/// <param name="container">The container (IContainer or ContainerBuilder).</param>
public AutofacServiceLocator(object container)
{
if (container == null)
throw new ArgumentNullException("container");
if (container is ContainerBuilder)
{
_registrar = new AutofacServiceRegistrar(this, container as ContainerBuilder, out _containerBuilder);
return;
}
Container = (container as IContainer);
if (Container == null)
throw new ArgumentOutOfRangeException("container", "Must be of type Autofac.IContainer");
}
//private AutofacServiceLocator(IComponentContext container)
//{
// if (container == null)
// throw new ArgumentNullException("container");
// //_registrar = new AutofacServiceRegistrar(this, containerBuilder, out _containerBuilder);
//}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_container != null)
{
var container = _container;
_container = null;
_registrar = null;
//_containerBuilder = null;
// prevent cyclical dispose
if (container != null)
container.Dispose();
}
}
Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLocatorManager.RegisterInstance<IAutofacServiceLocator>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { return Resolve(serviceType); }
/// <summary>
/// Creates the child.
/// </summary>
/// <returns></returns>
public IServiceLocator CreateChild(object tag)
{
//http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/
return new AutofacServiceLocator(_container.BeginLifetimeScope(tag));
}
/// <summary>
/// Gets the underlying container.
/// </summary>
/// <typeparam name="TContainer">The type of the container.</typeparam>
/// <returns></returns>
public TContainer GetUnderlyingContainer<TContainer>()
where TContainer : class { return (_container as TContainer); }
// registrar
/// <summary>
/// Gets the registrar.
/// </summary>
public IServiceRegistrar Registrar
{
get { return _registrar; }
}
// resolve
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public TService Resolve<TService>()
where TService : class
{
try { return (Container.IsRegistered<TService>() ? Container.Resolve<TService>() : Activator.CreateInstance<TService>()); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="name">The name.</param>
/// <returns></returns>
public TService Resolve<TService>(string name)
where TService : class
{
try { return Container.ResolveNamed<TService>(name); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public object Resolve(Type serviceType)
{
try { return (Container.IsRegistered(serviceType) ? Container.Resolve(serviceType) : Activator.CreateInstance(serviceType)); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public object Resolve(Type serviceType, string name)
{
try { return Container.ResolveNamed(name, serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
//
/// <summary>
/// Resolves all.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public IEnumerable<TService> ResolveAll<TService>()
where TService : class
{
try { return new List<TService>(Container.Resolve<IEnumerable<TService>>()); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves all.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<object> ResolveAll(Type serviceType)
{
var type = typeof(IEnumerable<>).MakeGenericType(serviceType);
try { return new List<object>((IEnumerable<object>)Container.Resolve(type)); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
// inject
/// <summary>
/// Injects the specified instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public TService Inject<TService>(TService instance)
where TService : class { return Container.InjectProperties(instance); }
// release and teardown
/// <summary>
/// Releases the specified instance.
/// </summary>
/// <param name="instance">The instance.</param>
public void Release(object instance) { throw new NotSupportedException(); }
/// <summary>
/// Tears down.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
public void TearDown<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
#region Domain specific
/// <summary>
/// Gets the container.
/// </summary>
public IContainer Container
{
get
{
if (_container == null)
_container = _containerBuilder();
return _container;
}
private set
{
_container = value;
_registrar = new AutofacServiceRegistrar(this, value);
}
}
#endregion
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Collections.Generic;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Atn
{
public class LL1Analyzer
{
/// <summary>
/// Special value added to the lookahead sets to indicate that we hit
/// a predicate during analysis if
/// <c>seeThruPreds==false</c>
/// .
/// </summary>
public const int HitPred = TokenConstants.InvalidType;
[NotNull]
public readonly ATN atn;
public LL1Analyzer(ATN atn)
{
this.atn = atn;
}
/// <summary>
/// Calculates the SLL(1) expected lookahead set for each outgoing transition
/// of an
/// <see cref="ATNState"/>
/// . The returned array has one element for each
/// outgoing transition in
/// <paramref name="s"/>
/// . If the closure from transition
/// <em>i</em> leads to a semantic predicate before matching a symbol, the
/// element at index <em>i</em> of the result will be
/// <see langword="null"/>
/// .
/// </summary>
/// <param name="s">the ATN state</param>
/// <returns>
/// the expected symbols for each outgoing transition of
/// <paramref name="s"/>
/// .
/// </returns>
[return: Nullable]
public virtual IntervalSet[] GetDecisionLookahead(ATNState s)
{
// System.out.println("LOOK("+s.stateNumber+")");
if (s == null)
{
return null;
}
IntervalSet[] look = new IntervalSet[s.NumberOfTransitions];
for (int alt = 0; alt < s.NumberOfTransitions; alt++)
{
look[alt] = new IntervalSet();
HashSet<ATNConfig> lookBusy = new HashSet<ATNConfig>();
bool seeThruPreds = false;
// fail to get lookahead upon pred
Look(s.Transition(alt).target, null, PredictionContext.EmptyLocal, look[alt], lookBusy, new BitSet(), seeThruPreds, false);
// Wipe out lookahead for this alternative if we found nothing
// or we had a predicate when we !seeThruPreds
if (look[alt].Count == 0 || look[alt].Contains(HitPred))
{
look[alt] = null;
}
}
return look;
}
/// <summary>
/// Compute set of tokens that can follow
/// <paramref name="s"/>
/// in the ATN in the
/// specified
/// <paramref name="ctx"/>
/// .
/// <p>If
/// <paramref name="ctx"/>
/// is
/// <see langword="null"/>
/// and the end of the rule containing
/// <paramref name="s"/>
/// is reached,
/// <see cref="TokenConstants.Epsilon"/>
/// is added to the result set.
/// If
/// <paramref name="ctx"/>
/// is not
/// <see langword="null"/>
/// and the end of the outermost rule is
/// reached,
/// <see cref="TokenConstants.Eof"/>
/// is added to the result set.</p>
/// </summary>
/// <param name="s">the ATN state</param>
/// <param name="ctx">
/// the complete parser context, or
/// <see langword="null"/>
/// if the context
/// should be ignored
/// </param>
/// <returns>
/// The set of tokens that can follow
/// <paramref name="s"/>
/// in the ATN in the
/// specified
/// <paramref name="ctx"/>
/// .
/// </returns>
[return: NotNull]
public virtual IntervalSet Look(ATNState s, PredictionContext ctx)
{
return Look(s, s.atn.ruleToStopState[s.ruleIndex], ctx);
}
/// <summary>
/// Compute set of tokens that can follow
/// <paramref name="s"/>
/// in the ATN in the
/// specified
/// <paramref name="ctx"/>
/// .
/// <p>If
/// <paramref name="ctx"/>
/// is
/// <see langword="null"/>
/// and the end of the rule containing
/// <paramref name="s"/>
/// is reached,
/// <see cref="TokenConstants.Epsilon"/>
/// is added to the result set.
/// If
/// <paramref name="ctx"/>
/// is not
/// <c>PredictionContext#EMPTY_LOCAL</c>
/// and the end of the outermost rule is
/// reached,
/// <see cref="TokenConstants.Eof"/>
/// is added to the result set.</p>
/// </summary>
/// <param name="s">the ATN state</param>
/// <param name="stopState">
/// the ATN state to stop at. This can be a
/// <see cref="BlockEndState"/>
/// to detect epsilon paths through a closure.
/// </param>
/// <param name="ctx">
/// the complete parser context, or
/// <see langword="null"/>
/// if the context
/// should be ignored
/// </param>
/// <returns>
/// The set of tokens that can follow
/// <paramref name="s"/>
/// in the ATN in the
/// specified
/// <paramref name="ctx"/>
/// .
/// </returns>
[return: NotNull]
public virtual IntervalSet Look(ATNState s, ATNState stopState, PredictionContext ctx)
{
IntervalSet r = new IntervalSet();
bool seeThruPreds = true;
// ignore preds; get all lookahead
bool addEOF = true;
Look(s, stopState, ctx, r, new HashSet<ATNConfig>(), new BitSet(), seeThruPreds, addEOF);
return r;
}
/// <summary>
/// Compute set of tokens that can follow
/// <paramref name="s"/>
/// in the ATN in the
/// specified
/// <paramref name="ctx"/>
/// .
/// <p/>
/// If
/// <paramref name="ctx"/>
/// is
/// <see cref="PredictionContext.EmptyLocal"/>
/// and
/// <paramref name="stopState"/>
/// or the end of the rule containing
/// <paramref name="s"/>
/// is reached,
/// <see cref="TokenConstants.Epsilon"/>
/// is added to the result set. If
/// <paramref name="ctx"/>
/// is not
/// <see cref="PredictionContext.EmptyLocal"/>
/// and
/// <paramref name="addEOF"/>
/// is
/// <see langword="true"/>
/// and
/// <paramref name="stopState"/>
/// or the end of the outermost rule is reached,
/// <see cref="TokenConstants.Eof"/>
/// is added to the result set.
/// </summary>
/// <param name="s">the ATN state.</param>
/// <param name="stopState">
/// the ATN state to stop at. This can be a
/// <see cref="BlockEndState"/>
/// to detect epsilon paths through a closure.
/// </param>
/// <param name="ctx">
/// The outer context, or
/// <see cref="PredictionContext.EmptyLocal"/>
/// if
/// the outer context should not be used.
/// </param>
/// <param name="look">The result lookahead set.</param>
/// <param name="lookBusy">
/// A set used for preventing epsilon closures in the ATN
/// from causing a stack overflow. Outside code should pass
/// <c>new HashSet<ATNConfig></c>
/// for this argument.
/// </param>
/// <param name="calledRuleStack">
/// A set used for preventing left recursion in the
/// ATN from causing a stack overflow. Outside code should pass
/// <c>new BitSet()</c>
/// for this argument.
/// </param>
/// <param name="seeThruPreds">
///
/// <see langword="true"/>
/// to true semantic predicates as
/// implicitly
/// <see langword="true"/>
/// and "see through them", otherwise
/// <see langword="false"/>
/// to treat semantic predicates as opaque and add
/// <see cref="HitPred"/>
/// to the
/// result if one is encountered.
/// </param>
/// <param name="addEOF">
/// Add
/// <see cref="TokenConstants.Eof"/>
/// to the result if the end of the
/// outermost context is reached. This parameter has no effect if
/// <paramref name="ctx"/>
/// is
/// <see cref="PredictionContext.EmptyLocal"/>
/// .
/// </param>
protected internal virtual void Look(ATNState s, ATNState stopState, PredictionContext ctx, IntervalSet look, HashSet<ATNConfig> lookBusy, BitSet calledRuleStack, bool seeThruPreds, bool addEOF)
{
// System.out.println("_LOOK("+s.stateNumber+", ctx="+ctx);
ATNConfig c = ATNConfig.Create(s, 0, ctx);
if (!lookBusy.Add(c))
{
return;
}
if (s == stopState)
{
if (PredictionContext.IsEmptyLocal(ctx))
{
look.Add(TokenConstants.Epsilon);
return;
}
else
{
if (ctx.IsEmpty)
{
if (addEOF)
{
look.Add(TokenConstants.Eof);
}
return;
}
}
}
if (s is RuleStopState)
{
if (ctx.IsEmpty && !PredictionContext.IsEmptyLocal(ctx))
{
if (addEOF)
{
look.Add(TokenConstants.Eof);
}
return;
}
bool removed = calledRuleStack.Get(s.ruleIndex);
try
{
calledRuleStack.Clear(s.ruleIndex);
for (int i = 0; i < ctx.Size; i++)
{
if (ctx.GetReturnState(i) == PredictionContext.EmptyFullStateKey)
{
continue;
}
ATNState returnState = atn.states[ctx.GetReturnState(i)];
// System.out.println("popping back to "+retState);
Look(returnState, stopState, ctx.GetParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
}
}
finally
{
if (removed)
{
calledRuleStack.Set(s.ruleIndex);
}
}
}
int n = s.NumberOfTransitions;
for (int i_1 = 0; i_1 < n; i_1++)
{
Transition t = s.Transition(i_1);
if (t is RuleTransition)
{
RuleTransition ruleTransition = (RuleTransition)t;
if (calledRuleStack.Get(ruleTransition.ruleIndex))
{
continue;
}
PredictionContext newContext = ctx.GetChild(ruleTransition.followState.stateNumber);
try
{
calledRuleStack.Set(ruleTransition.ruleIndex);
Look(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
}
finally
{
calledRuleStack.Clear(ruleTransition.ruleIndex);
}
}
else
{
if (t is AbstractPredicateTransition)
{
if (seeThruPreds)
{
Look(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
}
else
{
look.Add(HitPred);
}
}
else
{
if (t.IsEpsilon)
{
Look(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
}
else
{
if (t.GetType() == typeof(WildcardTransition))
{
look.AddAll(IntervalSet.Of(TokenConstants.MinUserTokenType, atn.maxTokenType));
}
else
{
// System.out.println("adding "+ t);
IntervalSet set = t.Label;
if (set != null)
{
if (t is NotSetTransition)
{
set = set.Complement(IntervalSet.Of(TokenConstants.MinUserTokenType, atn.maxTokenType));
}
look.AddAll(set);
}
}
}
}
}
}
}
}
}
| |
#region License and Terms
// CustomExtensions - Custom Extension Methods For C#
// Copyright (c) 2011 - 2013 Jonathan Comtois. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using CustomExtensions.ForIEnumerable;
using CustomExtensions.UnitTests.Customization.Fixtures;
using CustomExtensions.Validation;
using NUnit.Framework;
using Ploeh.AutoFixture;
namespace CustomExtensions.UnitTests.ForIEnumerablesTests
{
public partial class ForIEnumerablesTests
{
[TestFixture]
public class ReplaceTest
{
[Test]
public void Replace_OnEmptySequence_WithElement_WithNullProjection_ThrowsValidationException()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
Func<object, object> nullFunc = null;
Assert.That(() => emptySequence.Replace(objectValue, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnEmptySequence_WithElement_WithNullReplacement_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
object nullObject = null;
Assert.That(() => emptySequence.Replace(objectValue, nullObject), Is.Empty);
}
[Test]
public void Replace_OnEmptySequence_WithElement_WithProjection_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => emptySequence.Replace(objectValue, objectFunc), Is.Empty);
}
[Test]
public void Replace_OnEmptySequence_WithElement_WithReplacement_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
Assert.That(() => emptySequence.Replace(objectValue, objectValue), Is.Empty);
}
[Test]
public void Replace_OnEmptySequence_WithNullElement_WithNullProjection_ThrowsValidationException()
{
var emptySequence = Enumerable.Empty<object>();
object nullObject = null;
Func<object, object> nullFunc = null;
Assert.That(() => emptySequence.Replace(nullObject, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnEmptySequence_WithNullElement_WithNullReplacement_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
object nullObject = null;
Assert.That(() => emptySequence.Replace(nullObject, nullObject), Is.Empty);
}
[Test]
public void Replace_OnEmptySequence_WithNullElement_WithProjection_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
object nullObject = null;
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => emptySequence.Replace(nullObject, objectFunc), Is.Empty);
}
[Test]
public void Replace_OnEmptySequence_WithNullElement_WithReplacement_ReturnsEmptySequence()
{
var emptySequence = Enumerable.Empty<object>();
var fixture = new BaseFixture();
object nullObject = null;
var objectValue = fixture.Create<object>();
Assert.That(() => emptySequence.Replace(nullObject, objectValue), Is.Empty);
}
[Test]
public void Replace_OnNullSequence_WithElement_WithNullProjection_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
Func<object, object> nullFunc = null;
Assert.That(() => nullSequence.Replace(objectValue, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<MultiException>());
}
[Test]
public void Replace_OnNullSequence_WithElement_WithNullReplacement_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
object nullObject = null;
Assert.That(() => nullSequence.Replace(objectValue, nullObject), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnNullSequence_WithElement_WithProjection_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => nullSequence.Replace(objectValue, objectFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnNullSequence_WithElement_WithReplacement_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
var objectValue = fixture.Create<object>();
Assert.That(() => nullSequence.Replace(objectValue, objectValue), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnNullSequence_WithNullElement_WithNullProjection_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
object nullObject = null;
Func<object, object> nullFunc = null;
Assert.That(() => nullSequence.Replace(nullObject, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<MultiException>());
}
[Test]
public void Replace_OnNullSequence_WithNullElement_WithNullReplacement_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
object nullObject = null;
Assert.That(() => nullSequence.Replace(nullObject, nullObject), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnNullSequence_WithNullElement_WithProjection_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
object nullObject = null;
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => nullSequence.Replace(nullObject, objectFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnNullSequence_WithNullElement_WithReplacement_ThrowsValidationException()
{
IEnumerable<object> nullSequence = null;
var fixture = new BaseFixture();
object nullObject = null;
var objectValue = fixture.Create<object>();
Assert.That(() => nullSequence.Replace(nullObject, objectValue), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnSequenceWithNulls_WithNullElement_WithNullReplacement_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
sequence[1] = nullObject;
Assert.That(() => sequence.Replace(nullObject, nullObject), Is.EqualTo(sequence));
}
[Test]
public void Replace_OnSequenceWithNulls_WithNullElement_WithReplacement_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
sequence[0] = nullObject;
var objectValue = fixture.Create<object>();
var expected = new[] {objectValue, sequence[1], sequence[2]};
Assert.That(() => sequence.Replace(nullObject, objectValue), Is.EqualTo(expected));
}
[Test]
public void Replace_OnSequence_WithElement_WithNullProjection_ThrowsValidationException()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = fixture.Create<object>();
Func<object, object> nullFunc = null;
Assert.That(() => sequence.Replace(objectValue, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnSequence_WithElement_WithNullReplacement_ReturnsWithNullAsReplacement()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = sequence[2];
object nullObject = null;
var expected = new[] {sequence[0], sequence[1], nullObject};
Assert.That(() => sequence.Replace(objectValue, nullObject), Is.EqualTo(expected));
}
[Test]
public void Replace_OnSequence_WithElement_WithProjection_ReturnsSequenceWithReplacement()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = sequence[1];
var objectFunc = fixture.Create<Func<object, object>>();
var projectedValue = objectFunc(objectValue);
var expected = new[] {sequence[0], projectedValue, sequence[2]};
Assert.That(() => sequence.Replace(objectValue, objectFunc), Is.EqualTo(expected));
}
[Test]
public void Replace_OnSequence_WithElement_WithReplacement_ReturnsSequenceWithReplacement()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = sequence[0];
var replacementValue = fixture.Create<object>();
var expected = new[] {replacementValue, sequence[1], sequence[2]};
Assert.That(() => sequence.Replace(objectValue, replacementValue), Is.EqualTo(expected));
}
[Test]
public void Replace_OnSequence_WithNoMatches_WithProjection_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = fixture.Create<object>();
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => sequence.Replace(objectValue, objectFunc), Is.EqualTo(sequence));
}
[Test]
public void Replace_OnSequence_WithNoMatches_WithReplacement_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
var objectValue = fixture.Create<object>();
var replacementValue = fixture.Create<object>();
Assert.That(() => sequence.Replace(objectValue, replacementValue), Is.EqualTo(sequence));
}
[Test]
public void Replace_OnSequence_WithNullElement_WithNullProjection_ThrowsValidationException()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
Func<object, object> nullFunc = null;
Assert.That(() => sequence.Replace(nullObject, nullFunc), Throws.TypeOf<ValidationException>().With.InnerException.TypeOf<ArgumentNullException>());
}
[Test]
public void Replace_OnSequence_WithNullElement_WithNullReplacement_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
Assert.That(() => sequence.Replace(nullObject, nullObject), Is.EqualTo(sequence));
}
[Test]
public void Replace_OnSequence_WithNullElement_WithProjection_NullsReplacedInSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
sequence[1] = nullObject;
sequence[2] = nullObject;
var objectFunc = fixture.Create<Func<object, object>>();
var expected = new[] {sequence[0], objectFunc(sequence[1]), objectFunc(sequence[2])};
Assert.That(() => sequence.Replace(nullObject, objectFunc), Is.EqualTo(expected));
}
[Test]
public void Replace_OnSequence_WithNullElement_WithReplacement_ReturnsOriginalSequence()
{
var fixture = new MultipleMockingFixture();
var sequence = fixture.Create<IList<object>>();
object nullObject = null;
var objectValue = fixture.Create<object>();
Assert.That(() => sequence.Replace(nullObject, objectValue), Is.EqualTo(sequence));
}
[Test]
public void Replace_WithProjection_IsLazy()
{
var fixture = new BaseFixture();
var breakingSequence = fixture.Create<BreakingSequence<object>>();
var objectValue = fixture.Create<object>();
var objectFunc = fixture.Create<Func<object, object>>();
Assert.That(() => breakingSequence.Replace(objectValue, objectFunc), Throws.Nothing);
}
[Test]
public void Replace_WithReplacement_IsLazy()
{
var fixture = new BaseFixture();
var breakingSequence = fixture.Create<BreakingSequence<object>>();
var objectValue = fixture.Create<object>();
Assert.That(() => breakingSequence.Replace(objectValue, objectValue), Throws.Nothing);
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmDayEnd
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmDayEnd() : base()
{
FormClosed += frmDayEnd_FormClosed;
KeyPress += frmDayEnd_KeyPress;
Load += frmDayEnd_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.Label lblDemo;
public System.Windows.Forms.Label lblText;
public System.Windows.Forms.GroupBox _frmMode_4;
private System.Windows.Forms.Button withEventsField_cmdBack;
public System.Windows.Forms.Button cmdBack {
get { return withEventsField_cmdBack; }
set {
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click -= cmdBack_Click;
}
withEventsField_cmdBack = value;
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click += cmdBack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
public System.Windows.Forms.ListBox lstPOS;
public System.Windows.Forms.Label _Label1_3;
public System.Windows.Forms.Label _Label1_0;
public System.Windows.Forms.GroupBox _frmMode_0;
public System.Windows.Forms.MonthCalendar calDayEnd;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label _Label1_2;
public System.Windows.Forms.Label _Label1_1;
public System.Windows.Forms.GroupBox _frmMode_2;
public System.Windows.Forms.Label _Label1_4;
public System.Windows.Forms.Label _Label1_5;
public System.Windows.Forms.GroupBox _frmMode_1;
public System.Windows.Forms.PictureBox Picture2;
public System.Windows.Forms.GroupBox _frmMode_3;
//Public WithEvents MAPISession1 As MSMAPI.MAPISession
//Public WithEvents MAPIMessages1 As MSMAPI.MAPIMessages
public System.Windows.Forms.Label Label3;
//Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmDayEnd));
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this._frmMode_4 = new System.Windows.Forms.GroupBox();
this.lblDemo = new System.Windows.Forms.Label();
this.lblText = new System.Windows.Forms.Label();
this.cmdBack = new System.Windows.Forms.Button();
this.cmdNext = new System.Windows.Forms.Button();
this._frmMode_0 = new System.Windows.Forms.GroupBox();
this.lstPOS = new System.Windows.Forms.ListBox();
this._Label1_3 = new System.Windows.Forms.Label();
this._Label1_0 = new System.Windows.Forms.Label();
this._frmMode_2 = new System.Windows.Forms.GroupBox();
this.calDayEnd = new System.Windows.Forms.MonthCalendar();
this.Label2 = new System.Windows.Forms.Label();
this._Label1_2 = new System.Windows.Forms.Label();
this._Label1_1 = new System.Windows.Forms.Label();
this._frmMode_1 = new System.Windows.Forms.GroupBox();
this._Label1_4 = new System.Windows.Forms.Label();
this._Label1_5 = new System.Windows.Forms.Label();
this._frmMode_3 = new System.Windows.Forms.GroupBox();
this.Picture2 = new System.Windows.Forms.PictureBox();
this.Label3 = new System.Windows.Forms.Label();
this._frmMode_4.SuspendLayout();
this._frmMode_0.SuspendLayout();
this._frmMode_2.SuspendLayout();
this._frmMode_1.SuspendLayout();
this._frmMode_3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)this.Picture2).BeginInit();
this.SuspendLayout();
//
//_frmMode_4
//
this._frmMode_4.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_4.Controls.Add(this.lblDemo);
this._frmMode_4.Controls.Add(this.lblText);
this._frmMode_4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_4.Location = new System.Drawing.Point(412, 319);
this._frmMode_4.Name = "_frmMode_4";
this._frmMode_4.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_4.Size = new System.Drawing.Size(196, 313);
this._frmMode_4.TabIndex = 16;
this._frmMode_4.TabStop = false;
this._frmMode_4.Text = "Demo Version Notification";
//
//lblDemo
//
this.lblDemo.BackColor = System.Drawing.SystemColors.Control;
this.lblDemo.Cursor = System.Windows.Forms.Cursors.Default;
this.lblDemo.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblDemo.ForeColor = System.Drawing.Color.Black;
this.lblDemo.Location = new System.Drawing.Point(12, 138);
this.lblDemo.Name = "lblDemo";
this.lblDemo.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblDemo.Size = new System.Drawing.Size(175, 124);
this.lblDemo.TabIndex = 18;
//
//lblText
//
this.lblText.BackColor = System.Drawing.SystemColors.Control;
this.lblText.Cursor = System.Windows.Forms.Cursors.Default;
this.lblText.ForeColor = System.Drawing.Color.Black;
this.lblText.Location = new System.Drawing.Point(12, 33);
this.lblText.Name = "lblText";
this.lblText.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblText.Size = new System.Drawing.Size(175, 82);
this.lblText.TabIndex = 17;
this.lblText.Text = "The 4POS Application you are currently using is a Demo Version. The Demo version " + "is a fully functional version except that you may only run one ten Day End runs." + "";
//
//cmdBack
//
this.cmdBack.BackColor = System.Drawing.SystemColors.Control;
this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBack.Location = new System.Drawing.Point(4, 350);
this.cmdBack.Name = "cmdBack";
this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBack.Size = new System.Drawing.Size(85, 25);
this.cmdBack.TabIndex = 4;
this.cmdBack.Text = "E&xit";
this.cmdBack.UseVisualStyleBackColor = false;
//
//cmdNext
//
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Location = new System.Drawing.Point(118, 350);
this.cmdNext.Name = "cmdNext";
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.Size = new System.Drawing.Size(84, 25);
this.cmdNext.TabIndex = 3;
this.cmdNext.Text = "&Next >>";
this.cmdNext.UseVisualStyleBackColor = false;
//
//_frmMode_0
//
this._frmMode_0.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_0.Controls.Add(this.lstPOS);
this._frmMode_0.Controls.Add(this._Label1_3);
this._frmMode_0.Controls.Add(this._Label1_0);
this._frmMode_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_0.Location = new System.Drawing.Point(6, 12);
this._frmMode_0.Name = "_frmMode_0";
this._frmMode_0.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_0.Size = new System.Drawing.Size(196, 313);
this._frmMode_0.TabIndex = 0;
this._frmMode_0.TabStop = false;
this._frmMode_0.Text = "No Cashup Declarations";
//
//lstPOS
//
this.lstPOS.BackColor = System.Drawing.SystemColors.Window;
this.lstPOS.Cursor = System.Windows.Forms.Cursors.Default;
this.lstPOS.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lstPOS.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstPOS.ItemHeight = 16;
this.lstPOS.Location = new System.Drawing.Point(9, 18);
this.lstPOS.Name = "lstPOS";
this.lstPOS.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstPOS.Size = new System.Drawing.Size(178, 164);
this.lstPOS.TabIndex = 1;
//
//_Label1_3
//
this._Label1_3.BackColor = System.Drawing.SystemColors.Control;
this._Label1_3.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_3.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label1_3.ForeColor = System.Drawing.Color.Red;
this._Label1_3.Location = new System.Drawing.Point(12, 246);
this._Label1_3.Name = "_Label1_3";
this._Label1_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_3.Size = new System.Drawing.Size(178, 43);
this._Label1_3.TabIndex = 10;
this._Label1_3.Text = "All active Point Of Sales Devices have to be declared before your Day End Run.";
//
//_Label1_0
//
this._Label1_0.BackColor = System.Drawing.SystemColors.Control;
this._Label1_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label1_0.ForeColor = System.Drawing.Color.Red;
this._Label1_0.Location = new System.Drawing.Point(12, 201);
this._Label1_0.Name = "_Label1_0";
this._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_0.Size = new System.Drawing.Size(178, 40);
this._Label1_0.TabIndex = 2;
this._Label1_0.Text = "The following Point Of Sales Devices have not been declared.";
//
//_frmMode_2
//
this._frmMode_2.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_2.Controls.Add(this.calDayEnd);
this._frmMode_2.Controls.Add(this.Label2);
this._frmMode_2.Controls.Add(this._Label1_2);
this._frmMode_2.Controls.Add(this._Label1_1);
this._frmMode_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_2.Location = new System.Drawing.Point(210, 0);
this._frmMode_2.Name = "_frmMode_2";
this._frmMode_2.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_2.Size = new System.Drawing.Size(196, 313);
this._frmMode_2.TabIndex = 5;
this._frmMode_2.TabStop = false;
this._frmMode_2.Text = "Confirm Day End Run";
//
//calDayEnd
//
this.calDayEnd.Location = new System.Drawing.Point(9, 42);
this.calDayEnd.Name = "calDayEnd";
this.calDayEnd.TabIndex = 14;
//
//Label2
//
this.Label2.BackColor = System.Drawing.Color.Transparent;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label2.ForeColor = System.Drawing.Color.Blue;
this.Label2.Location = new System.Drawing.Point(6, 252);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(181, 52);
this.Label2.TabIndex = 15;
this.Label2.Text = "Please insure that there are no other users using the system before pressing the " + "\"Next\" button!";
//
//_Label1_2
//
this._Label1_2.BackColor = System.Drawing.SystemColors.Control;
this._Label1_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label1_2.Location = new System.Drawing.Point(9, 207);
this._Label1_2.Name = "_Label1_2";
this._Label1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_2.Size = new System.Drawing.Size(178, 43);
this._Label1_2.TabIndex = 9;
this._Label1_2.Text = "As part of the \"Day End\" run, the integrity of your database will be check and a " + "backup made.";
//
//_Label1_1
//
this._Label1_1.BackColor = System.Drawing.SystemColors.Control;
this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label1_1.Location = new System.Drawing.Point(15, 13);
this._Label1_1.Name = "_Label1_1";
this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_1.Size = new System.Drawing.Size(178, 34);
this._Label1_1.TabIndex = 6;
this._Label1_1.Text = "Use the date selector to select the correct date for your day end.";
//
//_frmMode_1
//
this._frmMode_1.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_1.Controls.Add(this._Label1_4);
this._frmMode_1.Controls.Add(this._Label1_5);
this._frmMode_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_1.Location = new System.Drawing.Point(210, 319);
this._frmMode_1.Name = "_frmMode_1";
this._frmMode_1.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_1.Size = new System.Drawing.Size(196, 313);
this._frmMode_1.TabIndex = 11;
this._frmMode_1.TabStop = false;
this._frmMode_1.Text = "No POS Trasactions";
//
//_Label1_4
//
this._Label1_4.BackColor = System.Drawing.SystemColors.Control;
this._Label1_4.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label1_4.ForeColor = System.Drawing.Color.Red;
this._Label1_4.Location = new System.Drawing.Point(9, 129);
this._Label1_4.Name = "_Label1_4";
this._Label1_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_4.Size = new System.Drawing.Size(178, 70);
this._Label1_4.TabIndex = 13;
this._Label1_4.Text = "There is no need to run your Day End Run.";
//
//_Label1_5
//
this._Label1_5.BackColor = System.Drawing.SystemColors.Control;
this._Label1_5.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Label1_5.ForeColor = System.Drawing.Color.Red;
this._Label1_5.Location = new System.Drawing.Point(12, 57);
this._Label1_5.Name = "_Label1_5";
this._Label1_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_5.Size = new System.Drawing.Size(178, 70);
this._Label1_5.TabIndex = 12;
this._Label1_5.Text = "There have been no Point Of Sale transactions since the last time this Day End Ru" + "n procedure was run.";
//
//_frmMode_3
//
this._frmMode_3.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_3.Controls.Add(this.Picture2);
this._frmMode_3.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_3.Location = new System.Drawing.Point(412, 0);
this._frmMode_3.Name = "_frmMode_3";
this._frmMode_3.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_3.Size = new System.Drawing.Size(196, 313);
this._frmMode_3.TabIndex = 7;
this._frmMode_3.TabStop = false;
this._frmMode_3.Text = "Day End Run Complete";
//
//Picture2
//
this.Picture2.BackColor = System.Drawing.SystemColors.Control;
this.Picture2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Picture2.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Picture2.Image = (System.Drawing.Image)resources.GetObject("Picture2.Image");
this.Picture2.Location = new System.Drawing.Point(27, 54);
this.Picture2.Name = "Picture2";
this.Picture2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture2.Size = new System.Drawing.Size(140, 205);
this.Picture2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.Picture2.TabIndex = 8;
//
//Label3
//
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Location = new System.Drawing.Point(6, 330);
this.Label3.Name = "Label3";
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.Size = new System.Drawing.Size(195, 15);
this.Label3.TabIndex = 19;
this.Label3.Text = "Please Wait, Stock Update progress...";
this.Label3.Visible = false;
//
//frmDayEnd
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(654, 483);
this.ControlBox = false;
this.Controls.Add(this._frmMode_4);
this.Controls.Add(this.cmdBack);
this.Controls.Add(this.cmdNext);
this.Controls.Add(this._frmMode_0);
this.Controls.Add(this._frmMode_2);
this.Controls.Add(this._frmMode_1);
this.Controls.Add(this._frmMode_3);
this.Controls.Add(this.Label3);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.Location = new System.Drawing.Point(3, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmDayEnd";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Day End Run";
this._frmMode_4.ResumeLayout(false);
this._frmMode_0.ResumeLayout(false);
this._frmMode_2.ResumeLayout(false);
this._frmMode_1.ResumeLayout(false);
this._frmMode_3.ResumeLayout(false);
this._frmMode_3.PerformLayout();
((System.ComponentModel.ISupportInitialize)this.Picture2).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class ImageCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fSource, fValue, fSizing, fMIMEType;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbExternal;
private System.Windows.Forms.RadioButton rbDatabase;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox cbSizing;
private System.Windows.Forms.ComboBox cbValueEmbedded;
private System.Windows.Forms.ComboBox cbMIMEType;
private System.Windows.Forms.ComboBox cbValueDatabase;
private System.Windows.Forms.TextBox tbValueExternal;
private System.Windows.Forms.Button bExternal;
private System.Windows.Forms.RadioButton rbEmbedded;
private System.Windows.Forms.Button bEmbedded;
private System.Windows.Forms.Button bDatabaseExpr;
private System.Windows.Forms.Button bMimeExpr;
private System.Windows.Forms.Button bEmbeddedExpr;
private System.Windows.Forms.Button bExternalExpr;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ImageCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode iNode = _ReportItems[0];
// Populate the EmbeddedImage names
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
string[] flds = _Draw.GetReportItemDataRegionFields(iNode, true);
if (flds != null)
this.cbValueDatabase.Items.AddRange(flds);
string source = _Draw.GetElementValue(iNode, "Source", "Embedded");
string val = _Draw.GetElementValue(iNode, "Value", "");
switch (source)
{
case "Embedded":
this.rbEmbedded.Checked = true;
this.cbValueEmbedded.Text = val;
break;
case "Database":
this.rbDatabase.Checked = true;
this.cbValueDatabase.Text = val;
this.cbMIMEType.Text = _Draw.GetElementValue(iNode, "MIMEType", "image/png");
break;
case "External":
default:
this.rbExternal.Checked = true;
this.tbValueExternal.Text = val;
break;
}
this.cbSizing.Text = _Draw.GetElementValue(iNode, "Sizing", "AutoSize");
fSource = fValue = fSizing = fMIMEType = false;
}
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.bExternalExpr = new System.Windows.Forms.Button();
this.bEmbeddedExpr = new System.Windows.Forms.Button();
this.bMimeExpr = new System.Windows.Forms.Button();
this.bDatabaseExpr = new System.Windows.Forms.Button();
this.bEmbedded = new System.Windows.Forms.Button();
this.bExternal = new System.Windows.Forms.Button();
this.tbValueExternal = new System.Windows.Forms.TextBox();
this.cbValueDatabase = new System.Windows.Forms.ComboBox();
this.cbMIMEType = new System.Windows.Forms.ComboBox();
this.cbValueEmbedded = new System.Windows.Forms.ComboBox();
this.rbDatabase = new System.Windows.Forms.RadioButton();
this.rbEmbedded = new System.Windows.Forms.RadioButton();
this.rbExternal = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.cbSizing = new System.Windows.Forms.ComboBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.bExternalExpr);
this.groupBox1.Controls.Add(this.bEmbeddedExpr);
this.groupBox1.Controls.Add(this.bMimeExpr);
this.groupBox1.Controls.Add(this.bDatabaseExpr);
this.groupBox1.Controls.Add(this.bEmbedded);
this.groupBox1.Controls.Add(this.bExternal);
this.groupBox1.Controls.Add(this.tbValueExternal);
this.groupBox1.Controls.Add(this.cbValueDatabase);
this.groupBox1.Controls.Add(this.cbMIMEType);
this.groupBox1.Controls.Add(this.cbValueEmbedded);
this.groupBox1.Controls.Add(this.rbDatabase);
this.groupBox1.Controls.Add(this.rbEmbedded);
this.groupBox1.Controls.Add(this.rbExternal);
this.groupBox1.Location = new System.Drawing.Point(16, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(408, 152);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Source";
//
// bExternalExpr
//
this.bExternalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExternalExpr.Location = new System.Drawing.Point(352, 24);
this.bExternalExpr.Name = "bExternalExpr";
this.bExternalExpr.Size = new System.Drawing.Size(24, 21);
this.bExternalExpr.TabIndex = 12;
this.bExternalExpr.Tag = "external";
this.bExternalExpr.Text = "fx";
this.bExternalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExternalExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bEmbeddedExpr
//
this.bEmbeddedExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bEmbeddedExpr.Location = new System.Drawing.Point(352, 56);
this.bEmbeddedExpr.Name = "bEmbeddedExpr";
this.bEmbeddedExpr.Size = new System.Drawing.Size(24, 21);
this.bEmbeddedExpr.TabIndex = 11;
this.bEmbeddedExpr.Tag = "embedded";
this.bEmbeddedExpr.Text = "fx";
this.bEmbeddedExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bEmbeddedExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMimeExpr
//
this.bMimeExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMimeExpr.Location = new System.Drawing.Point(184, 88);
this.bMimeExpr.Name = "bMimeExpr";
this.bMimeExpr.Size = new System.Drawing.Size(24, 21);
this.bMimeExpr.TabIndex = 10;
this.bMimeExpr.Tag = "mime";
this.bMimeExpr.Text = "fx";
this.bMimeExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMimeExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bDatabaseExpr
//
this.bDatabaseExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bDatabaseExpr.Location = new System.Drawing.Point(352, 120);
this.bDatabaseExpr.Name = "bDatabaseExpr";
this.bDatabaseExpr.Size = new System.Drawing.Size(24, 21);
this.bDatabaseExpr.TabIndex = 9;
this.bDatabaseExpr.Tag = "database";
this.bDatabaseExpr.Text = "fx";
this.bDatabaseExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDatabaseExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bEmbedded
//
this.bEmbedded.Location = new System.Drawing.Point(378, 56);
this.bEmbedded.Name = "bEmbedded";
this.bEmbedded.Size = new System.Drawing.Size(24, 21);
this.bEmbedded.TabIndex = 8;
this.bEmbedded.Text = "...";
this.bEmbedded.Click += new System.EventHandler(this.bEmbedded_Click);
//
// bExternal
//
this.bExternal.Location = new System.Drawing.Point(378, 24);
this.bExternal.Name = "bExternal";
this.bExternal.Size = new System.Drawing.Size(24, 21);
this.bExternal.TabIndex = 7;
this.bExternal.Text = "...";
this.bExternal.Click += new System.EventHandler(this.bExternal_Click);
//
// tbValueExternal
//
this.tbValueExternal.Location = new System.Drawing.Point(88, 24);
this.tbValueExternal.Name = "tbValueExternal";
this.tbValueExternal.Size = new System.Drawing.Size(256, 20);
this.tbValueExternal.TabIndex = 6;
this.tbValueExternal.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// cbValueDatabase
//
this.cbValueDatabase.Location = new System.Drawing.Point(88, 120);
this.cbValueDatabase.Name = "cbValueDatabase";
this.cbValueDatabase.Size = new System.Drawing.Size(256, 21);
this.cbValueDatabase.TabIndex = 5;
this.cbValueDatabase.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// cbMIMEType
//
this.cbMIMEType.Items.AddRange(new object[] {
"image/bmp",
"image/jpeg",
"image/gif",
"image/png",
"image/x-png"});
this.cbMIMEType.Location = new System.Drawing.Point(88, 88);
this.cbMIMEType.Name = "cbMIMEType";
this.cbMIMEType.Size = new System.Drawing.Size(88, 21);
this.cbMIMEType.TabIndex = 4;
this.cbMIMEType.Text = "image/jpeg";
this.cbMIMEType.SelectedIndexChanged += new System.EventHandler(this.cbMIMEType_SelectedIndexChanged);
//
// cbValueEmbedded
//
this.cbValueEmbedded.Location = new System.Drawing.Point(88, 56);
this.cbValueEmbedded.Name = "cbValueEmbedded";
this.cbValueEmbedded.Size = new System.Drawing.Size(256, 21);
this.cbValueEmbedded.TabIndex = 3;
this.cbValueEmbedded.TextChanged += new System.EventHandler(this.Value_TextChanged);
//
// rbDatabase
//
this.rbDatabase.Location = new System.Drawing.Point(8, 88);
this.rbDatabase.Name = "rbDatabase";
this.rbDatabase.Size = new System.Drawing.Size(80, 24);
this.rbDatabase.TabIndex = 2;
this.rbDatabase.Text = "Database";
this.rbDatabase.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbEmbedded
//
this.rbEmbedded.Location = new System.Drawing.Point(8, 56);
this.rbEmbedded.Name = "rbEmbedded";
this.rbEmbedded.Size = new System.Drawing.Size(80, 24);
this.rbEmbedded.TabIndex = 1;
this.rbEmbedded.Text = "Embedded";
this.rbEmbedded.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbExternal
//
this.rbExternal.Location = new System.Drawing.Point(8, 24);
this.rbExternal.Name = "rbExternal";
this.rbExternal.Size = new System.Drawing.Size(80, 24);
this.rbExternal.TabIndex = 0;
this.rbExternal.Text = "External";
this.rbExternal.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 184);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 23);
this.label1.TabIndex = 1;
this.label1.Text = "Sizing";
//
// cbSizing
//
this.cbSizing.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbSizing.Items.AddRange(new object[] {
"AutoSize",
"Fit",
"FitProportional",
"Clip"});
this.cbSizing.Location = new System.Drawing.Point(72, 184);
this.cbSizing.Name = "cbSizing";
this.cbSizing.Size = new System.Drawing.Size(96, 21);
this.cbSizing.TabIndex = 2;
this.cbSizing.SelectedIndexChanged += new System.EventHandler(this.cbSizing_SelectedIndexChanged);
//
// ImageCtl
//
this.Controls.Add(this.cbSizing);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Name = "ImageCtl";
this.Size = new System.Drawing.Size(472, 288);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fSource = fValue = fSizing = fMIMEType = false;
}
public void ApplyChanges(XmlNode node)
{
if (fSource || fValue || fMIMEType)
{
string source="";
string val="";
if (rbEmbedded.Checked)
{
val = cbValueEmbedded.Text;
source = "Embedded";
}
else if (rbDatabase.Checked)
{
source = "Database";
val = cbValueDatabase.Text;
_Draw.SetElement(node, "MIMEType", this.cbMIMEType.Text);
}
else
{ // must be external
source = "External";
val = tbValueExternal.Text;
}
_Draw.SetElement(node, "Source", source);
_Draw.SetElement(node, "Value", val);
}
if (fSizing)
_Draw.SetElement(node, "Sizing", this.cbSizing.Text);
}
private void Value_TextChanged(object sender, System.EventArgs e)
{
fValue = true;
}
private void cbMIMEType_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMIMEType = true;
}
private void rbSource_CheckedChanged(object sender, System.EventArgs e)
{
fSource = true;
this.cbValueDatabase.Enabled = this.cbMIMEType.Enabled =
this.bDatabaseExpr.Enabled = this.rbDatabase.Checked;
this.cbValueEmbedded.Enabled = this.bEmbeddedExpr.Enabled =
this.bEmbedded.Enabled = this.rbEmbedded.Checked;
this.tbValueExternal.Enabled = this.bExternalExpr.Enabled =
this.bExternal.Enabled = this.rbExternal.Checked;
}
private void cbSizing_SelectedIndexChanged(object sender, System.EventArgs e)
{
fSizing = true;
}
private void bExternal_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Bitmap Files (*.bmp)|*.bmp" +
"|JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif" +
"|GIF (*.gif)|*.gif" +
"|TIFF (*.tif;*.tiff)|*.tif;*.tiff" +
"|PNG (*.png)|*.png" +
"|All Picture Files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 6;
ofd.CheckFileExists = true;
try
{
if (ofd.ShowDialog(this) == DialogResult.OK)
{
tbValueExternal.Text = ofd.FileName;
}
}
finally
{
ofd.Dispose();
}
}
private void bEmbedded_Click(object sender, System.EventArgs e)
{
DialogEmbeddedImages dlgEI = new DialogEmbeddedImages(this._Draw);
dlgEI.StartPosition = FormStartPosition.CenterParent;
try
{
DialogResult dr = dlgEI.ShowDialog();
if (dr != DialogResult.OK)
return;
}
finally
{
dlgEI.Dispose();
}
// Populate the EmbeddedImage names
cbValueEmbedded.Items.Clear();
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "external":
c = tbValueExternal;
break;
case "embedded":
c = cbValueEmbedded;
break;
case "mime":
c = cbMIMEType;
break;
case "database":
c = cbValueDatabase;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
return;
}
}
}
| |
// Adapted from http://www.microframework.nl/2009/09/05/shahmac-digest-class/
// removed algorithms other than HMAC SHA-256 for size
using System;
using Microsoft.SPOT;
namespace ElzeKool
{
/// <summary>
/// Static class providing Secure Hashing Algorithm (SHA-1, SHA-224, SHA-256)
/// </summary>
public static class SHA
{
// Number used in SHA256 hash function
static readonly uint[] sha256_k = new uint[]
{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
// Rotate bits right
static uint rotateright(uint x, int n)
{
return ((x >> n) | (x << (32 - n)));
}
// Convert 4 bytes to big endian uint32
static uint big_endian_from_bytes(byte[] input, uint start)
{
uint r = 0;
r |= (((uint)input[start]) << 24);
r |= (((uint)input[start + 1]) << 16);
r |= (((uint)input[start + 2]) << 8);
r |= (((uint)input[start + 3]));
return r;
}
// Convert big endian uint32 to bytes
static void bytes_from_big_endian(uint input, ref byte[] output, int start)
{
output[start] = (byte)((input & 0xFF000000) >> 24);
output[start + 1] = (byte)((input & 0x00FF0000) >> 16);
output[start + 2] = (byte)((input & 0x0000FF00) >> 8);
output[start + 3] = (byte)((input & 0x000000FF));
}
// SHA-224/SHA-256 choice function
static uint choice(uint x, uint y, uint z)
{
return ((x & y) ^ (~x & z));
}
// SHA-224/SHA-256 majority function
static uint majority(uint x, uint y, uint z)
{
return ((x & y) ^ (x & z) ^ (y & z));
}
/// <summary>
/// Compute HMAC SHA-256
/// </summary>
/// <param name="secret">Secret</param>
/// <param name="value">Password</param>
/// <returns>32 byte HMAC_SHA256</returns>
public static byte[] computeHMAC_SHA256(byte[] secret, byte[] value)
{
// Create two arrays, bi and bo
byte[] bi = new byte[64 + value.Length];
byte[] bo = new byte[64 + 32];
// Copy secret to both arrays
Array.Copy(secret, bi, secret.Length);
Array.Copy(secret, bo, secret.Length);
for (int i = 0; i < 64; i++)
{
// Xor bi with 0x36
bi[i] = (byte)(bi[i] ^ 0x36);
// Xor bo with 0x5c
bo[i] = (byte)(bo[i] ^ 0x5c);
}
// Append value to bi
Array.Copy(value, 0, bi, 64, value.Length);
// Append SHA256(bi) to bo
byte[] sha_bi = computeSHA256(bi);
Array.Copy(sha_bi, 0, bo, 64, 32);
// Return SHA256(bo)
return computeSHA256(bo);
}
/// <summary>
/// Compute SHA-256 digest
/// </summary>
/// <param name="input">Input array</param>
public static byte[] computeSHA256(byte[] input)
{
// Initialize working parameters
uint a, b, c, d, e, f, g, h, i, s0, s1, t1, t2;
uint h0 = 0x6a09e667;
uint h1 = 0xbb67ae85;
uint h2 = 0x3c6ef372;
uint h3 = 0xa54ff53a;
uint h4 = 0x510e527f;
uint h5 = 0x9b05688c;
uint h6 = 0x1f83d9ab;
uint h7 = 0x5be0cd19;
uint blockstart = 0;
// Calculate how long the padded message should be
int newinputlength = input.Length + 1;
while ((newinputlength % 64) != 56) // length mod 512bits = 448bits
{
newinputlength++;
}
// Create array for padded data
byte[] processed = new byte[newinputlength + 8];
Array.Copy(input, processed, input.Length);
// Pad data with an 1
processed[input.Length] = 0x80;
// Pad data with big endian 64bit length of message
// We do only 32 bits becouse input.length is 32 bit
processed[processed.Length - 4] = (byte)(((input.Length * 8) & 0xFF000000) >> 24);
processed[processed.Length - 3] = (byte)(((input.Length * 8) & 0x00FF0000) >> 16);
processed[processed.Length - 2] = (byte)(((input.Length * 8) & 0x0000FF00) >> 8);
processed[processed.Length - 1] = (byte)(((input.Length * 8) & 0x000000FF));
// Block of 32 bits values used in calculations
uint[] wordblock = new uint[64];
// Now process each 512 bit block
while (blockstart < processed.Length)
{
// break chunk into sixteen 32-bit big-endian words
for (i = 0; i < 16; i++)
wordblock[i] = big_endian_from_bytes(processed, blockstart + (i * 4));
// Extend the sixteen 32-bit words into sixty-four 32-bit words:
for (i = 16; i < 64; i++)
{
s0 = rotateright(wordblock[i - 15], 7) ^ rotateright(wordblock[i - 15], 18) ^ (wordblock[i - 15] >> 3);
s1 = rotateright(wordblock[i - 2], 17) ^ rotateright(wordblock[i - 2], 19) ^ (wordblock[i - 2] >> 10);
wordblock[i] = wordblock[i - 16] + s0 + wordblock[i - 7] + s1;
}
// Initialize hash value for this chunk:
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
f = h5;
g = h6;
h = h7;
// Main loop
for (i = 0; i < 64; i++)
{
t1 = h + (rotateright(e, 6) ^ rotateright(e, 11) ^ rotateright(e, 25)) + choice(e, f, g) + sha256_k[i] + wordblock[i];
t2 = (rotateright(a, 2) ^ rotateright(a, 13) ^ rotateright(a, 22)) + majority(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
// Add this chunk's hash to result so far
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
h5 += f;
h6 += g;
h7 += h;
// Process next 512bit block
blockstart += 64;
}
// Prepare output
byte[] output = new byte[32];
bytes_from_big_endian(h0, ref output, 0);
bytes_from_big_endian(h1, ref output, 4);
bytes_from_big_endian(h2, ref output, 8);
bytes_from_big_endian(h3, ref output, 12);
bytes_from_big_endian(h4, ref output, 16);
bytes_from_big_endian(h5, ref output, 20);
bytes_from_big_endian(h6, ref output, 24);
bytes_from_big_endian(h7, ref output, 28);
return output;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class SensorRepeat
{
public AsyncCommandManager m_CmdManager;
public SensorRepeat(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d);
maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16);
}
private Object SenseLock = new Object();
private const int AGENT = 1;
private const int ACTIVE = 2;
private const int PASSIVE = 4;
private const int SCRIPTED = 8;
private double maximumRange = 96.0;
private int maximumToReturn = 16;
//
// SenseRepeater and Sensors
//
private class SenseRepeatClass
{
public uint localID;
public UUID itemID;
public double interval;
public DateTime next;
public string name;
public UUID keyID;
public int type;
public double range;
public double arc;
public SceneObjectPart host;
}
//
// Sensed entity
//
private class SensedEntity : IComparable
{
public SensedEntity(double detectedDistance, UUID detectedID)
{
distance = detectedDistance;
itemID = detectedID;
}
public int CompareTo(object obj)
{
if (!(obj is SensedEntity)) throw new InvalidOperationException();
SensedEntity ent = (SensedEntity)obj;
if (ent == null || ent.distance < distance) return 1;
if (ent.distance > distance) return -1;
return 0;
}
public UUID itemID;
public double distance;
}
private List<SenseRepeatClass> SenseRepeaters = new List<SenseRepeatClass>();
private object SenseRepeatListLock = new object();
public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type, double range,
double arc, double sec, SceneObjectPart host)
{
// Always remove first, in case this is a re-set
UnSetSenseRepeaterEvents(m_localID, m_itemID);
if (sec == 0) // Disabling timer
return;
// Add to timer
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = sec;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
lock (SenseRepeatListLock)
{
SenseRepeaters.Add(ts);
}
}
public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID)
{
// Remove from timer
lock (SenseRepeatListLock)
{
List<SenseRepeatClass> NewSensors = new List<SenseRepeatClass>();
foreach (SenseRepeatClass ts in SenseRepeaters)
{
if (ts.localID != m_localID && ts.itemID != m_itemID)
{
NewSensors.Add(ts);
}
}
SenseRepeaters.Clear();
SenseRepeaters = NewSensors;
}
}
public void CheckSenseRepeaterEvents()
{
// Nothing to do here?
if (SenseRepeaters.Count == 0)
return;
lock (SenseRepeatListLock)
{
// Go through all timers
foreach (SenseRepeatClass ts in SenseRepeaters)
{
// Time has passed?
if (ts.next.ToUniversalTime() < DateTime.Now.ToUniversalTime())
{
SensorSweep(ts);
// set next interval
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
}
}
} // lock
}
public void SenseOnce(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type,
double range, double arc, SceneObjectPart host)
{
// Add to timer
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = 0;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
SensorSweep(ts);
}
private void SensorSweep(SenseRepeatClass ts)
{
if (ts.host == null)
{
return;
}
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// Is the sensor type is AGENT and not SCRIPTED then include agents
if ((ts.type & AGENT) != 0 && (ts.type & SCRIPTED) == 0)
{
sensedEntities.AddRange(doAgentSensor(ts));
}
// If SCRIPTED or PASSIVE or ACTIVE check objects
if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0)
{
sensedEntities.AddRange(doObjectSensor(ts));
}
lock (SenseLock)
{
if (sensedEntities.Count == 0)
{
// send a "no_sensor"
// Add it to queue
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
// Sort the list to get everything ordered by distance
sensedEntities.Sort();
int count = sensedEntities.Count;
int idx;
List<DetectParams> detected = new List<DetectParams>();
for (idx = 0; idx < count; idx++)
{
try
{
DetectParams detect = new DetectParams();
detect.Key = sensedEntities[idx].itemID;
detect.Populate(m_CmdManager.m_ScriptEngine.World);
detected.Add(detect);
}
catch (Exception)
{
// Ignore errors, the object has been deleted or the avatar has gone and
// there was a problem in detect.Populate so nothing added to the list
}
if (detected.Count == maximumToReturn)
break;
}
if (detected.Count == 0)
{
// To get here with zero in the list there must have been some sort of problem
// like the object being deleted or the avatar leaving to have caused some
// difficulty during the Populate above so fire a no_sensor event
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("sensor",
new Object[] {new LSL_Types.LSLInteger(detected.Count) },
detected.ToArray()));
}
}
}
}
private List<SensedEntity> doObjectSensor(SenseRepeatClass ts)
{
List<EntityBase> Entities;
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If this is an object sense by key try to get it directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
EntityBase e = null;
m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e);
if (e == null)
return sensedEntities;
Entities = new List<EntityBase>();
Entities.Add(e);
}
else
{
Entities = m_CmdManager.m_ScriptEngine.World.GetEntities();
}
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.AbsolutePosition;
// pre define some things to avoid repeated definitions in the loop body
Vector3 toRegionPos;
double dis;
int objtype;
SceneObjectPart part;
float dx;
float dy;
float dz;
Quaternion q = SensePoint.RotationOffset;
if (SensePoint.ParentGroup.RootPart.IsAttachment)
{
// In attachments, the sensor cone always orients with the
// avatar rotation. This may include a nonzero elevation if
// in mouselook.
ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.RootPart.AttachedAvatar);
q = avatar.Rotation;
}
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
Vector3 ZeroVector = new Vector3(0, 0, 0);
bool nameSearch = (ts.name != null && ts.name != "");
foreach (EntityBase ent in Entities)
{
bool keep = true;
if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search
continue;
if (ent.IsDeleted) // taken so long to do this it has gone from the scene
continue;
if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar
continue;
toRegionPos = ent.AbsolutePosition;
// Calculation is in line for speed
dx = toRegionPos.X - fromRegionPos.X;
dy = toRegionPos.Y - fromRegionPos.Y;
dz = toRegionPos.Z - fromRegionPos.Z;
// Weed out those that will not fit in a cube the size of the range
// no point calculating if they are within a sphere the size of the range
// if they arent even in the cube
if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range)
dis = ts.range + 1.0;
else
dis = Math.Sqrt(dx * dx + dy * dy + dz * dz);
if (keep && dis <= ts.range && ts.host.UUID != ent.UUID)
{
// In Range and not the object containing the script, is it the right Type ?
objtype = 0;
part = ((SceneObjectGroup)ent).RootPart;
if (part.AttachmentPoint != 0) // Attached so ignore
continue;
if (part.Inventory.ContainsScripts())
{
objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ...
}
else
{
if (ent.Velocity.Equals(ZeroVector))
{
objtype |= PASSIVE; // Passive non-moving
}
else
{
objtype |= ACTIVE; // moving so active
}
}
// If any of the objects attributes match any in the requested scan type
if (((ts.type & objtype) != 0))
{
// Right type too, what about the other params , key and name ?
if (ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
Vector3 diff = toRegionPos - fromRegionPos;
LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj > ts.arc) keep = false;
}
if (keep == true)
{
// add distance for sorting purposes later
sensedEntities.Add(new SensedEntity(dis, ent.UUID));
}
}
}
}
return sensedEntities;
}
private List<SensedEntity> doAgentSensor(SenseRepeatClass ts)
{
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If nobody about quit fast
if(m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0)
return sensedEntities;
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.AbsolutePosition;
Quaternion q = SensePoint.RotationOffset;
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
bool attached = (SensePoint.AttachmentPoint != 0);
Vector3 toRegionPos;
double dis;
Action<ScenePresence> senseEntity = new Action<ScenePresence>(delegate(ScenePresence presence)
{
if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0)
return;
// if the object the script is in is attached and the avatar is the owner
// then this one is not wanted
if (attached && presence.UUID == SensePoint.OwnerID)
return;
toRegionPos = presence.AbsolutePosition;
dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));
// are they in range
if (dis <= ts.range)
{
// Are they in the required angle of view
if (ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
Vector3 diff = toRegionPos - fromRegionPos;
LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj <= ts.arc)
{
sensedEntities.Add(new SensedEntity(dis, presence.UUID));
}
}
else
{
sensedEntities.Add(new SensedEntity(dis, presence.UUID));
}
}
});
// If this is an avatar sense by key try to get them directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
ScenePresence sp;
// Try direct lookup by UUID
if(!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp))
return sensedEntities;
senseEntity(sp);
}
else if (ts.name != null && ts.name != "")
{
ScenePresence sp;
// Try lookup by name will return if/when found
if (!m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp))
return sensedEntities;
senseEntity(sp);
}
else
{
m_CmdManager.m_ScriptEngine.World.ForEachScenePresence(senseEntity);
}
return sensedEntities;
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
lock (SenseRepeatListLock)
{
foreach (SenseRepeatClass ts in SenseRepeaters)
{
if (ts.itemID == itemID)
{
data.Add(ts.interval);
data.Add(ts.name);
data.Add(ts.keyID);
data.Add(ts.type);
data.Add(ts.range);
data.Add(ts.arc);
}
}
}
return data.ToArray();
}
public void CreateFromData(uint localID, UUID itemID, UUID objectID,
Object[] data)
{
SceneObjectPart part =
m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart(
objectID);
if (part == null)
return;
int idx = 0;
while (idx < data.Length)
{
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = localID;
ts.itemID = itemID;
ts.interval = (double)data[idx];
ts.name = (string)data[idx+1];
ts.keyID = (UUID)data[idx+2];
ts.type = (int)data[idx+3];
ts.range = (double)data[idx+4];
ts.arc = (double)data[idx+5];
ts.host = part;
ts.next =
DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
SenseRepeaters.Add(ts);
idx += 6;
}
}
}
}
| |
using System;
using Eto.Parse.Parsers;
using Eto.Parse.Scanners;
using System.Collections.Generic;
using System.Linq;
using Eto.Parse.Writers;
using System.IO;
using System.CodeDom.Compiler;
namespace Eto.Parse.Grammars
{
/// <summary>
/// Grammar to build a parser grammar using Backus-Naur Form
/// </summary>
/// <remarks>
/// See https://en.wikipedia.org/wiki/Backus-Naur_Form.
///
/// This implements certain enhancements, such as grouping using brackets, repeating using curly braces, and
/// optional values using square brackets.
///
/// This grammar is not thread-safe.
/// </remarks>
public class BnfGrammar : Grammar
{
Dictionary<string, Parser> parserLookup = new Dictionary<string, Parser>(StringComparer.InvariantCultureIgnoreCase);
readonly Dictionary<string, Parser> baseLookup = new Dictionary<string, Parser>(StringComparer.InvariantCultureIgnoreCase);
readonly Parser sws = Terminals.SingleLineWhiteSpace.Repeat(0);
readonly Parser ws = Terminals.WhiteSpace.Repeat(0);
readonly Parser sq = Terminals.Set('\'');
readonly Parser dq = Terminals.Set('"');
readonly LiteralTerminal ruleSeparator = new LiteralTerminal("::=");
string startParserName;
readonly Parser rule;
readonly Parser listRepeat;
readonly Parser list;
readonly Parser repeatRule;
readonly Parser optionalRule;
readonly Parser literal;
readonly Parser ruleName;
/// <summary>
/// Gets or sets the separator for rules, which is usually '::=' for BNF
/// </summary>
/// <value>The rule separator</value>
protected string RuleSeparator { get { return ruleSeparator.Value; } set { ruleSeparator.Value = value; } }
/// <summary>
/// Gets the rule parser for each of the rule types
/// </summary>
/// <value>The rule parser.</value>
protected AlternativeParser RuleParser { get; private set; }
/// <summary>
/// Gets the term parser for each term, such as optional, repeating, grouping, etc
/// </summary>
/// <value>The term parser.</value>
protected AlternativeParser TermParser { get; private set; }
/// <summary>
/// Gets the expresssions parser to support different expressions. By default, only one expression
/// is defined: RuleNameParser & RuleSeparator & RuleParser & EOL
/// </summary>
/// <value>The expresssions this parser supports</value>
protected AlternativeParser Expresssions { get; private set; }
/// <summary>
/// Gets the rule name parser, by default is a string surrounded by angle brackets
/// </summary>
/// <value>The rule name parser.</value>
protected SequenceParser RuleNameParser { get; private set; }
/// <summary>
/// Gets the parsed rules
/// </summary>
/// <value>The rules.</value>
public Dictionary<string, Parser> Rules { get { return parserLookup; } protected set { parserLookup = value; } }
public BnfGrammar(bool enhanced = true)
: base("bnf")
{
if (enhanced)
{
foreach (var property in typeof(Terminals).GetProperties())
{
if (typeof(Parser).IsAssignableFrom(property.PropertyType))
{
var parser = property.GetValue(null, null) as Parser;
baseLookup[property.Name] = parser.Named(property.Name);
}
}
}
var lineEnd = sws & +(sws & Terminals.Eol);
literal = (
(sq & (+!sq).WithName("value").Optional() & sq)
| (dq & (+!dq).WithName("value").Optional() & dq)
).WithName("parser");
RuleNameParser = "<" & Terminals.Set('>').Inverse().Repeat().WithName("name") & ">";
RuleParser = new AlternativeParser(); // defined later
TermParser = literal | (ruleName = RuleNameParser.Named("parser"));
TermParser.Name = "term";
if (enhanced)
{
TermParser.Items.Add('(' & sws & RuleParser & sws & ')');
TermParser.Items.Add(repeatRule = ('{' & sws & RuleParser & sws & '}').WithName("parser"));
TermParser.Items.Add(optionalRule = ('[' & sws & RuleParser & sws & ']').WithName("parser"));
}
list = (TermParser & -(~((+Terminals.SingleLineWhiteSpace).WithName("ws")) & TermParser)).WithName("parser");
listRepeat = (list.Named("list") & ws & '|' & sws & ~(RuleParser.Named("expression"))).WithName("parser");
RuleParser.Items.Add(listRepeat);
RuleParser.Items.Add(list);
rule = (~lineEnd & sws & RuleNameParser.Named("ruleName") & ws & ruleSeparator & sws & RuleParser & lineEnd).WithName("parser");
Expresssions = new AlternativeParser();
Expresssions.Items.Add(rule);
this.Inner = ws & +Expresssions & ws;
AttachEvents();
}
void AttachEvents()
{
ruleName.Matched += m => {
Parser parser;
var name = m["name"].Text;
if (!parserLookup.TryGetValue(name, out parser) && !baseLookup.TryGetValue(name, out parser))
{
parser = Terminals.LetterOrDigit.Repeat();
parser.Name = name;
}
m.Tag = parser;
};
literal.Matched += m => m.Tag = new LiteralTerminal(m["value"].Text);
optionalRule.Matched += m => m.Tag = new OptionalParser((Parser)m["parser"].Tag);
repeatRule.Matched += m => m.Tag = new RepeatParser((Parser)m["parser"].Tag, 0) { Separator = sws };
list.Matched += m => {
if (m.Matches.Count > 1)
{
var parser = new SequenceParser();
foreach (var child in m.Matches)
{
if (child.Parser.Name == "ws")
parser.Items.Add(sws);
else if (child.Parser.Name == "term")
parser.Items.Add((Parser)child["parser"].Tag);
}
m.Tag = parser;
}
else
{
m.Tag = m["term"]["parser"].Tag;
}
};
listRepeat.Matched += m => {
// collapse alternatives to one alternative parser
var parser = (Parser)m["expression"]["parser"].Tag;
var alt = parser as AlternativeParser ?? new AlternativeParser(parser);
alt.Items.Insert(0, (Parser)m["list"]["parser"].Tag);
m.Tag = alt;
};
rule.Matched += m => {
var parser = (UnaryParser)m.Tag;
parser.Inner = (Parser)m["parser"].Tag;
m.Tag = parser;
};
rule.PreMatch += m => {
var name = m["ruleName"]["name"].Text;
Parser parser;
if (name == startParserName)
parser = new Grammar(name);
else
parser = new UnaryParser(name);
m.Tag = parser;
parserLookup[parser.Name] = parser;
};
}
protected override int InnerParse(ParseArgs args)
{
parserLookup = new Dictionary<string, Parser>();
return base.InnerParse(args);
}
public Grammar Build(string bnf, string startParserName)
{
this.startParserName = startParserName;
Parser parser;
var match = Match(new StringScanner(bnf));
if (!match.Success)
{
throw new FormatException(string.Format("Error parsing bnf: \n{0}", match.ErrorMessage));
}
if (!parserLookup.TryGetValue(startParserName, out parser))
throw new ArgumentException("the topParser specified is not found in this bnf");
return parser as Grammar;
}
public string ToCode(string bnf, string startParserName, string className = "GeneratedGrammar")
{
using (var writer = new StringWriter())
{
ToCode(bnf, startParserName, writer, className);
return writer.ToString();
}
}
public void ToCode(string bnf, string startParserName, TextWriter writer, string className = "GeneratedGrammar")
{
var parser = Build(bnf, startParserName);
var iw = new IndentedTextWriter(writer, " ");
iw.WriteLine("/* Date Created: {0}, Source BNF:", DateTime.Now);
iw.Indent ++;
foreach (var line in bnf.Split('\n'))
iw.WriteLine(line);
iw.Indent --;
iw.WriteLine("*/");
var parserWriter = new CodeParserWriter
{
ClassName = className
};
parserWriter.Write(parser, writer);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: reporting/rpc/folios_reporting_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Reporting.RPC {
public static partial class FoliosReportingSvc
{
static readonly string __ServiceName = "holms.types.reporting.rpc.FoliosReportingSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest> __Marshaller_GroupBookingAssociatedFoliosRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Marshaller_HtmlReportResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator> __Marshaller_GroupBookingIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping> __Marshaller_GroupBookingInvoiceMapping = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Reporting.RPC.BookingStatementRequest> __Marshaller_BookingStatementRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Reporting.RPC.BookingStatementRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest> __Marshaller_FolioPaymentReceiptRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetBookingAssociatedFoliosDetail = new grpc::Method<global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetBookingAssociatedFoliosDetail",
__Marshaller_GroupBookingAssociatedFoliosRequest,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetBookingAssociatedFoliosSummary = new grpc::Method<global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetBookingAssociatedFoliosSummary",
__Marshaller_GroupBookingAssociatedFoliosRequest,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetReservationFolioSummary = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetReservationFolioSummary",
__Marshaller_GroupBookingIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetBookingWorksheetDetail = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetBookingWorksheetDetail",
__Marshaller_GroupBookingIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetInvoice = new grpc::Method<global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetInvoice",
__Marshaller_GroupBookingInvoiceMapping,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Reporting.RPC.BookingStatementRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetBookingStatement = new grpc::Method<global::HOLMS.Types.Reporting.RPC.BookingStatementRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetBookingStatement",
__Marshaller_BookingStatementRequest,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetFolioPaymentReceipt = new grpc::Method<global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetFolioPaymentReceipt",
__Marshaller_FolioPaymentReceiptRequest,
__Marshaller_HtmlReportResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Reporting.RPC.FoliosReportingSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of FoliosReportingSvc</summary>
public abstract partial class FoliosReportingSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosDetail(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosSummary(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioSummary(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingWorksheetDetail(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetInvoice(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingStatement(global::HOLMS.Types.Reporting.RPC.BookingStatementRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetFolioPaymentReceipt(global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for FoliosReportingSvc</summary>
public partial class FoliosReportingSvcClient : grpc::ClientBase<FoliosReportingSvcClient>
{
/// <summary>Creates a new client for FoliosReportingSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public FoliosReportingSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for FoliosReportingSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public FoliosReportingSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected FoliosReportingSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected FoliosReportingSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingAssociatedFoliosDetail(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingAssociatedFoliosDetail(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingAssociatedFoliosDetail(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetBookingAssociatedFoliosDetail, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosDetailAsync(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingAssociatedFoliosDetailAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosDetailAsync(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetBookingAssociatedFoliosDetail, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingAssociatedFoliosSummary(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingAssociatedFoliosSummary(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingAssociatedFoliosSummary(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetBookingAssociatedFoliosSummary, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosSummaryAsync(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingAssociatedFoliosSummaryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingAssociatedFoliosSummaryAsync(global::HOLMS.Types.Reporting.RPC.GroupBookingAssociatedFoliosRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetBookingAssociatedFoliosSummary, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioSummary(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioSummary(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioSummary(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetReservationFolioSummary, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioSummaryAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioSummaryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioSummaryAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetReservationFolioSummary, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingWorksheetDetail(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingWorksheetDetail(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingWorksheetDetail(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetBookingWorksheetDetail, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingWorksheetDetailAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingWorksheetDetailAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingWorksheetDetailAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetBookingWorksheetDetail, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetInvoice(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetInvoice(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetInvoice(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetInvoice, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetInvoiceAsync(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetInvoiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetInvoiceAsync(global::HOLMS.Types.Booking.Groups.GroupBookingInvoiceMapping request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetInvoice, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingStatement(global::HOLMS.Types.Reporting.RPC.BookingStatementRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingStatement(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetBookingStatement(global::HOLMS.Types.Reporting.RPC.BookingStatementRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetBookingStatement, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingStatementAsync(global::HOLMS.Types.Reporting.RPC.BookingStatementRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetBookingStatementAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetBookingStatementAsync(global::HOLMS.Types.Reporting.RPC.BookingStatementRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetBookingStatement, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetFolioPaymentReceipt(global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFolioPaymentReceipt(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetFolioPaymentReceipt(global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetFolioPaymentReceipt, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetFolioPaymentReceiptAsync(global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFolioPaymentReceiptAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetFolioPaymentReceiptAsync(global::HOLMS.Types.Reporting.RPC.FolioPaymentReceiptRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetFolioPaymentReceipt, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override FoliosReportingSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new FoliosReportingSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(FoliosReportingSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetBookingAssociatedFoliosDetail, serviceImpl.GetBookingAssociatedFoliosDetail)
.AddMethod(__Method_GetBookingAssociatedFoliosSummary, serviceImpl.GetBookingAssociatedFoliosSummary)
.AddMethod(__Method_GetReservationFolioSummary, serviceImpl.GetReservationFolioSummary)
.AddMethod(__Method_GetBookingWorksheetDetail, serviceImpl.GetBookingWorksheetDetail)
.AddMethod(__Method_GetInvoice, serviceImpl.GetInvoice)
.AddMethod(__Method_GetBookingStatement, serviceImpl.GetBookingStatement)
.AddMethod(__Method_GetFolioPaymentReceipt, serviceImpl.GetFolioPaymentReceipt).Build();
}
}
}
#endregion
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira 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.
#endregion
namespace Boo.Lang.Compiler.Steps
{
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
/// <summary>
/// Summary description for ProcessAssignmentsToSpecialMembers.
/// </summary>
public abstract class ProcessAssignmentsToSpecialMembers : AbstractTransformerCompilerStep
{
Method _currentMethod;
override public void Run()
{
if (0 == Errors.Count)
{
Visit(CompileUnit);
}
}
override public void OnInterfaceDefinition(InterfaceDefinition node)
{
}
override public void OnEnumDefinition(EnumDefinition node)
{
}
override public void OnMethod(Method node)
{
_currentMethod = node;
Visit(node.Body);
}
override public void OnConstructor(Constructor node)
{
OnMethod(node);
}
override public void LeaveBinaryExpression(BinaryExpression node)
{
if (IsAssignmentToSpecialMember(node))
{
ProcessAssignmentToSpecialMember(node);
}
}
protected bool IsAssignmentToSpecialMember(BinaryExpression node)
{
if (BinaryOperatorType.Assign == node.Operator &&
NodeType.MemberReferenceExpression == node.Left.NodeType)
{
MemberReferenceExpression memberRef = node.Left as MemberReferenceExpression;
Expression target = memberRef.Target;
return !IsTerminalReferenceNode(target)
&& IsSpecialMemberTarget(target);
}
return false;
}
protected abstract bool IsSpecialMemberTarget(Expression container);
public class ChainItem
{
public Expression Container;
public InternalLocal Local;
public ChainItem(Expression container)
{
this.Container = container;
}
}
void ProcessAssignmentToSpecialMember(BinaryExpression node)
{
MemberReferenceExpression memberRef = (MemberReferenceExpression)node.Left;
List chain = WalkMemberChain(memberRef);
if (null == chain || 0 == chain.Count) return;
MethodInvocationExpression eval = CodeBuilder.CreateEvalInvocation(node.LexicalInfo);
// right hand side should always be executed before
// left hand side
InternalLocal value = DeclareTempLocal(GetExpressionType(node.Right));
eval.Arguments.Add(
CodeBuilder.CreateAssignment(
CodeBuilder.CreateReference(value),
node.Right));
foreach (ChainItem item in chain)
{
item.Local = DeclareTempLocal(item.Container.ExpressionType);
BinaryExpression tempInitialization = CodeBuilder.CreateAssignment(
node.LexicalInfo,
CodeBuilder.CreateReference(item.Local),
item.Container.CloneNode());
item.Container.ParentNode.Replace(item.Container,
CodeBuilder.CreateReference(item.Local));
eval.Arguments.Add(tempInitialization);
}
eval.Arguments.Add(
CodeBuilder.CreateAssignment(node.LexicalInfo,
node.Left,
CodeBuilder.CreateReference(value)));
PropagateChanges(eval, chain);
if (NodeType.ExpressionStatement != node.ParentNode.NodeType)
{
eval.Arguments.Add(CodeBuilder.CreateReference(value));
BindExpressionType(eval, value.Type);
}
ReplaceCurrentNode(eval);
}
protected virtual void PropagateChanges(MethodInvocationExpression eval, List chain)
{
foreach (ChainItem item in chain.Reversed)
{
eval.Arguments.Add(
CodeBuilder.CreateAssignment(
item.Container.CloneNode(),
CodeBuilder.CreateReference(item.Local)));
}
}
protected virtual List WalkMemberChain(MemberReferenceExpression memberRef)
{
List chain = new List();
while (true)
{
MemberReferenceExpression container = memberRef.Target as MemberReferenceExpression;
if (null == container ||
(IsSpecialMemberTarget(container)
&& IsReadOnlyMember(container)))
{
Warnings.Add(
CompilerWarningFactory.AssignmentToTemporary(memberRef));
return null;
}
if (IsSpecialMemberTarget(container)
&& EntityType.Field != container.Entity.EntityType)
{
chain.Insert(0, new ChainItem(container));
}
if (IsTerminalReferenceNode(container.Target))
{
break;
}
memberRef = container;
}
return chain;
}
protected virtual bool IsTerminalReferenceNode(Expression target)
{
NodeType type = target.NodeType;
return
NodeType.ReferenceExpression == type ||
NodeType.SelfLiteralExpression == type ||
NodeType.SuperLiteralExpression == type ||
ProcessMethodBodies.IsArraySlicing(target) ||
!IsSpecialMemberTarget(target);
}
protected virtual bool IsReadOnlyMember(MemberReferenceExpression container)
{
switch (container.Entity.EntityType)
{
case EntityType.Property:
{
return ((IProperty)container.Entity).GetSetMethod() == null;
}
case EntityType.Field:
{
return TypeSystemServices.IsReadOnlyField((IField)container.Entity);
}
}
return true;
}
InternalLocal DeclareTempLocal(IType localType)
{
return CodeBuilder.DeclareTempLocal(_currentMethod, localType);
}
}
}
| |
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
using UnityEngine;
using System.Collections;
using Pathfinding;
using System.Collections.Generic;
namespace Pathfinding {
/** Base class for all path types */
public abstract class Path {
/** Data for the thread calculating this path */
public PathHandler pathHandler;
/** Callback to call when the path is complete.
* This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
*/
public OnPathDelegate callback;
/** Immediate callback to call when the path is complete.
* \warning This may be called from a separate thread. Usually you do not want to use this one.
*
* \see callback
*/
public OnPathDelegate immediateCallback;
private PathState state;
private System.Object stateLock = new object();
/** Current state of the path.
* \see #CompleteState
*/
private PathCompleteState pathCompleteState;
/** Current state of the path */
public PathCompleteState CompleteState {
get { return pathCompleteState; }
protected set { pathCompleteState = value; }
}
/** If the path failed, this is true.
* \see #errorLog */
public bool error { get { return CompleteState == PathCompleteState.Error; }}
/** Additional info on what went wrong.
* \see #error */
private string _errorLog = "";
/** Log messages with info about eventual errors. */
public string errorLog {
get { return _errorLog; }
}
private GraphNode[] _path;
private Vector3[] _vectorPath;
/** Holds the path as a Node array. All nodes the path traverses. This might not be the same as all nodes the smoothed path traverses. */
public List<GraphNode> path;
/** Holds the (perhaps post processed) path as a Vector3 array */
public List<Vector3> vectorPath;
/** The max number of milliseconds per iteration (frame, in case of non-multithreading) */
protected float maxFrameTime;
/** The node currently being processed */
protected PathNode currentR;
public float duration; /**< The duration of this path in ms. How long it took to calculate the path */
/**< The number of frames/iterations this path has executed.
* This is the number of frames when not using multithreading.
* When using multithreading, this value is quite irrelevant
*/
public int searchIterations = 0;
public int searchedNodes; /**< Number of nodes this path has searched */
/** When the call was made to start the pathfinding for this path */
public System.DateTime callTime;
/* True if the path has been calculated (even if it had an error).
* Used by the multithreaded pathfinder to signal that this path object is safe to return. */
//public bool processed = false;
/** True if the path is currently recycled (i.e in the path pool).
* Do not set this value. Only read. It is used internally.
*/
public bool recycled = false;
/** True if the Reset function has been called.
* Used to allert users when they are doing it wrong.
*/
protected bool hasBeenReset = false;
/** Constraint for how to search for nodes */
public NNConstraint nnConstraint = PathNNConstraint.Default;
/** The next path to be searched.
* Linked list implementation.
* \warning You should never change this if you do not know what you are doing
*/
public Path next;
//These are variables which different scripts and custom graphs can use to get a bit more info about What is searching
//Not all are used in the standard graph types
//These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
//Note: These variables needs to be filled in by an external script to be usable
/** Radius for the unit searching for the path.
* \note Not used by any built-in pathfinders.
* These common name variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary).
* Or having to cast to another path type for acess.
*/
public int radius;
/** A mask for defining what type of ground a unit can traverse, not used in any default standard graph. \see #enabledTags
* \note Not used by any built-in pathfinders.
* These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
*/
public int walkabilityMask = -1;
/** Height of the character. Not used currently */
public int height;
/** Turning radius of the character. Not used currently */
public int turnRadius;
/** Speed of the character. Not used currently */
public int speed;
/* To store additional data. Note: this is SLOW. About 10-100 times slower than using the fields above.
* \since Removed in 3.0.8
* Currently not used */
//public Dictionary<string,int> customData = null;//new Dictionary<string,int>();
/** Determines which heuristic to use */
public Heuristic heuristic;
/** Scale of the heuristic values */
public float heuristicScale = 1F;
/** ID of this path. Used to distinguish between different paths */
public ushort pathID;
protected GraphNode hTargetNode; /** Target to use for H score calculation. Used alongside #hTarget. */
protected Int3 hTarget; /**< Target to use for H score calculations. \see Pathfinding.Node.H */
/** Which graph tags are traversable.
* This is a bitmask so -1 = all bits set = all tags traversable.
* For example, to set bit 5 to true, you would do
* \code myPath.enabledTags |= 1 << 5; \endcode
* To set it to false, you would do
* \code myPath.enabledTags &= ~(1 << 5); \endcode
*
* The Seeker has a popup field where you can set which tags to use.
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see CanTraverse
*/
public int enabledTags = -1;
static readonly int[] ZeroTagPenalties = new int[32];
/** The tag penalties that are actually used.
* If manualTagPenalties is null, this will be ZeroTagPenalties
* \see tagPenalties
*/
protected int[] internalTagPenalties = null;
/** Tag penalties set by other scripts
* \see tagPenalties
*/
protected int[] manualTagPenalties = null;
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
* \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]".
*
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see Seeker.tagPenalties
*/
public int[] tagPenalties {
get {
return manualTagPenalties;
}
set {
if (value == null || value.Length != 32) {
manualTagPenalties = null;
internalTagPenalties = ZeroTagPenalties;
} else {
manualTagPenalties = value;
internalTagPenalties = value;
}
}
}
public virtual bool FloodingPath {
get {
return false;
}
}
/** Total Length of the path.
* Calculates the total length of the #vectorPath.
* Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
* \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned.
*/
public float GetTotalLength () {
if (vectorPath == null) return float.PositiveInfinity;
float tot = 0;
for (int i=0;i<vectorPath.Count-1;i++) tot += Vector3.Distance (vectorPath[i],vectorPath[i+1]);
return tot;
}
/** Waits until this path has been calculated and returned.
* Allows for very easy scripting.
\code
//In an IEnumerator function
Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
yield return StartCoroutine (p.WaitForPath ());
//The path is calculated at this stage
\endcode
* \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
* while AstarPath.WaitForPath will halt all operations until the path has been calculated.
*
* \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
*
* \see AstarPath.WaitForPath
*/
public IEnumerator WaitForPath () {
if (GetState () == PathState.Created) throw new System.InvalidOperationException ("This path has not been started yet");
while (GetState () != PathState.Returned) yield return null;
}
public uint CalculateHScore (GraphNode node) {
uint v1;
switch (heuristic) {
case Heuristic.Euclidean:
v1 = (uint)(((GetHTarget () - node.position).costMagnitude)*heuristicScale);
return v1;
case Heuristic.Manhattan:
Int3 p2 = node.position;
v1 = (uint)((System.Math.Abs (hTarget.x-p2.x) + System.Math.Abs (hTarget.y-p2.y) + System.Math.Abs (hTarget.z-p2.z))*heuristicScale);
return v1;
case Heuristic.DiagonalManhattan:
Int3 p = GetHTarget () - node.position;
p.x = System.Math.Abs (p.x);
p.y = System.Math.Abs (p.y);
p.z = System.Math.Abs (p.z);
int diag = System.Math.Min (p.x,p.z);
int diag2 = System.Math.Max (p.x,p.z);
v1 = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
return v1;
}
return 0U;
}
/** Returns penalty for the given tag.
* \param tag A value between 0 (inclusive) and 32 (exclusive).
*/
public uint GetTagPenalty (int tag) {
return (uint)internalTagPenalties[tag];
}
public Int3 GetHTarget () {
return hTarget;
}
/** Returns if the node can be traversed.
* This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */
public bool CanTraverse (GraphNode node) {
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
}
public uint GetTraversalCost (GraphNode node) {
unchecked { return GetTagPenalty ((int)node.Tag ) + node.Penalty ; }
}
/** May be called by graph nodes to get a special cost for some connections.
* Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
* a very large area can be marked on the start and end nodes, this method will be called
* to get the actual cost for moving from the start position to its neighbours instead
* of as would otherwise be the case, from the start node's position to its neighbours.
* The position of a node and the actual start point on the node can vary quite a lot.
*
* The default behaviour of this method is to return the previous cost of the connection,
* essentiall making no change at all.
*
* This method should return the same regardless of the order of a and b.
* That is f(a,b) == f(b,a) should hold.
*
* \param a Moving from this node
* \param b Moving to this node
* \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.
*/
public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
return currentCost;
}
/** Returns if this path is done calculating.
* \returns If CompleteState is not PathCompleteState.NotCalculated.
*
* \note The path might not have been returned yet.
*
* \since Added in 3.0.8
*
* \see Seeker.IsDone
*/
public bool IsDone () {
return CompleteState != PathCompleteState.NotCalculated;
}
/** Threadsafe increment of the state */
public void AdvanceState (PathState s) {
lock (stateLock) {
state = (PathState)System.Math.Max ((int)state, (int)s);
}
}
/** Returns the state of the path in the pathfinding pipeline */
public PathState GetState () {
return (PathState)state;
}
/** Appends \a msg to #errorLog and logs \a msg to the console.
* Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame.
* Consider calling Error() along with this call.
*/
// Ugly Code Inc. wrote the below code :D
// What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled
// since the DISABLED define will never be enabled
// Ugly way of writing Conditional("!ASTAR_NO_LOGGING")
public void LogError (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) {
Debug.LogWarning (msg);
}
}
/** Logs an error and calls Error().
* This is called only if something is very wrong or the user is doing something he/she really should not be doing.
*/
public void ForceLogError (string msg) {
Error();
_errorLog += msg;
Debug.LogError (msg);
}
/** Appends a message to the #errorLog.
* Nothing is logged to the console.
*
* \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
*/
public void Log (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
}
/** Aborts the path because of an error.
* Sets #error to true.
* This function is called when an error has ocurred (e.g a valid path could not be found).
* \see LogError
*/
public void Error () {
CompleteState = PathCompleteState.Error;
}
/** Does some error checking.
* Makes sure the user isn't using old code paths and that no major errors have been done.
*
* \throws An exception if any errors are found
*/
private void ErrorCheck () {
if (!hasBeenReset) throw new System.Exception ("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor.");
if (recycled) throw new System.Exception ("The path is currently in a path pool. Are you sending the path for calculation twice?");
if (pathHandler == null) throw new System.Exception ("Field pathHandler is not set. Please report this bug.");
if (GetState() > PathState.Processing) throw new System.Exception ("This path has already been processed. Do not request a path with the same path object twice.");
}
/** Called when the path enters the pool.
* This method should release e.g pooled lists and other pooled resources
* The base version of this method releases vectorPath and path lists.
* Reset() will be called after this function, not before.
* \warning Do not call this function manually.
*/
public virtual void OnEnterPool () {
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release (vectorPath);
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release (path);
vectorPath = null;
path = null;
}
/** Reset all values to their default values.
*
* \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
* override this function, resetting ALL their variables to enable recycling of paths.
* If this is not done, trying to use that path type for pooling might result in weird behaviour.
* The best way is to reset to default values the variables declared in the extended path type and then
* call this base function in inheriting types with base.Reset ().
*
* \warning This function should not be called manually.
*/
public virtual void Reset () {
if (System.Object.ReferenceEquals (AstarPath.active, null))
throw new System.NullReferenceException ("No AstarPath object found in the scene. " +
"Make sure there is one or do not create paths in Awake");
hasBeenReset = true;
state = (int)PathState.Created;
releasedNotSilent = false;
pathHandler = null;
callback = null;
_errorLog = "";
pathCompleteState = PathCompleteState.NotCalculated;
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
currentR = null;
duration = 0;
searchIterations = 0;
searchedNodes = 0;
//calltime
nnConstraint = PathNNConstraint.Default;
next = null;
radius = 0;
walkabilityMask = -1;
height = 0;
turnRadius = 0;
speed = 0;
//heuristic = (Heuristic)0;
//heuristicScale = 1F;
heuristic = AstarPath.active.heuristic;
heuristicScale = AstarPath.active.heuristicScale;
pathID = 0;
enabledTags = -1;
tagPenalties = null;
callTime = System.DateTime.UtcNow;
pathID = AstarPath.active.GetNextPathID ();
hTarget = Int3.zero;
hTargetNode = null;
}
protected bool HasExceededTime (int searchedNodes, long targetTime) {
return System.DateTime.UtcNow.Ticks >= targetTime;
}
/** Recycle the path.
* Calling this means that the path and any variables on it are not needed anymore and the path can be pooled.
* All path data will be reset.
* Implement this in inheriting path types to support recycling of paths.
\code
public override void Recycle () {
//Recycle the Path (<Path> should be replaced by the path type it is implemented in)
PathPool<Path>.Recycle (this);
}
\endcode
*
* \warning Do not call this function directly, instead use the #Claim and #Release functions.
* \see Pathfinding.PathPool
* \see Reset
* \see Claim
* \see Release
*/
protected abstract void Recycle ();// {
// PathPool<Path>.Recycle (this);
//}
/** List of claims on this path with reference objects */
private List<System.Object> claimed = new List<System.Object>();
/** True if the path has been released with a non-silent call yet.
*
* \see Release
* \see ReleaseSilent
* \see Claim
*/
private bool releasedNotSilent = false;
/** Claim this path.
* A claim on a path will ensure that it is not recycled.
* If you are using a path, you will want to claim it when you first get it and then release it when you will not
* use it anymore. When there are no claims on the path, it will be recycled and put in a pool.
*
* \see Release
* \see Recycle
*/
public void Claim (System.Object o) {
if (System.Object.ReferenceEquals (o, null)) throw new System.ArgumentNullException ("o");
for ( int i = 0; i < claimed.Count; i++ ) {
// Need to use ReferenceEquals because it might be called from another thread
if ( System.Object.ReferenceEquals (claimed[i], o) )
throw new System.ArgumentException ("You have already claimed the path with that object ("+o.ToString()+"). Are you claiming the path with the same object twice?");
}
claimed.Add (o);
}
/** Releases the path silently.
* This will remove the claim by the specified object, but the path will not be recycled if the claim count reches zero unless a Release call (not silent) has been made earlier.
* This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not recycle paths.
* This enables users to skip the claim/release calls if they want without the path being recycled by the Seeker or AstarPath.
*/
public void ReleaseSilent (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals (claimed[i], o)) {
claimed.RemoveAt (i);
if (releasedNotSilent && claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Releases a path claim.
* Removes the claim of the path by the specified object.
* When the claim count reaches zero, the path will be recycled, all variables will be cleared and the path will be put in a pool to be used again.
* This is great for memory since less allocations are made.
* \see Claim
*/
public void Release (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals (claimed[i], o)) {
claimed.RemoveAt (i);
releasedNotSilent = true;
if (claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Traces the calculated path from the end node to the start.
* This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions.
* Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path).
*/
protected virtual void Trace (PathNode from) {
int count = 0;
PathNode c = from;
while (c != null) {
c = c.parent;
count++;
if (count > 1024) {
Debug.LogWarning ("Inifinity loop? >1024 node path. Remove this message if you really have that long paths (Path.cs, Trace function)");
break;
}
}
//Ensure capacities for lists
AstarProfiler.StartProfile ("Check List Capacities");
if (path.Capacity < count) path.Capacity = count;
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
AstarProfiler.EndProfile ();
c = from;
for (int i = 0;i<count;i++) {
path.Add (c.node);
c = c.parent;
}
int half = count/2;
for (int i=0;i<half;i++) {
GraphNode tmp = path[i];
path[i] = path[count-i-1];
path[count - i - 1] = tmp;
}
for (int i=0;i<count;i++) {
vectorPath.Add ((Vector3)path[i].position);
}
}
/** Returns a debug string for this path.
*/
public virtual string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
//debugStringBuilder.Length = 0;
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
text.Append (error ? "Path Failed : " : "Path Completed : ");
text.Append ("Computation Time ");
text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
text.Append ("Searched Nodes ");
text.Append (searchedNodes);
if (!error) {
text.Append (" Path Length ");
text.Append (path == null ? "Null" : path.Count.ToString ());
if (logMode == PathLog.Heavy) {
text.Append ("\nSearch Iterations "+searchIterations);
//text.Append ("\nBinary Heap size at complete: ");
// -2 because numberOfItems includes the next item to be added and item zero is not used
//text.Append (pathHandler.open == null ? "null" : (pathHandler.open.numberOfItems-2).ToString ());
}
/*"\nEnd node\n G = "+p.endNode.g+"\n H = "+p.endNode.h+"\n F = "+p.endNode.f+"\n Point "+p.endPoint
+"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+
"\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/
}
if (error) {
text.Append ("\nError: ");
text.Append (errorLog);
}
if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading ) {
text.Append ("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine ("NULL");
}
text.Append ("\nPath Number ");
text.Append (pathID);
return text.ToString ();
}
/** Calls callback to return the calculated path. \see #callback */
public virtual void ReturnPath () {
if (callback != null) {
callback (this);
}
}
/** Prepares low level path variables for calculation.
* Called before a path search will take place.
* Always called before the Prepare, Initialize and CalculateStep functions
*/
public void PrepareBase (PathHandler pathHandler) {
//Path IDs have overflowed 65K, cleanup is needed
//Since pathIDs are handed out sequentially, we can do this
if (pathHandler.PathID > pathID) {
pathHandler.ClearPathIDs ();
}
//Make sure the path has a reference to the pathHandler
this.pathHandler = pathHandler;
//Assign relevant path data to the pathHandler
pathHandler.InitializeForPath (this);
// Make sure that internalTagPenalties is an array which has the length 32
if (internalTagPenalties == null || internalTagPenalties.Length != 32)
internalTagPenalties = ZeroTagPenalties;
try {
ErrorCheck ();
} catch (System.Exception e) {
ForceLogError ("Exception in path "+pathID+"\n"+e.ToString());
}
}
public abstract void Prepare ();
/** Always called after the path has been calculated.
* Guaranteed to be called before other paths have been calculated on
* the same thread.
* Use for cleaning up things like node tagging and similar.
*/
public virtual void Cleanup () {}
/** Initializes the path.
* Sets up the open list and adds the first node to it
*/
public abstract void Initialize ();
/** Calculates the path until time has gone past \a targetTick */
public abstract void CalculateStep (long targetTick);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
namespace JCrypt
{
public class JCrypt: JCrypto
{
public JCrypt(int BLOCK_LENGTH = 32)
{
this.BLOCK_LENGTH = BLOCK_LENGTH;
}
public JCrypt(uint a, uint b, uint c, uint d, int BLOCK_LENGTH = 32)
{
A = a;
B = b;
C = c;
D = d;
this.BLOCK_LENGTH = BLOCK_LENGTH;
}
}
public abstract class JCrypto
{
public int ProgressAsPercentage { get { if (blocks.Count == 0) return 0; else return (BlockCount / 100) * BlocksProcessed; } }
public int BlocksProcessed { get { return blocksProcessed; } }
public int BlockCount { get; private set; }
public int BLOCK_LENGTH { get; set; }
public uint A { get { return a; } set { a = value; } }
public uint B { get { return b; } set { b = value; } }
public uint C { get { return c; } set { c = value; } }
public uint D { get { return d; } set { d = value; } }
private uint a = 0xBADA55;
private uint b = 0x223344;
private uint c = 0x152437;
private uint d = 0x525234;
private uint x;
private int blocksProcessed = 1;
private List<byte[]> blocks = new List<byte[]>();
private byte[] data;
private byte[] key;
public byte[] Encrypt(byte[] data, byte[] key, bool internalCall = false)
{
List<byte> result = new List<byte>();
this.data = data;
this.key = key;
if (!internalCall)
breakBlocks(data);
foreach (byte[] block in blocks)
{
foreach (byte b in encryptBlock(block))
result.Add(b);
blocksProcessed++;
}
return result.ToArray();
}
public byte[] Decrypt(byte[] data, byte[] key, bool internalCall = false)
{
List<byte> result = new List<byte>();
this.data = data;
this.key = key;
if (!internalCall)
breakBlocks(data);
foreach (byte[] block in blocks)
{
foreach (byte b in decryptBlock(block))
result.Add(b);
blocksProcessed++;
}
return result.ToArray();
}
public byte[] Encrypt(string filePath, string keyPath)
{
Stream fileStream = new StreamReader(filePath).BaseStream;
byte[] key = File.ReadAllBytes(keyPath);
return Encrypt(fileStream, key);
}
public byte[] Decrypt(string filePath, string keyPath)
{
Stream fileStream = new StreamReader(filePath).BaseStream;
byte[] key = File.ReadAllBytes(keyPath);
return Decrypt(fileStream, key);
}
public byte[] Encrypt(string filePath, byte[] key)
{
Stream fileStream = new StreamReader(filePath).BaseStream;
return Encrypt(fileStream, key);
}
public byte[] Decrypt(string filePath, byte[] key)
{
Stream fileStream = new StreamReader(filePath).BaseStream;
return Decrypt(fileStream, key);
}
public byte[] Encrypt(byte[] data, string keyPath)
{
return Encrypt(data, File.ReadAllBytes(keyPath));
}
public byte[] Decrypt(byte[] data, string keyPath)
{
return Decrypt(data, File.ReadAllBytes(keyPath));
}
public byte[] Encrypt(Stream fileStream, byte[] key)
{
BinaryReader blockReader = new BinaryReader(fileStream);
List<byte[]> encryptedBlocks = new List<byte[]>();
while (blockReader.BaseStream.Position < blockReader.BaseStream.Length)
{
List<byte> block = new List<byte>();
for (int x = 0; x <= BLOCK_LENGTH && blockReader.BaseStream.Position < blockReader.BaseStream.Length; x++)
block.Add(blockReader.ReadByte());
byte[] blockByte = block.ToArray();
blocks.Add(blockByte);
BlockCount++;
encryptedBlocks.Add(Encrypt(blockByte, key, true));
blocks.Remove(blockByte);
}
blockReader.Close();
List<byte> result = new List<byte>();
foreach (byte[] block in encryptedBlocks)
foreach (byte b in block)
result.Add(b);
return result.ToArray();
}
public byte[] Decrypt(Stream fileStream, byte[] key)
{
BinaryReader blockReader = new BinaryReader(fileStream);
List<byte[]> decryptedBlocks = new List<byte[]>();
while (blockReader.BaseStream.Position < blockReader.BaseStream.Length)
{
List<byte> block = new List<byte>();
for (int x = 0; x <= BLOCK_LENGTH && blockReader.BaseStream.Position < blockReader.BaseStream.Length; x++)
block.Add(blockReader.ReadByte());
byte[] blockByte = block.ToArray();
blocks.Add(blockByte);
BlockCount++;
decryptedBlocks.Add(Decrypt(blockByte, key, true));
blocks.Remove(blockByte);
}
blockReader.Close();
List<byte> result = new List<byte>();
foreach (byte[] block in decryptedBlocks)
foreach (byte b in block)
result.Add(b);
return result.ToArray();
}
private byte[] encryptBlock(byte[] block)
{
for (int x = 0; x < block.Length; x++)
foreach (byte b in key)
block[x] += TransformByte(b);
return block;
}
private byte[] decryptBlock(byte[] block)
{
for (int x = 0; x < block.Length; x++)
foreach (byte b in key)
block[x] -= TransformByte(b);
return block;
}
public virtual byte TransformByte(byte bl)
{
a = shiftLeft(bl, (int)(a + x));
b = (a + bl);
c = (a + b) | x;
d ^= c;
x = a ^ ((b | c) & d);
a |= d;
/* Console.WriteLine("a: " + (byte)a);
Console.WriteLine("b: " + (byte)b);
Console.WriteLine("c: " + (byte)c);
Console.WriteLine("d: " + (byte)d);
Console.WriteLine("x: " + (byte)x);*/
bl = (byte)((a * c) + b - x * d + bl);
return bl;
}
private void breakBlocks(byte[] bytes)
{
int i = 0;
while (i < bytes.Length)
{
byte[] buffer = new byte[BLOCK_LENGTH];
int j;
for (j = 0; j <= BLOCK_LENGTH; j++)
{
if (data.Length > i + j)
buffer[j] = data[i + j];
else
break;
}
i += j;
blocks.Add(buffer);
BlockCount++;
}
}
private byte shiftLeft(byte b, int bits)
{
return (byte)((byte)(b << bits) | (byte)(b >> 32 - bits));
}
private byte shiftRight(byte b, int bits)
{
return (byte)((byte)(b >> bits) | (byte)(b << 32 - bits));
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// 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 ComponentAce 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.
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using System;
namespace ComponentAce.Compression.Libs.ZLib
{
internal enum InflateBlockMode
{
TYPE = 0, // get type bits (3, including End bit)
LENS = 1, // get lengths for stored
STORED = 2, // processing stored block
TABLE = 3, // get table lengths
BTREE = 4, // get bit lengths tree for a dynamic block
DTREE = 5, // get length, distance trees for a dynamic block
CODES = 6, // processing fixed or dynamic block
DRY = 7, // output remaining Window bytes
DONE = 8, // finished last block, done
BAD = 9 // a data error--stuck here
}
internal sealed class InfBlocks
{
#region Fields
private const int MANY = 1440;
/// <summary>
/// current inflate_block mode
/// </summary>
private InflateBlockMode mode;
/// <summary>
/// if STORED, bytes left to copy
/// </summary>
private int left;
/// <summary>
/// table lengths (14 bits)
/// </summary>
private int table;
/// <summary>
/// index into blens (or border)
/// </summary>
private int index;
/// <summary>
/// bit lengths of codes
/// </summary>
private int[] blens;
/// <summary>
/// bit length tree depth
/// </summary>
private int[] bb = new int[1];
/// <summary>
/// bit length decoding tree
/// </summary>
private int[] tb = new int[1];
/// <summary>
/// if CODES, current state
/// </summary>
private InfCodes codes;
/// <summary>
/// true if this block is the last block
/// </summary>
private int last;
// mode independent information
/// <summary>
/// bits in bit buffer
/// </summary>
private int bitk;
/// <summary>
/// bit buffer
/// </summary>
private int bitb;
/// <summary>
/// single malloc for tree space
/// </summary>
private int[] hufts;
/// <summary>
/// sliding Window
/// </summary>
private byte[] window;
/// <summary>
/// one byte after sliding Window
/// </summary>
private int end;
/// <summary>
/// Window ReadPos pointer
/// </summary>
private int read;
/// <summary>
/// Window WritePos pointer
/// </summary>
private int write;
/// <summary>
/// need check
/// </summary>
private bool needCheck;
/// <summary>
/// check on output
/// </summary>
private long check;
#endregion
#region Properties
/// <summary>
/// sliding window
/// </summary>
public byte[] Window
{
get { return window; }
set { window = value; }
}
/// <summary>
/// one byte after sliding Window
/// </summary>
public int End
{
get { return end; }
set { end = value; }
}
/// <summary>
/// Window ReadPos pointer
/// </summary>
public int ReadPos
{
get { return read; }
set { read = value; }
}
/// <summary>
/// Window WritePos pointer
/// </summary>
public int WritePos
{
get { return write; }
set { write = value; }
}
/// <summary>
/// bits in bit buffer
/// </summary>
public int BitK
{
get { return bitk; }
set { bitk = value; }
}
/// <summary>
/// bit buffer
/// </summary>
public int BitB
{
get { return bitb; }
set { bitb = value; }
}
#endregion
#region Methods
internal InfBlocks(ZStream z, bool needCheck, int w)
{
hufts = new int[MANY * 3];
window = new byte[w];
end = w;
this.needCheck = needCheck;
mode = InflateBlockMode.TYPE;
reset(z, null);
}
/// <summary>
/// Resets this InfBlocks class instance
/// </summary>
internal void reset(ZStream z, long[] c)
{
if (c != null)
c[0] = check;
if (mode == InflateBlockMode.BTREE || mode == InflateBlockMode.DTREE)
{
blens = null;
}
if (mode == InflateBlockMode.CODES)
{
codes.free(z);
}
mode = InflateBlockMode.TYPE;
BitK = 0;
BitB = 0;
ReadPos = WritePos = 0;
if (this.needCheck)
z.adler = check = Adler32.GetAdler32Checksum(0L, null, 0, 0);
}
/// <summary>
/// Block processing functions
/// </summary>
internal int proc(ZStream z, int r)
{
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output Window WritePos pointer
int m; // bytes to End of Window or ReadPos pointer
// copy input/output information to locals (UPDATE macro restores)
{
p = z.next_in_index; n = z.avail_in; b = BitB; k = BitK;
}
{
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
}
// process input based on current state
while (true)
{
switch (mode)
{
case InflateBlockMode.TYPE:
while (k < (3))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = (int)(b & 7);
last = t & 1;
switch (ZLibUtil.URShift(t, 1))
{
case 0: // stored
{
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
t = k & 7; // go to byte boundary
{
b = ZLibUtil.URShift(b, (t)); k -= (t);
}
mode = InflateBlockMode.LENS; // get length of stored block
break;
case 1: // fixed
{
int[] bl = new int[1];
int[] bd = new int[1];
int[][] tl = new int[1][];
int[][] td = new int[1][];
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes = new InfCodes(bl[0], bd[0], tl[0], td[0], z);
}
{
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
mode = InflateBlockMode.CODES;
break;
case 2: // dynamic
{
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
mode = InflateBlockMode.TABLE;
break;
case 3: // illegal
{
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
mode = InflateBlockMode.BAD;
z.msg = "invalid block type";
r = (int)ZLibResultCode.Z_DATA_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
break;
case InflateBlockMode.LENS:
while (k < (32))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
if (((ZLibUtil.URShift((~b), 16)) & 0xffff) != (b & 0xffff))
{
mode = InflateBlockMode.BAD;
z.msg = "invalid stored block lengths";
r = (int)ZLibResultCode.Z_DATA_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
left = (b & 0xffff);
b = k = 0; // dump bits
mode = (left != 0) ? InflateBlockMode.STORED : (last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE);
break;
case InflateBlockMode.STORED:
if (n == 0)
{
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
if (m == 0)
{
if (q == End && ReadPos != 0)
{
q = 0; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
}
if (m == 0)
{
WritePos = q;
r = inflate_flush(z, r);
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
if (q == End && ReadPos != 0)
{
q = 0; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
}
if (m == 0)
{
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
}
}
r = (int)ZLibResultCode.Z_OK;
t = left;
if (t > n)
t = n;
if (t > m)
t = m;
Array.Copy(z.next_in, p, Window, q, t);
p += t; n -= t;
q += t; m -= t;
if ((left -= t) != 0)
break;
mode = last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE;
break;
case InflateBlockMode.TABLE:
while (k < (14))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
table = t = (b & 0x3fff);
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
mode = InflateBlockMode.BAD;
z.msg = "too many length or distance symbols";
r = (int)ZLibResultCode.Z_DATA_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
blens = new int[t];
{
b = ZLibUtil.URShift(b, (14)); k -= (14);
}
index = 0;
mode = InflateBlockMode.BTREE;
goto case InflateBlockMode.BTREE;
case InflateBlockMode.BTREE:
while (index < 4 + (ZLibUtil.URShift(table, 10)))
{
while (k < (3))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
blens[ZLibUtil.border[index++]] = b & 7;
{
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
}
while (index < 19)
{
blens[ZLibUtil.border[index++]] = 0;
}
bb[0] = 7;
t = InfTree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != (int)ZLibResultCode.Z_OK)
{
r = t;
if (r == (int)ZLibResultCode.Z_DATA_ERROR)
{
blens = null;
mode = InflateBlockMode.BAD;
}
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
index = 0;
mode = InflateBlockMode.DTREE;
goto case InflateBlockMode.DTREE;
case InflateBlockMode.DTREE:
while (true)
{
t = table;
if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)))
{
break;
}
int i, j, c;
t = bb[0];
while (k < (t))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = hufts[(tb[0] + (b & ZLibUtil.inflate_mask[t])) * 3 + 1];
c = hufts[(tb[0] + (b & ZLibUtil.inflate_mask[t])) * 3 + 2];
if (c < 16)
{
b = ZLibUtil.URShift(b, (t)); k -= (t);
blens[index++] = c;
}
else
{
// c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while (k < (t + i))
{
if (n != 0)
{
r = (int)ZLibResultCode.Z_OK;
}
else
{
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
b = ZLibUtil.URShift(b, (t)); k -= (t);
j += (b & ZLibUtil.inflate_mask[i]);
b = ZLibUtil.URShift(b, (i)); k -= (i);
i = index;
t = table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1))
{
blens = null;
mode = InflateBlockMode.BAD;
z.msg = "invalid bit length repeat";
r = (int)ZLibResultCode.Z_DATA_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
c = c == 16 ? blens[i - 1] : 0;
do
{
blens[i++] = c;
}
while (--j != 0);
index = i;
}
}
tb[0] = -1;
{
int[] bl = new int[1];
int[] bd = new int[1];
int[] tl = new int[1];
int[] td = new int[1];
bl[0] = 9; // must be <= 9 for lookahead assumptions
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = InfTree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, z);
if (t != (int)ZLibResultCode.Z_OK)
{
if (t == (int)ZLibResultCode.Z_DATA_ERROR)
{
blens = null;
mode = InflateBlockMode.BAD;
}
r = t;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
codes = new InfCodes(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
}
blens = null;
mode = InflateBlockMode.CODES;
goto case InflateBlockMode.CODES;
case InflateBlockMode.CODES:
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
if ((r = codes.proc(this, z, r)) != (int)ZLibResultCode.Z_STREAM_END)
{
return inflate_flush(z, r);
}
r = (int)ZLibResultCode.Z_OK;
codes.free(z);
p = z.next_in_index; n = z.avail_in; b = BitB; k = BitK;
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
if (last == 0)
{
mode = InflateBlockMode.TYPE;
break;
}
mode = InflateBlockMode.DRY;
goto case InflateBlockMode.DRY;
case InflateBlockMode.DRY:
WritePos = q;
r = inflate_flush(z, r);
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
if (ReadPos != WritePos)
{
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
mode = InflateBlockMode.DONE;
goto case InflateBlockMode.DONE;
case InflateBlockMode.DONE:
r = (int)ZLibResultCode.Z_STREAM_END;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
case InflateBlockMode.BAD:
r = (int)ZLibResultCode.Z_DATA_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
default:
r = (int)ZLibResultCode.Z_STREAM_ERROR;
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
}
}
/// <summary>
/// Frees inner buffers
/// </summary>
internal void free(ZStream z)
{
reset(z, null);
Window = null;
hufts = null;
//ZFREE(z, s);
}
/// <summary>
/// Sets dictionary
/// </summary>
internal void set_dictionary(byte[] d, int start, int n)
{
Array.Copy(d, start, Window, 0, n);
ReadPos = WritePos = n;
}
///<summary>
/// Returns true if inflate is currently at the End of a block generated
/// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
/// </summary>
internal int sync_point()
{
return mode == InflateBlockMode.LENS ? 1 : 0;
}
/// <summary>
/// copy as much as possible from the sliding Window to the output area
/// </summary>
internal int inflate_flush(ZStream z, int r)
{
int n;
int p;
int q;
// local copies of source and destination pointers
p = z.next_out_index;
q = ReadPos;
// compute number of bytes to copy as far as End of Window
n = (int) ((q <= WritePos?WritePos:End) - q);
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
r = (int)ZLibResultCode.Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (this.needCheck)
z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
// copy as far as End of Window
Array.Copy(Window, q, z.next_out, p, n);
p += n;
q += n;
// see if more to copy at beginning of Window
if (q == End)
{
// wrap pointers
q = 0;
if (WritePos == End)
WritePos = 0;
// compute bytes to copy
n = WritePos - q;
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
r = (int)ZLibResultCode.Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (this.needCheck)
z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
// copy
Array.Copy(Window, q, z.next_out, p, n);
p += n;
q += n;
}
// update pointers
z.next_out_index = p;
ReadPos = q;
// done
return r;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using BrushKey = System.Tuple<System.Int32>;
namespace Eto.Drawing
{
/// <summary>
/// List of brushes with common colors and brush cache for solid color brushes
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public static class Brushes
{
static readonly object cacheKey = new object();
static SolidBrush GetBrush (Color color)
{
var cache = Platform.Instance.Cache<BrushKey, SolidBrush>(cacheKey);
SolidBrush brush;
lock (cache) {
var key = new BrushKey (color.ToArgb ());
if (!cache.TryGetValue (key, out brush)) {
brush = new SolidBrush (color);
cache.Add (key, brush);
}
}
return brush;
}
/// <summary>
/// Gets a cached solid brush with the specified color
/// </summary>
/// <param name="color">Color of the cached solid brush to get</param>
public static SolidBrush Cached(Color color) { return GetBrush(color); }
/// <summary>
/// Clears the brush cache
/// </summary>
/// <remarks>
/// This is useful if you are using the <see cref="Cached(Color)"/> method to cache brushes and want to clear it
/// to conserve memory or resources.
/// </remarks>
public static void ClearCache()
{
var cache = Platform.Instance.Cache<BrushKey, SolidBrush>(cacheKey);
lock (cache) {
cache.Clear ();
}
}
/// <summary>Gets a solid brush with an ARGB value of #00000000</summary>
public static SolidBrush Transparent { get { return GetBrush(Colors.Transparent); } }
// Red colors
/// <summary>Gets a solid brush with a color ARGB value of #FFCD5C5C</summary>
public static SolidBrush IndianRed { get { return GetBrush(Colors.IndianRed); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF08080</summary>
public static SolidBrush LightCoral { get { return GetBrush(Colors.LightCoral); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFA8072</summary>
public static SolidBrush Salmon { get { return GetBrush(Colors.Salmon); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFE9967A</summary>
public static SolidBrush DarkSalmon { get { return GetBrush(Colors.DarkSalmon); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFA07A</summary>
public static SolidBrush LightSalmon { get { return GetBrush(Colors.LightSalmon); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF0000</summary>
public static SolidBrush Red { get { return GetBrush(Colors.Red); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDC143C</summary>
public static SolidBrush Crimson { get { return GetBrush(Colors.Crimson); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFB22222</summary>
public static SolidBrush Firebrick { get { return GetBrush(Colors.Firebrick); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF8B0000</summary>
public static SolidBrush DarkRed { get { return GetBrush(Colors.DarkRed); } }
// Pink colors
/// <summary>Gets a solid brush with a color ARGB value of #FFFFC0CB</summary>
public static SolidBrush Pink { get { return GetBrush(Colors.Pink); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFB6C1</summary>
public static SolidBrush LightPink { get { return GetBrush(Colors.LightPink); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF69B4</summary>
public static SolidBrush HotPink { get { return GetBrush(Colors.HotPink); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF1493</summary>
public static SolidBrush DeepPink { get { return GetBrush(Colors.DeepPink); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFC71585</summary>
public static SolidBrush MediumVioletRed { get { return GetBrush(Colors.MediumVioletRed); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDB7093</summary>
public static SolidBrush PaleVioletRed { get { return GetBrush(Colors.PaleVioletRed); } }
// Orange colors
/// <summary>Gets a solid brush with a color ARGB value of #FFFF7F50</summary>
public static SolidBrush Coral { get { return GetBrush(Colors.Coral); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF6347</summary>
public static SolidBrush Tomato { get { return GetBrush(Colors.Tomato); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF4500</summary>
public static SolidBrush OrangeRed { get { return GetBrush(Colors.OrangeRed); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF8C00</summary>
public static SolidBrush DarkOrange { get { return GetBrush(Colors.DarkOrange); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFA500</summary>
public static SolidBrush Orange { get { return GetBrush(Colors.Orange); } }
// Yellow colors
/// <summary>Gets a solid brush with a color ARGB value of #FFFFD700</summary>
public static SolidBrush Gold { get { return GetBrush(Colors.Gold); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFF00</summary>
public static SolidBrush Yellow { get { return GetBrush(Colors.Yellow); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFFE0</summary>
public static SolidBrush LightYellow { get { return GetBrush(Colors.LightYellow); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFACD</summary>
public static SolidBrush LemonChiffon { get { return GetBrush(Colors.LemonChiffon); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFAFAD2</summary>
public static SolidBrush LightGoldenrodYellow { get { return GetBrush(Colors.LightGoldenrodYellow); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFEFD5</summary>
public static SolidBrush PapayaWhip { get { return GetBrush(Colors.PapayaWhip); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFE4B5</summary>
public static SolidBrush Moccasin { get { return GetBrush(Colors.Moccasin); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFDAB9</summary>
public static SolidBrush PeachPuff { get { return GetBrush(Colors.PeachPuff); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFEEE8AA</summary>
public static SolidBrush PaleGoldenrod { get { return GetBrush(Colors.PaleGoldenrod); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF0E68C</summary>
public static SolidBrush Khaki { get { return GetBrush(Colors.Khaki); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFBDB76B</summary>
public static SolidBrush DarkKhaki { get { return GetBrush(Colors.DarkKhaki); } }
// Purple colors
/// <summary>Gets a solid brush with a color ARGB value of #FFE6E6FA</summary>
public static SolidBrush Lavender { get { return GetBrush(Colors.Lavender); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFD8BFD8</summary>
public static SolidBrush Thistle { get { return GetBrush(Colors.Thistle); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDDA0DD</summary>
public static SolidBrush Plum { get { return GetBrush(Colors.Plum); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFEE82EE</summary>
public static SolidBrush Violet { get { return GetBrush(Colors.Violet); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDA70D6</summary>
public static SolidBrush Orchid { get { return GetBrush(Colors.Orchid); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF00FF</summary>
public static SolidBrush Fuchsia { get { return GetBrush(Colors.Fuchsia); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFF00FF</summary>
public static SolidBrush Magenta { get { return GetBrush(Colors.Magenta); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFBA55D3</summary>
public static SolidBrush MediumOrchid { get { return GetBrush(Colors.MediumOrchid); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF9370DB</summary>
public static SolidBrush MediumPurple { get { return GetBrush(Colors.MediumPurple); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF8A2BE2</summary>
public static SolidBrush BlueViolet { get { return GetBrush(Colors.BlueViolet); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF9400D3</summary>
public static SolidBrush DarkViolet { get { return GetBrush(Colors.DarkViolet); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF9932CC</summary>
public static SolidBrush DarkOrchid { get { return GetBrush(Colors.DarkOrchid); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF8B008B</summary>
public static SolidBrush DarkMagenta { get { return GetBrush(Colors.DarkMagenta); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF800080</summary>
public static SolidBrush Purple { get { return GetBrush(Colors.Purple); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF4B0082</summary>
public static SolidBrush Indigo { get { return GetBrush(Colors.Indigo); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF483D8B</summary>
public static SolidBrush DarkSlateBlue { get { return GetBrush(Colors.DarkSlateBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF6A5ACD</summary>
public static SolidBrush SlateBlue { get { return GetBrush(Colors.SlateBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF7B68EE</summary>
public static SolidBrush MediumSlateBlue { get { return GetBrush(Colors.MediumSlateBlue); } }
// Green colors
/// <summary>Gets a solid brush with a color ARGB value of #FFADFF2F</summary>
public static SolidBrush GreenYellow { get { return GetBrush(Colors.GreenYellow); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF7FFF00</summary>
public static SolidBrush Chartreuse { get { return GetBrush(Colors.Chartreuse); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF7CFC00</summary>
public static SolidBrush LawnGreen { get { return GetBrush(Colors.LawnGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00FF00</summary>
public static SolidBrush Lime { get { return GetBrush(Colors.Lime); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF32CD32</summary>
public static SolidBrush LimeGreen { get { return GetBrush(Colors.LimeGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF98FB98</summary>
public static SolidBrush PaleGreen { get { return GetBrush(Colors.PaleGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF90EE90</summary>
public static SolidBrush LightGreen { get { return GetBrush(Colors.LightGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00FA9A</summary>
public static SolidBrush MediumSpringGreen { get { return GetBrush(Colors.MediumSpringGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00FF7F</summary>
public static SolidBrush SpringGreen { get { return GetBrush(Colors.SpringGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF3CB371</summary>
public static SolidBrush MediumSeaGreen { get { return GetBrush(Colors.MediumSeaGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF2E8B57</summary>
public static SolidBrush SeaGreen { get { return GetBrush(Colors.SeaGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF228B22</summary>
public static SolidBrush ForestGreen { get { return GetBrush(Colors.ForestGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF008000</summary>
public static SolidBrush Green { get { return GetBrush(Colors.Green); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF006400</summary>
public static SolidBrush DarkGreen { get { return GetBrush(Colors.DarkGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF9ACD32</summary>
public static SolidBrush YellowGreen { get { return GetBrush(Colors.YellowGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF6B8E23</summary>
public static SolidBrush OliveDrab { get { return GetBrush(Colors.OliveDrab); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF808000</summary>
public static SolidBrush Olive { get { return GetBrush(Colors.Olive); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF556B2F</summary>
public static SolidBrush DarkOliveGreen { get { return GetBrush(Colors.DarkOliveGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF66CDAA</summary>
public static SolidBrush MediumAquamarine { get { return GetBrush(Colors.MediumAquamarine); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF8FBC8F</summary>
public static SolidBrush DarkSeaGreen { get { return GetBrush(Colors.DarkSeaGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF20B2AA</summary>
public static SolidBrush LightSeaGreen { get { return GetBrush(Colors.LightSeaGreen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF008B8B</summary>
public static SolidBrush DarkCyan { get { return GetBrush(Colors.DarkCyan); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF008080</summary>
public static SolidBrush Teal { get { return GetBrush(Colors.Teal); } }
// Blue/Cyan colors
/// <summary>Gets a solid brush with a color ARGB value of #FF00FFFF</summary>
public static SolidBrush Aqua { get { return GetBrush(Colors.Aqua); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00FFFF</summary>
public static SolidBrush Cyan { get { return GetBrush(Colors.Cyan); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFE0FFFF</summary>
public static SolidBrush LightCyan { get { return GetBrush(Colors.LightCyan); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFAFEEEE</summary>
public static SolidBrush PaleTurquoise { get { return GetBrush(Colors.PaleTurquoise); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF7FFFD4</summary>
public static SolidBrush Aquamarine { get { return GetBrush(Colors.Aquamarine); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF40E0D0</summary>
public static SolidBrush Turquoise { get { return GetBrush(Colors.Turquoise); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF48D1CC</summary>
public static SolidBrush MediumTurquoise { get { return GetBrush(Colors.MediumTurquoise); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00CED1</summary>
public static SolidBrush DarkTurquoise { get { return GetBrush(Colors.DarkTurquoise); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF5F9EA0</summary>
public static SolidBrush CadetBlue { get { return GetBrush(Colors.CadetBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF4682B4</summary>
public static SolidBrush SteelBlue { get { return GetBrush(Colors.SteelBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFB0C4DE</summary>
public static SolidBrush LightSteelBlue { get { return GetBrush(Colors.LightSteelBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFB0E0E6</summary>
public static SolidBrush PowderBlue { get { return GetBrush(Colors.PowderBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFADD8E6</summary>
public static SolidBrush LightBlue { get { return GetBrush(Colors.LightBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF87CEEB</summary>
public static SolidBrush SkyBlue { get { return GetBrush(Colors.SkyBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF87CEFA</summary>
public static SolidBrush LightSkyBlue { get { return GetBrush(Colors.LightSkyBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00BFFF</summary>
public static SolidBrush DeepSkyBlue { get { return GetBrush(Colors.DeepSkyBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF1E90FF</summary>
public static SolidBrush DodgerBlue { get { return GetBrush(Colors.DodgerBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF6495ED</summary>
public static SolidBrush CornflowerBlue { get { return GetBrush(Colors.CornflowerBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF4169E1</summary>
public static SolidBrush RoyalBlue { get { return GetBrush(Colors.RoyalBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF0000FF</summary>
public static SolidBrush Blue { get { return GetBrush(Colors.Blue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF0000CD</summary>
public static SolidBrush MediumBlue { get { return GetBrush(Colors.MediumBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF00008B</summary>
public static SolidBrush DarkBlue { get { return GetBrush(Colors.DarkBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF000080</summary>
public static SolidBrush Navy { get { return GetBrush(Colors.Navy); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF191970</summary>
public static SolidBrush MidnightBlue { get { return GetBrush(Colors.MidnightBlue); } }
// Brown colors
/// <summary>Gets a solid brush with a color ARGB value of #FFFFF8DC</summary>
public static SolidBrush Cornsilk { get { return GetBrush(Colors.Cornsilk); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFEBCD</summary>
public static SolidBrush BlanchedAlmond { get { return GetBrush(Colors.BlanchedAlmond); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFE4C4</summary>
public static SolidBrush Bisque { get { return GetBrush(Colors.Bisque); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFDEAD</summary>
public static SolidBrush NavajoWhite { get { return GetBrush(Colors.NavajoWhite); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF5DEB3</summary>
public static SolidBrush Wheat { get { return GetBrush(Colors.Wheat); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDEB887</summary>
public static SolidBrush BurlyWood { get { return GetBrush(Colors.BurlyWood); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFD2B48C</summary>
public static SolidBrush Tan { get { return GetBrush(Colors.Tan); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFBC8F8F</summary>
public static SolidBrush RosyBrown { get { return GetBrush(Colors.RosyBrown); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF4A460</summary>
public static SolidBrush SandyBrown { get { return GetBrush(Colors.SandyBrown); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFDAA520</summary>
public static SolidBrush Goldenrod { get { return GetBrush(Colors.Goldenrod); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFB8860B</summary>
public static SolidBrush DarkGoldenrod { get { return GetBrush(Colors.DarkGoldenrod); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFCD853F</summary>
public static SolidBrush Peru { get { return GetBrush(Colors.Peru); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFD2691E</summary>
public static SolidBrush Chocolate { get { return GetBrush(Colors.Chocolate); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF8B4513</summary>
public static SolidBrush SaddleBrown { get { return GetBrush(Colors.SaddleBrown); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFA0522D</summary>
public static SolidBrush Sienna { get { return GetBrush(Colors.Sienna); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFA52A2A</summary>
public static SolidBrush Brown { get { return GetBrush(Colors.Brown); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF800000</summary>
public static SolidBrush Maroon { get { return GetBrush(Colors.Maroon); } }
// White colors
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFFFF</summary>
public static SolidBrush White { get { return GetBrush(Colors.White); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFAFA</summary>
public static SolidBrush Snow { get { return GetBrush(Colors.Snow); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF0FFF0</summary>
public static SolidBrush Honeydew { get { return GetBrush(Colors.Honeydew); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF5FFFA</summary>
public static SolidBrush MintCream { get { return GetBrush(Colors.MintCream); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF0FFFF</summary>
public static SolidBrush Azure { get { return GetBrush(Colors.Azure); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF0F8FF</summary>
public static SolidBrush AliceBlue { get { return GetBrush(Colors.AliceBlue); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF8F8FF</summary>
public static SolidBrush GhostWhite { get { return GetBrush(Colors.GhostWhite); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF5F5F5</summary>
public static SolidBrush WhiteSmoke { get { return GetBrush(Colors.WhiteSmoke); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFF5EE</summary>
public static SolidBrush Seashell { get { return GetBrush(Colors.Seashell); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFF5F5DC</summary>
public static SolidBrush Beige { get { return GetBrush(Colors.Beige); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFDF5E6</summary>
public static SolidBrush OldLace { get { return GetBrush(Colors.OldLace); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFAF0</summary>
public static SolidBrush FloralWhite { get { return GetBrush(Colors.FloralWhite); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFFFF0</summary>
public static SolidBrush Ivory { get { return GetBrush(Colors.Ivory); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFAEBD7</summary>
public static SolidBrush AntiqueWhite { get { return GetBrush(Colors.AntiqueWhite); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFAF0E6</summary>
public static SolidBrush Linen { get { return GetBrush(Colors.Linen); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFF0F5</summary>
public static SolidBrush LavenderBlush { get { return GetBrush(Colors.LavenderBlush); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFFFE4E1</summary>
public static SolidBrush MistyRose { get { return GetBrush(Colors.MistyRose); } }
// Gray colors
/// <summary>Gets a solid brush with a color ARGB value of #FFDCDCDC</summary>
public static SolidBrush Gainsboro { get { return GetBrush(Colors.Gainsboro); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFD3D3D3</summary>
public static SolidBrush LightGrey { get { return GetBrush(Colors.LightGrey); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFC0C0C0</summary>
public static SolidBrush Silver { get { return GetBrush(Colors.Silver); } }
/// <summary>Gets a solid brush with a color ARGB value of #FFA9A9A9</summary>
public static SolidBrush DarkGray { get { return GetBrush(Colors.DarkGray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF808080</summary>
public static SolidBrush Gray { get { return GetBrush(Colors.Gray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF696969</summary>
public static SolidBrush DimGray { get { return GetBrush(Colors.DimGray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF778899</summary>
public static SolidBrush LightSlateGray { get { return GetBrush(Colors.LightSlateGray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF708090</summary>
public static SolidBrush SlateGray { get { return GetBrush(Colors.SlateGray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF2F4F4F</summary>
public static SolidBrush DarkSlateGray { get { return GetBrush(Colors.DarkSlateGray); } }
/// <summary>Gets a solid brush with a color ARGB value of #FF000000</summary>
public static SolidBrush Black { get { return GetBrush(Colors.Black); } }
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace UnityEditor.XCodeEditor
{
using Debug = UnityEngine.Debug;
public class PBXParser
{
public const string PBX_HEADER_TOKEN = "// !$*UTF8*$!\n";
public const char WHITESPACE_SPACE = ' ';
public const char WHITESPACE_TAB = '\t';
public const char WHITESPACE_NEWLINE = '\n';
public const char WHITESPACE_CARRIAGE_RETURN = '\r';
public const char ARRAY_BEGIN_TOKEN = '(';
public const char ARRAY_END_TOKEN = ')';
public const char ARRAY_ITEM_DELIMITER_TOKEN = ',';
public const char DICTIONARY_BEGIN_TOKEN = '{';
public const char DICTIONARY_END_TOKEN = '}';
public const char DICTIONARY_ASSIGN_TOKEN = '=';
public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';';
public const char QUOTEDSTRING_BEGIN_TOKEN = '"';
public const char QUOTEDSTRING_END_TOKEN = '"';
public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\';
public const char END_OF_FILE = (char)0x1A;
public const string COMMENT_BEGIN_TOKEN = "/*";
public const string COMMENT_END_TOKEN = "*/";
public const string COMMENT_LINE_TOKEN = "//";
private const int BUILDER_CAPACITY = 20000;
//
private char[] data;
private int index;
// public bool success;
// private int indent;
public PBXDictionary Decode( string data )
{
// success = true;
if( !data.StartsWith( PBX_HEADER_TOKEN ) ) {
Debug.Log( "Wrong file format." );
return null;
}
data = data.Substring( 13 );
this.data = data.ToCharArray();
index = 0;
return (PBXDictionary)ParseValue();
}
public string Encode( PBXDictionary pbxData, bool readable = false )
{
// indent = 0;
StringBuilder builder = new StringBuilder( PBX_HEADER_TOKEN, BUILDER_CAPACITY );
bool success = SerializeValue( pbxData, builder, readable );
return ( success ? builder.ToString() : null );
}
#region Move
private char NextToken()
{
SkipWhitespaces();
return StepForeward();
}
private string Peek( int step = 1 )
{
string sneak = string.Empty;
for( int i = 1; i <= step; i++ ) {
if( data.Length - 1 < index + i ) {
break;
}
sneak += data[ index + i ];
}
return sneak;
}
private bool SkipWhitespaces()
{
bool whitespace = false;
while( Regex.IsMatch( StepForeward().ToString(), @"\s" ) )
whitespace = true;
StepBackward();
if( SkipComments() ) {
whitespace = true;
SkipWhitespaces();
}
return whitespace;
}
private bool SkipComments()
{
string s = string.Empty;
string tag = Peek( 2 );
switch( tag ) {
case COMMENT_BEGIN_TOKEN: {
while( Peek( 2 ).CompareTo( COMMENT_END_TOKEN ) != 0 ) {
s += StepForeward();
}
s += StepForeward( 2 );
break;
}
case COMMENT_LINE_TOKEN: {
while( !Regex.IsMatch( StepForeward().ToString(), @"\n" ) )
continue;
break;
}
default:
return false;
}
return true;
}
private char StepForeward( int step = 1 )
{
index = Math.Min( data.Length, index + step );
return data[ index ];
}
private char StepBackward( int step = 1 )
{
index = Math.Max( 0, index - step );
return data[ index ];
}
#endregion
#region Parse
private object ParseValue()
{
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "End of file" );
return null;
case DICTIONARY_BEGIN_TOKEN:
return ParseDictionary();
case ARRAY_BEGIN_TOKEN:
return ParseArray();
case QUOTEDSTRING_BEGIN_TOKEN:
return ParseString();
default:
StepBackward();
return ParseEntity();
}
}
// private T Convert<T>( PBXDictionary dictionary )
// {
// if( dictionary.ContainsKey( "isa" ) ){
//// ((string)dictionary["isa"]).CompareTo(
// Type targetType = Type.GetType( (string)dictionary["isa"] );
// if( targetType.IsSubclassOf( typeof(PBXObject) ) ) {
// Debug.Log( "ok" );
// T converted = (T)Activator.CreateInstance( targetType );
// return converted;
// }
// else {
// Debug.Log( "Warning: unknown PBX type: " + targetType.Name );
// return default(T);
// }
//
// }
// return default(T);
//
// }
private PBXDictionary ParseDictionary()
{
SkipWhitespaces();
PBXDictionary dictionary = new PBXDictionary();
string keyString = string.Empty;
object valueObject = null;
bool complete = false;
while( !complete ) {
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "Error: reached end of file inside a dictionary: " + index );
complete = true;
break;
case DICTIONARY_ITEM_DELIMITER_TOKEN:
keyString = string.Empty;
valueObject = null;
break;
case DICTIONARY_END_TOKEN:
keyString = string.Empty;
valueObject = null;
complete = true;
break;
case DICTIONARY_ASSIGN_TOKEN:
valueObject = ParseValue();
dictionary.Add( keyString, valueObject );
break;
default:
StepBackward();
keyString = ParseValue() as string;
break;
}
}
return dictionary;
}
private PBXList ParseArray()
{
PBXList list = new PBXList();
bool complete = false;
while( !complete ) {
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "Error: Reached end of file inside a list: " + list );
complete = true;
break;
case ARRAY_END_TOKEN:
complete = true;
break;
case ARRAY_ITEM_DELIMITER_TOKEN:
break;
default:
StepBackward();
list.Add( ParseValue() );
break;
}
}
return list;
}
private object ParseString()
{
string s = string.Empty;
char c = StepForeward();
while( c != QUOTEDSTRING_END_TOKEN ) {
s += c;
if( c == QUOTEDSTRING_ESCAPE_TOKEN )
s += StepForeward();
c = StepForeward();
}
return s;
}
private object ParseEntity()
{
string word = string.Empty;
while( !Regex.IsMatch( Peek(), @"[;,\s=]" ) ) {
word += StepForeward();
}
if( word.Length != 24 && Regex.IsMatch( word, @"^\d+$" ) ) {
return Int32.Parse( word );
}
return word;
}
#endregion
#region Serialize
private bool SerializeValue( object value, StringBuilder builder, bool readable = false )
{
if( value == null ) {
builder.Append( "null" );
}
else if( value is PBXObject ) {
SerializeDictionary( ((PBXObject)value).data, builder, readable );
}
else if( value is Dictionary<string, object> ) {
SerializeDictionary( (Dictionary<string, object>)value, builder, readable );
}
else if( value.GetType().IsArray ) {
SerializeArray( new ArrayList( (ICollection)value ), builder, readable );
}
else if( value is ArrayList ) {
SerializeArray( (ArrayList)value, builder, readable );
}
else if( value is string ) {
SerializeString( (string)value, builder, readable );
}
else if( value is Char ) {
SerializeString( Convert.ToString( (char)value ), builder, readable );
}
else if( value is bool ) {
builder.Append( Convert.ToInt32( value ).ToString() );
}
else if( value.GetType().IsPrimitive ) {
builder.Append( Convert.ToString( value ) );
}
// else if( value is Hashtable )
// {
// serializeObject( (Hashtable)value, builder );
// }
// else if( ( value is Boolean ) && ( (Boolean)value == true ) )
// {
// builder.Append( "NO" );
// }
// else if( ( value is Boolean ) && ( (Boolean)value == false ) )
// {
// builder.Append( "YES" );
// }
else {
Debug.LogWarning( "Error: unknown object of type " + value.GetType().Name );
return false;
}
return true;
}
private bool SerializeDictionary( Dictionary<string, object> dictionary, StringBuilder builder, bool readable = false )
{
builder.Append( DICTIONARY_BEGIN_TOKEN );
foreach( KeyValuePair<string, object> pair in dictionary ) {
SerializeString( pair.Key, builder );
builder.Append( DICTIONARY_ASSIGN_TOKEN );
SerializeValue( pair.Value, builder );
builder.Append( DICTIONARY_ITEM_DELIMITER_TOKEN );
}
builder.Append( DICTIONARY_END_TOKEN );
return true;
}
private bool SerializeArray( ArrayList anArray, StringBuilder builder, bool readable = false )
{
builder.Append( ARRAY_BEGIN_TOKEN );
for( int i = 0; i < anArray.Count; i++ )
{
object value = anArray[i];
if( !SerializeValue( value, builder ) )
{
return false;
}
builder.Append( ARRAY_ITEM_DELIMITER_TOKEN );
}
builder.Append( ARRAY_END_TOKEN );
return true;
}
private bool SerializeString( string aString, StringBuilder builder, bool useQuotes = false, bool readable = false )
{
// Is a GUID?
if( Regex.IsMatch( aString, @"^[A-F0-9]{24}$" ) ) {
builder.Append( aString );
return true;
}
// Is an empty string?
if( string.IsNullOrEmpty( aString ) ) {
builder.Append( QUOTEDSTRING_BEGIN_TOKEN );
builder.Append( QUOTEDSTRING_END_TOKEN );
return true;
}
if( !Regex.IsMatch( aString, @"^[A-Za-z0-9_.]+$" ) ) {
useQuotes = true;
}
if( useQuotes )
builder.Append( QUOTEDSTRING_BEGIN_TOKEN );
builder.Append( aString );
if( useQuotes )
builder.Append( QUOTEDSTRING_END_TOKEN );
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Storage;
using Microsoft.Extensions.Logging;
using Orleans.Hosting;
namespace UnitTests.StorageTests
{
public static class SiloBuilderExtensions
{
public static ISiloBuilder AddTestStorageProvider<T>(this ISiloBuilder builder, string name) where T : IGrainStorage
{
return builder.AddTestStorageProvider(name, (sp, n) => ActivatorUtilities.CreateInstance<T>(sp));
}
public static ISiloBuilder AddTestStorageProvider<T>(this ISiloBuilder builder, string name, Func<IServiceProvider, string, T> createInstance) where T : IGrainStorage
{
return builder.ConfigureServices(services =>
{
services.AddSingletonNamedService<IGrainStorage>(name, (sp, n) => createInstance(sp, n));
if (typeof(ILifecycleParticipant<ISiloLifecycle>).IsAssignableFrom(typeof(T)))
{
services.AddSingletonNamedService(name, (svc, n) => (ILifecycleParticipant<ISiloLifecycle>)svc.GetRequiredServiceByName<IGrainStorage>(name));
}
if (typeof(IControllable).IsAssignableFrom(typeof(T)))
{
services.AddSingletonNamedService(name, (svc, n) => (IControllable)svc.GetRequiredServiceByName<IGrainStorage>(name));
}
});
}
}
[DebuggerDisplay("MockStorageProvider:{Name}")]
public class MockStorageProvider : IControllable, IGrainStorage
{
public enum Commands
{
InitCount,
SetValue,
GetProvideState,
SetErrorInjection,
GetLastState,
ResetHistory
}
[Serializable]
[GenerateSerializer]
public class StateForTest
{
[Id(0)]
public int InitCount { get; set; }
[Id(1)]
public int CloseCount { get; set; }
[Id(2)]
public int ReadCount { get; set; }
[Id(3)]
public int WriteCount { get; set; }
[Id(4)]
public int DeleteCount { get; set; }
}
private static int _instanceNum;
private readonly int _id;
private int initCount, closeCount, readCount, writeCount, deleteCount;
private readonly int numKeys;
private readonly DeepCopier copier;
private ILocalDataStore StateStore;
private const string stateStoreKey = "State";
private ILogger logger;
public string LastId { get; private set; }
public object LastState { get; private set; }
public string Name { get; private set; }
public MockStorageProvider(ILoggerFactory loggerFactory, DeepCopier copier)
: this(Guid.NewGuid().ToString(), 2, loggerFactory, copier)
{ }
public MockStorageProvider(string name, ILoggerFactory loggerFactory, DeepCopier copier)
: this(name, 2, loggerFactory, copier)
{ }
public MockStorageProvider(string name, int numKeys, ILoggerFactory loggerFactory, DeepCopier copier)
{
_id = ++_instanceNum;
this.numKeys = numKeys;
this.copier = copier;
this.Name = name;
this.logger = loggerFactory.CreateLogger(string.Format("Storage.{0}-{1}", this.GetType().Name, this._id));
logger.Info(0, "Init Name={0}", name);
Interlocked.Increment(ref initCount);
StateStore = new HierarchicalKeyStore(numKeys);
logger.Info(0, "Finished Init Name={0}", name);
}
public StateForTest GetProviderState()
{
var state = new StateForTest();
state.InitCount = initCount;
state.CloseCount = closeCount;
state.DeleteCount = deleteCount;
state.ReadCount = readCount;
state.WriteCount = writeCount;
return state;
}
[Serializable]
[GenerateSerializer]
public class SetValueArgs
{
[Id(0)]
public Type StateType { get; set; }
[Id(1)]
public string GrainType { get; set; }
[Id(2)]
public GrainReference GrainReference { get; set; }
[Id(3)]
public string Name { get; set; }
[Id(4)]
public object Val { get; set; }
}
public void SetValue(SetValueArgs args)
{
SetValue(args.StateType, args.GrainType, args.GrainReference, args.Name, args.Val);
}
private void SetValue(Type stateType, string grainType, GrainReference grainReference, string name, object val)
{
lock (StateStore)
{
this.logger.Info("Setting stored value {0} for {1} to {2}", name, grainReference, val);
var keys = MakeGrainStateKeys(grainType, grainReference);
var storedDict = StateStore.ReadRow(keys);
if (!storedDict.ContainsKey(stateStoreKey))
{
storedDict[stateStoreKey] = Activator.CreateInstance(stateType);
}
var storedState = storedDict[stateStoreKey];
var field = storedState.GetType().GetProperty(name).GetSetMethod(true);
field.Invoke(storedState, new[] { val });
LastId = GetId(grainReference);
LastState = storedState;
}
}
public object GetLastState()
{
return LastState;
}
public T GetLastState<T>()
{
return (T) LastState;
}
private object GetLastState(string grainType, GrainReference grainReference, IGrainState grainState)
{
lock (StateStore)
{
var keys = MakeGrainStateKeys(grainType, grainReference);
var storedStateRow = StateStore.ReadRow(keys);
if (!storedStateRow.ContainsKey(stateStoreKey))
{
storedStateRow[stateStoreKey] = Activator.CreateInstance(grainState.State.GetType());
}
var storedState = storedStateRow[stateStoreKey];
LastId = GetId(grainReference);
LastState = storedState;
return storedState;
}
}
public virtual Task Close()
{
logger.Info(0, "Close");
Interlocked.Increment(ref closeCount);
StateStore.Clear();
return Task.CompletedTask;
}
public virtual Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
logger.Info(0, "ReadStateAsync for {0} {1}", grainType, grainReference);
Interlocked.Increment(ref readCount);
lock (StateStore)
{
var storedState = GetLastState(grainType, grainReference, grainState);
grainState.RecordExists = storedState != null;
grainState.State = this.copier.Copy(storedState); // Read current state data
}
return Task.CompletedTask;
}
public virtual Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
logger.Info(0, "WriteStateAsync for {0} {1}", grainType, grainReference);
Interlocked.Increment(ref writeCount);
lock (StateStore)
{
var storedState = this.copier.Copy(grainState.State); // Store current state data
var stateStore = new Dictionary<string, object> {{ stateStoreKey, storedState }};
StateStore.WriteRow(MakeGrainStateKeys(grainType, grainReference), stateStore, grainState.ETag);
LastId = GetId(grainReference);
LastState = storedState;
grainState.RecordExists = true;
}
return Task.CompletedTask;
}
public virtual Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
logger.Info(0, "ClearStateAsync for {0} {1}", grainType, grainReference);
Interlocked.Increment(ref deleteCount);
var keys = MakeGrainStateKeys(grainType, grainReference);
lock (StateStore)
{
StateStore.DeleteRow(keys, grainState.ETag);
LastId = GetId(grainReference);
LastState = null;
}
grainState.RecordExists = false;
return Task.CompletedTask;
}
private static string GetId(GrainReference grainReference)
{
return grainReference.ToKeyString();
}
private static IList<Tuple<string, string>> MakeGrainStateKeys(string grainType, GrainReference grainReference)
{
return new[]
{
Tuple.Create("GrainType", grainType),
Tuple.Create("GrainId", GetId(grainReference))
}.ToList();
}
public void ResetHistory()
{
// initCount = 0;
closeCount = readCount = writeCount = deleteCount = 0;
LastId = null;
LastState = null;
}
/// <summary>
/// A function to execute a control command.
/// </summary>
/// <param name="command">A serial number of the command.</param>
/// <param name="arg">An opaque command argument</param>
public virtual Task<object> ExecuteCommand(int command, object arg)
{
switch ((Commands)command)
{
case Commands.InitCount:
return Task.FromResult<object>(initCount);
case Commands.SetValue:
SetValue((SetValueArgs) arg);
return Task.FromResult<object>(true);
case Commands.GetProvideState:
return Task.FromResult<object>(GetProviderState());
case Commands.GetLastState:
return Task.FromResult(GetLastState());
case Commands.ResetHistory:
ResetHistory();
return Task.FromResult<object>(true);
default:
return Task.FromResult<object>(true);
}
}
}
}
| |
// 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.Linq;
using Xunit.Abstractions;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;
namespace System.Xml.Tests
{
public class LineInfo
{
public int LineNumber { get; private set; }
public int LinePosition { get; private set; }
public string FilePath { get; private set; }
public LineInfo(int lineNum, int linePos)
{
LineNumber = lineNum;
LinePosition = linePos;
FilePath = string.Empty;
}
public LineInfo(int lineNum, int linePos, string filePath)
{
LineNumber = lineNum;
LinePosition = linePos;
FilePath = filePath;
}
}
[Flags]
public enum ExceptionVerificationFlags
{
None = 0,
IgnoreMultipleDots = 1,
IgnoreLineInfo = 2,
}
public class ExceptionVerifier
{
private readonly Assembly _asm;
private Assembly _locAsm;
private readonly Hashtable _resources;
private string _actualMessage;
private string _expectedMessage;
private Exception _ex;
private ExceptionVerificationFlags _verificationFlags = ExceptionVerificationFlags.None;
private ITestOutputHelper _output;
public bool IgnoreMultipleDots
{
get
{
return (_verificationFlags & ExceptionVerificationFlags.IgnoreMultipleDots) != 0;
}
set
{
if (value)
_verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreMultipleDots;
else
_verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreMultipleDots);
}
}
public bool IgnoreLineInfo
{
get
{
return (_verificationFlags & ExceptionVerificationFlags.IgnoreLineInfo) != 0;
}
set
{
if (value)
_verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreLineInfo;
else
_verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreLineInfo);
}
}
private const string ESCAPE_ANY = "~%anything%~";
private const string ESCAPE_NUMBER = "~%number%~";
public ExceptionVerifier(string assemblyName, ExceptionVerificationFlags flags, ITestOutputHelper output)
{
_output = output;
if (assemblyName == null)
throw new VerifyException("Assembly name cannot be null");
_verificationFlags = flags;
try
{
switch (assemblyName.ToUpper())
{
case "SYSTEM.XML":
{
var dom = new XmlDocument();
_asm = dom.GetType().Assembly;
}
break;
default:
_asm = Assembly.LoadFrom(Path.Combine(GetRuntimeInstallDir(), assemblyName + ".dll"));
break;
}
if (_asm == null)
throw new VerifyException("Can not load assembly " + assemblyName);
// let's determine if this is a loc run, if it is then we need to load satellite assembly
_locAsm = null;
if (!CultureInfo.CurrentCulture.Equals(new CultureInfo("en-US")) && !CultureInfo.CurrentCulture.Equals(new CultureInfo("en")))
{
try
{
// load satellite assembly
_locAsm = _asm.GetSatelliteAssembly(new CultureInfo(CultureInfo.CurrentCulture.Parent.IetfLanguageTag));
}
catch (FileNotFoundException e1)
{
_output.WriteLine(e1.ToString());
}
catch (FileLoadException e2)
{
_output.WriteLine(e2.ToString());
}
}
}
catch (Exception e)
{
_output.WriteLine("Exception: " + e.Message);
_output.WriteLine("Stack: " + e.StackTrace);
throw new VerifyException("Error while loading assembly");
}
string[] resArray;
Stream resStream = null;
var bFound = false;
// Check that assembly manifest has resources
if (null != _locAsm)
resArray = _locAsm.GetManifestResourceNames();
else
resArray = _asm.GetManifestResourceNames();
foreach (var s in resArray)
{
if (s.EndsWith(".resources"))
{
resStream = null != _locAsm ? _locAsm.GetManifestResourceStream(s) : _asm.GetManifestResourceStream(s);
bFound = true;
if (bFound && resStream != null)
{
// Populate hashtable from resources
var resReader = new ResourceReader(resStream);
if (_resources == null)
{
_resources = new Hashtable();
}
var ide = resReader.GetEnumerator();
while (ide.MoveNext())
{
if (!_resources.ContainsKey(ide.Key.ToString()))
_resources.Add(ide.Key.ToString(), ide.Value.ToString());
}
resReader.Dispose();
}
//break;
}
}
if (!bFound || resStream == null)
throw new VerifyException("GetManifestResourceStream() failed");
}
private static string GetRuntimeInstallDir()
{
// Get mscorlib path
var s = typeof(object).Module.FullyQualifiedName;
// Remove mscorlib.dll from the path
return Directory.GetParent(s).ToString();
}
public ExceptionVerifier(string assemblyName, ITestOutputHelper output)
: this(assemblyName, ExceptionVerificationFlags.None, output)
{ }
private void ExceptionInfoOutput()
{
// Use reflection to obtain "res" property value
var exceptionType = _ex.GetType();
var fInfo = exceptionType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase) ??
exceptionType.BaseType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (fInfo == null)
throw new VerifyException("Cannot obtain Resource ID from Exception.");
_output.WriteLine(
"\n===== Original Exception Message =====\n" + _ex.Message +
"\n===== Resource Id =====\n" + fInfo.GetValue(_ex) +
"\n===== HelpLink =====\n" + _ex.HelpLink +
"\n===== Source =====\n" + _ex.Source /*+
"\n===== TargetSite =====\n" + ex.TargetSite + "\n"*/);
_output.WriteLine(
"\n===== InnerException =====\n" + _ex.InnerException +
"\n===== StackTrace =====\n" + _ex.StackTrace);
}
public string[] ReturnAllMatchingResIds(string message)
{
var ide = _resources.GetEnumerator();
var list = new ArrayList();
_output.WriteLine("===== All mached ResIDs =====");
while (ide.MoveNext())
{
var resMessage = ide.Value.ToString();
resMessage = ESCAPE_ANY + Regex.Replace(resMessage, @"\{\d*\}", ESCAPE_ANY) + ESCAPE_ANY;
resMessage = MakeEscapes(resMessage).Replace(ESCAPE_ANY, ".*");
if (Regex.Match(message, resMessage, RegexOptions.Singleline).ToString() == message)
{
list.Add(ide.Key);
_output.WriteLine(" [" + ide.Key.ToString() + "] = \"" + ide.Value.ToString() + "\"");
}
}
return (string[])list.ToArray(typeof(string[]));
}
// Common helper methods used by different overloads of IsExceptionOk()
private static void CheckNull(Exception e)
{
if (e == null)
{
throw new VerifyException("NULL exception passed to IsExceptionOk()");
}
}
private void CompareMessages()
{
if (IgnoreMultipleDots && _expectedMessage.EndsWith("."))
_expectedMessage = _expectedMessage.TrimEnd(new char[] { '.' }) + ".";
_expectedMessage = Regex.Escape(_expectedMessage);
_expectedMessage = _expectedMessage.Replace(ESCAPE_ANY, ".*");
_expectedMessage = _expectedMessage.Replace(ESCAPE_NUMBER, @"\d*");
// ignore case
_expectedMessage = _expectedMessage.ToLowerInvariant();
_actualMessage = _actualMessage.ToLowerInvariant();
if (!PlatformDetection.IsNetNative) // .NET Native toolchain optimizes away Exception messages
{
if (Regex.Match(_actualMessage, _expectedMessage, RegexOptions.Singleline).ToString() != _actualMessage)
{
// Unescape before printing the expected message string
_expectedMessage = Regex.Unescape(_expectedMessage);
_output.WriteLine("Mismatch in error message");
_output.WriteLine("===== Expected Message =====\n" + _expectedMessage);
_output.WriteLine("===== Expected Message Length =====\n" + _expectedMessage.Length);
_output.WriteLine("===== Actual Message =====\n" + _actualMessage);
_output.WriteLine("===== Actual Message Length =====\n" + _actualMessage.Length);
throw new VerifyException("Mismatch in error message");
}
}
}
public void IsExceptionOk(Exception e, string expectedResId)
{
CheckNull(e);
_ex = e;
if (expectedResId == null)
{
// Pint actual exception info and quit
// This can be used to dump exception properties, verify them and then plug them into our expected results
ExceptionInfoOutput();
throw new VerifyException("Did not pass resource ID to verify");
}
IsExceptionOk(e, new object[] { expectedResId });
}
public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues)
{
var list = new ArrayList { expectedResId };
foreach (var param in paramValues)
list.Add(param);
IsExceptionOk(e, list.ToArray());
}
public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues, LineInfo lineInfo)
{
var list = new ArrayList { expectedResId, lineInfo };
foreach (var param in paramValues)
list.Add(param);
IsExceptionOk(e, list.ToArray());
}
public void IsExceptionOk(Exception e, object[] IdsAndParams)
{
CheckNull(e);
_ex = e;
_actualMessage = e.Message;
_expectedMessage = ConstructExpectedMessage(IdsAndParams);
CompareMessages();
}
private static string MakeEscapes(string str)
{
return new[] { "\\", "$", "{", "[", "(", "|", ")", "*", "+", "?" }.Aggregate(str, (current, esc) => current.Replace(esc, "\\" + esc));
}
public string ConstructExpectedMessage(object[] IdsAndParams)
{
var lineInfoMessage = "";
var paramList = new ArrayList();
var paramsStartPosition = 1;
// Verify that input list contains at least one element - ResId
if (IdsAndParams.Length == 0 || !(IdsAndParams[0] is string))
throw new VerifyException("ResID at IDsAndParams[0] missing!");
string expectedResId = (IdsAndParams[0] as string);
// Verify that resource id exists in resources
if (!_resources.ContainsKey(expectedResId))
{
ExceptionInfoOutput();
throw new VerifyException("Resources in [" + _asm.GetName().Name + "] does not contain string resource: " + expectedResId);
}
// If LineInfo exist, construct LineInfo message
if (IdsAndParams.Length > 1 && (IdsAndParams[1] is LineInfo))
{
if (!IgnoreLineInfo)
{
var lineInfo = (IdsAndParams[1] as LineInfo);
// Xml_ErrorPosition = "Line {0}, position {1}."
lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? _resources["Xml_ErrorPosition"].ToString() : _resources["Xml_ErrorFilePosition"].ToString();
var lineNumber = lineInfo.LineNumber.ToString();
var linePosition = lineInfo.LinePosition.ToString();
lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? string.Format(lineInfoMessage, lineNumber, linePosition) : string.Format(lineInfoMessage, lineInfo.FilePath, lineNumber, linePosition);
}
else
lineInfoMessage = ESCAPE_ANY;
lineInfoMessage = " " + lineInfoMessage;
paramsStartPosition = 2;
}
string message = _resources[expectedResId].ToString();
for (var i = paramsStartPosition; i < IdsAndParams.Length; i++)
{
if (IdsAndParams[i] is object[])
paramList.Add(ConstructExpectedMessage(IdsAndParams[i] as object[]));
else
{
if (IdsAndParams[i] == null)
paramList.Add(ESCAPE_ANY);
else
paramList.Add(IdsAndParams[i] as string);
}
}
try
{
message = string.Format(message, paramList.ToArray());
}
catch (FormatException)
{
throw new VerifyException("Mismatch in number of parameters!");
}
return message + lineInfoMessage;
}
}
public class VerifyException : Exception
{
public VerifyException(string msg)
: base(msg)
{ }
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site
{
using Adxstudio.Xrm.Core.Flighting;
using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.Security;
using System.Web.WebPages;
using Adxstudio.Xrm;
using Adxstudio.Xrm.Core.Telemetry;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.Xrm.Portal.Configuration;
using Adxstudio.Xrm.AspNet.Cms;
public class Global : HttpApplication
{
private static bool _setupRunning;
void Application_Start(object sender, EventArgs e)
{
AntiForgeryConfig.CookieName = "__RequestVerificationToken"; // static name as its dependent on the ajax handler.
MvcHandler.DisableMvcResponseHeader = true;
_setupRunning = SetupConfig.ApplicationStart();
if (_setupRunning) return;
var areaRegistrationState = new PortalAreaRegistrationState();
Application[typeof(IPortalAreaRegistrationState).FullName] = areaRegistrationState;
AreaRegistration.RegisterAllAreas(areaRegistrationState);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
// Set the culture of the current request's thread to the current website's language.
// This is necessary in .NET 4.6 and above because the current thread doesn't retain the
// thread culture set within the Site.Startup OWIN middleware.
// https://stackoverflow.com/questions/36455801/owinmiddleware-doesnt-preserve-culture-change-in-net-4-6
// https://connect.microsoft.com/VisualStudio/feedback/details/2455357
// https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.110).aspx#Async
// https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-culture-and-asynchronous-operations
var languageContext = Context.GetContextLanguageInfo();
if (languageContext?.ContextLanguage != null)
{
ContextLanguageInfo.SetCultureInfo(languageContext.ContextLanguage.Lcid);
}
}
protected void Session_Start(object sender, EventArgs e)
{
Session["init"] = 0;
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)
// ignore non-user pings
&& TelemetryState.IsTelemetryEnabledUserAgent()
// ignore requests to and referred requests from specific paths
&& TelemetryState.IsTelemetryEnabledRequestPage()
// only report this telemetry when the portal is configured
&& SetupConfig.IsPortalConfigured())
{
PortalFeatureTrace.TraceInstance.LogSessionInfo(FeatureTraceCategory.SessionStart);
}
}
void Application_Error(object sender, EventArgs e)
{
WebEventSource.Log.UnhandledException(Server.GetLastError());
}
public override string GetVaryByCustomString(HttpContext context, string arg)
{
switch (arg)
{
case "roles":
return GetVaryByRolesString(context);
case "roles;language":
return string.Format("{0}{1}", GetVaryByRolesString(context), GetVaryByLanguageString());
case "roles;website":
return GetVaryByRolesAndWebsiteString(context);
case "roles;website;language":
return string.Format("{0}{1}", GetVaryByRolesAndWebsiteString(context), GetVaryByLanguageString());
case "user":
return GetVaryByUserString(context);
case "user;website":
return GetVaryByUserAndWebsiteString(context);
case "website":
return GetVaryByWebsiteString(context);
case "culture":
return CultureInfo.CurrentCulture.LCID.ToString();
case "user;language":
return string.Format("{0}{1}", GetVaryByUserString(context), GetVaryByLanguageString());
case "user;website;language":
return string.Format("{0}{1}", GetVaryByUserAndWebsiteString(context), GetVaryByLanguageString());
case "website;language":
return string.Format("{0}{1}", GetVaryByWebsiteString(context), GetVaryByLanguageString());
}
return base.GetVaryByCustomString(context, arg);
}
public void Profile_MigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
var portalAreaRegistrationState = Application[typeof(IPortalAreaRegistrationState).FullName] as IPortalAreaRegistrationState;
if (portalAreaRegistrationState != null)
{
portalAreaRegistrationState.OnProfile_MigrateAnonymous(sender, e);
}
}
private static string GetVaryByLanguageString()
{
var langContext = HttpContext.Current.GetContextLanguageInfo();
if (langContext.IsCrmMultiLanguageEnabled)
{
return string.Format(",{0}", langContext.ContextLanguage.Code);
}
return string.Empty;
}
private static string GetVaryByDisplayModesString(HttpContext context)
{
var availableDisplayModeIds = DisplayModeProvider.Instance
.GetAvailableDisplayModesForContext(context.Request.RequestContext.HttpContext, null)
.Select(mode => mode.DisplayModeId);
return string.Join(",", availableDisplayModeIds);
}
private static string GetVaryByRolesString(HttpContext context)
{
// If the role system is not enabled, fall back to varying cache by user.
if (!Roles.Enabled)
{
return GetVaryByUserString(context);
}
var roles = context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated
? Roles.GetRolesForUser()
.OrderBy(role => role)
.Aggregate(new StringBuilder(), (sb, role) => sb.AppendFormat("[{0}]", role))
.ToString()
: string.Empty;
return string.Format("IsAuthenticated={0},Roles={1},DisplayModes={2}",
context.Request.IsAuthenticated,
roles.GetHashCode(),
GetVaryByDisplayModesString(context).GetHashCode());
}
private static string GetVaryByRolesAndWebsiteString(HttpContext context)
{
return string.Format("{0},{1}", GetVaryByRolesString(context), GetVaryByWebsiteString(context));
}
private static string GetVaryByUserString(HttpContext context)
{
return string.Format("IsAuthenticated={0},Identity={1},Session={2},DisplayModes={3}",
context.Request.IsAuthenticated,
GetIdentity(context),
GetSessionId(context),
GetVaryByDisplayModesString(context).GetHashCode());
}
private static object GetIdentity(HttpContext context)
{
return context.Request.IsAuthenticated && context.User != null && context.User.Identity != null
? context.User.Identity.Name
: string.Empty;
}
private static readonly SessionStateSection SessionStateConfigurationSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
private static object GetSessionId(HttpContext context)
{
if (!context.Request.IsAuthenticated || SessionStateConfigurationSection == null)
{
return string.Empty;
}
var sessionCookie = context.Request.Cookies[SessionStateConfigurationSection.CookieName];
return sessionCookie == null ? string.Empty : sessionCookie.Value;
}
private static string GetVaryByUserAndWebsiteString(HttpContext context)
{
return string.Format("{0},{1}", GetVaryByUserString(context), GetVaryByWebsiteString(context));
}
private static string GetVaryByWebsiteString(HttpContext context)
{
var websiteId = GetWebsiteIdFromOwinContext(context) ?? GetWebsiteIdFromPortalContext(context);
return websiteId == null ? "Website=" : string.Format("Website={0}", websiteId.GetHashCode());
}
private static string GetWebsiteIdFromOwinContext(HttpContext context)
{
var owinContext = context.GetOwinContext();
if (owinContext == null)
{
return null;
}
var website = owinContext.GetWebsite();
return website == null ? null : website.Id.ToString();
}
private static string GetWebsiteIdFromPortalContext(HttpContext context)
{
var portalContext = PortalCrmConfigurationManager.CreatePortalContext(request: context.Request.RequestContext);
if (portalContext == null)
{
return null;
}
return portalContext.Website == null ? null : portalContext.Website.Id.ToString();
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
public abstract class NamedPipelineBase<TDelegate>
{
/// <summary>
/// Pipeline items to execute
/// </summary>
protected readonly List<PipelineItem<TDelegate>> pipelineItems;
protected NamedPipelineBase()
{
this.pipelineItems = new List<PipelineItem<TDelegate>>();
}
protected NamedPipelineBase(int capacity)
{
this.pipelineItems = new List<PipelineItem<TDelegate>>(capacity);
}
/// <summary>
/// Gets the current pipeline items
/// </summary>
public IEnumerable<PipelineItem<TDelegate>> PipelineItems
{
get { return this.pipelineItems.AsReadOnly(); }
}
/// <summary>
/// Gets the current pipeline item delegates
/// </summary>
public IEnumerable<TDelegate> PipelineDelegates
{
get { return this.pipelineItems.Select(pipelineItem => pipelineItem.Delegate); }
}
/// <summary>
/// Add an item to the start of the pipeline
/// </summary>
/// <param name="item">Item to add</param>
public virtual void AddItemToStartOfPipeline(TDelegate item)
{
this.AddItemToStartOfPipeline((PipelineItem<TDelegate>)item);
}
/// <summary>
/// Add an item to the start of the pipeline
/// </summary>
/// <param name="item">Item to add</param>
/// <param name="replaceInPlace">
/// Whether to replace an existing item with the same name in its current place,
/// rather than at the position requested. Defaults to false.
/// </param>
public virtual void AddItemToStartOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false)
{
this.InsertItemAtPipelineIndex(0, item, replaceInPlace);
}
/// <summary>
/// Add an item to the end of the pipeline
/// </summary>
/// <param name="item">Item to add</param>
public virtual void AddItemToEndOfPipeline(TDelegate item)
{
this.AddItemToEndOfPipeline((PipelineItem<TDelegate>)item);
}
/// <summary>
/// Add an item to the end of the pipeline
/// </summary>
/// <param name="item">Item to add</param>
/// <param name="replaceInPlace">
/// Whether to replace an existing item with the same name in its current place,
/// rather than at the position requested. Defaults to false.
/// </param>
public virtual void AddItemToEndOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false)
{
var existingIndex = this.RemoveByName(item.Name);
if (replaceInPlace && existingIndex != -1)
{
this.InsertItemAtPipelineIndex(existingIndex, item);
}
else
{
this.pipelineItems.Add(item);
}
}
/// <summary>
/// Add an item to a specific place in the pipeline.
/// </summary>
/// <param name="index">Index to add at</param>
/// <param name="item">Item to add</param>
public virtual void InsertItemAtPipelineIndex(int index, TDelegate item)
{
this.InsertItemAtPipelineIndex(index, (PipelineItem<TDelegate>)item);
}
/// <summary>
/// Add an item to a specific place in the pipeline.
/// </summary>
/// <param name="index">Index to add at</param>
/// <param name="item">Item to add</param>
/// <param name="replaceInPlace">
/// Whether to replace an existing item with the same name in its current place,
/// rather than at the position requested. Defaults to false.
/// </param>
public virtual void InsertItemAtPipelineIndex(int index, PipelineItem<TDelegate> item, bool replaceInPlace = false)
{
var existingIndex = this.RemoveByName(item.Name);
var newIndex = (replaceInPlace && existingIndex != -1) ? existingIndex : index;
this.pipelineItems.Insert(newIndex, item);
}
/// <summary>
/// Insert an item before a named item.
/// If the named item does not exist the item is inserted at the start of the pipeline.
/// </summary>
/// <param name="name">Name of the item to insert before</param>
/// <param name="item">Item to insert</param>
public virtual void InsertBefore(string name, TDelegate item)
{
this.InsertBefore(name, (PipelineItem<TDelegate>)item);
}
/// <summary>
/// Insert an item before a named item.
/// If the named item does not exist the item is inserted at the start of the pipeline.
/// </summary>
/// <param name="name">Name of the item to insert before</param>
/// <param name="item">Item to insert</param>
public virtual void InsertBefore(string name, PipelineItem<TDelegate> item)
{
var existingIndex =
this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.InvariantCulture));
if (existingIndex == -1)
{
existingIndex = 0;
}
this.InsertItemAtPipelineIndex(existingIndex, item);
}
/// <summary>
/// Insert an item after a named item.
/// If the named item does not exist the item is inserted at the end of the pipeline.
/// </summary>
/// <param name="name">Name of the item to insert after</param>
/// <param name="item">Item to insert</param>
public virtual void InsertAfter(string name, TDelegate item)
{
this.InsertAfter(name, (PipelineItem<TDelegate>)item);
}
/// <summary>
/// Insert an item after a named item.
/// If the named item does not exist the item is inserted at the end of the pipeline.
/// </summary>
/// <param name="name">Name of the item to insert after</param>
/// <param name="item">Item to insert</param>
public virtual void InsertAfter(string name, PipelineItem<TDelegate> item)
{
var existingIndex =
this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.InvariantCulture));
if (existingIndex == -1)
{
existingIndex = this.pipelineItems.Count;
}
existingIndex++;
if (existingIndex > this.pipelineItems.Count)
{
this.AddItemToEndOfPipeline(item);
}
else
{
this.InsertItemAtPipelineIndex(existingIndex, item);
}
}
/// <summary>
/// Remove a named pipeline item
/// </summary>
/// <param name="name">Name</param>
/// <returns>Index of item that was removed or -1 if nothing removed</returns>
public virtual int RemoveByName(string name)
{
var existingIndex =
this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.InvariantCulture));
if (existingIndex != -1)
{
this.pipelineItems.RemoveAt(existingIndex);
}
return existingIndex;
}
}
}
| |
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AmazonSqsTransport.Pipeline
{
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Amazon.SQS.Model;
using Contexts;
using GreenPipes;
using GreenPipes.Agents;
using GreenPipes.Internals.Extensions;
using Logging;
using Topology;
using Transports;
using Transports.Metrics;
public interface IBasicConsumer
{
Task HandleMessage(Message message);
}
/// <summary>
/// Receives messages from AmazonSQS, pushing them to the InboundPipe of the service endpoint.
/// </summary>
public sealed class AmazonSqsBasicConsumer :
Supervisor,
IBasicConsumer,
DeliveryMetrics
{
readonly IDeadLetterTransport _deadLetterTransport;
readonly TaskCompletionSource<bool> _deliveryComplete;
readonly IErrorTransport _errorTransport;
readonly Uri _inputAddress;
readonly ILog _log = Logger.Get<AmazonSqsBasicConsumer>();
readonly ModelContext _model;
readonly string _queueUrl;
readonly ConcurrentDictionary<string, AmazonSqsReceiveContext> _pending;
readonly IReceiveObserver _receiveObserver;
readonly IPipe<ReceiveContext> _receivePipe;
readonly ReceiveSettings _receiveSettings;
readonly AmazonSqsReceiveEndpointContext _context;
readonly IDeliveryTracker _tracker;
/// <summary>
/// The basic consumer receives messages pushed from the broker.
/// </summary>
/// <param name="model">The model context for the consumer</param>
/// <param name="queueUrl"></param>
/// <param name="inputAddress">The input address for messages received by the consumer</param>
/// <param name="receivePipe">The receive pipe to dispatch messages</param>
/// <param name="receiveObserver">The observer for receive events</param>
/// <param name="context">The topology</param>
/// <param name="deadLetterTransport"></param>
/// <param name="errorTransport"></param>
public AmazonSqsBasicConsumer(ModelContext model, string queueUrl, Uri inputAddress, IPipe<ReceiveContext> receivePipe,
IReceiveObserver receiveObserver, AmazonSqsReceiveEndpointContext context,
IDeadLetterTransport deadLetterTransport, IErrorTransport errorTransport)
{
_model = model;
_queueUrl = queueUrl;
_inputAddress = inputAddress;
_receivePipe = receivePipe;
_receiveObserver = receiveObserver;
_context = context;
_deadLetterTransport = deadLetterTransport;
_errorTransport = errorTransport;
_tracker = new DeliveryTracker(HandleDeliveryComplete);
_receiveSettings = model.GetPayload<ReceiveSettings>();
_pending = new ConcurrentDictionary<string, AmazonSqsReceiveContext>();
_deliveryComplete = new TaskCompletionSource<bool>();
SetReady();
}
public async Task HandleMessage(Message message)
{
if (IsStopping)
{
await WaitAndAbandonMessage(message).ConfigureAwait(false);
return;
}
using (var delivery = _tracker.BeginDelivery())
{
var redelivered = message.Attributes.ContainsKey("ApproximateReceiveCount") && (int.TryParse(message.Attributes["ApproximateReceiveCount"], out var approximateReceiveCount) && approximateReceiveCount > 1);
var context = new AmazonSqsReceiveContext(_inputAddress, message, redelivered, _receiveObserver, _context);
context.GetOrAddPayload(() => _errorTransport);
context.GetOrAddPayload(() => _deadLetterTransport);
context.GetOrAddPayload(() => _receiveSettings);
context.GetOrAddPayload(() => _model);
context.GetOrAddPayload(() => _model.ConnectionContext);
try
{
if (!_pending.TryAdd(message.MessageId, context))
if (_log.IsErrorEnabled)
_log.ErrorFormat("Duplicate BasicDeliver: {0}", message.MessageId);
await _receiveObserver.PreReceive(context).ConfigureAwait(false);
await _receivePipe.Send(context).ConfigureAwait(false);
await context.CompleteTask.ConfigureAwait(false);
// Acknowledge
await _model.DeleteMessage(_queueUrl, message.ReceiptHandle);
await _receiveObserver.PostReceive(context).ConfigureAwait(false);
}
catch (Exception ex)
{
await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
try
{
//_model.BasicNack(deliveryTag, false, true);
}
catch (Exception ackEx)
{
if (_log.IsErrorEnabled)
_log.ErrorFormat("An error occurred trying to NACK a message with delivery tag {0}: {1}", message.MessageId, ackEx.ToString());
}
}
finally
{
_pending.TryRemove(message.MessageId, out _);
context.Dispose();
}
}
}
long DeliveryMetrics.DeliveryCount => _tracker.DeliveryCount;
int DeliveryMetrics.ConcurrentDeliveryCount => _tracker.MaxConcurrentDeliveryCount;
void HandleDeliveryComplete()
{
if (IsStopping)
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Consumer shutdown completed: {0}", _context.InputAddress);
_deliveryComplete.TrySetResult(true);
}
}
async Task WaitAndAbandonMessage(Message message)
{
try
{
await _deliveryComplete.Task.ConfigureAwait(false);
}
catch (Exception exception)
{
if (_log.IsErrorEnabled)
_log.Debug("Shutting down, deliveryComplete Faulted: {_topology.InputAddress}", exception);
}
}
protected override async Task StopSupervisor(StopSupervisorContext context)
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Stopping consumer: {0}", _context.InputAddress);
SetCompleted(ActiveAndActualAgentsCompleted(context));
await Completed.ConfigureAwait(false);
}
async Task ActiveAndActualAgentsCompleted(StopSupervisorContext context)
{
await Task.WhenAll(context.Agents.Select(x => Completed)).UntilCompletedOrCanceled(context.CancellationToken).ConfigureAwait(false);
if (_tracker.ActiveDeliveryCount > 0)
{
try
{
await _deliveryComplete.Task.UntilCompletedOrCanceled(context.CancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
if (_log.IsWarnEnabled)
_log.WarnFormat("Stop canceled waiting for message consumers to complete: {0}", _context.InputAddress);
}
}
//try
//{
// _messageConsumer.Close();
// _messageConsumer.Dispose();
//}
//catch (OperationCanceledException)
//{
// if (_log.IsWarnEnabled)
// _log.WarnFormat("Exception canceling the consumer: {0}", _context.InputAddress);
//}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet is used to retrieve runspaces from the global cache
/// and write it to the pipeline. The runspaces are wrapped and
/// returned as PSSession objects.
///
/// The cmdlet can be used in the following ways:
///
/// List all the available runspaces
/// get-pssession
///
/// Get the PSSession from session name
/// get-pssession -Name sessionName
///
/// Get the PSSession for the specified ID
/// get-pssession -Id sessionId
///
/// Get the PSSession for the specified instance Guid
/// get-pssession -InstanceId sessionGuid
///
/// Get PSSessions from remote computer. Optionally filter on state, session instanceid or session name.
/// get-psession -ComputerName computerName -StateFilter Disconnected
///
/// Get PSSessions from virtual machine. Optionally filter on state, session instanceid or session name.
/// get-psession -VMName vmName -Name sessionName
///
/// Get PSSessions from container. Optionally filter on state, session instanceid or session name.
/// get-psession -ContainerId containerId -InstanceId instanceId
///
/// </summary>
[Cmdlet(VerbsCommon.Get, "PSSession", DefaultParameterSetName = PSRunspaceCmdlet.NameParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135219", RemotingCapability = RemotingCapability.OwnedByCommand)]
[OutputType(typeof(PSSession))]
public class GetPSSessionCommand : PSRunspaceCmdlet, IDisposable
{
#region Parameters
private const string ConnectionUriParameterSet = "ConnectionUri";
private const string ConnectionUriInstanceIdParameterSet = "ConnectionUriInstanceId";
/// <summary>
/// Computer names to connect to.
/// </summary>
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("Cn")]
public override String[] ComputerName { get; set; }
/// <summary>
/// This parameters specifies the appname which identifies the connection
/// end point on the remote machine. If this parameter is not specified
/// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats
/// not specified as well, then "WSMAN" will be used
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
public String ApplicationName
{
get { return _appName; }
set
{
_appName = ResolveAppName(value);
}
}
private String _appName;
/// <summary>
/// A complete URI(s) specified for the remote computer and shell to
/// connect to and create a runspace for.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("URI", "CU")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Uri[] ConnectionUri { get; set; }
/// <summary>
/// For WSMan sessions:
/// If this parameter is not specified then the value specified in
/// the environment variable DEFAULTREMOTESHELLNAME will be used. If
/// this is not set as well, then Microsoft.PowerShell is used.
///
/// For VM/Container sessions:
/// If this parameter is not specified then all sessions that match other filters are returned.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet)]
public String ConfigurationName { get; set; }
/// <summary>
/// The AllowRedirection parameter enables the implicit redirection functionality.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
public SwitchParameter AllowRedirection
{
get { return _allowRedirection; }
set { _allowRedirection = value; }
}
private bool _allowRedirection = false;
/// <summary>
/// Session names to filter on.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.NameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
[ValidateNotNullOrEmpty()]
public override string[] Name
{
get { return base.Name; }
set { base.Name = value; }
}
/// <summary>
/// Instance Ids to filter on.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.InstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet,
Mandatory = true)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public override Guid[] InstanceId
{
get { return base.InstanceId; }
set { base.InstanceId = value; }
}
/// <summary>
/// Specifies the credentials of the user to impersonate in the
/// remote machine. If this parameter is not specified then the
/// credentials of the current user process will be assumed.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[Credential()]
public PSCredential Credential
{
get { return _psCredential; }
set
{
_psCredential = value;
PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private PSCredential _psCredential;
/// <summary>
/// Use basic authentication to authenticate the user.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
public AuthenticationMechanism Authentication
{
get { return _authentication; }
set
{
_authentication = value;
PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private AuthenticationMechanism _authentication;
/// <summary>
/// Specifies the certificate thumbprint to be used to impersonate the user on the
/// remote machine.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
public string CertificateThumbprint
{
get { return _thumbprint; }
set
{
_thumbprint = value;
PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private string _thumbprint;
/// <summary>
/// Port specifies the alternate port to be used in case the
/// default ports are not used for the transport mechanism
/// (port 80 for http and port 443 for useSSL)
/// </summary>
/// <remarks>
/// Currently this is being accepted as a parameter. But in future
/// support will be added to make this a part of a policy setting.
/// When a policy setting is in place this parameter can be used
/// to override the policy setting
/// </remarks>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[ValidateRange((Int32)1, (Int32)UInt16.MaxValue)]
public Int32 Port { get; set; }
/// <summary>
/// This parameter suggests that the transport scheme to be used for
/// remote connections is useSSL instead of the default http.Since
/// there are only two possible transport schemes that are possible
/// at this point, a SwitchParameter is being used to switch between
/// the two.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL { get; set; }
/// <summary>
/// Allows the user of the cmdlet to specify a throttling value
/// for throttling the number of remote operations that can
/// be executed simultaneously.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
public Int32 ThrottleLimit { get; set; } = 0;
/// <summary>
/// Filters returned remote runspaces based on runspace state.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet)]
public SessionFilterState State { get; set; }
/// <summary>
/// Session options.
/// </summary>
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
public PSSessionOption SessionOption { get; set; }
#endregion
#region Overrides
/// <summary>
/// Resolves shellname
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
if (ConfigurationName == null)
{
ConfigurationName = string.Empty;
}
}
/// <summary>
/// Get the list of runspaces from the global cache and write them
/// down. If no computername or instance id is specified then
/// list all runspaces
/// </summary>
protected override void ProcessRecord()
{
if ((ParameterSetName == GetPSSessionCommand.NameParameterSet) && ((Name == null) || (Name.Length == 0)))
{
// that means Get-PSSession (with no parameters)..so retrieve all the runspaces.
GetAllRunspaces(true, true);
}
else if (ParameterSetName == GetPSSessionCommand.ComputerNameParameterSet ||
ParameterSetName == GetPSSessionCommand.ComputerInstanceIdParameterSet ||
ParameterSetName == GetPSSessionCommand.ConnectionUriParameterSet ||
ParameterSetName == GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)
{
// Perform the remote query for each provided computer name.
QueryForRemoteSessions();
}
else
{
GetMatchingRunspaces(true, true, this.State, this.ConfigurationName);
}
} // ProcessRecord
/// <summary>
/// End processing clean up.
/// </summary>
protected override void EndProcessing()
{
_stream.ObjectWriter.Close();
}
/// <summary>
/// User has signaled a stop for this cmdlet.
/// </summary>
protected override void StopProcessing()
{
_queryRunspaces.StopAllOperations();
}
#endregion Overrides
#region Private Methods
/// <summary>
/// Creates a connectionInfo object for each computer name and performs a remote
/// session query for each computer filtered by the filterState parameter.
/// </summary>
private void QueryForRemoteSessions()
{
// Get collection of connection objects for each computer name or
// connection uri.
Collection<WSManConnectionInfo> connectionInfos = GetConnectionObjects();
// Query for sessions.
Collection<PSSession> results = _queryRunspaces.GetDisconnectedSessions(connectionInfos, this.Host, _stream,
this.RunspaceRepository, ThrottleLimit,
State, InstanceId, Name, ConfigurationName);
// Write any error output from stream object.
Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead();
foreach (object streamObject in streamObjects)
{
if (this.IsStopping)
{
break;
}
WriteStreamObject((Action<Cmdlet>)streamObject);
}
// Write each session object.
foreach (PSSession session in results)
{
if (this.IsStopping)
{
break;
}
WriteObject(session);
}
}
private Collection<WSManConnectionInfo> GetConnectionObjects()
{
Collection<WSManConnectionInfo> connectionInfos = new Collection<WSManConnectionInfo>();
if (ParameterSetName == GetPSSessionCommand.ComputerNameParameterSet ||
ParameterSetName == GetPSSessionCommand.ComputerInstanceIdParameterSet)
{
string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme;
foreach (string computerName in ComputerName)
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.Scheme = scheme;
connectionInfo.ComputerName = ResolveComputerName(computerName);
connectionInfo.AppName = ApplicationName;
connectionInfo.ShellUri = ConfigurationName;
connectionInfo.Port = Port;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfos.Add(connectionInfo);
}
}
else if (ParameterSetName == GetPSSessionCommand.ConnectionUriParameterSet ||
ParameterSetName == GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)
{
foreach (var connectionUri in ConnectionUri)
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ConnectionUri = connectionUri;
connectionInfo.ShellUri = ConfigurationName;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfos.Add(connectionInfo);
}
}
return connectionInfos;
}
/// <summary>
/// Updates connection info with the data read from cmdlet's parameters.
/// </summary>
/// <param name="connectionInfo"></param>
private void UpdateConnectionInfo(WSManConnectionInfo connectionInfo)
{
if (ParameterSetName != GetPSSessionCommand.ConnectionUriParameterSet &&
ParameterSetName != GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)
{
// uri redirection is supported only with URI parameter set
connectionInfo.MaximumConnectionRedirectionCount = 0;
}
if (!_allowRedirection)
{
// uri redirection required explicit user consent
connectionInfo.MaximumConnectionRedirectionCount = 0;
}
// Update the connectionInfo object with passed in session options.
if (SessionOption != null)
{
connectionInfo.SetSessionOptions(SessionOption);
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose method of IDisposable.
/// </summary>
public void Dispose()
{
_stream.Dispose();
GC.SuppressFinalize(this);
}
#endregion
#region Private Members
// Object used for querying remote runspaces.
private QueryRunspaces _queryRunspaces = new QueryRunspaces();
// Object to collect output data from multiple threads.
private ObjectStream _stream = new ObjectStream();
#endregion
}
}
| |
// Support 4 different decompression libraries: DotNetZip, bzip2.net, SharpCompress, SharpZipLib
// Listed in order of decreasing performance, SharpZipLib is considerably slower than the others
//#define WITH_DOTNETZIP
//#define WITH_BZIP2NET
//#define WITH_SHARPCOMPRESS
//#define WITH_SHARPZIPLIB
//
// MpqHuffman.cs
//
// Authors:
// Foole (fooleau@gmail.com)
//
// (C) 2006 Foole (fooleau@gmail.com)
// Based on code from StormLib by Ladislav Zezula
//
// 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.IO.Compression;
namespace Foole.Mpq
{
/// <summary>
/// A Stream based class for reading a file from an MPQ file
/// </summary>
public class MpqStream : Stream
{
private Stream _stream;
private int _blockSize;
private MpqEntry _entry;
private uint[] _blockPositions;
private long _position;
private byte[] _currentData;
private int _currentBlockIndex = -1;
internal MpqStream(MpqArchive archive, MpqEntry entry)
{
_entry = entry;
_stream = archive.BaseStream;
_blockSize = archive.BlockSize;
if (_entry.IsCompressed && !_entry.IsSingleUnit)
LoadBlockPositions();
}
// Compressed files start with an array of offsets to make seeking possible
private void LoadBlockPositions()
{
int blockposcount = (int)((_entry.FileSize + _blockSize - 1) / _blockSize) + 1;
// Files with metadata have an extra block containing block checksums
if ((_entry.Flags & MpqFileFlags.FileHasMetadata) != 0)
blockposcount++;
_blockPositions = new uint[blockposcount];
lock(_stream)
{
_stream.Seek(_entry.FilePos, SeekOrigin.Begin);
BinaryReader br = new BinaryReader(_stream);
for(int i = 0; i < blockposcount; i++)
_blockPositions[i] = br.ReadUInt32();
}
uint blockpossize = (uint) blockposcount * 4;
/*
if(_blockPositions[0] != blockpossize)
_entry.Flags |= MpqFileFlags.Encrypted;
*/
if (_entry.IsEncrypted)
{
if (_entry.EncryptionSeed == 0) // This should only happen when the file name is not known
{
_entry.EncryptionSeed = MpqArchive.DetectFileSeed(_blockPositions[0], _blockPositions[1], blockpossize) + 1;
if (_entry.EncryptionSeed == 1)
throw new MpqParserException("Unable to determine encyption seed");
}
MpqArchive.DecryptBlock(_blockPositions, _entry.EncryptionSeed - 1);
if (_blockPositions[0] != blockpossize)
throw new MpqParserException("Decryption failed");
if (_blockPositions[1] > _blockSize + blockpossize)
throw new MpqParserException("Decryption failed");
}
}
private byte[] LoadBlock(int blockIndex, int expectedLength)
{
uint offset;
int toread;
uint encryptionseed;
if (_entry.IsCompressed)
{
offset = _blockPositions[blockIndex];
toread = (int)(_blockPositions[blockIndex + 1] - offset);
}
else
{
offset = (uint)(blockIndex * _blockSize);
toread = expectedLength;
}
offset += _entry.FilePos;
byte[] data = new byte[toread];
lock (_stream)
{
_stream.Seek(offset, SeekOrigin.Begin);
int read = _stream.Read(data, 0, toread);
if (read != toread)
throw new MpqParserException("Insufficient data or invalid data length");
}
if (_entry.IsEncrypted && _entry.FileSize > 3)
{
if (_entry.EncryptionSeed == 0)
throw new MpqParserException("Unable to determine encryption key");
encryptionseed = (uint)(blockIndex + _entry.EncryptionSeed);
MpqArchive.DecryptBlock(data, encryptionseed);
}
if (_entry.IsCompressed && (toread != expectedLength))
{
if ((_entry.Flags & MpqFileFlags.CompressedMulti) != 0)
data = DecompressMulti(data, expectedLength);
else
data = PKDecompress(new MemoryStream(data), expectedLength);
}
return data;
}
#region Stream overrides
public override bool CanRead
{ get { return true; } }
public override bool CanSeek
{ get { return true; } }
public override bool CanWrite
{ get { return false; } }
public override long Length
{ get { return _entry.FileSize; } }
public override long Position
{
get
{
return _position;
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
public override void Flush()
{
// NOP
}
public override long Seek(long offset, SeekOrigin origin)
{
long target;
switch (origin)
{
case SeekOrigin.Begin:
target = offset;
break;
case SeekOrigin.Current:
target = Position + offset;
break;
case SeekOrigin.End:
target = Length + offset;
break;
default:
throw new ArgumentException("Origin", "Invalid SeekOrigin");
}
if (target < 0)
throw new ArgumentOutOfRangeException("Attmpted to Seek before the beginning of the stream");
if (target >= Length)
throw new ArgumentOutOfRangeException("Attmpted to Seek beyond the end of the stream");
_position = target;
return _position;
}
public override void SetLength(long value)
{
throw new NotSupportedException("SetLength is not supported");
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_entry.IsSingleUnit)
return ReadInternalSingleUnit(buffer, offset, count);
int toread = count;
int readtotal = 0;
while (toread > 0)
{
int read = ReadInternal(buffer, offset, toread);
if (read == 0) break;
readtotal += read;
offset += read;
toread -= read;
}
return readtotal;
}
// SingleUnit entries can be compressed but are never encrypted
private int ReadInternalSingleUnit(byte[] buffer, int offset, int count)
{
if (_position >= Length)
return 0;
if (_currentData == null)
LoadSingleUnit();
int bytestocopy = Math.Min((int)(_currentData.Length - _position), count);
Array.Copy(_currentData, _position, buffer, offset, bytestocopy);
_position += bytestocopy;
return bytestocopy;
}
private void LoadSingleUnit()
{
// Read the entire file into memory
byte[] filedata = new byte[_entry.CompressedSize];
lock (_stream)
{
_stream.Seek(_entry.FilePos, SeekOrigin.Begin);
int read = _stream.Read(filedata, 0, filedata.Length);
if (read != filedata.Length)
throw new MpqParserException("Insufficient data or invalid data length");
}
if (_entry.CompressedSize == _entry.FileSize)
_currentData = filedata;
else
_currentData = DecompressMulti(filedata, (int)_entry.FileSize);
}
private int ReadInternal(byte[] buffer, int offset, int count)
{
// OW: avoid reading past the contents of the file
if (_position >= Length)
return 0;
BufferData();
int localposition = (int)(_position % _blockSize);
int bytestocopy = Math.Min(_currentData.Length - localposition, count);
if (bytestocopy <= 0) return 0;
Array.Copy(_currentData, localposition, buffer, offset, bytestocopy);
_position += bytestocopy;
return bytestocopy;
}
public override int ReadByte()
{
if (_position >= Length) return -1;
if (_entry.IsSingleUnit)
return ReadByteSingleUnit();
BufferData();
int localposition = (int)(_position % _blockSize);
_position++;
return _currentData[localposition];
}
private int ReadByteSingleUnit()
{
if (_currentData == null)
LoadSingleUnit();
return _currentData[_position++];
}
private void BufferData()
{
int requiredblock = (int)(_position / _blockSize);
if (requiredblock != _currentBlockIndex)
{
int expectedlength = (int)Math.Min(Length - (requiredblock * _blockSize), _blockSize);
_currentData = LoadBlock(requiredblock, expectedlength);
_currentBlockIndex = requiredblock;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("Writing is not supported");
}
#endregion Strem overrides
/* Compression types in order:
* 10 = BZip2
* 8 = PKLib
* 2 = ZLib
* 1 = Huffman
* 80 = IMA ADPCM Stereo
* 40 = IMA ADPCM Mono
*/
private static byte[] DecompressMulti(byte[] input, int outputLength)
{
Stream sinput = new MemoryStream(input);
byte comptype = (byte)sinput.ReadByte();
// WC3 onward mosly use Zlib
// Starcraft 1 mostly uses PKLib, plus types 41 and 81 for audio files
switch (comptype)
{
case 1: // Huffman
return MpqHuffman.Decompress(sinput).ToArray();
case 2: // ZLib/Deflate
return ZlibDecompress(sinput, outputLength);
case 8: // PKLib/Impode
return PKDecompress(sinput, outputLength);
case 0x10: // BZip2
return BZip2Decompress(sinput, outputLength);
case 0x80: // IMA ADPCM Stereo
return MpqWavCompression.Decompress(sinput, 2);
case 0x40: // IMA ADPCM Mono
return MpqWavCompression.Decompress(sinput, 1);
case 0x12:
// TODO: LZMA
throw new MpqParserException("LZMA compression is not yet supported");
// Combos
case 0x22:
// TODO: sparse then zlib
throw new MpqParserException("Sparse compression + Deflate compression is not yet supported");
case 0x30:
// TODO: sparse then bzip2
throw new MpqParserException("Sparse compression + BZip2 compression is not yet supported");
case 0x41:
sinput = MpqHuffman.Decompress(sinput);
return MpqWavCompression.Decompress(sinput, 1);
case 0x48:
{
byte[] result = PKDecompress(sinput, outputLength);
return MpqWavCompression.Decompress(new MemoryStream(result), 1);
}
case 0x81:
sinput = MpqHuffman.Decompress(sinput);
return MpqWavCompression.Decompress(sinput, 2);
case 0x88:
{
byte[] result = PKDecompress(sinput, outputLength);
return MpqWavCompression.Decompress(new MemoryStream(result), 2);
}
default:
throw new MpqParserException("Compression is not yet supported: 0x" + comptype.ToString("X"));
}
}
private static byte[] BZip2Decompress(Stream data, int expectedLength)
{
using (MemoryStream output = new MemoryStream(expectedLength))
{
using (var stream = new Ionic.BZip2.BZip2InputStream(data))
{
stream.CopyTo(output);
}
return output.ToArray();
}
}
private static byte[] ZlibDecompress(Stream data, int expectedLength)
{
using (MemoryStream output = new MemoryStream(expectedLength))
{
using (var stream = new Ionic.Zlib.ZlibStream(data, Ionic.Zlib.CompressionMode.Decompress))
{
stream.CopyTo(output);
}
return output.ToArray();
}
}
private static byte[] PKDecompress(Stream data, int expectedLength)
{
PKLibDecompress pk = new PKLibDecompress(data);
return pk.Explode(expectedLength);
}
}
}
| |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace CocosSharp
{
[DebuggerDisplay("{DebugDisplayString,nq}")]
public struct CCAffineTransform
{
public static readonly CCAffineTransform Identity = new CCAffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Matrix xnaMatrix;
#region Properties
internal Matrix XnaMatrix { get { return xnaMatrix; } }
public float A
{
get { return xnaMatrix.M11; }
set { xnaMatrix.M11 = value; }
}
public float B
{
get { return xnaMatrix.M12; }
set { xnaMatrix.M12 = value; }
}
public float C
{
get { return xnaMatrix.M21; }
set { xnaMatrix.M21 = value; }
}
public float D
{
get { return xnaMatrix.M22; }
set { xnaMatrix.M22 = value; }
}
public float Tx
{
get { return xnaMatrix.M41; }
set { xnaMatrix.M41 = value; }
}
public float Ty
{
get { return xnaMatrix.M42; }
set { xnaMatrix.M42 = value; }
}
public float Tz
{
get { return xnaMatrix.M43; }
set { xnaMatrix.M43 = value; }
}
public float Scale
{
set { ScaleX = value; ScaleY = value; }
}
public float ScaleX
{
get
{
float a2 = (float)Math.Pow (A, 2);
float b2 = (float)Math.Pow (B, 2);
return (float)Math.Sqrt (a2 + b2);
}
set
{
float rotX = RotationY;
A = value * (float)Math.Cos(rotX);
B = value * (float)Math.Sin(rotX);
}
}
public float ScaleY
{
get
{
float d2 = (float)Math.Pow(D, 2);
float c2 = (float)Math.Pow(C, 2);
return (float)Math.Sqrt(d2 + c2);
}
set
{
double rotY = RotationY;
C = -value * (float)Math.Sin(rotY);
D = value * (float)Math.Cos(rotY);
}
}
public float Rotation
{
set
{
float rotX = RotationX;
float rotY = RotationY;
float scaleX = ScaleX;
float scaleY = ScaleY;
A = scaleX * (float)Math.Cos(value);
B = scaleX * (float)Math.Sin(value);
C = -scaleY * (float)Math.Sin(rotY - rotX + value);
D = scaleY * (float)Math.Cos(rotY - rotX + value);
}
}
public float RotationX
{
get { return (float)Math.Atan2(B, A); }
}
public float RotationY
{
get { return (float)Math.Atan2(-C, D); }
}
public CCAffineTransform Inverse
{
get { return new CCAffineTransform(Matrix.Invert(XnaMatrix)); }
}
#endregion Properties
#region Constructors
public CCAffineTransform(float a, float b, float c, float d, float tx, float ty, float tz = 0.0f)
{
xnaMatrix = Matrix.Identity;
this.A = a;
this.B = b;
this.C = c;
this.D = d;
this.Tx = tx;
this.Ty = ty;
this.Tz = tz;
}
internal CCAffineTransform(Matrix xnaMatrixIn) : this()
{
xnaMatrix = xnaMatrixIn;
}
#endregion Constructors
public void Lerp(CCAffineTransform m1, CCAffineTransform m2, float t)
{
Matrix.Lerp(ref m1.xnaMatrix, ref m2.xnaMatrix, t, out xnaMatrix);
}
public void Concat(ref CCAffineTransform m)
{
CCAffineTransform.Concat(ref this, ref m, out this);
}
#region Transforming types
public void Transform(ref float x, ref float y, ref float z)
{
Vector3 vector = new Vector3(x, y, z);
Vector3.Transform(ref vector, ref xnaMatrix, out vector);
x = vector.X;
y = vector.Y;
z = vector.Z;
}
public void Transform(ref float x, ref float y)
{
float z = 0.0f;
Transform(ref x, ref y, ref z);
}
public void Transform(ref int x, ref int y)
{
var tmpX = A * x + C * y + Tx;
y = (int)(B * x + D * y + Ty);
x = (int)tmpX;
}
public CCPoint Transform(CCPoint point)
{
Transform(ref point);
return point;
}
public void Transform(ref CCPoint point)
{
Transform(ref point.X, ref point.Y);
}
public CCPoint3 Transform(CCPoint3 point)
{
Transform(ref point.X, ref point.Y, ref point.Z);
return point;
}
public void Transform(ref CCPoint3 point)
{
Transform(ref point.X, ref point.Y, ref point.Z);
}
public CCRect Transform(CCRect rect)
{
Transform(ref rect);
return rect;
}
public void Transform(ref CCRect rect)
{
float top = rect.MinY;
float left = rect.MinX;
float right = rect.MaxX;
float bottom = rect.MaxY;
CCPoint topLeft = new CCPoint(left, top);
CCPoint topRight = new CCPoint(right, top);
CCPoint bottomLeft = new CCPoint(left, bottom);
CCPoint bottomRight = new CCPoint(right, bottom);
Transform(ref topLeft);
Transform(ref topRight);
Transform(ref bottomLeft);
Transform(ref bottomRight);
float minX = Math.Min(Math.Min(topLeft.X, topRight.X), Math.Min(bottomLeft.X, bottomRight.X));
float maxX = Math.Max(Math.Max(topLeft.X, topRight.X), Math.Max(bottomLeft.X, bottomRight.X));
float minY = Math.Min(Math.Min(topLeft.Y, topRight.Y), Math.Min(bottomLeft.Y, bottomRight.Y));
float maxY = Math.Max(Math.Max(topLeft.Y, topRight.Y), Math.Max(bottomLeft.Y, bottomRight.Y));
rect.Origin.X = minX;
rect.Origin.Y = minY;
rect.Size.Width = maxX - minX;
rect.Size.Height = maxY - minY;
}
public void Transform(ref CCV3F_C4B_T2F quadPoint)
{
var x = quadPoint.Vertices.X;
var y = quadPoint.Vertices.Y;
var z = quadPoint.Vertices.Z;
Transform(ref x, ref y, ref z);
quadPoint.Vertices.X = x;
quadPoint.Vertices.Y = y;
quadPoint.Vertices.Z = z;
}
public void Transform(ref CCV3F_C4B quadPoint)
{
var x = quadPoint.Vertices.X;
var y = quadPoint.Vertices.Y;
var z = quadPoint.Vertices.Z;
Transform(ref x, ref y, ref z);
quadPoint.Vertices.X = x;
quadPoint.Vertices.Y = y;
quadPoint.Vertices.Z = z;
}
public void Transform(ref CCV3F_C4B_T2F_Quad quad)
{
Transform(ref quad.TopLeft);
Transform(ref quad.TopRight);
Transform(ref quad.BottomLeft);
Transform(ref quad.BottomRight);
}
public CCV3F_C4B_T2F_Quad Transform(CCV3F_C4B_T2F_Quad quad)
{
Transform(ref quad);
return quad;
}
#endregion Transforming types
internal string DebugDisplayString
{
get
{
if (this == Identity)
{
return "Identity";
}
return string.Concat(
"( ", xnaMatrix.M11.ToString(), " ", xnaMatrix.M12.ToString(), " ", xnaMatrix.M13.ToString(), " ", xnaMatrix.M14.ToString(), " ) \r\n",
"( ", xnaMatrix.M21.ToString(), " ", xnaMatrix.M22.ToString(), " ", xnaMatrix.M23.ToString(), " ", xnaMatrix.M24.ToString(), " ) \r\n",
"( ", xnaMatrix.M31.ToString(), " ", xnaMatrix.M32.ToString(), " ", xnaMatrix.M33.ToString(), " ", xnaMatrix.M34.ToString(), " ) \r\n",
"( ", xnaMatrix.M41.ToString(), " ", xnaMatrix.M42.ToString(), " ", xnaMatrix.M43.ToString(), " ", xnaMatrix.M44.ToString(), " )");
}
}
public override string ToString()
{
return xnaMatrix.ToString();
}
#region Equality
public override bool Equals(object obj)
{
bool flag = false;
if (obj is CCAffineTransform)
{
flag = this.Equals((CCAffineTransform) obj);
}
return flag;
}
public bool Equals(ref CCAffineTransform t)
{
return xnaMatrix == t.xnaMatrix;
}
public override int GetHashCode()
{
return xnaMatrix.GetHashCode();
}
#endregion Equality
#region Static methods
public static CCPoint Transform(CCPoint point, ref CCAffineTransform t)
{
Vector3 vec = point.XnaVector;
Vector3.Transform(ref vec, ref t.xnaMatrix, out vec);
return new CCPoint(vec.X, vec.Y);
}
public static CCPoint3 Transform(CCPoint3 point, ref CCAffineTransform t)
{
Vector3 vec = point.XnaVector;
Vector3.Transform(ref vec, ref t.xnaMatrix, out vec);
return new CCPoint3(vec);
}
public static CCSize Transform(CCSize size, ref CCAffineTransform t)
{
Vector3 vec = new Vector3(size.Width, size.Height, 0.0f);
Vector3.Transform(ref vec, ref t.xnaMatrix, out vec);
return new CCSize(vec.X, vec.Y);
}
public static CCAffineTransform Translate(CCAffineTransform t, float tx, float ty, float tz = 0.0f)
{
Matrix translate = Matrix.CreateTranslation(tx, ty, tz);
return new CCAffineTransform(Matrix.Multiply(translate, t.xnaMatrix));
}
public static CCAffineTransform Rotate(CCAffineTransform t, float anAngle)
{
var fSin = (float) Math.Sin(anAngle);
var fCos = (float) Math.Cos(anAngle);
return new CCAffineTransform(t.A * fCos + t.C * fSin,
t.B * fCos + t.D * fSin,
t.C * fCos - t.A * fSin,
t.D * fCos - t.B * fSin,
t.Tx,
t.Ty);
}
public static CCAffineTransform ScaleCopy(CCAffineTransform t, float sx, float sy, float sz = 1.0f)
{
Matrix scale = Matrix.CreateScale(sx, sy, sz);
return new CCAffineTransform(Matrix.Multiply(t.xnaMatrix, scale));
}
public static void Concat(ref CCAffineTransform t1, ref CCAffineTransform t2, out CCAffineTransform tOut)
{
Matrix concatMatrix;
Matrix.Multiply(ref t1.xnaMatrix, ref t2.xnaMatrix, out concatMatrix);
tOut = new CCAffineTransform(concatMatrix);
}
public static CCAffineTransform Concat(ref CCAffineTransform t1, ref CCAffineTransform t2)
{
CCAffineTransform tOut;
Concat(ref t1, ref t2, out tOut);
return tOut;
}
public static bool Equal(CCAffineTransform t1, CCAffineTransform t2)
{
return t1.xnaMatrix == t2.xnaMatrix;
}
public static CCAffineTransform Invert(CCAffineTransform t)
{
return new CCAffineTransform(Matrix.Invert(t.xnaMatrix));
}
public static void LerpCopy(ref CCAffineTransform m1, ref CCAffineTransform m2, float t, out CCAffineTransform res)
{
res = new CCAffineTransform(Matrix.Lerp(m1.xnaMatrix, m2.xnaMatrix, t));
}
public static CCRect Transform(CCRect rect, CCAffineTransform anAffineTransform)
{
return anAffineTransform.Transform(rect);
}
#endregion Static methods
#region Operators
public static CCAffineTransform operator +(CCAffineTransform affineTransform1, CCAffineTransform affineTransform2)
{
return new CCAffineTransform(affineTransform1.xnaMatrix + affineTransform2.xnaMatrix);
}
public static CCAffineTransform operator /(CCAffineTransform affineTransform1, CCAffineTransform affineTransform2)
{
return new CCAffineTransform(affineTransform1.xnaMatrix/affineTransform2.xnaMatrix);
}
public static CCAffineTransform operator /(CCAffineTransform affineTransform, float divider)
{
return new CCAffineTransform(affineTransform.xnaMatrix/divider);
}
public static bool operator ==(CCAffineTransform affineTransform1, CCAffineTransform affineTransform2)
{
return affineTransform1.xnaMatrix == affineTransform2.xnaMatrix;
}
public static bool operator !=(CCAffineTransform affineTransform1, CCAffineTransform affineTransform2)
{
return affineTransform1.xnaMatrix != affineTransform2.xnaMatrix;
}
public static CCAffineTransform operator -(CCAffineTransform affineTransform1, CCAffineTransform affineTransform2)
{
return new CCAffineTransform(affineTransform1.xnaMatrix - affineTransform2.xnaMatrix);
}
public static CCAffineTransform operator *(CCAffineTransform affinematrix1, CCAffineTransform affinematrix2)
{
return new CCAffineTransform(affinematrix1.xnaMatrix * affinematrix2.xnaMatrix);
}
public static CCAffineTransform operator -(CCAffineTransform affineTransform1)
{
Matrix transformedMat = -(affineTransform1.xnaMatrix);
return new CCAffineTransform(transformedMat);
}
#endregion Operators
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
/// <summary>
/// Binary builder implementation.
/// </summary>
internal class BinaryObjectBuilder : IBinaryObjectBuilder
{
/** Cached dictionary with no values. */
private static readonly IDictionary<int, BinaryBuilderField> EmptyVals =
new Dictionary<int, BinaryBuilderField>();
/** Binary. */
private readonly Binary _binary;
/** */
private readonly BinaryObjectBuilder _parent;
/** Initial binary object. */
private readonly BinaryObject _obj;
/** Type descriptor. */
private readonly IBinaryTypeDescriptor _desc;
/** Values. */
private SortedDictionary<string, BinaryBuilderField> _vals;
/** Contextual fields. */
private IDictionary<int, BinaryBuilderField> _cache;
/** Current context. */
private Context _ctx;
/** Write array action. */
private static readonly Action<BinaryWriter, object> WriteArrayAction =
(w, o) => w.WriteArrayInternal((Array) o);
/** Write collection action. */
private static readonly Action<BinaryWriter, object> WriteCollectionAction =
(w, o) => w.WriteCollection((ICollection) o);
/** Write timestamp action. */
private static readonly Action<BinaryWriter, object> WriteTimestampAction =
(w, o) => w.WriteTimestamp((DateTime?) o);
/** Write timestamp array action. */
private static readonly Action<BinaryWriter, object> WriteTimestampArrayAction =
(w, o) => w.WriteTimestampArray((DateTime?[])o);
/// <summary>
/// Constructor.
/// </summary>
/// <param name="binary">Binary.</param>
/// <param name="parent">Parent builder.</param>
/// <param name="obj">Initial binary object.</param>
/// <param name="desc">Type descriptor.</param>
public BinaryObjectBuilder(Binary binary, BinaryObjectBuilder parent,
BinaryObject obj, IBinaryTypeDescriptor desc)
{
Debug.Assert(binary != null);
Debug.Assert(desc != null);
_binary = binary;
_parent = parent ?? this;
_desc = desc;
_obj = obj ?? BinaryFromDescriptor(desc);
}
/** <inheritDoc /> */
public T GetField<T>(string name)
{
BinaryBuilderField field;
if (_vals != null && _vals.TryGetValue(name, out field))
return field != BinaryBuilderField.RmvMarker ? (T) field.Value : default(T);
int pos;
if (!_obj.TryGetFieldPosition(name, out pos))
return default(T);
T val;
if (TryGetCachedField(pos, out val))
return val;
val = _obj.GetField<T>(pos, this);
var fld = CacheField(pos, val);
SetField0(name, fld);
return val;
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetField<T>(string fieldName, T val)
{
return SetField0(fieldName,
new BinaryBuilderField(typeof (T), val, BinaryTypeId.GetTypeId(typeof (T))));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName,
new BinaryBuilderField(typeof (T[]), val, BinaryTypeId.Array, WriteArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanField(string fieldName, bool val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool), val, BinaryTypeId.Bool,
(w, o) => w.WriteBooleanField((bool) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanArrayField(string fieldName, bool[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool[]), val, BinaryTypeId.ArrayBool,
(w, o) => w.WriteBooleanArray((bool[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteField(string fieldName, byte val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte), val, BinaryTypeId.Byte,
(w, o) => w.WriteByteField((byte) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteArrayField(string fieldName, byte[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte[]), val, BinaryTypeId.ArrayByte,
(w, o) => w.WriteByteArray((byte[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharField(string fieldName, char val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char), val, BinaryTypeId.Char,
(w, o) => w.WriteCharField((char) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharArrayField(string fieldName, char[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char[]), val, BinaryTypeId.ArrayChar,
(w, o) => w.WriteCharArray((char[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCollectionField(string fieldName, ICollection val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (ICollection), val, BinaryTypeId.Collection,
WriteCollectionAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalField(string fieldName, decimal? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?), val, BinaryTypeId.Decimal,
(w, o) => w.WriteDecimal((decimal?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalArrayField(string fieldName, decimal?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?[]), val, BinaryTypeId.ArrayDecimal,
(w, o) => w.WriteDecimalArray((decimal?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDictionaryField(string fieldName, IDictionary val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (IDictionary), val, BinaryTypeId.Dictionary,
(w, o) => w.WriteDictionary((IDictionary) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleField(string fieldName, double val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double), val, BinaryTypeId.Double,
(w, o) => w.WriteDoubleField((double) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleArrayField(string fieldName, double[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double[]), val, BinaryTypeId.ArrayDouble,
(w, o) => w.WriteDoubleArray((double[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumField<T>(string fieldName, T val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T), val, BinaryTypeId.Enum,
(w, o) => w.WriteEnum((T) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T[]), val, BinaryTypeId.ArrayEnum,
(w, o) => w.WriteEnumArray((T[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatField(string fieldName, float val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float), val, BinaryTypeId.Float,
(w, o) => w.WriteFloatField((float) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatArrayField(string fieldName, float[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float[]), val, BinaryTypeId.ArrayFloat,
(w, o) => w.WriteFloatArray((float[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidField(string fieldName, Guid? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?), val, BinaryTypeId.Guid,
(w, o) => w.WriteGuid((Guid?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidArrayField(string fieldName, Guid?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?[]), val, BinaryTypeId.ArrayGuid,
(w, o) => w.WriteGuidArray((Guid?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntField(string fieldName, int val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int), val, BinaryTypeId.Int,
(w, o) => w.WriteIntField((int) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntArrayField(string fieldName, int[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int[]), val, BinaryTypeId.ArrayInt,
(w, o) => w.WriteIntArray((int[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongField(string fieldName, long val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long), val, BinaryTypeId.Long,
(w, o) => w.WriteLongField((long) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongArrayField(string fieldName, long[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long[]), val, BinaryTypeId.ArrayLong,
(w, o) => w.WriteLongArray((long[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortField(string fieldName, short val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short), val, BinaryTypeId.Short,
(w, o) => w.WriteShortField((short) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortArrayField(string fieldName, short[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short[]), val, BinaryTypeId.ArrayShort,
(w, o) => w.WriteShortArray((short[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringField(string fieldName, string val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string), val, BinaryTypeId.String,
(w, o) => w.WriteString((string) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringArrayField(string fieldName, string[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string[]), val, BinaryTypeId.ArrayString,
(w, o) => w.WriteStringArray((string[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampField(string fieldName, DateTime? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?), val, BinaryTypeId.Timestamp,
WriteTimestampAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampArrayField(string fieldName, DateTime?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?[]), val, BinaryTypeId.ArrayTimestamp,
WriteTimestampArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder RemoveField(string name)
{
return SetField0(name, BinaryBuilderField.RmvMarker);
}
/** <inheritDoc /> */
public IBinaryObject Build()
{
// Assume that resulting length will be no less than header + [fields_cnt] * 12;
int estimatedCapacity = BinaryObjectHeader.Size + (_vals == null ? 0 : _vals.Count*12);
using (var outStream = new BinaryHeapStream(estimatedCapacity))
{
BinaryWriter writer = _binary.Marshaller.StartMarshal(outStream);
writer.SetBuilder(this);
// All related builders will work in this context with this writer.
_parent._ctx = new Context(writer);
try
{
// Write.
writer.Write(this);
// Process metadata.
_binary.Marshaller.FinishMarshal(writer);
// Create binary object once metadata is processed.
return new BinaryObject(_binary.Marshaller, outStream.InternalArray, 0,
BinaryObjectHeader.Read(outStream, 0));
}
finally
{
// Cleanup.
_parent._ctx.Closed = true;
}
}
}
/// <summary>
/// Create child builder.
/// </summary>
/// <param name="obj">binary object.</param>
/// <returns>Child builder.</returns>
public BinaryObjectBuilder Child(BinaryObject obj)
{
var desc = _binary.Marshaller.GetDescriptor(true, obj.TypeId);
return new BinaryObjectBuilder(_binary, null, obj, desc);
}
/// <summary>
/// Get cache field.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
/// <returns><c>true</c> if value is found in cache.</returns>
public bool TryGetCachedField<T>(int pos, out T val)
{
if (_parent._cache != null)
{
BinaryBuilderField res;
if (_parent._cache.TryGetValue(pos, out res))
{
val = res != null ? (T) res.Value : default(T);
return true;
}
}
val = default(T);
return false;
}
/// <summary>
/// Add field to cache test.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
public BinaryBuilderField CacheField<T>(int pos, T val)
{
if (_parent._cache == null)
_parent._cache = new Dictionary<int, BinaryBuilderField>(2);
var hdr = _obj.Data[pos];
var field = new BinaryBuilderField(typeof(T), val, hdr, GetWriteAction(hdr, pos));
_parent._cache[pos] = field;
return field;
}
/// <summary>
/// Gets the write action by header.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="pos">Position.</param>
/// <returns>Write action.</returns>
private Action<BinaryWriter, object> GetWriteAction(byte header, int pos)
{
// We need special actions for all cases where SetField(X) produces different result from SetSpecialField(X)
// Arrays, Collections, Dates
switch (header)
{
case BinaryTypeId.Array:
return WriteArrayAction;
case BinaryTypeId.Collection:
return WriteCollectionAction;
case BinaryTypeId.Timestamp:
return WriteTimestampAction;
case BinaryTypeId.ArrayTimestamp:
return WriteTimestampArrayAction;
case BinaryTypeId.ArrayEnum:
using (var stream = new BinaryHeapStream(_obj.Data))
{
stream.Seek(pos, SeekOrigin.Begin + 1);
var elementTypeId = stream.ReadInt();
return (w, o) => w.WriteEnumArrayInternal((Array) o, elementTypeId);
}
default:
return null;
}
}
/// <summary>
/// Internal set field routine.
/// </summary>
/// <param name="fieldName">Name.</param>
/// <param name="val">Value.</param>
/// <returns>This builder.</returns>
private IBinaryObjectBuilder SetField0(string fieldName, BinaryBuilderField val)
{
if (_vals == null)
_vals = new SortedDictionary<string, BinaryBuilderField>();
_vals[fieldName] = val;
return this;
}
/// <summary>
/// Mutate binary object.
/// </summary>
/// <param name="inStream">Input stream with initial object.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="desc">Type descriptor.</param>
/// <param name="vals">Values.</param>
private void Mutate(
BinaryHeapStream inStream,
BinaryHeapStream outStream,
IBinaryTypeDescriptor desc,
IDictionary<string, BinaryBuilderField> vals)
{
// Set correct builder to writer frame.
BinaryObjectBuilder oldBuilder = _parent._ctx.Writer.SetBuilder(_parent);
int streamPos = inStream.Position;
try
{
// Prepare fields.
IBinaryTypeHandler metaHnd = _binary.Marshaller.GetBinaryTypeHandler(desc);
IDictionary<int, BinaryBuilderField> vals0;
if (vals == null || vals.Count == 0)
vals0 = EmptyVals;
else
{
vals0 = new Dictionary<int, BinaryBuilderField>(vals.Count);
foreach (KeyValuePair<string, BinaryBuilderField> valEntry in vals)
{
int fieldId = BinaryUtils.FieldId(desc.TypeId, valEntry.Key, desc.NameMapper, desc.IdMapper);
if (vals0.ContainsKey(fieldId))
throw new IgniteException("Collision in field ID detected (change field name or " +
"define custom ID mapper) [fieldName=" + valEntry.Key + ", fieldId=" + fieldId + ']');
vals0[fieldId] = valEntry.Value;
// Write metadata if: 1) it is enabled for type; 2) type is not null (i.e. it is neither
// remove marker, nor a field read through "GetField" method.
if (metaHnd != null && valEntry.Value.Type != null)
metaHnd.OnFieldWrite(fieldId, valEntry.Key, valEntry.Value.TypeId);
}
}
// Actual processing.
Mutate0(_parent._ctx, inStream, outStream, true, vals0);
// 3. Handle metadata.
if (metaHnd != null)
{
IDictionary<string, BinaryField> meta = metaHnd.OnObjectWriteFinished();
if (meta != null)
_parent._ctx.Writer.SaveMetadata(desc, meta);
}
}
finally
{
// Restore builder frame.
_parent._ctx.Writer.SetBuilder(oldBuilder);
inStream.Seek(streamPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Internal mutation routine.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <param name="changeHash">WHether hash should be changed.</param>
/// <param name="vals">Values to be replaced.</param>
/// <returns>Mutated object.</returns>
private void Mutate0(Context ctx, BinaryHeapStream inStream, IBinaryStream outStream,
bool changeHash, IDictionary<int, BinaryBuilderField> vals)
{
int inStartPos = inStream.Position;
int outStartPos = outStream.Position;
byte inHdr = inStream.ReadByte();
if (inHdr == BinaryUtils.HdrNull)
outStream.WriteByte(BinaryUtils.HdrNull);
else if (inHdr == BinaryUtils.HdrHnd)
{
int inHnd = inStream.ReadInt();
int oldPos = inStartPos - inHnd;
int newPos;
if (ctx.OldToNew(oldPos, out newPos))
{
// Handle is still valid.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - newPos);
}
else
{
// Handle is invalid, write full object.
int inRetPos = inStream.Position;
inStream.Seek(oldPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
inStream.Seek(inRetPos, SeekOrigin.Begin);
}
}
else if (inHdr == BinaryUtils.HdrFull)
{
var inHeader = BinaryObjectHeader.Read(inStream, inStartPos);
BinaryUtils.ValidateProtocolVersion(inHeader.Version);
int hndPos;
if (ctx.AddOldToNew(inStartPos, outStartPos, out hndPos))
{
// Object could be cached in parent builder.
BinaryBuilderField cachedVal;
if (_parent._cache != null && _parent._cache.TryGetValue(inStartPos, out cachedVal))
{
WriteField(ctx, cachedVal);
}
else
{
// New object, write in full form.
var inSchema = BinaryObjectSchemaSerializer.ReadSchema(inStream, inStartPos, inHeader,
_desc.Schema, _binary.Marshaller.Ignite);
var outSchema = BinaryObjectSchemaHolder.Current;
var schemaIdx = outSchema.PushSchema();
try
{
// Skip header as it is not known at this point.
outStream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
if (inSchema != null)
{
foreach (var inField in inSchema)
{
BinaryBuilderField fieldVal;
var fieldFound = vals.TryGetValue(inField.Id, out fieldVal);
if (fieldFound && fieldVal == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(inField.Id, outStream.Position - outStartPos);
if (!fieldFound)
fieldFound = _parent._cache != null &&
_parent._cache.TryGetValue(inField.Offset + inStartPos,
out fieldVal);
if (fieldFound)
{
WriteField(ctx, fieldVal);
vals.Remove(inField.Id);
}
else
{
// Field is not tracked, re-write as is.
inStream.Seek(inField.Offset + inStartPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
}
}
}
// Write remaining new fields.
foreach (var valEntry in vals)
{
if (valEntry.Value == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(valEntry.Key, outStream.Position - outStartPos);
WriteField(ctx, valEntry.Value);
}
var flags = inHeader.IsUserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (inHeader.IsCustomDotNetType)
flags |= BinaryObjectHeader.Flag.CustomDotNetType;
// Write raw data.
int outRawOff = outStream.Position - outStartPos;
if (inHeader.HasRaw)
{
var inRawOff = inHeader.GetRawOffset(inStream, inStartPos);
var inRawLen = inHeader.SchemaOffset - inRawOff;
flags |= BinaryObjectHeader.Flag.HasRaw;
outStream.Write(inStream.InternalArray, inStartPos + inRawOff, inRawLen);
}
// Write schema
int outSchemaOff = outRawOff;
var schemaPos = outStream.Position;
int outSchemaId;
if (inHeader.IsCompactFooter)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = outSchema.WriteSchema(outStream, schemaIdx, out outSchemaId, ref flags);
if (hasSchema)
{
outSchemaOff = schemaPos - outStartPos;
flags |= BinaryObjectHeader.Flag.HasSchema;
if (inHeader.HasRaw)
outStream.WriteInt(outRawOff);
if (_desc.Schema.Get(outSchemaId) == null)
_desc.Schema.Add(outSchemaId, outSchema.GetSchema(schemaIdx));
}
var outLen = outStream.Position - outStartPos;
var outHash = inHeader.HashCode;
if (changeHash)
{
// Get from identity resolver.
outHash = BinaryArrayEqualityComparer.GetHashCode(outStream,
outStartPos + BinaryObjectHeader.Size,
schemaPos - outStartPos - BinaryObjectHeader.Size);
}
var outHeader = new BinaryObjectHeader(inHeader.TypeId, outHash, outLen,
outSchemaId, outSchemaOff, flags);
BinaryObjectHeader.Write(outHeader, outStream, outStartPos);
outStream.Seek(outStartPos + outLen, SeekOrigin.Begin); // seek to the end of the object
}
finally
{
outSchema.PopSchema(schemaIdx);
}
}
}
else
{
// Object has already been written, write as handle.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - hndPos);
}
// Synchronize input stream position.
inStream.Seek(inStartPos + inHeader.Length, SeekOrigin.Begin);
}
else
{
// Try writing as well-known type with fixed size.
outStream.WriteByte(inHdr);
if (!WriteAsPredefined(inHdr, inStream, outStream, ctx))
throw new IgniteException("Unexpected header [position=" + (inStream.Position - 1) +
", header=" + inHdr + ']');
}
}
/// <summary>
/// Writes the specified field.
/// </summary>
private static void WriteField(Context ctx, BinaryBuilderField field)
{
var action = field.WriteAction;
if (action != null)
action(ctx.Writer, field.Value);
else
ctx.Writer.Write(field.Value);
}
/// <summary>
/// Process binary object inverting handles if needed.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="port">Binary object.</param>
internal void ProcessBinary(IBinaryStream outStream, BinaryObject port)
{
// Special case: writing binary object with correct inversions.
using (var inStream = new BinaryHeapStream(port.Data))
{
inStream.Seek(port.Offset, SeekOrigin.Begin);
// Use fresh context to ensure correct binary inversion.
Mutate0(new Context(), inStream, outStream, false, EmptyVals);
}
}
/// <summary>
/// Process child builder.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="builder">Builder.</param>
internal void ProcessBuilder(IBinaryStream outStream, BinaryObjectBuilder builder)
{
using (var inStream = new BinaryHeapStream(builder._obj.Data))
{
inStream.Seek(builder._obj.Offset, SeekOrigin.Begin);
// Builder parent context might be null only in one case: if we never met this group of
// builders before. In this case we set context to their parent and track it. Context
// cleanup will be performed at the very end of build process.
if (builder._parent._ctx == null || builder._parent._ctx.Closed)
builder._parent._ctx = new Context(_parent._ctx);
builder.Mutate(inStream, (BinaryHeapStream) outStream, builder._desc,
builder._vals);
}
}
/// <summary>
/// Write object as a predefined type if possible.
/// </summary>
/// <param name="hdr">Header.</param>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <returns><c>True</c> if was written.</returns>
private bool WriteAsPredefined(byte hdr, BinaryHeapStream inStream, IBinaryStream outStream,
Context ctx)
{
switch (hdr)
{
case BinaryTypeId.Byte:
TransferBytes(inStream, outStream, 1);
break;
case BinaryTypeId.Short:
TransferBytes(inStream, outStream, 2);
break;
case BinaryTypeId.Int:
TransferBytes(inStream, outStream, 4);
break;
case BinaryTypeId.Long:
TransferBytes(inStream, outStream, 8);
break;
case BinaryTypeId.Float:
TransferBytes(inStream, outStream, 4);
break;
case BinaryTypeId.Double:
TransferBytes(inStream, outStream, 8);
break;
case BinaryTypeId.Char:
TransferBytes(inStream, outStream, 2);
break;
case BinaryTypeId.Bool:
TransferBytes(inStream, outStream, 1);
break;
case BinaryTypeId.Decimal:
TransferBytes(inStream, outStream, 4); // Transfer scale
int magLen = inStream.ReadInt(); // Transfer magnitude length.
outStream.WriteInt(magLen);
TransferBytes(inStream, outStream, magLen); // Transfer magnitude.
break;
case BinaryTypeId.String:
BinaryUtils.WriteString(BinaryUtils.ReadString(inStream), outStream);
break;
case BinaryTypeId.Guid:
TransferBytes(inStream, outStream, 16);
break;
case BinaryTypeId.Timestamp:
TransferBytes(inStream, outStream, 12);
break;
case BinaryTypeId.ArrayByte:
TransferArray(inStream, outStream, 1);
break;
case BinaryTypeId.ArrayShort:
TransferArray(inStream, outStream, 2);
break;
case BinaryTypeId.ArrayInt:
TransferArray(inStream, outStream, 4);
break;
case BinaryTypeId.ArrayLong:
TransferArray(inStream, outStream, 8);
break;
case BinaryTypeId.ArrayFloat:
TransferArray(inStream, outStream, 4);
break;
case BinaryTypeId.ArrayDouble:
TransferArray(inStream, outStream, 8);
break;
case BinaryTypeId.ArrayChar:
TransferArray(inStream, outStream, 2);
break;
case BinaryTypeId.ArrayBool:
TransferArray(inStream, outStream, 1);
break;
case BinaryTypeId.ArrayDecimal:
case BinaryTypeId.ArrayString:
case BinaryTypeId.ArrayGuid:
case BinaryTypeId.ArrayTimestamp:
int arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, null);
break;
case BinaryTypeId.ArrayEnum:
case BinaryTypeId.Array:
int type = inStream.ReadInt();
outStream.WriteInt(type);
if (type == BinaryTypeId.Unregistered)
{
outStream.WriteByte(inStream.ReadByte()); // String header.
BinaryUtils.WriteString(BinaryUtils.ReadString(inStream), outStream); // String data.
}
arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, EmptyVals);
break;
case BinaryTypeId.Collection:
int colLen = inStream.ReadInt();
outStream.WriteInt(colLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < colLen; i++)
Mutate0(ctx, inStream, outStream, false, EmptyVals);
break;
case BinaryTypeId.Dictionary:
int dictLen = inStream.ReadInt();
outStream.WriteInt(dictLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < dictLen; i++)
{
Mutate0(ctx, inStream, outStream, false, EmptyVals);
Mutate0(ctx, inStream, outStream, false, EmptyVals);
}
break;
case BinaryTypeId.Binary:
TransferArray(inStream, outStream, 1); // Data array.
TransferBytes(inStream, outStream, 4); // Offset in array.
break;
case BinaryTypeId.Enum:
TransferBytes(inStream, outStream, 8); // int typeId, int value.
break;
default:
return false;
}
return true;
}
/// <summary>
/// Transfer bytes from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="cnt">Bytes count.</param>
private static void TransferBytes(BinaryHeapStream inStream, IBinaryStream outStream, int cnt)
{
outStream.Write(inStream.InternalArray, inStream.Position, cnt);
inStream.Seek(cnt, SeekOrigin.Current);
}
/// <summary>
/// Transfer array of fixed-size elements from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="elemSize">Element size.</param>
private static void TransferArray(BinaryHeapStream inStream, IBinaryStream outStream,
int elemSize)
{
int len = inStream.ReadInt();
outStream.WriteInt(len);
TransferBytes(inStream, outStream, elemSize * len);
}
/// <summary>
/// Create empty binary object from descriptor.
/// </summary>
/// <param name="desc">Descriptor.</param>
/// <returns>Empty binary object.</returns>
private BinaryObject BinaryFromDescriptor(IBinaryTypeDescriptor desc)
{
const int len = BinaryObjectHeader.Size;
var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None;
if (_binary.Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hdr = new BinaryObjectHeader(desc.TypeId, 0, len, 0, len, flags);
using (var stream = new BinaryHeapStream(len))
{
BinaryObjectHeader.Write(hdr, stream, 0);
return new BinaryObject(_binary.Marshaller, stream.InternalArray, 0, hdr);
}
}
/// <summary>
/// Mutation context.
/// </summary>
private class Context
{
/** Map from object position in old binary to position in new binary. */
private IDictionary<int, int> _oldToNew;
/** Parent context. */
private readonly Context _parent;
/** Binary writer. */
private readonly BinaryWriter _writer;
/** Children contexts. */
private ICollection<Context> _children;
/** Closed flag; if context is closed, it can no longer be used. */
private bool _closed;
/// <summary>
/// Constructor for parent context where writer invocation is not expected.
/// </summary>
public Context()
{
// No-op.
}
/// <summary>
/// Constructor for parent context.
/// </summary>
/// <param name="writer">Writer</param>
public Context(BinaryWriter writer)
{
_writer = writer;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="parent">Parent context.</param>
public Context(Context parent)
{
_parent = parent;
_writer = parent._writer;
if (parent._children == null)
parent._children = new List<Context>();
parent._children.Add(this);
}
/// <summary>
/// Add another old-to-new position mapping.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <param name="hndPos">Handle position.</param>
/// <returns><c>True</c> if ampping was added, <c>false</c> if mapping already existed and handle
/// position in the new object is returned.</returns>
public bool AddOldToNew(int oldPos, int newPos, out int hndPos)
{
if (_oldToNew == null)
_oldToNew = new Dictionary<int, int>();
if (_oldToNew.TryGetValue(oldPos, out hndPos))
return false;
_oldToNew[oldPos] = newPos;
return true;
}
/// <summary>
/// Get mapping of old position to the new one.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <returns><c>True</c> if mapping exists.</returns>
public bool OldToNew(int oldPos, out int newPos)
{
return _oldToNew.TryGetValue(oldPos, out newPos);
}
/// <summary>
/// Writer.
/// </summary>
public BinaryWriter Writer
{
get { return _writer; }
}
/// <summary>
/// Closed flag.
/// </summary>
public bool Closed
{
get
{
return _closed;
}
set
{
Context ctx = this;
while (ctx != null)
{
ctx._closed = value;
if (_children != null) {
foreach (Context child in _children)
child.Closed = value;
}
ctx = ctx._parent;
}
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// X509Chain.cs
//
namespace System.Security.Cryptography.X509Certificates {
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using _FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
[Flags]
public enum X509ChainStatusFlags {
NoError = 0x00000000,
NotTimeValid = 0x00000001,
NotTimeNested = 0x00000002,
Revoked = 0x00000004,
NotSignatureValid = 0x00000008,
NotValidForUsage = 0x00000010,
UntrustedRoot = 0x00000020,
RevocationStatusUnknown = 0x00000040,
Cyclic = 0x00000080,
InvalidExtension = 0x00000100,
InvalidPolicyConstraints = 0x00000200,
InvalidBasicConstraints = 0x00000400,
InvalidNameConstraints = 0x00000800,
HasNotSupportedNameConstraint = 0x00001000,
HasNotDefinedNameConstraint = 0x00002000,
HasNotPermittedNameConstraint = 0x00004000,
HasExcludedNameConstraint = 0x00008000,
PartialChain = 0x00010000,
CtlNotTimeValid = 0x00020000,
CtlNotSignatureValid = 0x00040000,
CtlNotValidForUsage = 0x00080000,
OfflineRevocation = 0x01000000,
NoIssuanceChainPolicy = 0x02000000
}
public struct X509ChainStatus {
private X509ChainStatusFlags m_status;
private string m_statusInformation;
public X509ChainStatusFlags Status {
get {
return m_status;
}
set {
m_status = value;
}
}
public string StatusInformation {
get {
if (m_statusInformation == null)
return String.Empty;
return m_statusInformation;
}
set {
m_statusInformation = value;
}
}
}
public class X509Chain {
private uint m_status;
private X509ChainPolicy m_chainPolicy;
private X509ChainStatus[] m_chainStatus;
private X509ChainElementCollection m_chainElementCollection;
private SafeCertChainHandle m_safeCertChainHandle;
private bool m_useMachineContext;
private readonly object m_syncRoot = new object();
public static X509Chain Create() {
return (X509Chain) CryptoConfig.CreateFromName("X509Chain");
}
public X509Chain () : this (false) {}
public X509Chain (bool useMachineContext) {
m_status = 0;
m_chainPolicy = null;
m_chainStatus = null;
m_chainElementCollection = new X509ChainElementCollection();
m_safeCertChainHandle = SafeCertChainHandle.InvalidHandle;
m_useMachineContext = useMachineContext;
}
// Package protected constructor for creating a chain from a PCCERT_CHAIN_CONTEXT
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public X509Chain (IntPtr chainContext) {
if (chainContext == IntPtr.Zero)
throw new ArgumentNullException("chainContext");
m_safeCertChainHandle = CAPI.CertDuplicateCertificateChain(chainContext);
if (m_safeCertChainHandle == null || m_safeCertChainHandle == SafeCertChainHandle.InvalidHandle)
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidContextHandle), "chainContext");
Init();
}
public IntPtr ChainContext {
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
return m_safeCertChainHandle.DangerousGetHandle();
}
}
public X509ChainPolicy ChainPolicy {
get {
if (m_chainPolicy == null)
m_chainPolicy = new X509ChainPolicy();
return m_chainPolicy;
}
set {
if (value == null)
throw new ArgumentNullException("value");
m_chainPolicy = value;
}
}
public X509ChainStatus[] ChainStatus {
get {
// We give the user a reference to the array since we'll never access it.
if (m_chainStatus == null) {
if (m_status == 0) {
m_chainStatus = new X509ChainStatus[0]; // empty array
} else {
m_chainStatus = GetChainStatusInformation(m_status);
}
}
return m_chainStatus;
}
}
public X509ChainElementCollection ChainElements {
get {
return m_chainElementCollection;
}
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
public bool Build (X509Certificate2 certificate) {
lock (m_syncRoot) {
if (certificate == null || certificate.CertContext.IsInvalid)
throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "certificate");
// Chain building opens and enumerates the root store to see if the root of the chain is trusted.
StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates);
sp.Demand();
X509ChainPolicy chainPolicy = this.ChainPolicy;
if (chainPolicy.RevocationMode == X509RevocationMode.Online) {
if (certificate.Extensions[CAPI.szOID_CRL_DIST_POINTS] != null ||
certificate.Extensions[CAPI.szOID_AUTHORITY_INFO_ACCESS] != null) {
// If there is a CDP or AIA extension, we demand unrestricted network access and store add permission
// since CAPI can download certificates into the CA store from the network.
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new WebPermission(PermissionState.Unrestricted));
ps.AddPermission(new StorePermission(StorePermissionFlags.AddToStore));
ps.Demand();
}
}
Reset();
int hr = BuildChain(m_useMachineContext ? new IntPtr(CAPI.HCCE_LOCAL_MACHINE) : new IntPtr(CAPI.HCCE_CURRENT_USER),
certificate.CertContext,
chainPolicy.ExtraStore,
chainPolicy.ApplicationPolicy,
chainPolicy.CertificatePolicy,
chainPolicy.RevocationMode,
chainPolicy.RevocationFlag,
chainPolicy.VerificationTime,
chainPolicy.UrlRetrievalTimeout,
ref m_safeCertChainHandle);
if (hr != CAPI.S_OK)
return false;
// Init.
Init();
// Verify the chain using the specified policy.
CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));
PolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags;
if (!CAPI.CertVerifyCertificateChainPolicy(new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE),
m_safeCertChainHandle,
ref PolicyPara,
ref PolicyStatus))
// The API failed.
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.SetLastError(PolicyStatus.dwError);
return (PolicyStatus.dwError == 0);
}
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
public void Reset () {
m_status = 0;
m_chainStatus = null;
m_chainElementCollection = new X509ChainElementCollection();
if (!m_safeCertChainHandle.IsInvalid) {
m_safeCertChainHandle.Dispose();
m_safeCertChainHandle = SafeCertChainHandle.InvalidHandle;
}
}
private unsafe void Init () {
using (SafeCertChainHandle safeCertChainHandle = CAPI.CertDuplicateCertificateChain(m_safeCertChainHandle)) {
CAPI.CERT_CHAIN_CONTEXT pChain = new CAPI.CERT_CHAIN_CONTEXT(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_CONTEXT)));
uint cbSize = (uint) Marshal.ReadInt32(safeCertChainHandle.DangerousGetHandle());
if (cbSize > Marshal.SizeOf(pChain))
cbSize = (uint) Marshal.SizeOf(pChain);
X509Utils.memcpy(m_safeCertChainHandle.DangerousGetHandle(), new IntPtr(&pChain), cbSize);
m_status = pChain.dwErrorStatus;
Debug.Assert(pChain.cChain > 0);
m_chainElementCollection = new X509ChainElementCollection(Marshal.ReadIntPtr(pChain.rgpChain));
}
}
internal static X509ChainStatus[] GetChainStatusInformation (uint dwStatus) {
if (dwStatus == 0)
return new X509ChainStatus[0];
int count = 0;
for (uint bits = dwStatus; bits != 0; bits = bits >> 1) {
if ((bits & 0x1) != 0)
count++;
}
X509ChainStatus[] chainStatus = new X509ChainStatus[count];
int index = 0;
if ((dwStatus & CAPI.CERT_TRUST_IS_NOT_SIGNATURE_VALID) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.TRUST_E_CERT_SIGNATURE);
chainStatus[index].Status = X509ChainStatusFlags.NotSignatureValid;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_NOT_SIGNATURE_VALID;
}
if ((dwStatus & CAPI.CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.TRUST_E_CERT_SIGNATURE);
chainStatus[index].Status = X509ChainStatusFlags.CtlNotSignatureValid;
index++;
dwStatus &= ~CAPI.CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_UNTRUSTED_ROOT) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_UNTRUSTEDROOT);
chainStatus[index].Status = X509ChainStatusFlags.UntrustedRoot;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_UNTRUSTED_ROOT;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_PARTIAL_CHAIN) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_CHAINING);
chainStatus[index].Status = X509ChainStatusFlags.PartialChain;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_PARTIAL_CHAIN;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_REVOKED) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CRYPT_E_REVOKED);
chainStatus[index].Status = X509ChainStatusFlags.Revoked;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_REVOKED;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_NOT_VALID_FOR_USAGE) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_WRONG_USAGE);
chainStatus[index].Status = X509ChainStatusFlags.NotValidForUsage;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
}
if ((dwStatus & CAPI.CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_WRONG_USAGE);
chainStatus[index].Status = X509ChainStatusFlags.CtlNotValidForUsage;
index++;
dwStatus &= ~CAPI.CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_NOT_TIME_VALID) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_EXPIRED);
chainStatus[index].Status = X509ChainStatusFlags.NotTimeValid;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_NOT_TIME_VALID;
}
if ((dwStatus & CAPI.CERT_TRUST_CTL_IS_NOT_TIME_VALID) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_EXPIRED);
chainStatus[index].Status = X509ChainStatusFlags.CtlNotTimeValid;
index++;
dwStatus &= ~CAPI.CERT_TRUST_CTL_IS_NOT_TIME_VALID;
}
if ((dwStatus & CAPI.CERT_TRUST_INVALID_NAME_CONSTRAINTS) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_NAME);
chainStatus[index].Status = X509ChainStatusFlags.InvalidNameConstraints;
index++;
dwStatus &= ~CAPI.CERT_TRUST_INVALID_NAME_CONSTRAINTS;
}
if ((dwStatus & CAPI.CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_NAME);
chainStatus[index].Status = X509ChainStatusFlags.HasNotSupportedNameConstraint;
index++;
dwStatus &= ~CAPI.CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT;
}
if ((dwStatus & CAPI.CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_NAME);
chainStatus[index].Status = X509ChainStatusFlags.HasNotDefinedNameConstraint;
index++;
dwStatus &= ~CAPI.CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT;
}
if ((dwStatus & CAPI.CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_NAME);
chainStatus[index].Status = X509ChainStatusFlags.HasNotPermittedNameConstraint;
index++;
dwStatus &= ~CAPI.CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT;
}
if ((dwStatus & CAPI.CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_NAME);
chainStatus[index].Status = X509ChainStatusFlags.HasExcludedNameConstraint;
index++;
dwStatus &= ~CAPI.CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT;
}
if ((dwStatus & CAPI.CERT_TRUST_INVALID_POLICY_CONSTRAINTS) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_POLICY);
chainStatus[index].Status = X509ChainStatusFlags.InvalidPolicyConstraints;
index++;
dwStatus &= ~CAPI.CERT_TRUST_INVALID_POLICY_CONSTRAINTS;
}
if ((dwStatus & CAPI.CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_INVALID_POLICY);
chainStatus[index].Status = X509ChainStatusFlags.NoIssuanceChainPolicy;
index++;
dwStatus &= ~CAPI.CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY;
}
if ((dwStatus & CAPI.CERT_TRUST_INVALID_BASIC_CONSTRAINTS) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.TRUST_E_BASIC_CONSTRAINTS);
chainStatus[index].Status = X509ChainStatusFlags.InvalidBasicConstraints;
index++;
dwStatus &= ~CAPI.CERT_TRUST_INVALID_BASIC_CONSTRAINTS;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_NOT_TIME_NESTED) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CERT_E_VALIDITYPERIODNESTING);
chainStatus[index].Status = X509ChainStatusFlags.NotTimeNested;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_NOT_TIME_NESTED;
}
if ((dwStatus & CAPI.CERT_TRUST_REVOCATION_STATUS_UNKNOWN) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CRYPT_E_NO_REVOCATION_CHECK);
chainStatus[index].Status = X509ChainStatusFlags.RevocationStatusUnknown;
index++;
dwStatus &= ~CAPI.CERT_TRUST_REVOCATION_STATUS_UNKNOWN;
}
if ((dwStatus & CAPI.CERT_TRUST_IS_OFFLINE_REVOCATION) != 0) {
chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(CAPI.CRYPT_E_REVOCATION_OFFLINE);
chainStatus[index].Status = X509ChainStatusFlags.OfflineRevocation;
index++;
dwStatus &= ~CAPI.CERT_TRUST_IS_OFFLINE_REVOCATION;
}
int shiftCount = 0;
for (uint bits = dwStatus; bits != 0; bits = bits >> 1) {
if ((bits & 0x1) != 0) {
chainStatus[index].Status = (X509ChainStatusFlags) (1 << shiftCount);
chainStatus[index].StatusInformation = SR.GetString(SR.Unknown_Error);
index++;
}
shiftCount++;
}
return chainStatus;
}
//
// Builds a certificate chain.
//
internal static unsafe int BuildChain (IntPtr hChainEngine,
SafeCertContextHandle pCertContext,
X509Certificate2Collection extraStore,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag,
DateTime verificationTime,
TimeSpan timeout,
ref SafeCertChainHandle ppChainContext) {
if (pCertContext == null || pCertContext.IsInvalid)
throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "pCertContext");
SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle;
if (extraStore != null && extraStore.Count > 0)
hCertStore = X509Utils.ExportToMemoryStore(extraStore);
CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA();
// Initialize the structure size.
ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara);
SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle;
SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle;
try {
// Application policy
if (applicationPolicy != null && applicationPolicy.Count > 0) {
ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND;
ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle();
}
// Certificate policy
if (certificatePolicy != null && certificatePolicy.Count > 0) {
ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND;
ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle();
}
ChainPara.dwUrlRetrievalTimeout = (uint) Math.Floor(timeout.TotalMilliseconds);
_FILETIME ft = new _FILETIME();
*((long*) &ft) = verificationTime.ToFileTime();
uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);
// Build the chain.
if (!CAPI.CertGetCertificateChain(hChainEngine,
pCertContext,
ref ft,
hCertStore,
ref ChainPara,
flags,
IntPtr.Zero,
ref ppChainContext))
return Marshal.GetHRForLastWin32Error();
}
finally {
applicationPolicyHandle.Dispose();
certificatePolicyHandle.Dispose();
}
return CAPI.S_OK;
}
}
}
| |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Pipeline
{
using System;
using MassTransit.Internal;
using MassTransit.Pipeline;
using MassTransit.Pipeline.Configuration;
using Messages;
using NUnit.Framework;
using Rhino.Mocks;
using TestConsumers;
[TestFixture]
public class The_SubscriptionPublisher_should_add_subscriptions
{
[SetUp]
public void Setup()
{
_builder = MockRepository.GenerateMock<IObjectBuilder>();
_endpoint = MockRepository.GenerateMock<IEndpoint>();
_endpoint.Stub(x => x.Uri).Return(_uri);
_bus = MockRepository.GenerateMock<IServiceBus>();
_bus.Stub(x => x.Endpoint).Return(_endpoint);
_unsubscribe = MockRepository.GenerateMock<UnsubscribeAction>();
_subscriptionEvent = MockRepository.GenerateMock<ISubscriptionEvent>();
_pipeline = MessagePipelineConfigurator.CreateDefault(_builder, _bus);
_pipeline.Configure(x => x.Register(_subscriptionEvent));
}
private IObjectBuilder _builder;
private IServiceBus _bus;
private readonly Uri _uri = new Uri("msmq://localhost/mt_client");
private IEndpoint _endpoint;
private MessagePipeline _pipeline;
private ISubscriptionEvent _subscriptionEvent;
private UnsubscribeAction _unsubscribe;
[Test]
public void for_batch_component_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<IndividualBatchMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
_pipeline.Subscribe<TestBatchConsumer<IndividualBatchMessage, Guid>>();
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_batch_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<IndividualBatchMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestBatchConsumer<IndividualBatchMessage, Guid>();
_pipeline.Subscribe(consumer);
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_component_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
_pipeline.Subscribe<TestMessageConsumer<PingMessage>>();
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_correlated_subscriptions()
{
Guid pongGuid = Guid.NewGuid();
_subscriptionEvent.Expect(x => x.SubscribedTo<PongMessage,Guid>(pongGuid)).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(pongGuid);
_pipeline.Subscribe(consumer);
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_regular_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestMessageConsumer<PingMessage>();
_pipeline.Subscribe(consumer);
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_selective_component_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
_pipeline.Subscribe<TestSelectiveConsumer<PingMessage>>();
_subscriptionEvent.VerifyAllExpectations();
}
[Test]
public void for_selective_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestSelectiveConsumer<PingMessage>();
_pipeline.Subscribe(consumer);
_subscriptionEvent.VerifyAllExpectations();
}
}
[TestFixture]
public class The_SubscriptionPublisher_should_remove_subscriptions
{
[SetUp]
public void Setup()
{
_builder = MockRepository.GenerateMock<IObjectBuilder>();
_endpoint = MockRepository.GenerateMock<IEndpoint>();
_endpoint.Stub(x => x.Uri).Return(_uri);
_unsubscribe = MockRepository.GenerateMock<UnsubscribeAction>();
_bus = MockRepository.GenerateMock<IServiceBus>();
_bus.Stub(x => x.Endpoint).Return(_endpoint);
_subscriptionEvent = MockRepository.GenerateMock<ISubscriptionEvent>();
_pipeline = MessagePipelineConfigurator.CreateDefault(_builder, _bus);
_pipeline.Configure(x => x.Register(_subscriptionEvent));
}
private IObjectBuilder _builder;
private IServiceBus _bus;
private readonly Uri _uri = new Uri("msmq://localhost/mt_client");
private IEndpoint _endpoint;
private MessagePipeline _pipeline;
private ISubscriptionEvent _subscriptionEvent;
private UnsubscribeAction _unsubscribe;
[Test]
public void for_batch_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<IndividualBatchMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestBatchConsumer<IndividualBatchMessage, Guid>();
var token = _pipeline.Subscribe(consumer);
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_batch_subscriptions_but_not_when_another_exists()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<IndividualBatchMessage>()).Repeat.Twice().Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestBatchConsumer<IndividualBatchMessage, Guid>();
var token = _pipeline.Subscribe(consumer);
var consumerB = new TestBatchConsumer<IndividualBatchMessage, Guid>();
var tokenB = _pipeline.Subscribe(consumerB);
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasNotCalled(x => x());
}
[Test]
public void for_component_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var token = _pipeline.Subscribe<TestMessageConsumer<PingMessage>>();
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_correlated_subscriptions()
{
Guid pongGuid = Guid.NewGuid();
_subscriptionEvent.Expect(x => x.SubscribedTo<PongMessage,Guid>(pongGuid)).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(pongGuid);
var remove = _pipeline.Subscribe(consumer);
remove();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_correlated_subscriptions_but_not_when_another_exists()
{
Guid pongGuid = Guid.NewGuid();
_subscriptionEvent.Expect(x => x.SubscribedTo<PongMessage, Guid>(pongGuid)).Repeat.Twice().Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(pongGuid);
var otherConsumer = new TestCorrelatedConsumer<PongMessage, Guid>(pongGuid);
var remove = _pipeline.Subscribe(consumer);
var removeOther = _pipeline.Subscribe(otherConsumer);
remove();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasNotCalled(x => x());
_unsubscribe.BackToRecord();
_unsubscribe.Replay();
removeOther();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_regular_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestMessageConsumer<PingMessage>();
var token = _pipeline.Subscribe(consumer);
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_selective_component_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var token = _pipeline.Subscribe<TestSelectiveConsumer<PingMessage>>();
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
[Test]
public void for_selective_subscriptions()
{
_subscriptionEvent.Expect(x => x.SubscribedTo<PingMessage>()).Return(() =>
{
_unsubscribe();
return true;
});
var consumer = new TestSelectiveConsumer<PingMessage>();
var token = _pipeline.Subscribe(consumer);
token();
_subscriptionEvent.VerifyAllExpectations();
_unsubscribe.AssertWasCalled(x => x());
}
}
}
| |
//
// Sample showing the core Element-based API to create a dialog
//
using System;
using System.Linq;
using MonoTouch.Dialog;
using UIKit;
namespace Sample
{
public partial class AppDelegate
{
public void DemoElementApi ()
{
var root = CreateRoot ();
var dv = new DialogViewController (root, true);
navigation.PushViewController (dv, true);
}
RootElement CreateRoot ()
{
return new RootElement ("Settings") {
new Section (){
new BooleanElement ("Airplane Mode", false),
new RootElement ("Notifications", 0, 0) {
new Section (null, "Turn off Notifications to disable Sounds\n" +
"Alerts and Home Screen Badges for the\napplications below."){
new BooleanElement ("Notifications", false)
}
}},
new Section (){
CreateSoundSection (),
new RootElement ("Brightness"){
new Section (){
new FloatElement (null, null, 0.5f),
new BooleanElement ("Auto-brightness", false),
}
},
new RootElement ("Wallpaper"){
new Section (){
new ImageElement (null),
new ImageElement (null),
new ImageElement (null)
}
}
},
new Section () {
new EntryElement ("Login", "Your login name", null)
{
EnablesReturnKeyAutomatically = true,
AlignEntryWithAllSections = true,
},
new EntryElement ("Password", "Your password", null, true)
{
EnablesReturnKeyAutomatically = true,
AlignEntryWithAllSections = true,
},
new DateElement ("Select Date", DateTime.Now),
new TimeElement ("Select Time", DateTime.Now),
},
new Section () {
new EntryElement ("Another Field", "Aligns with above fields", null)
{
AlignEntryWithAllSections = true,
},
},
new Section () {
CreateGeneralSection (),
//new RootElement ("Mail, Contacts, Calendars"),
//new RootElement ("Phone"),
//new RootElement ("Safari"),
//new RootElement ("Messages"),
//new RootElement ("iPod"),
//new RootElement ("Photos"),
//new RootElement ("Store"),
},
new Section () {
new HtmlElement ("About", "http://monotouch.net"),
new MultilineElement ("Remember to eat\nfruits and vegetables\nevery day")
}
};
}
RootElement CreateSoundSection ()
{
return new RootElement ("Sounds"){
new Section ("Silent") {
new BooleanElement ("Vibrate", true),
},
new Section ("Ring") {
new BooleanElement ("Vibrate", true),
new FloatElement (null, null, 0.8f),
new RootElement ("Ringtone", new RadioGroup (0)){
new Section ("Custom"){
new RadioElement ("Circus Music"),
new RadioElement ("True Blood"),
},
new Section ("Standard"){
from n in "Marimba,Alarm,Ascending,Bark,Xylophone".Split (',')
select (Element) new RadioElement (n)
}
},
new RootElement ("New Text Message", new RadioGroup (3)){
new Section (){
from n in "None,Tri-tone,Chime,Glass,Horn,Bell,Eletronic".Split (',')
select (Element) new RadioElement (n)
}
},
new BooleanElement ("New Voice Mail", false),
new BooleanElement ("New Mail", false),
new BooleanElement ("Sent Mail", true),
new BooleanElement ("Calendar Alerts", true),
new BooleanElement ("Lock Sounds", true),
new BooleanElement ("Keyboard Clicks", false)
}
};
}
public RootElement CreateGeneralSection ()
{
return new RootElement ("General") {
new Section (){
new RootElement ("About"){
new Section ("My Phone") {
new RootElement ("Network", new RadioGroup (null, 0)) {
new Section (){
new RadioElement ("My First Network"),
new RadioElement ("Second Network"),
}
},
new StringElement ("Songs", "23"),
new StringElement ("Videos", "3"),
new StringElement ("Photos", "24"),
new StringElement ("Applications", "50"),
new StringElement ("Capacity", "14.6GB"),
new StringElement ("Available", "12.8GB"),
new StringElement ("Version", "3.0 (FOOBAR)"),
new StringElement ("Carrier", "My Carrier"),
new StringElement ("Serial Number", "555-3434"),
new StringElement ("Model", "The"),
new StringElement ("Wi-Fi Address", "11:22:33:44:55:66"),
new StringElement ("Bluetooth", "aa:bb:cc:dd:ee:ff:00"),
},
new Section () {
new HtmlElement ("Monologue", "http://www.go-mono.com/monologue"),
}
},
new RootElement ("Usage"){
new Section ("Time since last full charge"){
new StringElement ("Usage", "0 minutes"),
new StringElement ("Standby", "0 minutes"),
},
new Section ("Call time") {
new StringElement ("Current Period", "4 days, 21 hours"),
new StringElement ("Lifetime", "7 days, 20 hours")
},
new Section ("Celullar Network Data"){
new StringElement ("Sent", "10 bytes"),
new StringElement ("Received", "30 TB"),
},
new Section (null, "Last Reset: 1/1/08 4:44pm"){
new StringElement ("Reset Statistics"){
Alignment = UITextAlignment.Center
}
}
}
},
new Section (){
new RootElement ("Network"){
new Section (null, "Using 3G loads data faster\nand burns the battery"){
new BooleanElement ("Enable 3G", true)
},
new Section (null, "Turn this on if you are Donald Trump"){
new BooleanElement ("Data Roaming", false),
},
new Section (){
new RootElement ("VPN", 0, 0){
new Section (){
new BooleanElement ("VPN", false),
},
new Section ("Choose a configuration"){
new StringElement ("Add VPN Configuration")
}
}
}
},
new RootElement ("Bluetooth", 0, 0){
new Section (){
new BooleanElement ("Bluetooth", false)
}
},
new BooleanElement ("Location Services", true),
},
new Section (){
new RootElement ("Auto-Lock", new RadioGroup (0)){
new Section (){
new RadioElement ("1 Minute"),
new RadioElement ("2 Minutes"),
new RadioElement ("3 Minutes"),
new RadioElement ("4 Minutes"),
new RadioElement ("5 Minutes"),
new RadioElement ("Never"),
}
},
// Can be implemented with StringElement + Tapped, but makes sample larger
// new StringElement ("Passcode lock"),
new BooleanElement ("Restrictions", false),
},
new Section () {
new RootElement ("Home", new RadioGroup (2)){
new Section ("Double-click the Home Button for:"){
new RadioElement ("Home"),
new RadioElement ("Search"),
new RadioElement ("Phone favorites"),
new RadioElement ("Camera"),
new RadioElement ("iPod"),
},
new Section (null, "When playing music, show iPod controls"){
new BooleanElement ("iPod Controls", true),
}
// Missing feature: sortable list of data
// SearchResults
},
new RootElement ("Date & Time"){
new Section (){
new BooleanElement ("24-Hour Time", false),
},
new Section (){
new BooleanElement ("Set Automatically", false),
// TimeZone: Can be implemented with string + tapped event
// SetTime: Can be imeplemeneted with String + Tapped Event
}
},
new RootElement ("Keyboard"){
new Section (null, "Double tapping the space bar will\n" +
"insert a period followed by a space"){
new BooleanElement ("Auto-Correction", true),
new BooleanElement ("Auto-Capitalization", true),
new BooleanElement ("Enable Caps Lock", false),
new BooleanElement ("\".\" Shortcut", true),
},
new Section (){
new RootElement ("International Keyboards", new Group ("kbd")){
new Section ("Using Checkboxes"){
new CheckboxElement ("English", true, "kbd"),
new CheckboxElement ("Spanish", false, "kbd"),
new CheckboxElement ("French", false, "kbd"),
},
new Section ("Using BooleanElement"){
new BooleanElement ("Portuguese", true, "kbd"),
new BooleanElement ("German", false, "kbd"),
},
new Section ("Or mixing them"){
new BooleanElement ("Italian", true, "kbd"),
new CheckboxElement ("Czech", true, "kbd"),
}
}
}
}
}
};
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
namespace Microsoft.Azure.Management.Resources
{
public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IDeploymentOperationOperations _deploymentOperations;
/// <summary>
/// Operations for managing deployment operations.
/// </summary>
public virtual IDeploymentOperationOperations DeploymentOperations
{
get { return this._deploymentOperations; }
}
private IDeploymentOperations _deployments;
/// <summary>
/// Operations for managing deployments.
/// </summary>
public virtual IDeploymentOperations Deployments
{
get { return this._deployments; }
}
private IProviderOperations _providers;
/// <summary>
/// Operations for managing providers.
/// </summary>
public virtual IProviderOperations Providers
{
get { return this._providers; }
}
private IResourceGroupOperations _resourceGroups;
/// <summary>
/// Operations for managing resource groups.
/// </summary>
public virtual IResourceGroupOperations ResourceGroups
{
get { return this._resourceGroups; }
}
private IResourceOperations _resources;
/// <summary>
/// Operations for managing resources.
/// </summary>
public virtual IResourceOperations Resources
{
get { return this._resources; }
}
private ITagOperations _tags;
/// <summary>
/// Operations for managing tags.
/// </summary>
public virtual ITagOperations Tags
{
get { return this._tags; }
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
private ResourceManagementClient()
: base()
{
this._deploymentOperations = new DeploymentOperationOperations(this);
this._deployments = new DeploymentOperations(this);
this._providers = new ProviderOperations(this);
this._resourceGroups = new ResourceGroupOperations(this);
this._resources = new ResourceOperations(this);
this._tags = new TagOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private ResourceManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._deploymentOperations = new DeploymentOperationOperations(this);
this._deployments = new DeploymentOperations(this);
this._providers = new ProviderOperations(this);
this._resourceGroups = new ResourceGroupOperations(this);
this._resources = new ResourceOperations(this);
this._tags = new TagOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// ResourceManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of ResourceManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ResourceManagementClient> client)
{
base.Clone(client);
if (client is ResourceManagementClient)
{
ResourceManagementClient clonedClient = ((ResourceManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
Tracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = operationStatusLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-04-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.RecoveryServices.Backup;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
/// <summary>
/// The Resource Manager API includes operations for managing the backup
/// engines registered to your Recovery Services Vault.
/// </summary>
internal partial class BackupEngineOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IBackupEngineOperations
{
/// <summary>
/// Initializes a new instance of the BackupEngineOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal BackupEngineOperations(RecoveryServicesBackupManagementClient client)
{
this._client = client;
}
private RecoveryServicesBackupManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient.
/// </summary>
public RecoveryServicesBackupManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Lists all the backup engines registered to your Recovery Services
/// Vault based on the query parameters and the pagination parameters
/// passed in the arguments.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='queryParams'>
/// Required. Query parameters for listing backup engines.
/// </param>
/// <param name='paginationParams'>
/// Optional. Pagination parameters for controlling the response.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response returned by the list backup engines operation.
/// </returns>
public async Task<BackupEngineListResponse> ListAsync(string resourceGroupName, string resourceName, BackupEngineListQueryParams queryParams, PaginationRequest paginationParams, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (queryParams == null)
{
throw new ArgumentNullException("queryParams");
}
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("queryParams", queryParams);
tracingParameters.Add("paginationParams", paginationParams);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/";
url = url + "vaults";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/backupEngines";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-05-01");
List<string> odataFilter = new List<string>();
if (queryParams.BackupManagementType != null)
{
odataFilter.Add("backupManagementType eq '" + Uri.EscapeDataString(queryParams.BackupManagementType) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (paginationParams != null && paginationParams.SkipToken != null)
{
queryParameters.Add("$skiptoken=" + Uri.EscapeDataString(paginationParams.SkipToken));
}
if (paginationParams != null && paginationParams.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(paginationParams.Top));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
BackupEngineListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new BackupEngineListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
BackupEngineResourceList itemListInstance = new BackupEngineResourceList();
result.ItemList = itemListInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
BackupEngineResource backupEngineResourceInstance = new BackupEngineResource();
itemListInstance.BackupEngines.Add(backupEngineResourceInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["backupEngineType"]);
if (typeName == "DpmBackupEngine")
{
DpmBackupEngine dpmBackupEngineInstance = new DpmBackupEngine();
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
dpmBackupEngineInstance.FriendlyName = friendlyNameInstance;
}
JToken backupManagementTypeValue = propertiesValue["backupManagementType"];
if (backupManagementTypeValue != null && backupManagementTypeValue.Type != JTokenType.Null)
{
string backupManagementTypeInstance = ((string)backupManagementTypeValue);
dpmBackupEngineInstance.BackupManagementType = backupManagementTypeInstance;
}
JToken registrationStatusValue = propertiesValue["registrationStatus"];
if (registrationStatusValue != null && registrationStatusValue.Type != JTokenType.Null)
{
string registrationStatusInstance = ((string)registrationStatusValue);
dpmBackupEngineInstance.RegistrationStatus = registrationStatusInstance;
}
JToken healthStatusValue = propertiesValue["healthStatus"];
if (healthStatusValue != null && healthStatusValue.Type != JTokenType.Null)
{
string healthStatusInstance = ((string)healthStatusValue);
dpmBackupEngineInstance.HealthStatus = healthStatusInstance;
}
JToken backupEngineTypeValue = propertiesValue["backupEngineType"];
if (backupEngineTypeValue != null && backupEngineTypeValue.Type != JTokenType.Null)
{
string backupEngineTypeInstance = ((string)backupEngineTypeValue);
dpmBackupEngineInstance.BackupEngineType = backupEngineTypeInstance;
}
JToken canReRegisterValue = propertiesValue["canReRegister"];
if (canReRegisterValue != null && canReRegisterValue.Type != JTokenType.Null)
{
bool canReRegisterInstance = ((bool)canReRegisterValue);
dpmBackupEngineInstance.CanReRegister = canReRegisterInstance;
}
JToken backupEngineIdValue = propertiesValue["backupEngineId"];
if (backupEngineIdValue != null && backupEngineIdValue.Type != JTokenType.Null)
{
string backupEngineIdInstance = ((string)backupEngineIdValue);
dpmBackupEngineInstance.BackupEngineId = backupEngineIdInstance;
}
backupEngineResourceInstance.Properties = dpmBackupEngineInstance;
}
if (typeName == "AzureBackupServerEngine")
{
AzureBackupServerEngine azureBackupServerEngineInstance = new AzureBackupServerEngine();
JToken friendlyNameValue2 = propertiesValue["friendlyName"];
if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null)
{
string friendlyNameInstance2 = ((string)friendlyNameValue2);
azureBackupServerEngineInstance.FriendlyName = friendlyNameInstance2;
}
JToken backupManagementTypeValue2 = propertiesValue["backupManagementType"];
if (backupManagementTypeValue2 != null && backupManagementTypeValue2.Type != JTokenType.Null)
{
string backupManagementTypeInstance2 = ((string)backupManagementTypeValue2);
azureBackupServerEngineInstance.BackupManagementType = backupManagementTypeInstance2;
}
JToken registrationStatusValue2 = propertiesValue["registrationStatus"];
if (registrationStatusValue2 != null && registrationStatusValue2.Type != JTokenType.Null)
{
string registrationStatusInstance2 = ((string)registrationStatusValue2);
azureBackupServerEngineInstance.RegistrationStatus = registrationStatusInstance2;
}
JToken healthStatusValue2 = propertiesValue["healthStatus"];
if (healthStatusValue2 != null && healthStatusValue2.Type != JTokenType.Null)
{
string healthStatusInstance2 = ((string)healthStatusValue2);
azureBackupServerEngineInstance.HealthStatus = healthStatusInstance2;
}
JToken backupEngineTypeValue2 = propertiesValue["backupEngineType"];
if (backupEngineTypeValue2 != null && backupEngineTypeValue2.Type != JTokenType.Null)
{
string backupEngineTypeInstance2 = ((string)backupEngineTypeValue2);
azureBackupServerEngineInstance.BackupEngineType = backupEngineTypeInstance2;
}
JToken canReRegisterValue2 = propertiesValue["canReRegister"];
if (canReRegisterValue2 != null && canReRegisterValue2.Type != JTokenType.Null)
{
bool canReRegisterInstance2 = ((bool)canReRegisterValue2);
azureBackupServerEngineInstance.CanReRegister = canReRegisterInstance2;
}
JToken backupEngineIdValue2 = propertiesValue["backupEngineId"];
if (backupEngineIdValue2 != null && backupEngineIdValue2.Type != JTokenType.Null)
{
string backupEngineIdInstance2 = ((string)backupEngineIdValue2);
azureBackupServerEngineInstance.BackupEngineId = backupEngineIdInstance2;
}
backupEngineResourceInstance.Properties = azureBackupServerEngineInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
backupEngineResourceInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
backupEngineResourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
backupEngineResourceInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
backupEngineResourceInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
backupEngineResourceInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken eTagValue = valueValue["eTag"];
if (eTagValue != null && eTagValue.Type != JTokenType.Null)
{
string eTagInstance = ((string)eTagValue);
backupEngineResourceInstance.ETag = eTagInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
itemListInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace ManagedBass.Sfx
{
/// <summary>
/// BassSfx is an extention to the BASS audio library, providing a set of functions for rendering Sonique Visualization plugins or Winamp visualization plugins on a provided device context (hDC).
/// </summary>
public static class BassSfx
{
const string DllName = "bass_sfx";
[DllImport(DllName)]
static extern BassSfxError BASS_SFX_ErrorGetCode();
/// <summary>
/// Retrieves the error code for the most recent BASS_SFX function call.
/// </summary>
/// <returns>
/// If no error occured during the last BASS_SFX function call then BASS_SFX_OK is returned, else one of the <see cref="BassSfxError" /> values is returned.
/// See the function description for an explanation of what the error code means.
/// </returns>
public static BassSfxError LastError => BASS_SFX_ErrorGetCode();
/// <summary>
/// Frees all resources used by SFX.
/// </summary>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>This function should be called before your program exits.</remarks>
[DllImport(DllName, EntryPoint = "BASS_SFX_Free")]
public static extern bool Free();
[DllImport(DllName)]
static extern int BASS_SFX_GetVersion();
/// <summary>
/// Gets the version number of the bass_sfx.dll that is loaded.
/// </summary>
public static Version Version => Extensions.GetVersion(BASS_SFX_GetVersion());
/// <summary>
/// Initialize the SFX library. This will initialize the library for use.
/// </summary>
/// <param name="hInstance">Your application instance handle.</param>
/// <param name="hWnd">Your main windows form handle.</param>
/// <returns>If an error occurred then <see langword="false" /> is returned, else <see langword="true" /> is returned.</returns>
/// <remarks>
/// Call this method prior to any other BASS_SFX methods.
/// <para>Call <see cref="Free" /> to free all resources and before your program exits.</para>
/// </remarks>
/// <exception cref="BassSfxError.Already">Already initialized.</exception>
/// <exception cref="BassSfxError.Memory">There is insufficient memory.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_Init")]
public static extern bool Init(IntPtr hInstance, IntPtr hWnd);
/// <summary>
/// Calls the 'clicked' function of a Sonique visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="X">The x coordinate of the click relative to the top left of your visual window.</param>
/// <param name="Y">The y coordinate of the click relative to the top left of your visual window.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>
/// This function is only valid for Sonique Visualization plugins.
/// You must have created a plugin object using <see cref="PluginCreate" /> before you can use this function.
/// </remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="Errors.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginClicked")]
public static extern bool PluginClicked(int Handle, int X, int Y);
/// <summary>
/// Shows the configuration dialog window for the SFX plugin (Winamp only).
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginConfig")]
public static extern bool PluginConfig(int Handle);
/// <summary>
/// Creates a plugin object for use in the SFX.
/// </summary>
/// <param name="File">The filename and path of the plugin to load.</param>
/// <param name="hWnd">The handle of the window where the plugin is to be rendered.</param>
/// <param name="Width">The initial width for the plugins rendering window.</param>
/// <param name="Height">The initial height for the plugins rendering window.</param>
/// <param name="Flags">Any combination of <see cref="BassSfxFlags"/>.</param>
/// <returns>If successful, the new SFX plugin handle is returned, else 0 is returned.</returns>
/// <remarks>
/// Once you create a plugin using this function you can perform a number of different function calls on it.
/// The <paramref name="Width" /> and <paramref name="Height" /> parameters are only useful for BassBox, WMP, and Sonique plugins.
/// Winamp ignores these parameters so you can just pass in 0 for winamp plugins.
/// Windows Media Player plugins can be created using the full path to a dll file or by using the CLSID GUID from the registry.
/// <para>Mainly you might use the <see cref="PluginStart" />, <see cref="PluginSetStream" /> or <see cref="PluginRender" /> methods.</para>
/// </remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.FileOpen">Can't open the plugin file.</exception>
/// <exception cref="BassSfxError.Format">Unsupported plugin format.</exception>
/// <exception cref="BassSfxError.GUID">Can't open WMP plugin using specified GUID.</exception>
/// <exception cref="BassSfxError.Memory">There is insufficient memory.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginCreateW", CharSet = CharSet.Unicode)]
public static extern int PluginCreate(string File, IntPtr hWnd, int Width, int Height, BassSfxFlags Flags);
/// <summary>
/// Modifies and/or retrieves a plugin's flags.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Flags">Any combination of <see cref="BassSfxFlags"/>.</param>
/// <param name="Mask">The flags (as above) to modify. Flags that are not included in this are left as they are, so it can be set to 0 (<see cref="BassSfxFlags.Default" />) in order to just retrieve the current flags.</param>
/// <returns>If successful, the plugin's updated flags are returned, else -1 is returned. Use <see cref="LastError" /> to get the error code.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginFlags")]
public static extern BassSfxFlags PluginFlags(int Handle, BassSfxFlags Flags, BassSfxFlags Mask);
/// <summary>
/// Free a sonique visual plugin and resources from memory.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>It is very important to call this function after you are done using a plugin to avoid memory leaks.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginFree")]
public static extern bool PluginFree(int Handle);
/// <summary>
/// Gets the name of a loaded SFX plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, the name of the plugin is returned, else <see langword="null" /> is returned.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
public static string PluginGetName(int Handle)
{
return Marshal.PtrToStringUni(BASS_SFX_PluginGetNameW(Handle));
}
[DllImport(DllName)]
static extern IntPtr BASS_SFX_PluginGetNameW(int Handle);
/// <summary>
/// Get the type of visual plugin loaded.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, the type of plugin is returned.</returns>
/// <remarks>You must have created a plugin object using <see cref="PluginCreate" /> before you can use this function.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginGetType")]
public static extern BassSfxPlugin PluginGetType(int Handle);
/// <summary>
/// Gets the active module for a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, the active module (zero based index) is returned, else -1 is returned.</returns>
/// <remarks>
/// Visual plugins might provide multiple independent modules.
/// You might get the number of available modules with <see cref="PluginModuleGetCount" />.
/// However, you can only start/activate one module at a time for a certain visual plugin.
/// <para>Note: Sonique plugins only ever have 1 module. Winamp plugins can have multiple modules. So this call is really only useful for Winamp.</para>
/// </remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginModuleGetActive")]
public static extern int PluginModuleGetActive(int Handle);
/// <summary>
/// Gets the number of modules available in the visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, the number of modules is returned, else -1 is returned.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginModuleGetCount")]
public static extern int PluginModuleGetCount(int Handle);
/// <summary>
/// Returns the name of a certain module of a loaded visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Module">The module number to get the name from (the first module is 0).</param>
/// <returns>The name of the module on success or <see langword="null" /> on error (or if no module with that number exists).</returns>
/// <remarks>
/// Visual plugins might provide multiple independent modules.
/// You might get the number of available modules with <see cref="PluginModuleGetCount" />.
/// However, you can only start/activate one module at a time for a certain visual plugin.
/// <para>Note: Sonique plugins only ever have 1 module. Winamp plugins can have multiple modules. So this call is really only useful for Winamp.</para>
/// <para>You can use this method in a setup dialog to list all the available modules of a visual plugin.</para>
/// </remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
public static string PluginModuleGetName(int Handle, int Module)
{
return Marshal.PtrToStringUni(BASS_SFX_PluginModuleGetNameW(Handle, Module));
}
[DllImport(DllName)]
static extern IntPtr BASS_SFX_PluginModuleGetNameW(int Handle, int Module);
/// <summary>
/// Sets the active module for a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Module">The module number to set active (the first module is 0).</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>
/// Visual plugins might provide multiple independent modules.
/// You might get the number of available modules with <see cref="PluginModuleGetCount" />.
/// However, you can only start/activate one module at a time for a certain visual plugin.
/// <para>Note: Sonique plugins only ever have 1 module. Winamp plugins can have multiple modules. So this call is really only useful for Winamp.</para>
/// </remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginModuleSetActive")]
public static extern bool PluginModuleSetActive(int Handle, int Module);
/// <summary>
/// Renders a Sonique, BassBox or Windows Media Player visual plugin to a device context.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Channel">The BASS channel to render, can be a HSTREAM or HMUSIC handle.</param>
/// <param name="hDC">The device context handle of the control to which you want to render the plugin.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>Only for use with Sonique, BassBox or Windows Media Player plugins.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginRender")]
public static extern bool PluginRender(int Handle, int Channel, IntPtr hDC);
/// <summary>
/// Resizes a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Width">The new width of your visual window.</param>
/// <param name="Height">The new height of your visual window.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>You must have created a plugin object using <see cref="PluginCreate" /> before you can use this function.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginResize")]
public static extern bool PluginResize(int Handle, int Width, int Height);
/// <summary>
/// Resizes and moves a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Left">The new left location of your visual window.</param>
/// <param name="Top">The new top location of your visual window.</param>
/// <param name="Width">The new width of your visual window.</param>
/// <param name="Height">The new height of your visual window.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>You must have created a plugin object using <see cref="PluginCreate" /> before you can use this function.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginResizeMove")]
public static extern bool PluginResizeMove(int Handle, int Left, int Top, int Width, int Height);
/// <summary>
/// Sets a BASS channel on a SFX plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <param name="Channel">The BASS channel to render, can be a HSTREAM or HMUSIC handle.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginSetStream")]
public static extern bool PluginSetStream(int Handle, int Channel);
/// <summary>
/// Starts a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>Use <see cref="PluginStop" /> to stop a SFX plugin.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginStart")]
public static extern bool PluginStart(int Handle);
/// <summary>
/// Stops a visual plugin.
/// </summary>
/// <param name="Handle">The SFX plugin handle (as obtained by <see cref="PluginCreate" />).</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <remarks>Use <see cref="PluginStart" /> to start a SFX plugin.</remarks>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Handle">Invalid SFX handle.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_PluginStop")]
public static extern bool PluginStop(int Handle);
/// <summary>
/// Retrieves information on a registered windows media player plugin.
/// </summary>
/// <param name="Index">The plugin to get the information of... 0 = first.</param>
/// <param name="Info"><see cref="BassSfxPluginInfo" /> instance where to store the plugin information at.</param>
/// <returns>If successful, then <see langword="true" /> is returned, else <see langword="false" /> is returned.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
[DllImport(DllName, EntryPoint = "BASS_SFX_WMP_GetPluginW")]
public static extern bool WMPGetPlugin(int Index, out BassSfxPluginInfo Info);
/// <summary>
/// Retrieves information on a registered windows media player plugin.
/// </summary>
/// <param name="Index">The plugin to get the information of... 0 = first.</param>
/// <returns>An instance of the <see cref="BassSfxPluginInfo" /> on success, else <see langword="null" />.</returns>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
public static BassSfxPluginInfo WMPGetPlugin(int Index)
{
if (!WMPGetPlugin(Index, out var info))
throw new BassException();
return info;
}
/// <summary>
/// Returns the total number of WMP plugins currently available for use.
/// </summary>
/// <exception cref="BassSfxError.Init"><see cref="Init" /> has not been successfully called.</exception>
/// <exception cref="BassSfxError.Memory">Memory error.</exception>
/// <exception cref="BassSfxError.Unknown">Some other mystery problem!</exception>
public static int WMPGetPluginCount()
{
var i = 0;
while (WMPGetPlugin(i, out var info))
++i;
return i;
}
}
}
| |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Reactive.Testing;
using Neo4j.Driver.Reactive;
using Xunit;
using Xunit.Abstractions;
using static Neo4j.Driver.IntegrationTests.VersionComparison;
using static Neo4j.Driver.Reactive.Utils;
using static Neo4j.Driver.Tests.Assertions;
namespace Neo4j.Driver.IntegrationTests.Reactive
{
public class TransactionIT : AbstractRxIT
{
private const string BehaviourDifferenceWJavaDriver = "TODO: Behaviour Difference w/Java Driver";
private readonly IRxSession session;
public TransactionIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
: base(output, fixture)
{
session = NewSession();
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldCommitEmptyTx()
{
var bookmarkBefore = session.LastBookmark;
session.BeginTransaction()
.SelectMany(tx => tx.Commit<int>())
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
var bookmarkAfter = session.LastBookmark;
bookmarkBefore.Should().BeNull();
bookmarkAfter.Should().NotBe(bookmarkBefore);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldRollbackEmptyTx()
{
var bookmarkBefore = session.LastBookmark;
session.BeginTransaction()
.SelectMany(tx => tx.Rollback<int>())
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
var bookmarkAfter = session.LastBookmark;
bookmarkBefore.Should().BeNull();
bookmarkAfter.Should().Be(bookmarkBefore);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldRunStatementAndCommit()
{
session.BeginTransaction()
.SelectMany(txc =>
txc.Run("CREATE (n:Node {id: 42}) RETURN n")
.Records()
.Select(r => r["n"].As<INode>()["id"].As<int>())
.Concat(txc.Commit<int>())
.Catch(txc.Rollback<int>()))
.WaitForCompletion()
.AssertEqual(
OnNext(0, 42),
OnCompleted<int>(0));
CountNodes(42).Should().Be(1);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldRunStatementAndRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 4242);
VerifyCanRollback(txc);
CountNodes(4242).Should().Be(0);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsAndCommit()
{
return VerifyRunMultipleStatements(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsAndRollback()
{
return VerifyRunMultipleStatements(false);
}
private async Task VerifyRunMultipleStatements(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Records().SingleOrDefaultAsync();
var result2 = txc.Run("CREATE (n:Node {id : 2})");
await result2.Records().SingleOrDefaultAsync();
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result3.Records().SingleOrDefaultAsync();
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsWithoutWaitingAndCommit()
{
return VerifyRunMultipleStatementsWithoutWaiting(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsWithoutWaitingAndRollback()
{
return VerifyRunMultipleStatementsWithoutWaiting(false);
}
private async Task VerifyRunMultipleStatementsWithoutWaiting(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
var result2 = txc.Run("CREATE (n:Node {id : 2})");
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Records().Concat(result2.Records()).Concat(result3.Records()).SingleOrDefaultAsync();
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsWithoutStreamingAndCommit()
{
return VerifyRunMultipleStatementsWithoutStreaming(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleStatementsWithoutStreamingAndRollback()
{
return VerifyRunMultipleStatementsWithoutStreaming(false);
}
private async Task VerifyRunMultipleStatementsWithoutStreaming(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
var result2 = txc.Run("CREATE (n:Node {id : 2})");
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Keys().Concat(result2.Keys()).Concat(result3.Keys());
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterAFailedStatement()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongStatement(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0, MatchesException<ClientException>()));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldSucceedToRollbackAfterAFailedStatement()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongStatement(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterSuccessfulAndFailedStatements()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 5);
VerifyCanReturnOne(txc);
VerifyFailsWithWrongStatement(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0, MatchesException<ClientException>()));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldSucceedToRollbackAfterSuccessfulAndFailedStatements()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 5);
VerifyCanReturnOne(txc);
VerifyFailsWithWrongStatement(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldFailToRunAnotherStatementAfterAFailedOne()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongStatement(txc);
txc.Run("CREATE ()")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0,
Matches<Exception>(exc =>
exc.Message.Should().Contain("Cannot run statement in this transaction"))));
VerifyCanRollback(txc);
}
[RequireServerFact]
public void ShouldFailToBeginTxcWithInvalidBookmark()
{
Server.Driver
.RxSession(
o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(Bookmark.From("InvalidBookmark")))
.BeginTransaction()
.WaitForCompletion()
.AssertEqual(
OnError<IRxTransaction>(0,
Matches<Exception>(exc => exc.Message.Should().Contain("InvalidBookmark"))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotAllowCommitAfterCommit()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanCommit(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot commit this transaction, because it has already been committed."))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotAllowRollbackAfterRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanRollback(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot rollback this transaction, because it has already been rolled back."))));
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanRollback(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot commit this transaction, because it has already been rolled back."))));
}
[RequireServerFact]
public async Task ShouldFailToRollbackAfterCommit()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanCommit(txc);
txc.Rollback<string>()
.WaitForCompletion()
.AssertEqual(
OnError<string>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot rollback this transaction, because it has already been committed."))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldFailToRunStatementAfterCompletedTxcAndCommit()
{
return VerifyFailToRunStatementAfterCompletedTxc(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldFailToRunStatementAfterCompletedTxcAndRollback()
{
return VerifyFailToRunStatementAfterCompletedTxc(false);
}
private async Task VerifyFailToRunStatementAfterCompletedTxc(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 15);
VerifyCanCommitOrRollback(txc, commit);
CountNodes(15).Should().Be(commit ? 1 : 0);
txc.Run("CREATE ()")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0,
Matches<Exception>(exc => exc.Message.Should().Contain("Cannot run statement in this"))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldUpdateBookmark()
{
var bookmark1 = session.LastBookmark;
var txc1 = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc1, 20);
VerifyCanCommit(txc1);
var bookmark2 = session.LastBookmark;
var txc2 = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc2, 20);
VerifyCanCommit(txc2);
var bookmark3 = session.LastBookmark;
bookmark1.Should().BeNull();
bookmark2.Should().NotBe(bookmark1);
bookmark3.Should().NotBe(bookmark1).And.NotBe(bookmark2);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldPropagateFailuresFromStatements()
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (:TestNode) RETURN 1 as n");
var result2 = txc.Run("CREATE (:TestNode) RETURN 2 as n");
var result3 = txc.Run("RETURN 10 / 0 as n");
var result4 = txc.Run("CREATE (:TestNode) RETURN 3 as n");
Observable.Concat(
result1.Records(),
result2.Records(),
result3.Records(),
result4.Records())
.WaitForCompletion()
.AssertEqual(
OnNext(0, MatchesRecord(new[] {"n"}, 1)),
OnNext(0, MatchesRecord(new[] {"n"}, 2)),
OnError<IRecord>(0, Matches<Exception>(exc => exc.Message.Should().Contain("/ by zero"))));
VerifyCanRollback(txc);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotRunUntilSubscribed()
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("RETURN 1");
var result2 = txc.Run("RETURN 2");
var result3 = txc.Run("RETURN 3");
var result4 = txc.Run("RETURN 4");
Observable.Concat(
result4.Records(),
result3.Records(),
result2.Records(),
result1.Records())
.Select(r => r[0].As<int>())
.WaitForCompletion()
.AssertEqual(
OnNext(0, 4),
OnNext(0, 3),
OnNext(0, 2),
OnNext(0, 1),
OnCompleted<int>(0));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldNotPropagateFailureIfNotExecutedAndCommitted()
{
return VerifyNotPropagateFailureIfNotExecuted(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldNotPropagateFailureIfNotExecutedAndRollBacked()
{
return VerifyNotPropagateFailureIfNotExecuted(false);
}
private async Task VerifyNotPropagateFailureIfNotExecuted(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
txc.Run("RETURN ILLEGAL");
VerifyCanCommitOrRollback(txc, commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotPropagateRunFailureFromSummary()
{
var txc = await session.BeginTransaction().SingleAsync();
var result = txc.Run("RETURN Wrong");
result.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0, MatchesException<ClientException>()));
result.Summary()
.WaitForCompletion()
.AssertEqual(
OnNext(0, Matches<IResultSummary>(x => x.Should().NotBeNull())),
OnCompleted<IResultSummary>(0));
VerifyCanRollback(txc);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldHandleNestedQueries()
{
const int size = 1024;
var messages = session.BeginTransaction()
.SelectMany(txc =>
txc.Run("UNWIND range(1, $size) AS x RETURN x", new {size})
.Records()
.Select(r => r[0].As<int>())
.Buffer(50)
.SelectMany(x =>
txc.Run("UNWIND $x AS id CREATE (n:Node {id: id}) RETURN n.id", new {x}).Records())
.Select(r => r[0].As<int>())
.Concat(txc.Commit<int>())
.Catch((Exception exc) => txc.Rollback<int>().Concat(Observable.Throw<int>(exc))))
.WaitForCompletion()
.ToList();
messages.Should()
.HaveCount(size + 1).And
.NotContain(n => n.Value.Kind == NotificationKind.OnError);
}
private static void VerifyCanCommit(IRxTransaction txc)
{
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
private static void VerifyCanRollback(IRxTransaction txc)
{
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
private static void VerifyCanCommitOrRollback(IRxTransaction txc, bool commit)
{
if (commit)
{
VerifyCanCommit(txc);
}
else
{
VerifyCanRollback(txc);
}
}
private static void VerifyCanCreateNode(IRxTransaction txc, int id)
{
txc.Run("CREATE (n:Node {id: $id}) RETURN n", new {id})
.Records()
.Select(r => r["n"].As<INode>())
.SingleAsync()
.WaitForCompletion()
.AssertEqual(
OnNext(0, Matches<INode>(node => node.Should().BeEquivalentTo(new
{
Labels = new[] {"Node"},
Properties = new Dictionary<string, object>
{
{"id", (long) id}
}
}))),
OnCompleted<INode>(0));
}
private static void VerifyCanReturnOne(IRxTransaction txc)
{
txc.Run("RETURN 1")
.Records()
.Select(r => r[0].As<int>())
.WaitForCompletion()
.AssertEqual(
OnNext(0, 1),
OnCompleted<int>(0));
}
private static void VerifyFailsWithWrongStatement(IRxTransaction txc)
{
txc.Run("RETURN")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0, MatchesException<ClientException>(e => e.Code.Contains("SyntaxError"))));
}
private void VerifyCommittedOrRollbacked(bool commit)
{
if (commit)
{
CountNodes(1).Should().Be(2);
CountNodes(2).Should().Be(1);
}
else
{
CountNodes(1).Should().Be(0);
CountNodes(2).Should().Be(0);
}
}
private int CountNodes(int id)
{
return NewSession()
.Run("MATCH (n:Node {id: $id}) RETURN count(n)", new {id})
.Records()
.Select(r => r[0].As<int>())
.SingleAsync()
.Wait();
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="E06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="E07_RegionObjects"/> of type <see cref="E07_RegionColl"/> (1:M relation to <see cref="E08_Region"/>)<br/>
/// This class is an item of <see cref="E05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class E06_Country : BusinessBase<E06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
[NotUndoable]
[NonSerialized]
internal int parent_SubContinent_ID = 0;
#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 <see cref="ParentSubContinentID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "ParentSubContinentID");
/// <summary>
/// Gets or sets the ParentSubContinentID.
/// </summary>
/// <value>The ParentSubContinentID.</value>
public int ParentSubContinentID
{
get { return GetProperty(ParentSubContinentIDProperty); }
set { SetProperty(ParentSubContinentIDProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E07_Country_Child> E07_Country_SingleObjectProperty = RegisterProperty<E07_Country_Child>(p => p.E07_Country_SingleObject, "E07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E07 Country Single Object ("parent load" child property).
/// </summary>
/// <value>The E07 Country Single Object.</value>
public E07_Country_Child E07_Country_SingleObject
{
get { return GetProperty(E07_Country_SingleObjectProperty); }
private set { LoadProperty(E07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E07_Country_ReChild> E07_Country_ASingleObjectProperty = RegisterProperty<E07_Country_ReChild>(p => p.E07_Country_ASingleObject, "E07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E07 Country ASingle Object ("parent load" child property).
/// </summary>
/// <value>The E07 Country ASingle Object.</value>
public E07_Country_ReChild E07_Country_ASingleObject
{
get { return GetProperty(E07_Country_ASingleObjectProperty); }
private set { LoadProperty(E07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<E07_RegionColl> E07_RegionObjectsProperty = RegisterProperty<E07_RegionColl>(p => p.E07_RegionObjects, "E07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the E07 Region Objects ("parent load" child property).
/// </summary>
/// <value>The E07 Region Objects.</value>
public E07_RegionColl E07_RegionObjects
{
get { return GetProperty(E07_RegionObjectsProperty); }
private set { LoadProperty(E07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E06_Country"/> object.</returns>
internal static E06_Country NewE06_Country()
{
return DataPortal.CreateChild<E06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="E06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E06_Country"/> object.</returns>
internal static E06_Country GetE06_Country(SafeDataReader dr)
{
E06_Country obj = new E06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(E07_RegionObjectsProperty, E07_RegionColl.NewE07_RegionColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E06_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 E06_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="E06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(E07_Country_SingleObjectProperty, DataPortal.CreateChild<E07_Country_Child>());
LoadProperty(E07_Country_ASingleObjectProperty, DataPortal.CreateChild<E07_Country_ReChild>());
LoadProperty(E07_RegionObjectsProperty, DataPortal.CreateChild<E07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E06_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"));
LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID"));
_rowVersion = dr.GetValue("RowVersion") as byte[];
// parent properties
parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="E07_Country_Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(E07_Country_Child child)
{
LoadProperty(E07_Country_SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="E07_Country_ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(E07_Country_ReChild child)
{
LoadProperty(E07_Country_ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="E06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE06_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;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E06_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("UpdateE06_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;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", ReadProperty(ParentSubContinentIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="E06_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("DeleteE06_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(E07_Country_SingleObjectProperty, DataPortal.CreateChild<E07_Country_Child>());
LoadProperty(E07_Country_ASingleObjectProperty, DataPortal.CreateChild<E07_Country_ReChild>());
LoadProperty(E07_RegionObjectsProperty, DataPortal.CreateChild<E07_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
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.Base.HostedSolution;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.Portal.HostedSolution
{
public partial class UserGeneralSettings : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindServiceLevels();
BindSettings();
BindPicture();
MailboxTabsId.Visible = (PanelRequest.Context == "Mailbox");
UserTabsId.Visible = (PanelRequest.Context == "User");
pnlThumbnailphoto.Visible = (PanelRequest.Context == "Mailbox");
if (GetLocalizedString("buttonPanel.OnSaveClientClick") != null)
buttonPanel.OnSaveClientClick = GetLocalizedString("buttonPanel.OnSaveClientClick");
}
else
{
if (upThumbnailphoto.HasFile)
SavePicture(upThumbnailphoto.FileBytes);
}
}
private void BindPicture()
{
try
{
// get settings
OrganizationUser user = ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID,
PanelRequest.AccountID);
if ((user.AccountType== ExchangeAccountType.Mailbox) ||
(user.AccountType== ExchangeAccountType.Room) ||
(user.AccountType== ExchangeAccountType.SharedMailbox) ||
(user.AccountType== ExchangeAccountType.Equipment))
{
imgThumbnailphoto.Visible = true;
imgThumbnailphoto.ImageUrl = "~/DesktopModules/WebsitePanel/ThumbnailPhoto.ashx" + "?" + "ItemID=" + PanelRequest.ItemID +
"&AccountID=" + PanelRequest.AccountID;
}
else
{
imgThumbnailphoto.Visible = false;
}
}
catch { } // skip
}
private void BindSettings()
{
try
{
BindPasswordSettings();
// get settings
OrganizationUser user = ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID,
PanelRequest.AccountID);
litDisplayName.Text = PortalAntiXSS.Encode(user.DisplayName);
lblUserDomainName.Text = user.DomainUserName;
// bind form
txtDisplayName.Text = user.DisplayName;
chkDisable.Checked = user.Disabled;
txtFirstName.Text = user.FirstName;
txtInitials.Text = user.Initials;
txtLastName.Text = user.LastName;
txtJobTitle.Text = user.JobTitle;
txtCompany.Text = user.Company;
txtDepartment.Text = user.Department;
txtOffice.Text = user.Office;
manager.SetAccount(user.Manager);
txtBusinessPhone.Text = user.BusinessPhone;
txtFax.Text = user.Fax;
txtHomePhone.Text = user.HomePhone;
txtMobilePhone.Text = user.MobilePhone;
txtPager.Text = user.Pager;
txtWebPage.Text = user.WebPage;
txtAddress.Text = user.Address;
txtCity.Text = user.City;
txtState.Text = user.State;
txtZip.Text = user.Zip;
country.Country = user.Country;
txtNotes.Text = user.Notes;
txtExternalEmailAddress.Text = user.ExternalEmail;
txtExternalEmailAddress.Enabled = user.AccountType == ExchangeAccountType.User;
lblUserDomainName.Text = user.DomainUserName;
txtSubscriberNumber.Text = user.SubscriberNumber;
lblUserPrincipalName.Text = user.UserPrincipalName;
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (cntx.Quotas.ContainsKey(Quotas.EXCHANGE2007_ISCONSUMER))
{
if (cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue != 1)
{
locSubscriberNumber.Visible = false;
txtSubscriberNumber.Visible = false;
}
}
if (user.LevelId > 0 && secServiceLevels.Visible)
{
secServiceLevels.IsCollapsed = false;
ServiceLevel serviceLevel = ES.Services.Organizations.GetSupportServiceLevel(user.LevelId);
litServiceLevel.Visible = true;
litServiceLevel.Text = serviceLevel.LevelName;
litServiceLevel.ToolTip = serviceLevel.LevelDescription;
bool addLevel = ddlServiceLevels.Items.FindByValue(serviceLevel.LevelId.ToString()) == null;
addLevel = addLevel && cntx.Quotas.ContainsKey(Quotas.SERVICE_LEVELS + serviceLevel.LevelName);
addLevel = addLevel ? cntx.Quotas[Quotas.SERVICE_LEVELS + serviceLevel.LevelName].QuotaAllocatedValue != 0 : addLevel;
if (addLevel)
{
ddlServiceLevels.Items.Add(new ListItem(serviceLevel.LevelName, serviceLevel.LevelId.ToString()));
}
bool levelInDDL = ddlServiceLevels.Items.FindByValue(serviceLevel.LevelId.ToString()) != null;
if (levelInDDL)
{
ddlServiceLevels.Items.FindByValue(string.Empty).Selected = false;
ddlServiceLevels.Items.FindByValue(serviceLevel.LevelId.ToString()).Selected = true;
}
}
chkVIP.Checked = user.IsVIP && secServiceLevels.Visible;
imgVipUser.Visible = user.IsVIP && secServiceLevels.Visible;
if (cntx.Quotas.ContainsKey(Quotas.ORGANIZATION_ALLOWCHANGEUPN))
{
if (cntx.Quotas[Quotas.ORGANIZATION_ALLOWCHANGEUPN].QuotaAllocatedValue != 1)
{
lblUserPrincipalName.Visible = true;
upn.Visible = false;
ddlEmailAddresses.Visible = false;
btnSetUserPrincipalName.Visible = false;
chkInherit.Visible = false;
}
else
{
lblUserPrincipalName.Visible = false;
upn.Visible = false;
ddlEmailAddresses.Visible = false;
btnSetUserPrincipalName.Visible = true;
chkInherit.Visible = true;
if (user.AccountType == ExchangeAccountType.Mailbox)
{
ddlEmailAddresses.Visible = true;
WebsitePanel.EnterpriseServer.ExchangeEmailAddress[] emails = ES.Services.ExchangeServer.GetMailboxEmailAddresses(PanelRequest.ItemID, PanelRequest.AccountID);
foreach (WebsitePanel.EnterpriseServer.ExchangeEmailAddress mail in emails)
{
ListItem li = new ListItem();
li.Text = mail.EmailAddress;
li.Value = mail.EmailAddress;
li.Selected = mail.IsPrimary;
ddlEmailAddresses.Items.Add(li);
}
foreach (ListItem li in ddlEmailAddresses.Items)
{
if (li.Value == user.UserPrincipalName)
{
ddlEmailAddresses.ClearSelection();
li.Selected = true;
break;
}
}
}
else
{
upn.Visible = true;
if (!string.IsNullOrEmpty(user.UserPrincipalName))
{
string[] Tmp = user.UserPrincipalName.Split('@');
upn.AccountName = Tmp[0];
if (Tmp.Length > 1)
{
upn.DomainName = Tmp[1];
}
}
}
}
}
if (user.Locked)
chkLocked.Enabled = true;
else
chkLocked.Enabled = false;
chkLocked.Checked = user.Locked;
password.ValidationEnabled = true;
password.Password = string.Empty;
var settings = ES.Services.Organizations.GetWebDavSystemSettings();
btnResetUserPassword.Visible = settings != null && Utils.ParseBool(settings[EnterpriseServer.SystemSettings.WEBDAV_PASSWORD_RESET_ENABLED_KEY], false);
chkUserMustChangePassword.Checked = user.UserMustChangePassword;
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("ORGANIZATION_GET_USER_SETTINGS", ex);
}
}
private void BindServiceLevels()
{
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
OrganizationStatistics stats = ES.Services.Organizations.GetOrganizationStatisticsByOrganization(PanelRequest.ItemID);
if (cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels))
{
List<ServiceLevel> enabledServiceLevels = new List<ServiceLevel>();
foreach (var serviceLevel in ES.Services.Organizations.GetSupportServiceLevels())
{
if (CheckServiceLevelQuota(serviceLevel, stats.ServiceLevels))
{
enabledServiceLevels.Add(serviceLevel);
}
}
ddlServiceLevels.DataSource = enabledServiceLevels;
ddlServiceLevels.DataTextField = "LevelName";
ddlServiceLevels.DataValueField = "LevelId";
ddlServiceLevels.DataBind();
ddlServiceLevels.Items.Insert(0, new ListItem("<Select Service Level>", string.Empty));
ddlServiceLevels.Items.FindByValue(string.Empty).Selected = true;
secServiceLevels.Visible = true;
}
else { secServiceLevels.Visible = false; }
}
private void BindPasswordSettings()
{
var grainedPasswordSettigns = ES.Services.Organizations.GetOrganizationPasswordSettings(PanelRequest.ItemID);
if (grainedPasswordSettigns != null)
{
password.SetUserPolicy(grainedPasswordSettigns);
}
else
{
messageBox.ShowErrorMessage("UNABLETOLOADPASSWORDSETTINGS");
}
}
private bool CheckServiceLevelQuota(ServiceLevel serviceLevel, List<QuotaValueInfo> quotas)
{
var quota = quotas.FirstOrDefault(q => q.QuotaName.Replace(Quotas.SERVICE_LEVELS, "") == serviceLevel.LevelName);
if (quota == null)
return false;
if (quota.QuotaAllocatedValue == -1)
return true;
return quota.QuotaAllocatedValue > quota.QuotaUsedValue;
}
private void SaveSettings()
{
if (!Page.IsValid)
return;
try
{
int result = ES.Services.Organizations.SetUserGeneralSettings(
PanelRequest.ItemID, PanelRequest.AccountID,
txtDisplayName.Text,
string.Empty,
false,
chkDisable.Checked,
chkLocked.Checked,
txtFirstName.Text,
txtInitials.Text,
txtLastName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
txtZip.Text,
country.Country,
txtJobTitle.Text,
txtCompany.Text,
txtDepartment.Text,
txtOffice.Text,
manager.GetAccount(),
txtBusinessPhone.Text,
txtFax.Text,
txtHomePhone.Text,
txtMobilePhone.Text,
txtPager.Text,
txtWebPage.Text,
txtNotes.Text,
txtExternalEmailAddress.Text,
txtSubscriberNumber.Text,
string.IsNullOrEmpty(ddlServiceLevels.SelectedValue) ? 0 : int.Parse(ddlServiceLevels.SelectedValue),
chkVIP.Checked,
chkUserMustChangePassword.Checked);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
// update title
litDisplayName.Text = txtDisplayName.Text;
if (!chkLocked.Checked)
chkLocked.Enabled = false;
litServiceLevel.Visible = !string.IsNullOrEmpty(ddlServiceLevels.SelectedValue) && secServiceLevels.Visible;
if (litServiceLevel.Visible)
{
ServiceLevel serviceLevel = ES.Services.Organizations.GetSupportServiceLevel(int.Parse(ddlServiceLevels.SelectedValue));
litServiceLevel.Text = serviceLevel.LevelName;
litServiceLevel.ToolTip = serviceLevel.LevelDescription;
}
imgVipUser.Visible = chkVIP.Checked && secServiceLevels.Visible;
messageBox.ShowSuccessMessage("ORGANIZATION_UPDATE_USER_SETTINGS");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("ORGANIZATION_UPDATE_USER_SETTINGS", ex);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveSettings();
}
protected void btnSaveExit_Click(object sender, EventArgs e)
{
SaveSettings();
Response.Redirect(PortalUtils.EditUrl("ItemID", PanelRequest.ItemID.ToString(),
(PanelRequest.Context == "Mailbox") ? "mailboxes" : "users",
"SpaceID=" + PanelSecurity.PackageId));
}
protected void btnSetUserPrincipalName_Click(object sender, EventArgs e)
{
string userPrincipalName = string.Empty;
if (upn.Visible)
userPrincipalName = upn.Email;
else
if (ddlEmailAddresses.Visible)
userPrincipalName = (string)ddlEmailAddresses.SelectedValue;
if (string.IsNullOrEmpty(userPrincipalName)) return;
try
{
int result = ES.Services.Organizations.SetUserPrincipalName(
PanelRequest.ItemID, PanelRequest.AccountID,
userPrincipalName.ToLower(),
chkInherit.Checked);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
messageBox.ShowSuccessMessage("ORGANIZATION_SET_USER_USERPRINCIPALNAME");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("ORGANIZATION_SET_USER_USERPRINCIPALNAME", ex);
}
}
protected void btnSetUserPassword_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
try
{
int result = ES.Services.Organizations.SetUserPassword(
PanelRequest.ItemID, PanelRequest.AccountID,
password.Password);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
messageBox.ShowSuccessMessage("ORGANIZATION_SET_USER_PASSWORD");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("ORGANIZATION_SET_USER_PASSWORD", ex);
}
}
protected void btnResetUserPassword_Click(object sender, EventArgs e)
{
Response.Redirect(PortalUtils.EditUrl("ItemID", PanelRequest.ItemID.ToString(),
"user_reset_password",
"SpaceID=" + PanelSecurity.PackageId,
"Context=" + ((PanelRequest.Context == "Mailbox") ? "Mailbox" : "User"),
"AccountID=" + PanelRequest.AccountID));
}
private void SavePicture(byte[] picture)
{
try
{
ResultObject result = ES.Services.ExchangeServer.SetPicture(
PanelRequest.ItemID, PanelRequest.AccountID,
picture);
if (!result.IsSuccess)
{
messageBox.ShowErrorMessage("ORGANIZATION_UPDATE_USER_SETTINGS");
return;
}
messageBox.ShowSuccessMessage("ORGANIZATION_UPDATE_USER_SETTINGS");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("ORGANIZATION_UPDATE_USER_SETTINGS", ex);
}
BindPicture();
}
protected void btnClearThumbnailphoto_Click(object sender, EventArgs e)
{
SavePicture(null);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Xunit;
namespace ResourceGroups.Tests
{
public class LiveDeploymentTests : TestBase
{
const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js";
const string GoodWebsiteTemplateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/201-web-app-github-deploy/azuredeploy.json";
const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js";
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClientWithHandler(context, handler);
}
// TODO: Fix
[Fact (Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
JObject json = JObject.Parse(handler.Request);
Assert.NotNull(client.Deployments.Get(groupName, deploymentName));
}
}
[Fact()]
public void CreateDeploymentWithStringTemplateAndParameters()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json")),
Parameters = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account-parameters.json")),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deployment = client.Deployments.Get(groupName, deploymentName);
Assert.Equal("Succeeded", deployment.Properties.ProvisioningState);
}
}
[Fact]
public void CreateDeploymentAndValidateProperties()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(
@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
Assert.NotNull(deploymentCreateResult.Id);
Assert.Equal(deploymentName, deploymentCreateResult.Name);
TestUtilities.Wait(1000);
var deploymentListResult = client.Deployments.List(groupName, null);
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
}
}
[Fact]
public void ValidateGoodDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csres");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
//TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ValidateGoodDeploymentWithInlineTemplate()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
Template = File.ReadAllText(Path.Combine("ScenarioTests", "good-website.json")),
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
//Action
var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters);
//Assert
Assert.Null(validationResult.Error);
Assert.NotNull(validationResult.Properties);
Assert.NotNull(validationResult.Properties.Providers);
Assert.Equal(1, validationResult.Properties.Providers.Count);
Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty);
}
}
[Fact]
public void ValidateBadDeployment()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = BadTemplateUri,
},
Parameters =
JObject.Parse(@"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
var result = client.Deployments.Validate(groupName, deploymentName, parameters);
Assert.NotNull(result);
Assert.Equal("InvalidTemplate", result.Error.Code);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void CreateDummyDeploymentProducesOperations()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
var dictionary = new Dictionary<string, object> {
{"string", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"securestring", new Dictionary<string, object>() {
{"value", "myvalue"},
}},
{"int", new Dictionary<string, object>() {
{"value", 42},
}},
{"bool", new Dictionary<string, object>() {
{"value", true},
}}
};
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = DummyTemplateUri
},
Parameters = dictionary,
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
string resourceName = TestUtilities.GenerateName("csmr");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
Assert.NotNull(operations.First().Id);
Assert.NotNull(operations.First().OperationId);
Assert.NotNull(operations.First().Properties);
}
}
// TODO: Fix
[Fact(Skip = "TODO: Re-record test")]
public void ListDeploymentsWorksWithFilter()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
string resourceName = TestUtilities.GenerateName("csmr");
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse(@"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'siteLocation': {'value': 'westus'}, 'sku': {'value': 'Standard'}}"),
Mode = DeploymentMode.Incremental,
}
};
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
var deploymentListResult = client.Deployments.List(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Running"));
if (null == deploymentListResult|| deploymentListResult.Count() == 0)
{
deploymentListResult = client.Deployments.List(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Accepted"));
}
var deploymentGetResult = client.Deployments.Get(groupName, deploymentName);
Assert.NotEmpty(deploymentListResult);
Assert.Equal(deploymentName, deploymentGetResult.Name);
Assert.Equal(deploymentName, deploymentListResult.First().Name);
Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri);
Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri);
Assert.NotNull(deploymentGetResult.Properties.ProvisioningState);
Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState);
Assert.NotNull(deploymentGetResult.Properties.CorrelationId);
Assert.NotNull(deploymentListResult.First().Properties.CorrelationId);
Assert.True(deploymentGetResult.Properties.Parameters.ToString().Contains("mctest0101"));
Assert.True(deploymentListResult.First().Properties.Parameters.ToString().Contains("mctest0101"));
}
}
[Fact]
public void CreateLargeWebDeploymentTemplateWorks()
{
var handler = new RecordedDelegatingHandler();
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceName = TestUtilities.GenerateName("csmr");
string groupName = TestUtilities.GenerateName("csmrg");
string deploymentName = TestUtilities.GenerateName("csmd");
var client = GetResourceManagementClient(context, handler);
var parameters = new Deployment
{
Properties = new DeploymentProperties()
{
TemplateLink = new TemplateLink
{
Uri = GoodWebsiteTemplateUri,
},
Parameters =
JObject.Parse("{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'hostingPlanName': {'value': 'someplan'}, 'sku': {'value': 'F1'}}"),
Mode = DeploymentMode.Incremental,
}
};
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "South Central US" });
client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);
// Wait until deployment completes
TestUtilities.Wait(30000);
var operations = client.DeploymentOperations.List(groupName, deploymentName, null);
Assert.True(operations.Any());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ALang
{
public sealed class ElementResultType
{
public List<LanguageType> ResultTypes;
public static ElementResultType Create(params LanguageType[] elements)
{
return new ElementResultType {ResultTypes = elements.ToList()};
}
public static ElementResultType Create(IEnumerable<LanguageType> elements)
{
return new ElementResultType {ResultTypes = elements.ToList()};
}
}
public abstract class ValueElement : TreeElement
{
public abstract int NumberOfBranches { get; }
public bool IsGet
{
get { return m_isGet; }
set
{
m_isGet = value;
foreach (var child in m_children)
{
((ValueElement) child).IsGet = value;
}
}
}
public bool IsSet
{
get { return m_isSet; }
set
{
m_isSet = value;
foreach (var child in m_children)
{
((ValueElement) child).IsSet = value;
}
}
}
public ElementResultType ResultType
{
get
{
if (m_result == null)
{
UpdateResultType();
}
return m_result;
}
protected set { m_result = value; }
}
public virtual void GenerateForBranch(Generator generator, int branch)
{
}
public void UpdateResultType()
{
foreach (ValueElement elem in Children<ValueElement>())
{
elem.UpdateResultType();
}
DoUpdateResultType();
}
protected abstract void DoUpdateResultType();
private ElementResultType m_result = null;
private bool m_isGet = false;
private bool m_isSet = false;
}
public class ConstValElement : ValueElement
{
public override int NumberOfBranches
{
get { return 1; }
}
public override bool IsCompileTime
{
get { return true; }
}
public string Type { get; set; }
public string Value
{
get { return m_value; }
set
{
m_value = value;
if(LanguageSymbols.Instance != null)
{
UpdateResultType();
}
}
}
public override void GenerateForBranch(Generator generator, int branch)
{
var valContainer = new StringToValue {TypeName = Type, StringVal = Value};
generator.AddOp(GenCodes.Push, 2,
ByteConverter.New()
.CastInt32(LanguageSymbols.Instance.GetTypeSize(Type))
.CastValueContainer(valContainer)
.Bytes);
}
public override void GenerateInstructions(Generator generator)
{
GenerateForBranch(generator, -1);
}
public override void PrepareBeforeGenerate()
{
UpdateResultType();
}
protected override void DoUpdateResultType()
{
Type = LanguageSymbols.Instance.GetTypeOfConstVal(m_value);
ResultType = ElementResultType.Create(LanguageSymbols.Instance.GetTypeByName(Type));
}
private string m_value;
}
public class GetVariableElement : ValueElement
{
public enum GenerateOptions
{
Address, Value
};
public override int NumberOfBranches
{
get { return 1; }
}
public string VarType
{
get { return m_varType; }
set
{
m_varType = value;
UpdateResultType();
}
}
public string VarName { get; set; }
public GenerateOptions ResultOfGeneration { get; set; }
public override void GenerateForBranch(Generator generator, int branch)
{
if (ResultOfGeneration == GenerateOptions.Value)
{
generator.AddOp(GenCodes.GetLVarVal, 2,
ByteConverter.New()
.CastInt32(generator.GetLocalVarAddress(VarType, VarName))
.CastInt32(LanguageSymbols.Instance.GetTypeSize(VarType))
.Bytes);
}
else
{
generator.AddOp(GenCodes.PushVarAddress, 1,
ByteConverter.New()
.CastInt64(generator.GetLocalVarAddress(VarType, VarName))
.Bytes);
}
}
public override void GenerateInstructions(Generator generator)
{
GenerateForBranch(generator, -1);
}
public override void PrepareBeforeGenerate()
{
var funcElem = RootParent<FunctionElement>();
var variable = funcElem.GetVariable(VarName);
Compilation.Assert(variable != null, $"Variable '{VarName}' isn't exist", -1);
if (variable != null)
{
VarType = variable.VarType;
}
else
{
Compilation.WriteCritical($"Variable '{VarName}' doesn't exist");
}
UpdateResultType();
}
protected override void DoUpdateResultType()
{
ResultType = ElementResultType.Create(LanguageSymbols.Instance.GetTypeByName(VarType));
}
private string m_varType;
}
public class FunctionCallElement : ValueElement
{
public override int NumberOfBranches
{
get { return CallArguments.Count; }
}
public override int RequiredSpaceInLocals
{
get { return m_returnTypesSize.Aggregate((l, r) => l + r); }
}
public LanguageFunction FunctionInfo
{
get { return m_langFunction; }
set
{
m_langFunction = value;
UpdateResultType();
}
}
public List<ValueElement> CallArguments { get; set; }
public override void GenerateForBranch(Generator generator, int branch)
{
if (!m_isGenerateCalled)
{
foreach (ValueElement i in CallArguments)
{
i.GenerateForBranch(generator, -1);
}
generator.AddOp(GenCodes.CallFunc, 2, ByteConverter
.New()
.CastInt32(generator.GetFunctionAddress(FunctionInfo.BuildName))
.CastInt32(
FunctionInfo.Arguments.Select(arg =>
LanguageSymbols
.Instance
.GetTypeSize(arg.TypeInfo.Name))
.Aggregate(0, (val1, val2) => val1 + val2)
)
.Bytes);
int addressOffset = RequiredSpaceInLocals;
foreach (var retTypeSize in m_returnTypesSize)
{
addressOffset -= retTypeSize;
generator.AddOp(GenCodes.ConvertAddressSetTempVar, 1,
ByteConverter.New().CastInt32(addressOffset).CastInt32(retTypeSize).Bytes);
}
}
m_isGenerateCalled = true;
if (branch != -1 && FunctionInfo.ReturnTypes.Count > 0)
{
int offset = 0;
for (int i = 0; i < branch; ++i)
{
offset += m_returnTypesSize[i];
}
generator.AddOp(GenCodes.ConvertAddressGetTempVar, 2,
ByteConverter.New()
.CastInt32(offset)
.CastInt32(m_returnTypesSize[branch])
.Bytes);
}
}
public override void PrepareBeforeGenerate()
{
CallArguments.ForEach(arg => arg.IsGet = true);
UpdateResultType();
}
public override void CleanUpStatement(Generator generator)
{
}
public override void GenerateInstructions(Generator generator)
{
GenerateForBranch(generator, -1);
}
protected override void DoUpdateResultType()
{
ResultType = ElementResultType.Create(FunctionInfo.ReturnTypes);
m_returnTypesSize = (from retType in FunctionInfo.ReturnTypes
select LanguageSymbols.Instance.GetTypeSize(retType.Name)).ToList();
}
private LanguageFunction m_langFunction;
List<int> m_returnTypesSize;
private bool m_isGenerateCalled;
}
public class MultipleValElement : ValueElement
{
public override int NumberOfBranches
{
get { return m_values.Count; }
}
public override int RequiredSpaceInLocals
{
get { return m_values.Max(val => val.RequiredSpaceInLocals); }
}
public void AddValue(ValueElement elem)
{
m_values.Add(elem);
AddChild(elem);
}
public List<ValueElement> GetValues()
{
return m_values;
}
public override void PrepareBeforeGenerate()
{
m_values = Children<ValueElement>().ToList();
UpdateResultType();
}
public override void GenerateForBranch(Generator generator, int branch)
{
m_values[branch].GenerateForBranch(generator, 0);
}
public override void GenerateInstructions(Generator generator)
{
for (var index = 0; index < m_values.Count; index++)
{
GenerateForBranch(generator, index);
++index;
}
}
protected override void DoUpdateResultType()
{
ResultType = ElementResultType.Create(m_values.Select(val => val.ResultType.ResultTypes[0]));
}
private List<ValueElement> m_values = new List<ValueElement>();
}
public class VarDeclarationElement : TreeElement
{
public string VarType;
public string VarName;
public bool IgnoreInitialization;
public ValueElement InitVal;
public override void PrepareBeforeGenerate()
{
if (IgnoreInitialization)
return;
InitVal.IsGet = true;
}
public override void GenerateInstructions(Generator generator)
{
if (IgnoreInitialization)
{
return;
}
InitVal.GenerateInstructions(generator);
generator.AddOp(GenCodes.NewLVar, 2,
ByteConverter.New()
.CastInt32(generator.GetLocalVarAddress(VarType, VarName))
.CastInt32(LanguageSymbols.Instance.GetTypeSize(VarType))
.Bytes);
}
public void GenLowLevelDelete(Generator generator)
{
}
}
public class MultipleVarDeclarationElement : TreeElement
{
public override void GenerateInstructions(Generator generator)
{
foreach (var i in Vars)
{
i.GenerateInstructions(generator);
}
}
public void AddVar(VarDeclarationElement elem)
{
Vars.Add(elem);
AddChild(elem);
}
public VarDeclarationElement GetVar(int i)
{
return Vars[i];
}
public List<VarDeclarationElement> GetVars()
{
return Vars; //TODO: AsReadOnly
}
private List<VarDeclarationElement> Vars = new List<VarDeclarationElement>();
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal class MidObj
{
public int i;
public Object parent;
public MidObj(int _i, Object obj)
{
i = _i;
parent = obj;
}
}
internal class MiddlePin
{
public byte[] smallNonePinned; // this is very small, 3 or 4 ptr size
public byte[] pinnedObj; // this is very small as well, 3 or 4 ptr size
public byte[] nonePinned; // this is variable size
}
internal class MyRequest
{
public GCHandle pin;
public MidObj[] mObj;
public byte[] obj;
private bool _is_pinned;
private static int s_count;
// We distinguish between permanent and mid so we can free Mid and
// influence the demotion effect. If Mid is a lot, we will hit
// demotion; otherwise they will make into gen2.
public MyRequest(int sizePermanent, int sizeMid, bool pinned)
{
if ((s_count % 32) == 0)
{
sizePermanent = 1;
sizeMid = 1;
}
mObj = new MidObj[sizeMid];
mObj[0] = new MidObj(s_count, this);
obj = new byte[sizePermanent];
FillInPin(obj);
_is_pinned = pinned;
if (pinned)
{
pin = GCHandle.Alloc(obj, GCHandleType.Pinned);
}
s_count++;
}
private void FillInPin(byte[] pinnedObj)
{
int len = pinnedObj.Length;
int lenToFill = 10;
if (lenToFill > len)
{
lenToFill = len - 1;
}
for (int i = 0; i < lenToFill; i++)
{
obj[len - i - 1] = (byte)(0x11 * i);
}
}
public void Free()
{
if (_is_pinned)
{
lock (this)
{
if (_is_pinned)
{
pin.Free();
_is_pinned = false;
}
}
}
}
}
internal class MemoryAlloc
{
private MyRequest[] _old = null;
private MyRequest[] _med = null;
private int _num_old_data = 2000;
private int _num_med_data = 200;
private int _mean_old_alloc_size = 1000;
private int _mean_med_alloc_size = 300;
private int _mean_young_alloc_size = 60;
private int _old_time = 3;
private int _med_time = 2;
private int _young_time = 1;
private int _index = 0;
private int _iter_count = 0;
private Rand _rand;
// pinning 10%.
private double _pinRatio = 0.1;
private double _fragRatio = 0.2;
public MemoryAlloc(int iter, Rand _rand, int i)
{
_iter_count = iter;
if (_iter_count == 0)
_iter_count = 1000;
this._rand = _rand;
_index = i;
}
public void RunTest()
{
AllocTest();
SteadyState();
}
public void CreateFragmentation()
{
int iFreeInterval = (int)((double)1 / _fragRatio);
//Console.WriteLine("{0}: Freeing approx every {1} object", index, iFreeInterval);
int iNextFree = _rand.getRand(iFreeInterval) + 1;
int iFreedObjects = 0;
int iGen2Objects = 0;
for (int j = 0; j < _old.Length; j++)
{
//int iGen = GC.GetGeneration(old[j].mObj);
int iGen = _rand.getRand(3);
//Console.WriteLine("old[{0}] is in gen{1}", j, iGen);
if (iGen == 2)
{
iGen2Objects++;
if (iGen2Objects == iNextFree)
{
iFreedObjects++;
if (_old[j].mObj == null)
{
//Console.WriteLine("old[{0}].mObj is null", j);
}
else
{
int iLen = _old[j].mObj.Length;
_old[j].mObj = new MidObj[iLen];
}
int inc = _rand.getRand(iFreeInterval) + 1;
iNextFree += inc;
}
}
}
// Console.WriteLine("there are {0} gen2 objects (total {1}), freed {2}",
// iGen2Objects, old.Length, iFreedObjects);
}
// This pins every few objects (defined by pinRatio) in the old array.
// med is just created with non pinned.
public void AllocTest()
{
// Console.WriteLine(index + ": Allocating memory - old: " + num_old_data + "[~" + mean_old_alloc_size + "]; med: "
// + num_med_data + "[~" + mean_med_alloc_size + "]");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
_old = new MyRequest[_num_old_data];
_med = new MyRequest[_num_med_data];
bool fIsPinned = false;
int iPinInterval = (int)((double)1 / _pinRatio);
//Console.WriteLine("Pinning approx every {0} object", iPinInterval);
int iPinnedObject = 0;
int iPinnedMidSize = 0;
//int iNextPin = iPinInterval / 5 + rand.getRand(iPinInterval);
int iNextPin = _rand.getRand(iPinInterval * 4) + 1;
//Console.WriteLine("Pin object {0}", iNextPin);
for (int j = 0; j < _old.Length; j++)
{
//old [j] = new byte [GetSizeRandom (mean_old_alloc_size)];
if (j == iNextPin)
{
fIsPinned = true;
//iNextPin = j + iPinInterval / 5 + rand.getRand(iPinInterval);
iNextPin = j + _rand.getRand(iPinInterval * 4) + 1;
//Console.WriteLine("Pin object {0}", iNextPin);
}
else
{
fIsPinned = false;
}
iPinnedMidSize = _mean_old_alloc_size * 2;
if (fIsPinned)
{
iPinnedObject++;
if ((iPinnedObject % 10) == 0)
{
iPinnedMidSize = _mean_old_alloc_size * 10;
//Console.WriteLine("{0}th pinned object, non pin size is {1}", iPinnedObject, iPinnedMidSize);
}
else
{
//Console.WriteLine("{0}th pinned object, non pin size is {1}", iPinnedObject, iPinnedMidSize);
}
}
//Console.WriteLine("item {0}: {1}, pin size: {2}, non pin size: {3}", j, (fIsPinned ? "pinned" : "not pinned"), mean_old_alloc_size, iPinnedMidSize);
byte[] temp = new byte[_mean_med_alloc_size * 3];
_old[j] = new MyRequest(_mean_old_alloc_size, iPinnedMidSize, fIsPinned);
//if ((j % (old.Length / 10)) == 0)
//{
// Console.WriteLine("{0}: allocated {1} on old array, {2}ms elapsed, Heap size {3}, gen0: {4}, gen1: {5}, gen2: {6})",
// index,
// j,
// (int)stopwatch.Elapsed.TotalMilliseconds,
// GC.GetTotalMemory(false),
// GC.CollectionCount(0),
// GC.CollectionCount(1),
// GC.CollectionCount(2));
//}
}
//Console.WriteLine("pinned {0} objects out of {1}", iPinnedObject, old.Length);
{
// Console.WriteLine("{0}: allocated {1} on old array, {2}ms elapsed, Heap size {3}, gen0: {4}, gen1: {5}, gen2: {6})",
// index,
// old.Length,
// (int)stopwatch.Elapsed.TotalMilliseconds,
// GC.GetTotalMemory(false),
// GC.CollectionCount(0),
// GC.CollectionCount(1),
// GC.CollectionCount(2));
}
for (int j = 0; j < _med.Length; j++)
{
//med [j] = new byte [GetSizeRandom (mean_med_alloc_size)];
_med[j] = new MyRequest(_mean_med_alloc_size, (_mean_med_alloc_size * 2), false);
}
stopwatch.Stop();
// Console.WriteLine ("{0}: startup: {1:d} seconds({2:d} ms. Heap size {3})",
// index, (int)stopwatch.Elapsed.TotalSeconds, (int)stopwatch.Elapsed.TotalMilliseconds,
// GC.GetTotalMemory(false));
}
public void SteadyState()
{
Console.WriteLine(_index + ": replacing old every " + _old_time + "; med every " + _med_time + ";creating young " + _young_time + "times ("
+ "(size " + _mean_young_alloc_size + ")");
Console.WriteLine("iterating {0} times", _iter_count);
int iter_interval = _iter_count / 10;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
//int lastGen2Count = 0;
int lastGen1Count = 0;
int checkInterval = _old.Length / 10;
int lastChecked = 0;
int iCheckedEnd = 0;
int timeoutInterval = 5;
double pinRatio = 0.1;
bool fIsPinned = false;
int iPinInterval = (int)((double)1 / pinRatio);
Console.WriteLine("Pinning every {0} object", iPinInterval);
int iNextPin = _rand.getRand(iPinInterval * 4) + 1;
int iPinnedObject = 0;
int iPinnedMidSize = _mean_old_alloc_size * 2;
int countObjects = 0;
int countObjectsGen1 = 0;
int[] countWithGen = new int[3];
MiddlePin[] steadyPinningArray = new MiddlePin[100];
GCHandle[] steadyPinningHandles = new GCHandle[100];
int steadyPinningIndex = 0;
for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++)
{
steadyPinningArray[steadyPinningIndex] = new MiddlePin();
steadyPinningHandles[steadyPinningIndex] = new GCHandle();
}
for (int j = 0; j < _iter_count; j++)
{
if (steadyPinningIndex >= steadyPinningArray.Length)
{
steadyPinningIndex = 0;
// Console.WriteLine("steady array wrapped, press enter to continue");
// Console.ReadLine();
}
byte[] tempObj = new byte[1];
steadyPinningArray[steadyPinningIndex].smallNonePinned = new byte[8];
steadyPinningArray[steadyPinningIndex].pinnedObj = new byte[8];
steadyPinningArray[steadyPinningIndex].nonePinned = new byte[24];
steadyPinningHandles[steadyPinningIndex] = GCHandle.Alloc(steadyPinningArray[steadyPinningIndex].pinnedObj, GCHandleType.Pinned);
steadyPinningArray[steadyPinningIndex].smallNonePinned[3] = 0x31;
steadyPinningArray[steadyPinningIndex].smallNonePinned[5] = 0x51;
steadyPinningArray[steadyPinningIndex].smallNonePinned[7] = 0x71;
steadyPinningArray[steadyPinningIndex].pinnedObj[3] = 0x21;
steadyPinningArray[steadyPinningIndex].pinnedObj[5] = 0x41;
steadyPinningArray[steadyPinningIndex].pinnedObj[7] = 0x61;
tempObj = new byte[256];
steadyPinningIndex++;
countObjects = 0;
countObjectsGen1 = 0;
iCheckedEnd = lastChecked + checkInterval;
if (iCheckedEnd > _old.Length)
{
iCheckedEnd = _old.Length;
}
//Console.WriteLine("timing out item {0} to {1}", lastChecked, iCheckedEnd);
// time out requests in this range.
// for the range we are looking at time out requests (ie, end them and replace them with new ones).
// we go from the beginning of the range to the end, time out every Nth one; then time out everyone
// after that, and so on.
for (int iIter = 0; iIter < timeoutInterval; iIter++)
{
for (int iCheckIndex = 0; iCheckIndex < ((iCheckedEnd - lastChecked) / timeoutInterval); iCheckIndex++)
{
int iItemIndex = (lastChecked + iCheckIndex * timeoutInterval + iIter) % _old.Length;
// Console.WriteLine("replacing item {0}", iItemIndex);
_old[iItemIndex].Free();
countObjects++;
if ((countObjects % 10) == 0)
{
byte[] temp = new byte[_mean_med_alloc_size * 3];
temp[0] = (byte)27; // 0x1b
}
else if ((countObjects % 4) == 0)
{
byte[] temp = new byte[1];
temp[0] = (byte)27; // 0x1b
}
if (countObjects == iNextPin)
{
fIsPinned = true;
iNextPin += _rand.getRand(iPinInterval * 4) + 1;
}
else
{
fIsPinned = false;
}
iPinnedMidSize = _mean_old_alloc_size * 2;
if (fIsPinned)
{
iPinnedObject++;
if ((iPinnedObject % 10) == 0)
{
iPinnedMidSize = _mean_old_alloc_size * 10;
}
}
//Console.WriteLine("perm {0}, mid {1}, {2}", mean_old_alloc_size, iPinnedMidSize, (fIsPinned ? "pinned" : "not pinned"));
_old[iItemIndex] = new MyRequest(_mean_old_alloc_size, iPinnedMidSize, fIsPinned);
}
}
for (int i = 0; i < 3; i++)
{
countWithGen[i] = 0;
}
// Console.WriteLine("Checking {0} to {1}", lastChecked, iCheckedEnd);
for (int iItemIndex = lastChecked; iItemIndex < iCheckedEnd; iItemIndex++)
{
//int iGen = GC.GetGeneration(old[iItemIndex].mObj);
int iGen = _rand.getRand(3);
countWithGen[iGen]++;
if (iGen == 1)
{
//Console.WriteLine("item {0} is in gen1, getting rid of it", iItemIndex);
if ((countObjectsGen1 % 5) == 0)
_old[iItemIndex].mObj = null;
countObjectsGen1++;
}
}
// Console.WriteLine("{0} in gen0, {1} in gen1, {2} in gen2",
// countWithGen[0],
// countWithGen[1],
// countWithGen[2]);
//
// Console.WriteLine("{0} objects out of {1} are in gen1", countObjectsGen1, (iCheckedEnd - lastChecked));
if (iCheckedEnd == _old.Length)
{
lastChecked = 0;
}
else
{
lastChecked += checkInterval;
}
int currentGen1Count = GC.CollectionCount(1);
if ((currentGen1Count - lastGen1Count) > 30)
{
GC.Collect(2, GCCollectionMode.Forced, false);
Console.WriteLine("{0}: iter {1}, heap size: {2}", _index, j, GC.GetTotalMemory(false));
lastGen1Count = currentGen1Count;
}
}
for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++)
{
if (steadyPinningHandles[steadyPinningIndex].IsAllocated)
steadyPinningHandles[steadyPinningIndex].Free();
}
stopwatch.Stop();
Console.WriteLine("{0}: steady: {1:d} seconds({2:d} ms. Heap size {3})",
_index, (int)stopwatch.Elapsed.TotalSeconds, (int)stopwatch.Elapsed.TotalMilliseconds,
GC.GetTotalMemory(false));
}
}
internal class FreeListTest
{
private static int s_iLastGen0Count;
private static int s_iLastGen1Count;
private static void InducedGen2()
{
int iCurrentGen0Count = GC.CollectionCount(0);
if ((iCurrentGen0Count - s_iLastGen0Count) > 50)
{
//Console.WriteLine("we've done {0} gen0 GCs, inducing a gen2", (iCurrentGen0Count - iLastGen0Count));
s_iLastGen0Count = iCurrentGen0Count;
GC.Collect(2, GCCollectionMode.Forced, false);
//GC.Collect(2);
}
int iCurrentGen1Count = GC.CollectionCount(1);
if ((iCurrentGen1Count - s_iLastGen1Count) > 10)
{
//Console.WriteLine("we've done {0} gen1 GCs, inducing a gen2", (iCurrentGen1Count - iLastGen1Count));
s_iLastGen1Count = iCurrentGen1Count;
GC.Collect(2, GCCollectionMode.Forced, false);
}
}
public static int Main(String[] args)
{
if (GCSettings.IsServerGC == true)
{
Console.WriteLine("we are using server GC");
}
int iter_num = 500000;
if (args.Length >= 1)
{
iter_num = int.Parse(args[0]);
Console.WriteLine("iterating {0} times", iter_num);
}
// ProjectN doesn't support thread! for now just do everything on the main thread.
//int threadCount = 8;
// int threadCount = 1;
// if (args.Length >= 2)
// {
// threadCount = int.Parse(args[1]);
// Console.WriteLine ("creating {0} threads", threadCount);
// }
long tStart, tEnd;
tStart = Environment.TickCount;
// MyThread t;
// ThreadStart ts;
// Thread[] threads = new Thread[threadCount];
//
// for (int i = 0; i < threadCount; i++)
// {
// t = new MyThread(i, iter_num, old, med);
// ts = new ThreadStart(t.TimeTest);
// threads[i] = new Thread( ts );
// threads[i].Start();
// }
//
// for (int i = 0; i < threadCount; i++)
// {
// threads[i].Join();
// }
//
Console.WriteLine("start with {0} gen1 GCs", s_iLastGen1Count);
s_iLastGen0Count = GC.CollectionCount(0);
s_iLastGen1Count = GC.CollectionCount(1);
for (int iter = 0; iter < 1; iter++)
{
MemoryAlloc[] maArr = new MemoryAlloc[16];
Rand rand = new Rand();
for (int i = 0; i < maArr.Length; i++)
{
maArr[i] = new MemoryAlloc(rand.getRand(500), rand, i);
maArr[i].AllocTest();
//Console.WriteLine("{0} allocated", i);
InducedGen2();
for (int iAllocated = 0; iAllocated < i; iAllocated++)
{
//Console.WriteLine("creating fragmentation in obj {0}", iAllocated);
maArr[iAllocated].CreateFragmentation();
InducedGen2();
}
}
for (int i = 0; i < maArr.Length; i++)
{
InducedGen2();
Console.WriteLine("steady state for " + i);
maArr[i].SteadyState();
Console.WriteLine("DONE: steady state for " + i);
}
}
tEnd = Environment.TickCount;
Console.WriteLine("Test completed; " + (tEnd - tStart) + "ms");
// Console.WriteLine("Press any key to exit.");
// Console.ReadLine();
return 100;
}
};
internal sealed class Rand
{
/* Generate Random numbers
*/
private int _x = 0;
public int getRand()
{
_x = (314159269 * _x + 278281) & 0x7FFFFFFF;
return _x;
}
// obtain random number in the range 0 .. r-1
public int getRand(int r)
{
// require r >= 0
int x = (int)(((long)getRand() * r) >> 31);
return x;
}
public double getFloat()
{
return (double)getRand() / (double)0x7FFFFFFF;
}
};
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace Apache.NMS.ZMQ
{
/// <summary>
/// An object capable of receiving messages from some destination
/// </summary>
public class MessageConsumer : IMessageConsumer
{
protected static readonly TimeSpan zeroTimeout = new TimeSpan(0);
private readonly Session session;
private readonly AcknowledgementMode acknowledgementMode;
private Destination destination;
private event MessageListener listener;
private int listenerCount = 0;
private Thread asyncDeliveryThread = null;
private object asyncDeliveryLock = new object();
private bool asyncDelivery = false;
private bool asyncInit = false;
private byte[] rawDestinationName;
private ConsumerTransformerDelegate consumerTransformer;
public ConsumerTransformerDelegate ConsumerTransformer
{
get { return this.consumerTransformer; }
set { this.consumerTransformer = value; }
}
public MessageConsumer(Session sess, AcknowledgementMode ackMode, IDestination dest, string selector)
{
// UNUSED_PARAM(selector); // Selectors are not currently supported
if(null == sess.Connection.Context)
{
throw new NMSConnectionException();
}
this.session = sess;
this.destination = (Destination) dest;
this.rawDestinationName = Destination.encoding.GetBytes(this.destination.Name);
this.acknowledgementMode = ackMode;
}
private object listenerLock = new object();
public event MessageListener Listener
{
add
{
lock(listenerLock)
{
this.listener += value;
if(0 == this.listenerCount)
{
StartAsyncDelivery();
}
this.listenerCount++;
}
}
remove
{
lock(listenerLock)
{
this.listener -= value;
if(this.listenerCount > 0)
{
this.listenerCount--;
if(0 == this.listenerCount)
{
StopAsyncDelivery();
}
}
}
}
}
/// <summary>
/// Receive message from subscriber
/// </summary>
/// <returns>
/// message interface
/// </returns>
public IMessage Receive()
{
return Receive(TimeSpan.MaxValue);
}
/// <summary>
/// Receive message from subscriber
/// </summary>
/// <returns>
/// message interface
/// </returns>
public IMessage Receive(TimeSpan timeout)
{
int size;
byte[] receivedMsg = this.destination.ReceiveBytes(timeout, out size);
if(size > 0)
{
// Strip off the subscribed destination name.
// TODO: Support decoding of all message types + all meta data (e.g., headers and properties)
int msgStart = this.rawDestinationName.Length;
int msgLength = receivedMsg.Length - msgStart;
string msgContent = Encoding.UTF8.GetString(receivedMsg, msgStart, msgLength);
return ToNmsMessage(msgContent);
}
return null;
}
/// <summary>
/// Receive message from subscriber
/// </summary>
/// <returns>
/// message interface
/// </returns>
public IMessage ReceiveNoWait()
{
return Receive(zeroTimeout);
}
/// <summary>
/// Clean up
/// </summary>
public void Dispose()
{
Close();
}
/// <summary>
/// Clean up
/// </summary>
public void Close()
{
StopAsyncDelivery();
this.destination = null;
}
protected virtual void StopAsyncDelivery()
{
lock(this.asyncDeliveryLock)
{
this.asyncDelivery = false;
if(null != this.asyncDeliveryThread)
{
Tracer.Info("Stopping async delivery thread.");
this.asyncDeliveryThread.Interrupt();
if(!this.asyncDeliveryThread.Join(10000))
{
Tracer.Info("Aborting async delivery thread.");
this.asyncDeliveryThread.Abort();
}
this.asyncDeliveryThread = null;
Tracer.Info("Async delivery thread stopped.");
}
}
}
protected virtual void StartAsyncDelivery()
{
Debug.Assert(null == this.asyncDeliveryThread);
lock(this.asyncDeliveryLock)
{
this.asyncInit = false;
this.asyncDelivery = true;
this.asyncDeliveryThread = new Thread(new ThreadStart(MsgDispatchLoop));
this.asyncDeliveryThread.Name = string.Format("MsgConsumerAsync: {0}", this.destination.Name);
this.asyncDeliveryThread.IsBackground = true;
this.asyncDeliveryThread.Start();
while(!asyncInit)
{
Thread.Sleep(1);
}
}
}
protected virtual void MsgDispatchLoop()
{
Tracer.InfoFormat("Starting dispatcher thread consumer: {0}", this.asyncDeliveryThread.Name);
TimeSpan receiveWait = TimeSpan.FromSeconds(2);
// Signal that this thread has started.
asyncInit = true;
while(asyncDelivery)
{
try
{
IMessage message = Receive(receiveWait);
if(asyncDelivery)
{
if(null != message)
{
try
{
listener(message);
}
catch(Exception ex)
{
HandleAsyncException(ex);
}
}
else
{
Thread.Sleep(0);
}
}
}
catch(ThreadAbortException ex)
{
Tracer.InfoFormat("Thread abort received in thread: {0} : {1}", this, ex.Message);
break;
}
catch(Exception ex)
{
Tracer.ErrorFormat("Exception while receiving message in thread: {0} : {1}", this, ex.Message);
}
}
Tracer.InfoFormat("Stopped dispatcher thread consumer: {0}", this.asyncDeliveryThread.Name);
}
protected virtual void HandleAsyncException(Exception e)
{
this.session.Connection.HandleException(e);
}
/// <summary>
/// Create nms message object
/// </summary>
/// <param name="message">
/// zmq message object
/// </param>
/// <returns>
/// nms message object
/// </returns>
protected virtual IMessage ToNmsMessage(string messageText)
{
// Strip off the destination name prefix.
IMessage nmsMessage = new TextMessage(messageText);
try
{
nmsMessage.NMSMessageId = "";
nmsMessage.NMSDestination = this.destination;
nmsMessage.NMSDeliveryMode = MsgDeliveryMode.NonPersistent;
nmsMessage.NMSPriority = MsgPriority.Normal;
nmsMessage.NMSTimestamp = DateTime.Now;
nmsMessage.NMSTimeToLive = new TimeSpan(0);
nmsMessage.NMSType = "";
}
catch(InvalidOperationException)
{
// Log error
}
if(null != this.ConsumerTransformer)
{
IMessage transformedMessage = ConsumerTransformer(this.session, this, nmsMessage);
if(null != transformedMessage)
{
nmsMessage = transformedMessage;
}
}
return nmsMessage;
}
}
}
| |
using IrcClientCore;
using Microsoft.AppCenter.Crashes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Template10.Common;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.ExtendedExecution;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
namespace WinIRC.Net
{
public class IrcSocket : UWPSocketBase
{
private const int socketReceiveBufferSize = 1024;
private IBackgroundTaskRegistration task = null;
private DataReaderLoadOperation readOperation;
private SafeLineReader dataStreamLineReader;
private CancellationTokenSource socketCancellation;
public IrcSocket(Irc irc) : base(irc) { }
public override async Task Connect()
{
var autoReconnect = Config.GetBoolean(Config.AutoReconnect, true);
if (Server == null)
return;
try
{
foreach (var current in BackgroundTaskRegistration.AllTasks)
{
if (current.Value.Name == BackgroundTaskName)
{
task = current.Value;
break;
}
}
if (task == null)
{
var socketTaskBuilder = new BackgroundTaskBuilder();
socketTaskBuilder.Name = "WinIRCBackgroundTask." + Server.Name;
var trigger = new SocketActivityTrigger();
socketTaskBuilder.SetTrigger(trigger);
//task = socketTaskBuilder.Register();
}
}
catch (Exception e)
{
Debug.WriteLine(e);
}
parent.IsAuthed = false;
parent.ReadOrWriteFailed = false;
if (!ConnCheck.HasInternetAccess)
{
var msg = autoReconnect
? "We'll try to connect once a connection is available."
: "Please try again once your connection is restored";
var error = IrcUWPBase.CreateBasicToast("No connection detected.", msg);
error.ExpirationTime = DateTime.Now.AddDays(2);
ToastNotificationManager.CreateToastNotifier().Show(error);
if (!autoReconnect)
{
Disconnect(attemptReconnect: autoReconnect);
}
return;
}
streamSocket = new StreamSocket();
streamSocket.Control.KeepAlive = true;
if (Config.GetBoolean(Config.IgnoreSSL))
{
streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
}
if (task != null) streamSocket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake);
dataStreamLineReader = new SafeLineReader();
try
{
var protectionLevel = Server.Ssl ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
Debug.WriteLine("Attempting to connect...");
await streamSocket.ConnectAsync(new Windows.Networking.HostName(Server.Hostname), Server.Port.ToString(), protectionLevel);
Debug.WriteLine("Connected!");
reader = new DataReader(streamSocket.InputStream);
writer = new DataWriter(streamSocket.OutputStream);
parent.IsConnected = true;
parent.IsConnecting = false;
ConnectionHandler();
}
catch (Exception e)
{
var msg = autoReconnect
? "Attempting to reconnect..."
: "Please try again later.";
parent.AddError("Error whilst connecting: " + e.Message + "\n" + msg);
parent.AddError(e.StackTrace);
parent.AddError("If this error keeps occuring, ensure your connection settings are correct.");
Disconnect(attemptReconnect: autoReconnect);
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
}
private async void ConnectionHandler()
{
parent.AttemptAuth();
// while loop to keep the connection open
while (parent.IsConnected)
{
if (parent.Transferred) { await Task.Delay(1); continue; }
await ReadFromServer(reader, writer);
}
}
public async void SocketTransfer()
{
if (streamSocket == null) return;
try
{
// set a variable to ensure the while loop doesn't continue trying to process connections
parent.Transferred = true;
// detatch all the buffers
await streamSocket.CancelIOAsync();
// transfer the socket
streamSocket.TransferOwnership(Server.Name);
streamSocket = null;
}
catch (Exception e)
{
var toast = IrcUWPBase.CreateBasicToast("Error when activating background socket", e.Message);
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
public void SocketReturn()
{
SocketActivityInformation socketInformation;
if (SocketActivityInformation.AllSockets.TryGetValue(Server.Name, out socketInformation))
{
// take the socket back, and hook up all the readers and writers so we can do stuff again
streamSocket = socketInformation.StreamSocket;
reader = new DataReader(streamSocket.InputStream);
writer = new DataWriter(streamSocket.OutputStream);
parent.Transferred = false;
}
}
public async Task ReadFromServer(DataReader reader, DataWriter writer)
{
// set the DataReader to only wait for available data
reader.InputStreamOptions = InputStreamOptions.Partial;
try
{
await reader.LoadAsync(socketReceiveBufferSize);
while (reader.UnconsumedBufferLength > 0)
{
bool breakLoop = false;
byte readChar;
do
{
if (reader.UnconsumedBufferLength > 0)
readChar = reader.ReadByte();
else
{
breakLoop = true;
break;
}
} while (!dataStreamLineReader.Add(readChar));
if (breakLoop)
return;
// Read next line from data stream.
var line = dataStreamLineReader.SafeFlushLine();
if (line == null) break;
if (line.Length == 0) continue;
await parent.RecieveLine(line);
}
}
catch (Exception e)
{
parent.AddError("Error with connection: " + e.Message);
parent.AddError(e.StackTrace);
parent.ReadOrWriteFailed = true;
parent.IsConnected = false;
if (Server != null)
Disconnect(attemptReconnect: Config.GetBoolean(Config.AutoReconnect));
return;
}
}
}
// Reads lines from text sources safely; unterminated lines are not returned.
internal class SafeLineReader
{
// Current incomplete line;
private string currentLine;
private List<byte> bytesList = new List<byte>();
private bool endOfLine = false;
private char PreviousCharacter()
{
return currentLine[currentLine.Length - 1];
}
public bool Add(byte b)
{
char character = (char)b;
if (character == '\n' && PreviousCharacter() == '\r')
endOfLine = true;
bytesList.Add(b);
currentLine += character;
return endOfLine;
}
public string FlushLine()
{
var buffer = bytesList.ToArray();
currentLine = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
string tempLine = currentLine.Substring(0, currentLine.Length - 2);
currentLine = String.Empty;
endOfLine = false;
bytesList.Clear();
return tempLine;
}
public string SafeFlushLine()
{
if (endOfLine)
return FlushLine();
else
return null;
}
}
}
| |
//
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Apache.Http;
using Apache.Http.Auth;
using Apache.Http.Client;
using Apache.Http.Client.Methods;
using Apache.Http.Client.Protocol;
using Apache.Http.Conn;
using Apache.Http.Entity;
using Apache.Http.Impl.Auth;
using Apache.Http.Impl.Client;
using Apache.Http.Protocol;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Support
{
public class RemoteRequest : Runnable
{
private const int MaxRetries = 2;
private const int RetryDelayMs = 10 * 1000;
protected internal ScheduledExecutorService workExecutor;
protected internal readonly HttpClientFactory clientFactory;
protected internal string method;
protected internal Uri url;
protected internal object body;
protected internal Authenticator authenticator;
protected internal RemoteRequestCompletionBlock onPreCompletion;
protected internal RemoteRequestCompletionBlock onCompletion;
protected internal RemoteRequestCompletionBlock onPostCompletion;
private int retryCount;
private Database db;
protected internal HttpRequestMessage request;
protected internal IDictionary<string, object> requestHeaders;
public RemoteRequest(ScheduledExecutorService workExecutor, HttpClientFactory clientFactory
, string method, Uri url, object body, Database db, IDictionary<string, object>
requestHeaders, RemoteRequestCompletionBlock onCompletion)
{
this.clientFactory = clientFactory;
this.method = method;
this.url = url;
this.body = body;
this.onCompletion = onCompletion;
this.workExecutor = workExecutor;
this.requestHeaders = requestHeaders;
this.db = db;
this.request = CreateConcreteRequest();
Log.V(Log.TagSync, "%s: RemoteRequest created, url: %s", this, url);
}
public virtual void Run()
{
Log.V(Log.TagSync, "%s: RemoteRequest run() called, url: %s", this, url);
HttpClient httpClient = clientFactory.GetHttpClient();
ClientConnectionManager manager = httpClient.GetConnectionManager();
PreemptivelySetAuthCredentials(httpClient);
request.AddHeader("Accept", "multipart/related, application/json");
AddRequestHeaders(request);
SetBody(request);
ExecuteRequest(httpClient, request);
Log.V(Log.TagSync, "%s: RemoteRequest run() finished, url: %s", this, url);
}
public virtual void Abort()
{
if (request != null)
{
request.Abort();
}
else
{
Log.W(Log.TagRemoteRequest, "%s: Unable to abort request since underlying request is null"
, this);
}
}
public virtual HttpRequestMessage GetRequest()
{
return request;
}
protected internal virtual void AddRequestHeaders(HttpRequestMessage request)
{
foreach (string requestHeaderKey in requestHeaders.Keys)
{
request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString
());
}
}
public virtual void SetOnPostCompletion(RemoteRequestCompletionBlock onPostCompletion
)
{
this.onPostCompletion = onPostCompletion;
}
public virtual void SetOnPreCompletion(RemoteRequestCompletionBlock onPreCompletion
)
{
this.onPreCompletion = onPreCompletion;
}
protected internal virtual HttpRequestMessage CreateConcreteRequest()
{
HttpRequestMessage request = null;
if (Sharpen.Runtime.EqualsIgnoreCase(method, "GET"))
{
request = new HttpGet(url.ToExternalForm());
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase(method, "PUT"))
{
request = new HttpPut(url.ToExternalForm());
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase(method, "POST"))
{
request = new HttpPost(url.ToExternalForm());
}
}
}
return request;
}
protected internal virtual void SetBody(HttpRequestMessage request)
{
// set body if appropriate
if (body != null && request is HttpEntityEnclosingRequestBase)
{
byte[] bodyBytes = null;
try
{
bodyBytes = Manager.GetObjectMapper().WriteValueAsBytes(body);
}
catch (Exception e)
{
Log.E(Log.TagRemoteRequest, "Error serializing body of request", e);
}
ByteArrayEntity entity = new ByteArrayEntity(bodyBytes);
entity.SetContentType("application/json");
((HttpEntityEnclosingRequestBase)request).SetEntity(entity);
}
}
/// <summary>Set Authenticator for BASIC Authentication</summary>
public virtual void SetAuthenticator(Authenticator authenticator)
{
this.authenticator = authenticator;
}
/// <summary>
/// Retry this remote request, unless we've already retried MAX_RETRIES times
/// NOTE: This assumes all requests are idempotent, since even though we got an error back, the
/// request might have succeeded on the remote server, and by retrying we'd be issuing it again.
/// </summary>
/// <remarks>
/// Retry this remote request, unless we've already retried MAX_RETRIES times
/// NOTE: This assumes all requests are idempotent, since even though we got an error back, the
/// request might have succeeded on the remote server, and by retrying we'd be issuing it again.
/// PUT and POST requests aren't generally idempotent, but the ones sent by the replicator are.
/// </remarks>
/// <returns>true if going to retry the request, false otherwise</returns>
protected internal virtual bool RetryRequest()
{
if (retryCount >= MaxRetries)
{
return false;
}
workExecutor.Schedule(this, RetryDelayMs, TimeUnit.Milliseconds);
retryCount += 1;
Log.D(Log.TagRemoteRequest, "Will retry in %d ms", RetryDelayMs);
return true;
}
protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
request)
{
object fullBody = null;
Exception error = null;
HttpResponse response = null;
try
{
Log.V(Log.TagSync, "%s: RemoteRequest executeRequest() called, url: %s", this, url
);
if (request.IsAborted())
{
Log.V(Log.TagSync, "%s: RemoteRequest has already been aborted", this);
RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted"
, this, request)), response);
return;
}
Log.V(Log.TagSync, "%s: RemoteRequest calling httpClient.execute", this);
response = httpClient.Execute(request);
Log.V(Log.TagSync, "%s: RemoteRequest called httpClient.execute", this);
// add in cookies to global store
try
{
if (httpClient is DefaultHttpClient)
{
DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
this.clientFactory.AddCookies(defaultHttpClient.GetCookieStore().GetCookies());
}
}
catch (Exception e)
{
Log.E(Log.TagRemoteRequest, "Unable to add in cookies to global store", e);
}
StatusLine status = response.GetStatusLine();
if (Utils.IsTransientError(status) && RetryRequest())
{
return;
}
if (status.GetStatusCode() >= 300)
{
Log.E(Log.TagRemoteRequest, "Got error status: %d for %s. Reason: %s", status.GetStatusCode
(), request, status.GetReasonPhrase());
error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase(
));
}
else
{
HttpEntity temp = response.GetEntity();
if (temp != null)
{
InputStream stream = null;
try
{
stream = temp.GetContent();
fullBody = Manager.GetObjectMapper().ReadValue<object>(stream);
}
finally
{
try
{
stream.Close();
}
catch (IOException)
{
}
}
}
}
}
catch (IOException e)
{
Log.E(Log.TagRemoteRequest, "io exception", e);
error = e;
// Treat all IOExceptions as transient, per:
// http://hc.apache.org/httpclient-3.x/exception-handling.html
Log.V(Log.TagSync, "%s: RemoteRequest calling retryRequest()", this);
if (RetryRequest())
{
return;
}
}
catch (Exception e)
{
Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
error = e;
}
Log.V(Log.TagSync, "%s: RemoteRequest calling respondWithResult. error: %s", this
, error);
RespondWithResult(fullBody, error, response);
}
protected internal virtual void PreemptivelySetAuthCredentials(HttpClient httpClient
)
{
bool isUrlBasedUserInfo = false;
string userInfo = url.GetUserInfo();
if (userInfo != null)
{
isUrlBasedUserInfo = true;
}
else
{
if (authenticator != null)
{
AuthenticatorImpl auth = (AuthenticatorImpl)authenticator;
userInfo = auth.AuthUserInfo();
}
}
if (userInfo != null)
{
if (userInfo.Contains(":") && !userInfo.Trim().Equals(":"))
{
string[] userInfoElements = userInfo.Split(":");
string username = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[0]) : userInfoElements
[0];
string password = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[1]) : userInfoElements
[1];
Credentials credentials = new UsernamePasswordCredentials(username, password);
if (httpClient is DefaultHttpClient)
{
DefaultHttpClient dhc = (DefaultHttpClient)httpClient;
MessageProcessingHandler preemptiveAuth = new _MessageProcessingHandler_286(credentials
);
dhc.AddRequestInterceptor(preemptiveAuth, 0);
}
}
else
{
Log.W(Log.TagRemoteRequest, "RemoteRequest Unable to parse user info, not setting credentials"
);
}
}
}
private sealed class _MessageProcessingHandler_286 : MessageProcessingHandler
{
public _MessageProcessingHandler_286(Credentials credentials)
{
this.credentials = credentials;
}
/// <exception cref="Apache.Http.HttpException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public void Process(HttpWebRequest request, HttpContext context)
{
AuthState authState = (AuthState)context.GetAttribute(ClientContext.TargetAuthState
);
if (authState.GetAuthScheme() == null)
{
authState.SetAuthScheme(new BasicScheme());
authState.SetCredentials(credentials);
}
}
private readonly Credentials credentials;
}
public virtual void RespondWithResult(object result, Exception error, HttpResponse
response)
{
if (workExecutor != null)
{
workExecutor.Submit(new _Runnable_307(this, response, error, result));
}
else
{
// don't let this crash the thread
Log.E(Log.TagRemoteRequest, "Work executor was null!");
}
}
private sealed class _Runnable_307 : Runnable
{
public _Runnable_307(RemoteRequest _enclosing, HttpResponse response, Exception error
, object result)
{
this._enclosing = _enclosing;
this.response = response;
this.error = error;
this.result = result;
}
public void Run()
{
try
{
if (this._enclosing.onPreCompletion != null)
{
this._enclosing.onPreCompletion.OnCompletion(response, error);
}
this._enclosing.onCompletion.OnCompletion(result, error);
if (this._enclosing.onPostCompletion != null)
{
this._enclosing.onPostCompletion.OnCompletion(response, error);
}
}
catch (Exception e)
{
Log.E(Log.TagRemoteRequest, "RemoteRequestCompletionBlock throw Exception", e);
}
}
private readonly RemoteRequest _enclosing;
private readonly HttpResponse response;
private readonly Exception error;
private readonly object result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using log4net;
using Polly;
using Xpressive.Home.Contracts.Gateway;
using Xpressive.Home.Contracts.Messaging;
using Xpressive.Home.Contracts.Services;
using Action = Xpressive.Home.Contracts.Gateway.Action;
namespace Xpressive.Home.Plugins.Lifx
{
internal sealed class LifxGateway : GatewayBase, ILifxGateway
{
private static readonly ILog _log = LogManager.GetLogger(typeof(LifxGateway));
private readonly IMessageQueue _messageQueue;
private readonly IDeviceConfigurationBackupService _deviceConfigurationBackupService;
private readonly string _token;
private readonly object _deviceLock = new object();
private readonly LifxLocalClient _localClient = new LifxLocalClient();
public LifxGateway(IMessageQueue messageQueue, IDeviceConfigurationBackupService deviceConfigurationBackupService) : base("Lifx")
{
_messageQueue = messageQueue;
_deviceConfigurationBackupService = deviceConfigurationBackupService;
_canCreateDevices = false;
_token = ConfigurationManager.AppSettings["lifx.token"];
_localClient.DeviceDiscovered += (s, e) =>
{
AddLifxDevice(e.Id, () => new LifxDevice(e));
};
_localClient.VariableChanged += (s, e) =>
{
var device = _devices.ToArray().Cast<LifxDevice>().SingleOrDefault(d => d.Id.Equals(e.Item1.Id));
if (device != null)
{
device.Name = e.Item1.Name;
}
var variable = $"{Name}.{e.Item1.Id}.{e.Item2}";
_messageQueue.Publish(new UpdateVariableMessage(variable, e.Item3));
};
}
public override IDevice CreateEmptyDevice()
{
throw new NotSupportedException();
}
public IEnumerable<LifxDevice> GetDevices()
{
return Devices.OfType<LifxDevice>();
}
public override IEnumerable<IAction> GetActions(IDevice device)
{
if (device is LifxDevice)
{
yield return new Action("Switch On") { Fields = { "Transition time in seconds" } };
yield return new Action("Switch Off") { Fields = { "Transition time in seconds" } };
yield return new Action("Change Color") { Fields = { "Color", "Transition time in seconds" } };
yield return new Action("Change Brightness") { Fields = { "Brightness", "Transition time in seconds" } };
}
}
public void SwitchOn(LifxDevice device, int transitionTimeInSeconds)
{
var parameters = new Dictionary<string, string>
{
{"Transition time in seconds", transitionTimeInSeconds.ToString()}
};
var action = GetActions(device).Single(a => a.Name.Equals("Switch On", StringComparison.Ordinal));
StartActionInNewTask(device, action, parameters);
}
public void SwitchOff(LifxDevice device, int transitionTimeInSeconds)
{
var parameters = new Dictionary<string, string>
{
{"Transition time in seconds", transitionTimeInSeconds.ToString()}
};
var action = GetActions(device).Single(a => a.Name.Equals("Switch Off", StringComparison.Ordinal));
StartActionInNewTask(device, action, parameters);
}
public void ChangeColor(LifxDevice device, string hexColor, int transitionTimeInSeconds)
{
var parameters = new Dictionary<string, string>
{
{"Color", hexColor},
{"Transition time in seconds", transitionTimeInSeconds.ToString()}
};
var action = GetActions(device).Single(a => a.Name.Equals("Change Color", StringComparison.Ordinal));
StartActionInNewTask(device, action, parameters);
}
public void ChangeBrightness(LifxDevice device, double brightness, int transitionTimeInSeconds)
{
var parameters = new Dictionary<string, string>
{
{"Brightness", brightness.ToString("F2")},
{"Transition time in seconds", transitionTimeInSeconds.ToString()}
};
var action = GetActions(device).Single(a => a.Name.Equals("Change Brightness", StringComparison.Ordinal));
StartActionInNewTask(device, action, parameters);
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });
FindLocalBulbs(cancellationToken);
FindCloudBulbsAsync(cancellationToken).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });
var backupDto = _deviceConfigurationBackupService.Get<LocalLifxLightConfigurationBackupDto>(Name);
if (backupDto != null)
{
foreach (var ipAddress in backupDto.LocalIpAddresses)
{
var temporaryDevice = new LifxLocalLight
{
Endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), 56700)
};
await _localClient.GetLightStateAsync(temporaryDevice);
}
}
}
private async Task FindCloudBulbsAsync(CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(_token))
{
_messageQueue.Publish(new NotifyUserMessage("Add LIFX cloud token to config file."));
return;
}
while (!cancellationToken.IsCancellationRequested)
{
await ExecuteWithRetriesAsync(GetHttpLights, "get cloud bulbs");
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken).ContinueWith(_ => { });
}
}
private void FindLocalBulbs(CancellationToken cancellationToken)
{
try
{
_localClient.StartLifxNetwork(cancellationToken);
}
catch (Exception e)
{
_log.Error(e.Message, e);
}
}
protected override async Task ExecuteInternalAsync(IDevice device, IAction action, IDictionary<string, string> values)
{
if (string.IsNullOrEmpty(_token))
{
return;
}
if (device == null)
{
_log.Warn($"Unable to execute action {action.Name} because the device was not found.");
return;
}
var bulb = (LifxDevice) device;
int seconds;
double brightness;
string s;
if (!action.Fields.Contains("Transition time in seconds") ||
!values.TryGetValue("Transition time in seconds", out s) ||
!int.TryParse(s, out seconds))
{
seconds = 0;
}
string b;
if (!action.Fields.Contains("Brightness") ||
!values.TryGetValue("Brightness", out b) ||
!double.TryParse(b, out brightness))
{
brightness = 0;
}
string color;
if (!values.TryGetValue("Color", out color))
{
color = string.Empty;
}
if (bulb.Source == LifxSource.Cloud)
{
var description = $"action {action.Name} for cloud bulb {bulb.Name}";
await ExecuteWithRetriesAsync(() => ExecuteCloudAction(bulb, action.Name, seconds, brightness, color), description);
}
else
{
var description = $"action {action.Name} for local bulb {bulb.Name}";
await ExecuteWithRetriesAsync(() => ExecuteLocalAction(bulb, action.Name, seconds, brightness, color), description);
}
}
private async Task ExecuteWithRetriesAsync(Func<Task> func, string description)
{
try
{
var policy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(5)
});
await policy.ExecuteAsync(async () => await func());
}
catch (WebException e)
{
_log.Error($"Error while executing {description}: {e.Message}");
}
catch (XmlException e)
{
_log.Error($"Error while executing {description}: {e.Message}");
}
catch (Exception e)
{
_log.Error(e.Message, e);
}
}
private async Task ExecuteLocalAction(LifxDevice device, string action, int seconds, double brightness, string color)
{
var light = _localClient.Lights.SingleOrDefault(l => l.Id.Equals(device.Id));
var b = (ushort)(brightness * 65535);
if (light == null)
{
return;
}
var hsbk = light.Color;
if (hsbk == null)
{
hsbk = new HsbkColor
{
Kelvin = 4500
};
}
switch (action.ToLowerInvariant())
{
case "switch on":
if (seconds == 0)
{
await _localClient.SetPowerAsync(light, true);
}
else if (seconds > 0)
{
await _localClient.SetPowerAsync(light, TimeSpan.FromSeconds(seconds), true);
}
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
break;
case "switch off":
if (seconds == 0)
{
await _localClient.SetPowerAsync(light, false);
}
else if (seconds > 0)
{
await _localClient.SetPowerAsync(light, TimeSpan.FromSeconds(seconds), false);
}
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", false));
break;
case "change color":
var rgb = color.ParseRgb();
var hsb = rgb.ToHsbk();
hsbk.Hue = hsb.Hue;
hsbk.Saturation = hsb.Saturation;
hsbk.Brightness = hsb.Brightness;
await _localClient.SetColorAsync(light, hsbk, TimeSpan.FromSeconds(seconds));
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Color", rgb.ToString()));
break;
case "change brightness":
hsbk.Brightness = brightness;
await _localClient.SetColorAsync(light, hsbk, TimeSpan.FromSeconds(seconds));
//var db = Math.Round(brightness, 2);
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Brightness", db));
//_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
break;
default:
return;
}
}
private async Task ExecuteCloudAction(LifxDevice device, string action, int seconds, double brightness, string color)
{
var client = new LifxHttpClient(_token);
var lights = await client.GetLights();
var light = lights.SingleOrDefault(l => l.Id.Equals(device.Id));
if (light == null)
{
return;
}
switch (action.ToLowerInvariant())
{
case "switch on":
await client.SwitchOn(light, seconds);
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
break;
case "switch off":
await client.SwitchOff(light, seconds);
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", false));
break;
case "change color":
var rgb = color.ParseRgb();
await client.ChangeColor(light, rgb.ToString(), seconds);
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Color", rgb.ToString()));
break;
case "change brightness":
await client.ChangeBrightness(light, brightness, seconds);
var db = Math.Round(brightness, 2);
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Brightness", db));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", true));
break;
default:
return;
}
}
private async Task GetHttpLights()
{
var client = new LifxHttpClient(_token);
var lights = await client.GetLights();
foreach (var light in lights)
{
var device = AddLifxDevice(light?.Id, () => new LifxDevice(light));
if (device != null)
{
UpdateDeviceVariables(device, light);
}
}
}
private LifxDevice AddLifxDevice(string id, Func<LifxDevice> create)
{
if (string.IsNullOrEmpty(id))
{
return null;
}
lock (_deviceLock)
{
var device = _devices.Cast<LifxDevice>().SingleOrDefault(d => d.Id.Equals(id));
if (device == null)
{
device = create();
_devices.Add(device);
}
return device;
}
}
private void UpdateDeviceVariables(LifxDevice device, LifxHttpLight light)
{
var brightness = Math.Round(light.Brightness, 2);
var groupName = light.Group.Name;
var name = light.Label;
var isOn = light.Power == LifxHttpLight.PowerState.On;
var isConnected = light.IsConnected;
var color = light.GetHexColor();
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Brightness", brightness));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsOn", isOn));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "IsConnected", isConnected));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Name", name));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "GroupName", groupName));
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, "Color", color));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var ipAddresses = _localClient.Lights.Select(l => l.Endpoint.Address.ToString()).ToList();
var backupDto = new LocalLifxLightConfigurationBackupDto(ipAddresses);
_deviceConfigurationBackupService.Save(Name, backupDto);
_localClient.Dispose();
}
}
private class LocalLifxLightConfigurationBackupDto
{
public LocalLifxLightConfigurationBackupDto(IEnumerable<string> ipAddresses)
{
if (ipAddresses == null)
{
LocalIpAddresses = new List<string>(0);
}
else
{
LocalIpAddresses = new List<string>(ipAddresses);
}
}
public List<string> LocalIpAddresses { get; }
}
}
}
| |
// 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.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== ValidateText =====================
public class TCValidateText : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateText(ITestOutputHelper output): base(output)
{
_output = output;
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
try
{
val.ValidateText((XmlValueGetter)null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void TopLevelText()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateText(StringGetter("foo"));
val.EndValidation();
Assert.True(!holder.IsCalledA);
return;
}
[Theory]
[InlineData("single")]
[InlineData("multiple")]
public void SanityTestForSimpleType_MultipleCallInOneContext(String param)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("PatternElement", "", info);
val.ValidateEndOfAttributes(null);
if (param == "single")
val.ValidateText(StringGetter("foo123bar"));
else
{
val.ValidateText(StringGetter("foo"));
val.ValidateText(StringGetter("123"));
val.ValidateText(StringGetter("bar"));
}
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.TextOnly);
return;
}
[Fact]
public void MixedContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("MixedElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("some text"));
val.ValidateElement("child", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateText(StringGetter("some other text"));
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.Mixed);
return;
}
[Fact]
public void ElementOnlyContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateText(StringGetter("some text"));
}
catch (XmlSchemaValidationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, new object[] { "Sch_InvalidTextInElementExpecting",
// new object[] { "Sch_ElementName", "ElementOnlyElement" },
// new object[] { "Sch_ElementName", "child" } });
return;
}
Assert.True(false);
}
[Fact]
public void EmptyContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateText(StringGetter("some text"));
}
catch (XmlSchemaValidationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_InvalidTextInEmpty");
return;
}
Assert.True(false);
}
}
// ===================== ValidateWhitespace =====================
public class TCValidateWhitespace : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateWhitespace(ITestOutputHelper output): base(output)
{
_output = output;
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
try
{
val.ValidateWhitespace((XmlValueGetter)null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void TopLevelWhitespace()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateWhitespace(StringGetter(" \t\r\n"));
val.EndValidation();
Assert.True(!holder.IsCalledA);
return;
}
[Fact]
public void WhitespaceInsideElement_Single()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateWhitespace(StringGetter(" \t\r\n"));
val.ValidateElement("child", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateWhitespace(StringGetter(" \t\r\n"));
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.ElementOnly);
return;
}
[Fact]
public void WhitespaceInEmptyContent__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateWhitespace(StringGetter(" \r\n\t"));
}
catch (XmlSchemaValidationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_InvalidWhitespaceInEmpty");
return;
}
Assert.True(false);
}
[Fact]
public void PassNonWhitespaceContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", null);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateWhitespace(StringGetter("this is not whitespace"));
}
catch (Exception) // Replace with concrete exception type
{
// Verify exception
Assert.True(false);
}
return;
}
}
// ===================== ValidateEndElement =====================
public class TCValidateEndElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCValidateEndElement(ITestOutputHelper output): base(output)
{
_output = output;
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null);
return;
}
// BUG 305258
[Fact]
public void SanityTestForComplexTypes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2", "e3" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.TextOnly);
}
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.ElementOnly);
val.EndValidation();
return;
}
[Fact]
public void IncompleteContet__Valid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.ElementOnly);
val.EndValidation();
return;
}
[Fact]
public void IncompleteContent__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
Assert.True(holder.IsCalledA);
Assert.Equal(holder.lastSeverity, XmlSeverityType.Error);
Assert.Equal(info.Validity, XmlSchemaValidity.Invalid);
return;
}
[Fact]
public void TextNodeWithoutValidateTextCall()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.EndValidation();
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.TextOnly);
return;
}
// 2nd overload
[Fact]
public void Typed_NullXmlSchemaInfo()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null, "123");
return;
}
[Fact]
public void Typed_NullTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateEndElement(info, null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void CallValidateTextThenValidateEndElementWithTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("1"));
try
{
val.ValidateEndElement(info, "23");
}
catch (InvalidOperationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_InvalidEndElementCall");
return;
}
Assert.True(false);
}
[Fact]
public void CheckSchemaInfoAfterCallingValidateEndElementWithTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info, "123");
val.EndValidation();
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.TextOnly);
Assert.Equal(info.IsDefault, false);
Assert.Equal(info.IsNil, false);
Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.Int);
return;
}
//bug #305258
[Fact]
public void SanityTestForEmptyTypes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.ContentType, XmlSchemaContentType.Empty);
val.EndValidation();
return;
}
[Theory]
[InlineData("valid")]
[InlineData("duplicate")]
[InlineData("missing")]
[InlineData("ignore")]
public void TestForIdentityConstraints_Valid_InvalidDuplicateKey_InvalidKeyRefMissing_InvalidIdentitiConstraintIsSet(String constrType)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
string[] keys = new string[] { };
string[] keyrefs = new string[] { };
bool secondPass;
switch (constrType)
{
case "valid":
keys = new string[] { "1", "2" };
keyrefs = new string[] { "1", "1", "2" };
break;
case "duplicate":
keys = new string[] { "1", "1" };
keyrefs = new string[] { "1", "1", "2" };
break;
case "missing":
keys = new string[] { "1", "2" };
keyrefs = new string[] { "1", "1", "3" };
break;
case "ignore":
keys = new string[] { "1", "1" };
keyrefs = new string[] { "2", "2" };
break;
default:
Assert.True(false);
break;
}
if (constrType == "ignore")
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS, "", XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema);
else
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS);
val.Initialize();
val.ValidateElement("root", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("desc", "", info);
val.ValidateEndOfAttributes(null);
foreach (string str in keyrefs)
{
val.ValidateElement("elemDesc", "", info);
val.ValidateAttribute("number", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("foo"));
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
secondPass = false;
foreach (string str in keys)
{
val.ValidateElement("elem", "", info);
val.ValidateAttribute("number", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("bar", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
if (constrType == "duplicate" && secondPass)
{
try
{
val.ValidateEndElement(info);
Assert.True(false);
}
catch (XmlSchemaValidationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_DuplicateKey", new string[] { "1", "numberKey" });
return;
}
}
else
val.ValidateEndElement(info);
secondPass = true;
}
if (constrType == "missing")
{
try
{
val.ValidateEndElement(info);
Assert.True(false);
}
catch (XmlSchemaValidationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_UnresolvedKeyref", new string[] { "3", "numberKey" });
return;
}
}
else
{
val.ValidateEndElement(info);
val.EndValidation();
}
return;
}
//Bug #305376
[Fact]
public void AllXmlSchemaInfoArgsCanBeNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("WithAttributesElement", "", null);
val.ValidateAttribute("attr1", "", StringGetter("foo"), null);
val.ValidateAttribute("attr2", "", StringGetter("foo"), null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null);
val.ValidateElement("foo", "", null, "EmptyType", null, null, null);
val.SkipToEndElement(null);
val.ValidateElement("NumberElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null, "123");
return;
}
[Theory]
[InlineData("first")]
[InlineData("second")] //(BUG #307549)
public void TestXmlSchemaInfoValuesAfterUnionValidation_Without_With_ValidationEndElementOverload(String overload)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("UnionElement", "", null);
val.ValidateEndOfAttributes(null);
if (overload == "first")
{
val.ValidateText(StringGetter("false"));
val.ValidateEndElement(info);
}
else
val.ValidateEndElement(info, "false");
Assert.Equal(info.MemberType.TypeCode, XmlTypeCode.Boolean);
return;
}
//BUG #308578
[Fact]
public void CallValidateEndElementWithTypedValueForComplexContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
try
{
val.ValidateEndElement(info, "23");
}
catch (InvalidOperationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, (string)null);
return;
}
Assert.True(false);
}
}
// ===================== SkipToEndElement =====================
public class TCSkipToEndElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
public TCSkipToEndElement(ITestOutputHelper output): base(output)
{
_output = output;
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.SkipToEndElement(null);
return;
}
//bug #306869
[Theory]
[InlineData("valid")]
[InlineData("invalid")]
public void SkipAfterValidating_ValidContent_IncompleteContent(String validity)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
bool valid = (validity == "valid");
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
string[] tmp;
if (valid) tmp = new string[] { "e1", "e2", "e2" };
else tmp = new string[] { "e1", "e2" };
foreach (string name in tmp)
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.SkipToEndElement(info);
val.EndValidation();
Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown);
return;
}
//bug #306869
[Fact]
public void ValidateTextAndSkip()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("foo"));
val.SkipToEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown);
return;
}
//bug #306869
[Fact]
public void ValidateAttributesAndSkip()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("WithAttributesElement", "", info);
val.ValidateAttribute("attr1", "", StringGetter("foo"), info);
val.SkipToEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown);
return;
}
[Fact]
public void CheckThatSkipToEndElementJumpsIntoRightContext()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NestedElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("foo", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("bar", "", info);
val.ValidateEndOfAttributes(null);
val.SkipToEndElement(info);
val.SkipToEndElement(info);
val.SkipToEndElement(info);
try
{
val.SkipToEndElement(info);
}
catch (InvalidOperationException)
{
//XmlExceptionVerifier.IsExceptionOk(e, "Sch_InvalidEndElementMultiple", new string[] { "SkipToEndElement" });
return;
}
Assert.True(false);
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// FolderSharedItem
/// </summary>
[DataContract]
public partial class FolderSharedItem : IEquatable<FolderSharedItem>, IValidatableObject
{
public FolderSharedItem()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderSharedItem" /> class.
/// </summary>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="FolderId">FolderId.</param>
/// <param name="Name">Name.</param>
/// <param name="Owner">Owner.</param>
/// <param name="ParentFolderId">ParentFolderId.</param>
/// <param name="ParentFolderUri">ParentFolderUri.</param>
/// <param name="Shared">When set to **true**, this custom tab is shared..</param>
/// <param name="SharedGroups">SharedGroups.</param>
/// <param name="SharedUsers">SharedUsers.</param>
/// <param name="Uri">Uri.</param>
/// <param name="User">User.</param>
public FolderSharedItem(ErrorDetails ErrorDetails = default(ErrorDetails), string FolderId = default(string), string Name = default(string), UserInfo Owner = default(UserInfo), string ParentFolderId = default(string), string ParentFolderUri = default(string), string Shared = default(string), List<MemberGroupSharedItem> SharedGroups = default(List<MemberGroupSharedItem>), List<UserSharedItem> SharedUsers = default(List<UserSharedItem>), string Uri = default(string), UserInfo User = default(UserInfo))
{
this.ErrorDetails = ErrorDetails;
this.FolderId = FolderId;
this.Name = Name;
this.Owner = Owner;
this.ParentFolderId = ParentFolderId;
this.ParentFolderUri = ParentFolderUri;
this.Shared = Shared;
this.SharedGroups = SharedGroups;
this.SharedUsers = SharedUsers;
this.Uri = Uri;
this.User = User;
}
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Gets or Sets FolderId
/// </summary>
[DataMember(Name="folderId", EmitDefaultValue=false)]
public string FolderId { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Owner
/// </summary>
[DataMember(Name="owner", EmitDefaultValue=false)]
public UserInfo Owner { get; set; }
/// <summary>
/// Gets or Sets ParentFolderId
/// </summary>
[DataMember(Name="parentFolderId", EmitDefaultValue=false)]
public string ParentFolderId { get; set; }
/// <summary>
/// Gets or Sets ParentFolderUri
/// </summary>
[DataMember(Name="parentFolderUri", EmitDefaultValue=false)]
public string ParentFolderUri { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// Gets or Sets SharedGroups
/// </summary>
[DataMember(Name="sharedGroups", EmitDefaultValue=false)]
public List<MemberGroupSharedItem> SharedGroups { get; set; }
/// <summary>
/// Gets or Sets SharedUsers
/// </summary>
[DataMember(Name="sharedUsers", EmitDefaultValue=false)]
public List<UserSharedItem> SharedUsers { get; set; }
/// <summary>
/// Gets or Sets Uri
/// </summary>
[DataMember(Name="uri", EmitDefaultValue=false)]
public string Uri { get; set; }
/// <summary>
/// Gets or Sets User
/// </summary>
[DataMember(Name="user", EmitDefaultValue=false)]
public UserInfo User { 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 FolderSharedItem {\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" FolderId: ").Append(FolderId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Owner: ").Append(Owner).Append("\n");
sb.Append(" ParentFolderId: ").Append(ParentFolderId).Append("\n");
sb.Append(" ParentFolderUri: ").Append(ParentFolderUri).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" SharedGroups: ").Append(SharedGroups).Append("\n");
sb.Append(" SharedUsers: ").Append(SharedUsers).Append("\n");
sb.Append(" Uri: ").Append(Uri).Append("\n");
sb.Append(" User: ").Append(User).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 FolderSharedItem);
}
/// <summary>
/// Returns true if FolderSharedItem instances are equal
/// </summary>
/// <param name="other">Instance of FolderSharedItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FolderSharedItem other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.FolderId == other.FolderId ||
this.FolderId != null &&
this.FolderId.Equals(other.FolderId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Owner == other.Owner ||
this.Owner != null &&
this.Owner.Equals(other.Owner)
) &&
(
this.ParentFolderId == other.ParentFolderId ||
this.ParentFolderId != null &&
this.ParentFolderId.Equals(other.ParentFolderId)
) &&
(
this.ParentFolderUri == other.ParentFolderUri ||
this.ParentFolderUri != null &&
this.ParentFolderUri.Equals(other.ParentFolderUri)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.SharedGroups == other.SharedGroups ||
this.SharedGroups != null &&
this.SharedGroups.SequenceEqual(other.SharedGroups)
) &&
(
this.SharedUsers == other.SharedUsers ||
this.SharedUsers != null &&
this.SharedUsers.SequenceEqual(other.SharedUsers)
) &&
(
this.Uri == other.Uri ||
this.Uri != null &&
this.Uri.Equals(other.Uri)
) &&
(
this.User == other.User ||
this.User != null &&
this.User.Equals(other.User)
);
}
/// <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.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.FolderId != null)
hash = hash * 59 + this.FolderId.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Owner != null)
hash = hash * 59 + this.Owner.GetHashCode();
if (this.ParentFolderId != null)
hash = hash * 59 + this.ParentFolderId.GetHashCode();
if (this.ParentFolderUri != null)
hash = hash * 59 + this.ParentFolderUri.GetHashCode();
if (this.Shared != null)
hash = hash * 59 + this.Shared.GetHashCode();
if (this.SharedGroups != null)
hash = hash * 59 + this.SharedGroups.GetHashCode();
if (this.SharedUsers != null)
hash = hash * 59 + this.SharedUsers.GetHashCode();
if (this.Uri != null)
hash = hash * 59 + this.Uri.GetHashCode();
if (this.User != null)
hash = hash * 59 + this.User.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
#if DEBUG
//#define TRACE
#endif
using System;
using Rynchodon.Autopilot.Data;
using Rynchodon.Autopilot.Pathfinding;
using Rynchodon.Threading;
using Rynchodon.Utility;
using Rynchodon.Utility.Vectors;
using Sandbox.Game.Entities;
using Sandbox.Game.GameSystems;
using Sandbox.ModAPI;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot.Movement
{
/// <summary>
/// Performs the movement calculations and the movements.
/// </summary>
/// TODO: mover components, normal ship, missing thrusters, and helicopter
/// current system is a mess of trying to guess what is going on
public class Mover
{
#region S.E. Constants
private const float pixelsForMaxRotation = 20;
private const float RollControlMultiplier = 0.2f;
private const float MaxInverseTensor = 1f / 125000f;
#endregion
/// <summary>Fraction of force used to calculate maximum speed.</summary>
public const float AvailableForceRatio = 0.5f;
public const float OverworkedThreshold = 0.75f;
/// <summary>How far from the destination a ship needs to be to take a curved path instead of a straight one.</summary>
public const float PlanetMoveDist = 1000f;
public const float DistanceSpeedFactor = 0.2f;
private const ulong WriggleAfter = 500ul, StuckAfter = WriggleAfter + 2000ul, MoveAwayAfter = StuckAfter + 100ul;
public readonly AllNavigationSettings NavSet;
private IMyCubeGrid m_grid;
private GyroProfiler m_gyro;
private Vector3 m_moveForceRatio = Vector3.Zero;
private Vector3 m_moveAccel;
private Vector3 m_rotateTargetVelocity = Vector3.Zero;
private Vector3 m_rotateForceRatio = Vector3.Zero;
//private Vector3 m_prevMoveControl = Vector3.Zero;
//private Vector2 m_prevRotateControl = Vector2.Zero;
//private float m_prevRollControl = 0f;
private Vector3 m_lastMoveAccel = Vector3.Zero;
//private float m_bestAngle = float.MaxValue;
private ulong m_lastMoveAttempt = ulong.MaxValue, m_lastAccel = ulong.MaxValue;
private bool m_stopped, m_thrustHigh;
/// <summary>Controlling block for the grid.</summary>
public readonly ShipControllerBlock Block;
public ThrustProfiler Thrust { get; private set; }
public RotateChecker RotateCheck;
private Logable Log { get { return new Logable(Block?.Controller); } }
private bool CheckStuck(ulong duration)
{
return (Globals.UpdateCount - m_lastMoveAttempt) < 100ul && (Globals.UpdateCount - m_lastAccel) > duration;
}
/// <summary>Value is false iff this Mover is making progress.</summary>
public bool MoveStuck
{
get
{
return CheckStuck(StuckAfter);
}
set
{
if (value)
m_lastAccel = ulong.MinValue;
else
m_lastAccel = Globals.UpdateCount;
}
}
public DirectionWorld LinearVelocity
{
get { return Block.Physics.LinearVelocity; }
}
public DirectionWorld AngularVelocity
{
get { return Block.Physics.AngularVelocity; }
}
/// <summary>
/// Creates a Mover for a given ShipControllerBlock and AllNavigationSettings
/// </summary>
/// <param name="block">Controlling block for the grid</param>
/// <param name="NavSet">Navigation settings to use.</param>
public Mover(ShipControllerBlock block, RotateChecker rotateCheck)
{
this.Block = block;
this.NavSet = new AllNavigationSettings(block.CubeBlock);
this.RotateCheck = rotateCheck;
this.NavSet.AfterTaskComplete += NavSet_AfterTaskComplete;
CheckGrid();
}
private void NavSet_AfterTaskComplete()
{
MoveStuck = false;
}
/// <summary>
/// Sets target linear force to zero, optionally enables damping.
/// </summary>
public void StopMove(bool enableDampeners = true)
{
//Log.DebugLog("entered", "StopMove()");
m_moveForceRatio = m_moveAccel = Vector3.Zero;
SetDamping(enableDampeners);
}
/// <summary>
/// Sets target angular force to zero.
/// </summary>
public void StopRotate()
{
//Log.DebugLog("stopping rotation", "StopRotate()");
m_rotateTargetVelocity = m_rotateForceRatio = Vector3.Zero;
//m_prevRotateControl = Vector2.Zero;
//m_prevRollControl = 0f;
}
/// <summary>
/// Stop movement and rotation of the controller.
/// </summary>
/// <param name="enableDampeners">If true, dampeners will be enabled. If false, they will not be toggled.</param>
public void MoveAndRotateStop(bool enableDampeners = true)
{
if (enableDampeners)
SetDamping(true);
if (m_stopped)
{
Log.TraceLog("already stopped");
return;
}
Log.DebugLog("stopping movement and rotation, dampeners: " + enableDampeners);
m_moveForceRatio = m_moveAccel = Vector3.Zero;
StopRotate();
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => {
Block.Controller.MoveAndRotateStopped();
Thrust.ClearOverrides();
//m_gyro.ClearOverrides();
});
m_stopped = true;
}
#region Move
/// <summary>
/// Calculates the force necessary to move the grid.
/// </summary>
/// <param name="block">To get world position from.</param>
/// <param name="destPoint">The world position of the destination</param>
/// <param name="destVelocity">The speed of the destination</param>
/// <param name="landing">Puts an emphasis on not overshooting the target.</param>
public void CalcMove(PseudoBlock block, ref Vector3 destDisp, ref Vector3 destVelocity)
{
Log.DebugLog("Not on autopilot thread: " + ThreadTracker.ThreadName, Logger.severity.ERROR, condition: !ThreadTracker.ThreadName.StartsWith("Autopilot"));
CheckGrid();
m_lastMoveAttempt = Globals.UpdateCount;
Thrust.Update();
// using local vectors
Vector3 velocity = LinearVelocity;
MatrixD positionToLocal = Block.CubeBlock.WorldMatrixNormalizedInv;
MatrixD directionToLocal = positionToLocal.GetOrientation();
destVelocity = Vector3.Transform(destVelocity, directionToLocal);
velocity = Vector3.Transform(velocity, directionToLocal);
Vector3 targetVelocity;
//float distance;
if (destDisp.LengthSquared() > 0.01f)
{
destDisp = Vector3.Transform(destDisp, directionToLocal);
float distance = destDisp.Length();
targetVelocity = MaximumVelocity(destDisp);
// project targetVelocity onto destination direction (take shortest path)
Vector3 destDir = destDisp / distance;
targetVelocity = Vector3.Dot(targetVelocity, destDir) * destDir;
// apply relative speed limit
float relSpeedLimit = NavSet.Settings_Current.SpeedMaxRelative;
float landingSpeed = Math.Max(distance * DistanceSpeedFactor, DistanceSpeedFactor);
if (relSpeedLimit > landingSpeed)
relSpeedLimit = landingSpeed;
if (relSpeedLimit < float.MaxValue)
{
float tarSpeedSq_1 = targetVelocity.LengthSquared();
if (tarSpeedSq_1 > relSpeedLimit * relSpeedLimit)
{
targetVelocity *= relSpeedLimit / (float)Math.Sqrt(tarSpeedSq_1);
//Log.DebugLog("imposing relative speed limit: " + relSpeedLimit + ", targetVelocity: " + targetVelocity, "CalcMove()");
}
}
}
else
{
targetVelocity = Vector3.Zero;
}
targetVelocity += destVelocity;
// apply speed limit
float tarSpeedSq = targetVelocity.LengthSquared();
float speedRequest = NavSet.Settings_Current.SpeedTarget;
if (tarSpeedSq > speedRequest * speedRequest)
{
targetVelocity *= speedRequest / (float)Math.Sqrt(tarSpeedSq);
//Log.DebugLog("imposing speed limit: " + speedRequest + ", targetVelocity: " + targetVelocity, "CalcMove()");
}
m_moveAccel = targetVelocity - velocity;
if (m_moveAccel.LengthSquared() < 0.01f)
{
Log.DebugLog("Wriggle unstuck autopilot. Near target velocity, move accel: " + m_moveAccel + ". m_lastMoveAccel set to now", condition: (Globals.UpdateCount - m_lastAccel) > WriggleAfter);
m_lastMoveAccel = m_moveAccel;
m_lastAccel = Globals.UpdateCount;
}
else
{
float diffSq; Vector3.DistanceSquared(ref m_moveAccel, ref m_lastMoveAccel, out diffSq);
if (diffSq > 1f)
{
Log.DebugLog("Wriggle unstuck autopilot. Change in move accel from " + m_lastMoveAccel + " to " + m_moveAccel + ". m_lastMoveAccel set to now", condition: (Globals.UpdateCount - m_lastAccel) > WriggleAfter);
m_lastMoveAccel = m_moveAccel;
m_lastAccel = Globals.UpdateCount;
}
}
CalcMove(ref velocity);
Log.TraceLog(string.Empty
//+ "block: " + block.Block.getBestName()
//+ ", dest point: " + destPoint
//+ ", position: " + block.WorldPosition
+ "destDisp: " + destDisp
+ ", destVelocity: " + destVelocity
+ ", targetVelocity: " + targetVelocity
+ ", velocity: " + velocity
+ ", m_moveAccel: " + m_moveAccel
+ ", moveForceRatio: " + m_moveForceRatio);
}
private void CalcMove(ref Vector3 velocity)
{
DirectionBlock gravBlock = Thrust.WorldGravity.ToBlock(Block.CubeBlock);
m_moveForceRatio = ToForceRatio(m_moveAccel - gravBlock.vector);
// dampeners
bool enableDampeners = false;
m_thrustHigh = false;
for (int index = 0; index < 3; index++)
{
//const float minForceRatio = 0.1f;
//const float zeroForceRatio = 0.01f;
float velDim = velocity.GetDim(index);
// dampeners are useful for precise stopping but they do not always work properly
if (velDim < 1f && velDim > -1f)
{
float targetVelDim = m_moveAccel.GetDim(index) + velDim;
if (targetVelDim < 0.01f && targetVelDim > -0.01f)
{
//Log.DebugLog("for dim: " + index + ", target velocity near zero: " + targetVelDim);
m_moveForceRatio.SetDim(index, 0f);
enableDampeners = true;
continue;
}
}
float forceRatio = m_moveForceRatio.GetDim(index);
if (forceRatio < 1f && forceRatio > -1f)
{
//if (forceRatio > zeroForceRatio && forceRatio < minForceRatio)
// moveForceRatio.SetDim(i, minForceRatio);
//else if (forceRatio < -zeroForceRatio && forceRatio > -minForceRatio)
// moveForceRatio.SetDim(i, -minForceRatio);
continue;
}
if (forceRatio < -10f || 10f < forceRatio)
m_thrustHigh = true;
// force ratio is > 1 || < -1. If it is useful, use dampeners
if (velDim < 1f && velDim > -1f)
continue;
if (Math.Sign(forceRatio) * Math.Sign(velDim) < 0)
{
//Log.DebugLog("damping, i: " + index + ", force ratio: " + forceRatio + ", velocity: " + velDim + ", sign of forceRatio: " + Math.Sign(forceRatio) + ", sign of velocity: " + Math.Sign(velDim));
m_moveForceRatio.SetDim(index, 0);
enableDampeners = true;
m_thrustHigh = true;
}
//else
// Log.DebugLog("not damping, i: " + i + ", force ratio: " + forceRatio + ", velocity: " + velDim + ", sign of forceRatio: " + Math.Sign(forceRatio) + ", sign of velocity: " + Math.Sign(velDim), "CalcMove()");
}
SetDamping(enableDampeners);
}
/// <summary>
/// Calculates the maximum velocity that will allow the grid to stop at the destination.
/// </summary>
/// <param name="localDisp">The displacement to the destination.</param>
/// <returns>The maximum velocity that will allow the grid to stop at the destination.</returns>
private Vector3 MaximumVelocity(Vector3 localDisp)
{
Vector3 result = Vector3.Zero;
if (localDisp.X > 0f)
result.X = MaximumSpeed(localDisp.X, Base6Directions.Direction.Left);
else if (localDisp.X < 0f)
result.X = -MaximumSpeed(-localDisp.X, Base6Directions.Direction.Right);
if (localDisp.Y > 0f)
result.Y = MaximumSpeed(localDisp.Y, Base6Directions.Direction.Down);
else if (localDisp.Y < 0f)
result.Y = -MaximumSpeed(-localDisp.Y, Base6Directions.Direction.Up);
if (localDisp.Z > 0f)
result.Z = MaximumSpeed(localDisp.Z, Base6Directions.Direction.Forward);
else if (localDisp.Z < 0f)
result.Z = -MaximumSpeed(-localDisp.Z, Base6Directions.Direction.Backward);
//Log.DebugLog("displacement: " + localDisp + ", maximum velocity: " + result, "MaximumVelocity()");
return result;
}
/// <summary>
/// Calculates the maximum speed that will allow the grid to stop at the destination.
/// </summary>
/// <param name="dist">The distance to the destination</param>
/// <param name="direct">The directional thrusters to use</param>
/// <returns>The maximum speed that will allow the grid to stop at the destination.</returns>
private float MaximumSpeed(float dist, Base6Directions.Direction direct)
{
if (dist < 0.01f)
return 0f;
direct = Block.CubeBlock.Orientation.TransformDirection(direct);
float force = Thrust.GetForceInDirection(direct, true) * AvailableForceRatio;
if (force < 1f)
{
//Log.DebugLog("No thrust available in direction: " + direct + ", dist: " + dist, "MaximumSpeed()", Logger.severity.DEBUG);
return dist * 0.1f;
}
float accel = -force / Block.Physics.Mass;
//Log.DebugLog("direction: " + direct + ", dist: " + dist + ", max accel: " + accel + ", mass: " + Block.Physics.Mass + ", max speed: " + PrettySI.makePretty(Math.Sqrt(-2f * accel * dist)) + " m/s" + ", cap: " + dist * 0.5f + " m/s", "MaximumSpeed()");
//return Math.Min((float)Math.Sqrt(-2f * accel * dist), dist * 0.25f); // capped for the sake of autopilot's reaction time
return (float)Math.Sqrt(-2f * accel * dist);
}
/// <summary>
/// Calculate the force ratio from acceleration.
/// </summary>
/// <param name="blockAccel">Acceleration</param>
/// <returns>Force ratio</returns>
private Vector3 ToForceRatio(Vector3 blockAccel)
{
Vector3 result = Vector3.Zero;
if (blockAccel.X > 0f)
result.X = blockAccel.X * Block.Physics.Mass / Thrust.GetForceInDirection(Base6Directions.GetFlippedDirection(Block.CubeBlock.Orientation.Left));
else if (blockAccel.X < 0f)
result.X = blockAccel.X * Block.Physics.Mass / Thrust.GetForceInDirection(Block.CubeBlock.Orientation.Left);
if (blockAccel.Y > 0f)
result.Y = blockAccel.Y * Block.Physics.Mass / Thrust.GetForceInDirection(Block.CubeBlock.Orientation.Up);
else if (blockAccel.Y < 0f)
result.Y = blockAccel.Y * Block.Physics.Mass / Thrust.GetForceInDirection(Base6Directions.GetFlippedDirection(Block.CubeBlock.Orientation.Up));
if (blockAccel.Z > 0f)
result.Z = blockAccel.Z * Block.Physics.Mass / Thrust.GetForceInDirection(Base6Directions.GetFlippedDirection(Block.CubeBlock.Orientation.Forward));
else if (blockAccel.Z < 0f)
result.Z = blockAccel.Z * Block.Physics.Mass / Thrust.GetForceInDirection(Block.CubeBlock.Orientation.Forward);
//Log.DebugLog("accel: " + localAccel + ", force ratio: " + result + ", mass: " + Block.Physics.Mass, "ToForceRatio()");
return result;
}
#endregion Move
#region Rotate
/// <summary>
/// Rotate to face the best direction for flight.
/// </summary>
public void CalcRotate()
{
//Log.DebugLog("entered CalcRotate()", "CalcRotate()");
//Vector3 pathMoveResult = m_newPathfinder.m_targetDirection;
//if (!pathMoveResult.IsValid())
//{
// CalcRotate_Stop();
// return;
//}
// if the ship is limited, it must always face accel direction
if (!Thrust.CanMoveAnyDirection() && m_moveAccel != Vector3.Zero)
{
//Log.DebugLog("limited thrust");
CalcRotate_Accel();
return;
}
//if (NavSet.Settings_Current.NearingDestination)
//{
// CalcRotate_Stop();
// return;
//}
if (m_thrustHigh && m_moveAccel != Vector3.Zero)
{
m_thrustHigh = false;
//Log.DebugLog("accel high");
CalcRotate_Accel();
return;
}
CalcRotate_Hover();
}
/// <summary>
/// Match orientation with the target block.
/// </summary>
/// <param name="block">The navigation block</param>
/// <param name="destBlock">The destination block</param>
/// <param name="forward">The direction of destBlock that will be matched to navigation block's forward</param>
/// <param name="upward">The direction of destBlock that will be matched to navigation block's upward</param>
/// <returns>True iff localMatrix is facing the same direction as destBlock's forward</returns>
public void CalcRotate(PseudoBlock block, IMyCubeBlock destBlock, Base6Directions.Direction? forward, Base6Directions.Direction? upward)
{
//Log.DebugLog("entered CalcRotate(PseudoBlock block, IMyCubeBlock destBlock, Base6Directions.Direction? forward, Base6Directions.Direction? upward)", "CalcRotate()");
if (forward == null)
forward = Base6Directions.Direction.Forward;
RelativeDirection3F faceForward = RelativeDirection3F.FromWorld(block.Grid, destBlock.WorldMatrix.GetDirectionVector(forward.Value));
RelativeDirection3F faceUpward = upward.HasValue ? RelativeDirection3F.FromWorld(block.Grid, destBlock.WorldMatrix.GetDirectionVector(upward.Value)) : null;
CalcRotate(block.LocalMatrix, faceForward, faceUpward);
}
/// <summary>
/// Calculates the force necessary to rotate the grid.
/// </summary>
/// <param name="Direction">The direction to face the localMatrix in.</param>
/// <param name="block"></param>
/// <returns>True iff localMatrix is facing Direction</returns>
public void CalcRotate(PseudoBlock block, RelativeDirection3F Direction, RelativeDirection3F UpDirect = null, IMyEntity targetEntity = null)
{
//Log.DebugLog("entered CalcRotate(PseudoBlock block, RelativeDirection3F Direction, RelativeDirection3F UpDirect = null, IMyEntity targetEntity = null)", "CalcRotate()");
CalcRotate(block.LocalMatrix, Direction, UpDirect, targetEntity: targetEntity);
}
/// <summary>
/// Rotate to face the acceleration direction. If acceleration is zero, invokes CalcRotate_Stop.
/// </summary>
public void CalcRotate_Accel()
{
if (m_moveAccel == Vector3.Zero)
{
CalcRotate_Stop();
return;
}
if (SignificantGravity())
CalcRotate_InGravity(RelativeDirection3F.FromBlock(Block.CubeBlock, m_moveAccel));
else
CalcRotate(Thrust.Standard.LocalMatrix, RelativeDirection3F.FromBlock(Block.CubeBlock, m_moveAccel));
}
/// <summary>
/// Calculate the best rotation to stop the ship.
/// </summary>
/// TODO: if ship cannot rotate quickly, find a reasonable alternative to facing primary
public void CalcRotate_Stop()
{
//Log.DebugLog("entered CalcRotate_Stop()", "CalcRotate_Stop()");
Vector3 linearVelocity = LinearVelocity;
if (!Thrust.CanMoveAnyDirection() || linearVelocity.LengthSquared() > 1f)
{
//Log.DebugLog("rotate to stop");
if (SignificantGravity())
CalcRotate_InGravity(RelativeDirection3F.FromWorld(Block.CubeGrid, -linearVelocity));
else
CalcRotate(Thrust.Standard.LocalMatrix, RelativeDirection3F.FromWorld(Block.CubeGrid, -linearVelocity));
return;
}
CalcRotate_Hover();
}
/// <summary>
/// When in space, stops rotation. When in gravity, rotate to hover.
/// </summary>
private void CalcRotate_Hover()
{
if (SignificantGravity())
{
float accel = Thrust.SecondaryForce / Block.Physics.Mass;
if (accel > Thrust.GravityStrength)
{
Log.DebugLog("facing secondary away from gravity, secondary: " + Thrust.Gravity.LocalMatrix.Forward + ", away from gravity: " + (-Thrust.LocalGravity.vector));
CalcRotate(Thrust.Gravity.LocalMatrix, RelativeDirection3F.FromLocal(Block.CubeGrid, -Thrust.LocalGravity.vector), gravityAdjusted: true);
}
else
{
Log.DebugLog("facing primary away from gravity, primary: " + Thrust.Standard.LocalMatrix.Forward + ", away from gravity: " + (-Thrust.LocalGravity.vector));
CalcRotate(Thrust.Standard.LocalMatrix, RelativeDirection3F.FromLocal(Block.CubeGrid, -Thrust.LocalGravity.vector), gravityAdjusted: true);
}
return;
}
//Log.DebugLog("stopping rotation");
StopRotate();
}
private void CalcRotate_InGravity(RelativeDirection3F direction)
{
//Log.DebugLog("entered CalcRotate_InGravity(RelativeDirection3F direction)", "CalcRotate_InGravity()");
float secondaryAccel = Thrust.SecondaryForce / Block.Physics.Mass;
RelativeDirection3F fightGrav = RelativeDirection3F.FromLocal(Block.CubeGrid, -Thrust.LocalGravity.vector);
if (secondaryAccel > Thrust.GravityStrength)
{
// secondary thrusters are strong enough to fight gravity
if (Vector3.Dot(direction.ToLocalNormalized(), fightGrav.ToLocalNormalized()) > 0f)
{
// direction is away from gravity
Log.DebugLog("Facing primary towards direction(" + direction.ToLocalNormalized() + "), rolling secondary away from gravity(" + fightGrav.ToLocalNormalized() + ")");
CalcRotate(Thrust.Standard.LocalMatrix, direction, fightGrav, gravityAdjusted: true);
return;
}
else
{
// direction is towards gravity
Log.DebugLog("Facing secondary away from gravity(" + fightGrav.ToLocalNormalized() + "), rolling primary towards direction(" + direction.ToLocalNormalized() + ")");
CalcRotate(Thrust.Gravity.LocalMatrix, fightGrav, direction, gravityAdjusted: true);
return;
}
}
// secondary thrusters are not strong enough to fight gravity
if (secondaryAccel > 1f)
{
Log.DebugLog("Facing primary towards gravity(" + fightGrav.ToLocalNormalized() + "), rolling secondary towards direction(" + direction.ToLocalNormalized() + ")");
CalcRotate(Thrust.Standard.LocalMatrix, fightGrav, direction, gravityAdjusted: true);
return;
}
// helicopter
float primaryAccel = Math.Max(Thrust.PrimaryForce / Block.Physics.Mass - Thrust.GravityStrength, 1f); // obviously less than actual value but we do not need maximum theoretical acceleration
DirectionGrid moveAccel = m_moveAccel != Vector3.Zero ? ((DirectionBlock)m_moveAccel).ToGrid(Block.CubeBlock) : LinearVelocity.ToGrid(Block.CubeGrid) * -0.5f;
if (moveAccel.vector.LengthSquared() > primaryAccel * primaryAccel)
{
//Log.DebugLog("move accel is over available acceleration: " + moveAccel.vector.Length() + " > " + primaryAccel, "CalcRotate_InGravity()");
moveAccel = Vector3.Normalize(moveAccel.vector) * primaryAccel;
}
//Log.DebugLog("Facing primary away from gravity and towards direction, moveAccel: " + moveAccel + ", fight gravity: " + fightGrav.ToLocal() + ", direction: " + direction.ToLocalNormalized() + ", new direction: " + (moveAccel + fightGrav.ToLocal()));
Vector3 dirV = moveAccel + fightGrav.ToLocal();
direction = RelativeDirection3F.FromLocal(Block.CubeGrid, dirV);
CalcRotate(Thrust.Standard.LocalMatrix, direction, gravityAdjusted: true);
Vector3 fightGravDirection = fightGrav.ToLocal() / Thrust.GravityStrength;
// determine acceleration needed in forward direction to move to desired altitude or remain at current altitude
float projectionMagnitude = Vector3.Dot(dirV, fightGravDirection) / Vector3.Dot(Thrust.Standard.LocalMatrix.Forward, fightGravDirection);
Vector3 projectionDirection = ((DirectionGrid)Thrust.Standard.LocalMatrix.Forward).ToBlock(Block.CubeBlock);
m_moveForceRatio = projectionDirection * projectionMagnitude * Block.CubeGrid.Physics.Mass / Thrust.PrimaryForce;
Log.DebugLog("changed moveForceRatio, projectionMagnitude: " + projectionMagnitude + ", projectionDirection: " + projectionDirection + ", moveForceRatio: " + m_moveForceRatio);
}
// necessary wrapper for main CalcRotate, should always be called.
private void CalcRotate(Matrix localMatrix, RelativeDirection3F Direction, RelativeDirection3F UpDirect = null, bool gravityAdjusted = false, IMyEntity targetEntity = null)
{
//Log.DebugLog("entered CalcRotate(Matrix localMatrix, RelativeDirection3F Direction, RelativeDirection3F UpDirect = null, bool levelingOff = false, IMyEntity targetEntity = null)", "CalcRotate()");
CheckGrid();
Thrust.Update();
if (!gravityAdjusted && ThrustersOverWorked())
{
CalcRotate_InGravity(Direction);
return;
}
in_CalcRotate(localMatrix, Direction, UpDirect, targetEntity);
}
/// <summary>
/// Calculates the force necessary to rotate the grid. Two degrees of freedom are used to rotate forward toward Direction; the remaining degree is used to face upward towards UpDirect.
/// </summary>
/// <param name="localMatrix">The matrix to rotate to face the direction, use a block's local matrix or result of GetMatrix()</param>
/// <param name="Direction">The direction to face the localMatrix in.</param>
private void in_CalcRotate(Matrix localMatrix, RelativeDirection3F Direction, RelativeDirection3F UpDirect, IMyEntity targetEntity)
{
Log.DebugLog("Direction == null", Logger.severity.ERROR, condition: Direction == null);
m_gyro.Update();
float minimumMoment = Math.Min(m_gyro.InvertedInertiaMoment.Min(), MaxInverseTensor);
if (minimumMoment <= 0f)
{
// == 0f, not calculated yet. < 0f, we have math failure
StopRotate();
Log.DebugLog("minimumMoment < 0f", Logger.severity.FATAL, condition: minimumMoment < 0f);
return;
}
localMatrix.M41 = 0; localMatrix.M42 = 0; localMatrix.M43 = 0; localMatrix.M44 = 1;
Matrix inverted; Matrix.Invert(ref localMatrix, out inverted);
localMatrix = localMatrix.GetOrientation();
inverted = inverted.GetOrientation();
Vector3 localDirect = Direction.ToLocalNormalized();
Vector3 rotBlockDirect; Vector3.Transform(ref localDirect, ref inverted, out rotBlockDirect);
float azimuth, elevation; Vector3.GetAzimuthAndElevation(rotBlockDirect, out azimuth, out elevation);
Vector3 rotaRight = localMatrix.Right;
Vector3 rotaUp = localMatrix.Up;
Vector3 NFR_right = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaRight));
Vector3 NFR_up = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaUp));
Vector3 displacement = -elevation * NFR_right - azimuth * NFR_up;
if (UpDirect != null)
{
Vector3 upLocal = UpDirect.ToLocalNormalized();
Vector3 upRotBlock; Vector3.Transform(ref upLocal, ref inverted, out upRotBlock);
upRotBlock.Z = 0f;
upRotBlock.Normalize();
float roll = Math.Sign(upRotBlock.X) * (float)Math.Acos(MathHelper.Clamp(upRotBlock.Y, -1f, 1f));
Vector3 rotaBackward = localMatrix.Backward;
Vector3 NFR_backward = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaBackward));
//Log.DebugLog("upLocal: " + upLocal + ", upRotBlock: " + upRotBlock + ", roll: " + roll + ", displacement: " + displacement + ", NFR_backward: " + NFR_backward + ", change: " + roll * NFR_backward, "in_CalcRotate()");
displacement += roll * NFR_backward;
}
m_lastMoveAttempt = Globals.UpdateCount;
RotateCheck.TestRotate(displacement);
float distanceAngle = displacement.Length();
//if (distanceAngle < m_bestAngle || float.IsNaN(NavSet.Settings_Current.DistanceAngle))
//{
// m_bestAngle = distanceAngle;
// if (RotateCheck.ObstructingEntity == null)
// m_lastAccel = Globals.UpdateCount;
//}
NavSet.Settings_Task_NavWay.DistanceAngle = distanceAngle;
//Log.DebugLog("localDirect: " + localDirect + ", rotBlockDirect: " + rotBlockDirect + ", elevation: " + elevation + ", NFR_right: " + NFR_right + ", azimuth: " + azimuth + ", NFR_up: " + NFR_up + ", disp: " + displacement, "in_CalcRotate()");
m_rotateTargetVelocity = MaxAngleVelocity(displacement, minimumMoment, targetEntity != null);
// adjustment to face a moving entity
if (targetEntity != null)
{
Vector3 relativeLinearVelocity = (targetEntity.GetLinearVelocity() - LinearVelocity) * 1.1f;
float distance = Vector3.Distance(targetEntity.GetCentre(), Block.CubeBlock.GetPosition());
//Log.DebugLog("relativeLinearVelocity: " + relativeLinearVelocity + ", tangentialVelocity: " + tangentialVelocity + ", localTangVel: " + localTangVel, "in_CalcRotate()");
float RLV_pitch = Vector3.Dot(relativeLinearVelocity, Block.CubeBlock.WorldMatrix.Down);
float RLV_yaw = Vector3.Dot(relativeLinearVelocity, Block.CubeBlock.WorldMatrix.Right);
float angl_pitch = (float)Math.Atan2(RLV_pitch, distance);
float angl_yaw = (float)Math.Atan2(RLV_yaw, distance);
Log.DebugLog("relativeLinearVelocity: " + relativeLinearVelocity + ", RLV_yaw: " + RLV_yaw + ", RLV_pitch: " + RLV_pitch + ", angl_yaw: " + angl_yaw + ", angl_pitch: " + angl_pitch + ", total adjustment: " + (NFR_right * angl_pitch + NFR_up * angl_yaw));
m_rotateTargetVelocity += NFR_right * angl_pitch + NFR_up * angl_yaw;
}
//Log.DebugLog("targetVelocity: " + m_rotateTargetVelocity, "in_CalcRotate()");
if (RotateCheck.ObstructingEntity != null)
{
float maxVel = (float)Math.Atan2(1d, Block.CubeGrid.LocalVolume.Radius);
float lenSq = m_rotateTargetVelocity.LengthSquared();
if (lenSq > maxVel)
{
Log.DebugLog("Reducing target velocity from " + Math.Sqrt(lenSq) + " to " + maxVel);
Vector3 normVel; Vector3.Divide(ref m_rotateTargetVelocity, (float)Math.Sqrt(lenSq), out normVel);
Vector3.Multiply(ref normVel, maxVel, out m_rotateTargetVelocity);
}
}
// angular velocity is reversed
Vector3 angularVelocity = AngularVelocity.ToBlock(Block.CubeBlock);// ((DirectionWorld)(-Block.Physics.AngularVelocity)).ToBlock(Block.CubeBlock);
m_rotateForceRatio = (m_rotateTargetVelocity + angularVelocity) / (minimumMoment * m_gyro.GyroForce);
//Log.DebugLog("targetVelocity: " + m_rotateTargetVelocity + ", angularVelocity: " + angularVelocity + ", accel: " + (m_rotateTargetVelocity + angularVelocity));
//Log.DebugLog("minimumMoment: " + minimumMoment + ", force: " + m_gyro.GyroForce + ", rotateForceRatio: " + m_rotateForceRatio);
// dampeners
for (int index = 0; index < 3; index++)
{
// if targetVelocity is close to 0, use dampeners
float target = m_rotateTargetVelocity.GetDim(index);
if (target > -0.01f && target < 0.01f)
{
//Log.DebugLog("target near 0 for " + i + ", " + target, "in_CalcRotate()");
m_rotateTargetVelocity.SetDim(index, 0f);
m_rotateForceRatio.SetDim(index, 0f);
continue;
}
}
}
/// <summary>
/// Calulates the maximum angular velocity to stop at the destination.
/// </summary>
/// <param name="disp">Displacement to the destination.</param>
/// <returns>The maximum angular velocity to stop at the destination.</returns>
private Vector3 MaxAngleVelocity(Vector3 disp, float minimumMoment, bool fast)
{
Vector3 result = Vector3.Zero;
// S.E. provides damping for angular motion, we will ignore this
float accel = -minimumMoment * m_gyro.GyroForce;
for (int index = 0; index < 3; index++)
{
float dim = disp.GetDim(index);
if (dim > 0)
result.SetDim(index, MaxAngleSpeed(accel, dim, fast));
else if (dim < 0)
result.SetDim(index, -MaxAngleSpeed(accel, -dim, fast));
}
return result;
}
/// <summary>
/// Calculates the maximum angular speed to stop at the destination.
/// </summary>
/// <param name="accel">negative number, maximum deceleration</param>
/// <param name="dist">positive number, distance to travel</param>
/// <returns>The maximum angular speed to stop at the destination</returns>
private float MaxAngleSpeed(float accel, float dist, bool fast)
{
//Log.DebugLog("accel: " + accel + ", dist: " + dist, "MaxAngleSpeed()");
float actual = (float)Math.Sqrt(-2 * accel * dist);
if (fast)
return Math.Min(actual, dist * 10f);
return Math.Min(actual, dist * 2f);
}
#endregion Rotate
/// <summary>
/// Apply the calculated force ratios to the controller.
/// </summary>
public void MoveAndRotate()
{
CheckGrid();
//Log.DebugLog("moveForceRatio: " + moveForceRatio + ", rotateForceRatio: " + rotateForceRatio + ", move length: " + moveForceRatio.Length(), "MoveAndRotate()");
// if all the force ratio values are 0, Autopilot has to stop the ship, MoveAndRotate will not
if (m_moveForceRatio == Vector3.Zero && m_rotateTargetVelocity == Vector3.Zero)
{
//Log.DebugLog("Stopping the ship, move: " + m_moveForceRatio + ", rotate: " + m_rotateTargetVelocity);
// should not toggle dampeners, grid may just have landed
MoveAndRotateStop(false);
return;
}
if (m_moveForceRatio != Vector3.Zero && CheckStuck(WriggleAfter))
{
ulong upWoMove = Globals.UpdateCount - m_lastAccel;
if (m_rotateForceRatio != Vector3.Zero)
{
// wriggle
float wriggle = (upWoMove - WriggleAfter) * 0.0001f;
//Log.DebugLog("wriggle: " + wriggle + ", updates w/o moving: " + upWoMove);
m_rotateForceRatio.X += (0.5f - (float)Globals.Random.NextDouble()) * wriggle;
m_rotateForceRatio.Y += (0.5f - (float)Globals.Random.NextDouble()) * wriggle;
m_rotateForceRatio.Z += (0.5f - (float)Globals.Random.NextDouble()) * wriggle;
}
// increase force
m_moveForceRatio *= 1f + (upWoMove - WriggleAfter) * 0.1f;
}
// clamp values
Vector3 moveControl;
moveControl.X = MathHelper.Clamp(m_moveForceRatio.X, -1f, 1f);
moveControl.Y = MathHelper.Clamp(m_moveForceRatio.Y, -1f, 1f);
moveControl.Z = MathHelper.Clamp(m_moveForceRatio.Z, -1f, 1f);
Vector3 rotateControl = -m_rotateForceRatio; // control torque is opposite of move indicator
Vector3.ClampToSphere(ref rotateControl, 1f);
m_stopped = false;
MyShipController controller = Block.Controller;
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => {
//Log.DebugLog("rotate control: " + rotateControl + ", previous: " + m_prevRotateControl + ", delta: " + (rotateControl - m_prevRotateControl), "MoveAndRotate()");
if (Block.Controller.GridGyroSystem != null)
{
DirectionGrid gridRotate = ((DirectionBlock)rotateControl).ToGrid(Block.CubeBlock);
Block.Controller.GridGyroSystem.ControlTorque = gridRotate;
}
else
Log.DebugLog("No gyro system");
MyEntityThrustComponent thrustComponent = Block.CubeGrid.Components.Get<MyEntityThrustComponent>();
if (thrustComponent != null)
{
DirectionGrid gridMove = ((DirectionBlock)moveControl).ToGrid(Block.CubeBlock);
thrustComponent.ControlThrust = gridMove;
}
else
Log.DebugLog("No thrust component");
});
}
private void CheckGrid()
{
if (m_grid != Block.CubeGrid)
{
Log.DebugLog("Grid Changed! from " + m_grid.getBestName() + " to " + Block.CubeGrid.getBestName(), Logger.severity.INFO, condition: m_grid != null);
m_grid = Block.CubeGrid;
this.Thrust = new ThrustProfiler(Block.CubeBlock);
this.m_gyro = new GyroProfiler(m_grid);
}
}
/// <summary>
/// Ship is in danger of being brought down by gravity.
/// </summary>
public bool ThrustersOverWorked(float threshold = OverworkedThreshold)
{
Log.DebugLog("myThrust == null", Logger.severity.FATAL, condition: Thrust == null);
return Thrust.GravityReactRatio.vector.AbsMax() >= threshold;
}
/// <summary>
/// Ship may want to adjust for gravity.
/// </summary>
public bool SignificantGravity()
{
return Thrust.GravityStrength > 1f;
}
public void SetControl(bool enable)
{
if (Block.AutopilotControl != enable)
{
Log.DebugLog("setting control, AutopilotControl: " + Block.AutopilotControl + ", enable: " + enable);
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => {
if (!enable)
{
Block.Controller.MoveAndRotateStopped();
Thrust.ClearOverrides();
//m_gyro.ClearOverrides();
}
Block.AutopilotControl = enable;
});
}
}
public void SetDamping(bool enable)
{
Sandbox.Game.Entities.IMyControllableEntity control = Block.Controller as Sandbox.Game.Entities.IMyControllableEntity;
if (control.EnabledDamping != enable)
{
Log.TraceLog("setting damp, EnabledDamping: " + control.EnabledDamping + ", enable: " + enable);
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => {
if (control.EnabledDamping != enable)
control.SwitchDamping();
});
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Replays;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Replays;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Mania.Tests
{
public class TestSceneHoldNoteInput : RateAdjustedBeatmapTestScene
{
private const double time_before_head = 250;
private const double time_head = 1500;
private const double time_during_hold_1 = 2500;
private const double time_tail = 4000;
private const double time_after_tail = 5250;
private List<JudgementResult> judgementResults;
/// <summary>
/// -----[ ]-----
/// o o
/// </summary>
[Test]
public void TestNoInput()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_before_head),
new ManiaReplayFrame(time_after_tail),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Miss);
assertNoteJudgement(HitResult.IgnoreHit);
}
/// <summary>
/// -----[ ]-----
/// x o
/// </summary>
[Test]
public void TestPressTooEarlyAndReleaseAfterTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_before_head, ManiaAction.Key1),
new ManiaReplayFrame(time_after_tail, ManiaAction.Key1),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// x o
/// </summary>
[Test]
public void TestPressTooEarlyAndReleaseAtTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_before_head, ManiaAction.Key1),
new ManiaReplayFrame(time_tail),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// xo x o
/// </summary>
[Test]
public void TestPressTooEarlyThenPressAtStartAndReleaseAfterTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_before_head, ManiaAction.Key1),
new ManiaReplayFrame(time_before_head + 10),
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_after_tail),
});
assertHeadJudgement(HitResult.Perfect);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// xo x o
/// </summary>
[Test]
public void TestPressTooEarlyThenPressAtStartAndReleaseAtTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_before_head, ManiaAction.Key1),
new ManiaReplayFrame(time_before_head + 10),
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_tail),
});
assertHeadJudgement(HitResult.Perfect);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Perfect);
}
/// <summary>
/// -----[ ]-----
/// xo o
/// </summary>
[Test]
public void TestPressAtStartAndBreak()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_head + 10),
new ManiaReplayFrame(time_after_tail),
});
assertHeadJudgement(HitResult.Perfect);
assertTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// xo x o
/// </summary>
[Test]
public void TestPressAtStartThenBreakThenRepressAndReleaseAfterTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_head + 10),
new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1),
new ManiaReplayFrame(time_after_tail),
});
assertHeadJudgement(HitResult.Perfect);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// xo x o o
/// </summary>
[Test]
public void TestPressAtStartThenBreakThenRepressAndReleaseAtTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_head + 10),
new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1),
new ManiaReplayFrame(time_tail),
});
assertHeadJudgement(HitResult.Perfect);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Meh);
}
/// <summary>
/// -----[ ]-----
/// x o
/// </summary>
[Test]
public void TestPressDuringNoteAndReleaseAfterTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1),
new ManiaReplayFrame(time_after_tail),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Miss);
}
/// <summary>
/// -----[ ]-----
/// x o o
/// </summary>
[Test]
public void TestPressDuringNoteAndReleaseAtTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1),
new ManiaReplayFrame(time_tail),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickHit);
assertTailJudgement(HitResult.Meh);
}
/// <summary>
/// -----[ ]-----
/// xo o
/// </summary>
[Test]
public void TestPressAndReleaseAtTail()
{
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_tail, ManiaAction.Key1),
new ManiaReplayFrame(time_tail + 10),
});
assertHeadJudgement(HitResult.Miss);
assertTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Meh);
}
[Test]
public void TestMissReleaseAndHitSecondRelease()
{
var windows = new ManiaHitWindows();
windows.SetDifficulty(10);
var beatmap = new Beatmap<ManiaHitObject>
{
HitObjects =
{
new HoldNote
{
StartTime = 1000,
Duration = 500,
Column = 0,
},
new HoldNote
{
StartTime = 1000 + 500 + windows.WindowFor(HitResult.Miss) + 10,
Duration = 500,
Column = 0,
},
},
BeatmapInfo =
{
BaseDifficulty = new BeatmapDifficulty
{
SliderTickRate = 4,
OverallDifficulty = 10,
},
Ruleset = new ManiaRuleset().RulesetInfo
},
};
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(beatmap.HitObjects[1].StartTime, ManiaAction.Key1),
new ManiaReplayFrame(beatmap.HitObjects[1].GetEndTime()),
}, beatmap);
AddAssert("first hold note missed", () => judgementResults.Where(j => beatmap.HitObjects[0].NestedHitObjects.Contains(j.HitObject))
.All(j => !j.Type.IsHit()));
AddAssert("second hold note missed", () => judgementResults.Where(j => beatmap.HitObjects[1].NestedHitObjects.Contains(j.HitObject))
.All(j => j.Type.IsHit()));
}
[Test]
public void TestHitTailBeforeLastTick()
{
const int tick_rate = 8;
const double tick_spacing = TimingControlPoint.DEFAULT_BEAT_LENGTH / tick_rate;
const double time_last_tick = time_head + tick_spacing * (int)((time_tail - time_head) / tick_spacing - 1);
var beatmap = new Beatmap<ManiaHitObject>
{
HitObjects =
{
new HoldNote
{
StartTime = time_head,
Duration = time_tail - time_head,
Column = 0,
}
},
BeatmapInfo =
{
BaseDifficulty = new BeatmapDifficulty { SliderTickRate = tick_rate },
Ruleset = new ManiaRuleset().RulesetInfo
},
};
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_last_tick - 5)
}, beatmap);
assertHeadJudgement(HitResult.Perfect);
assertLastTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Ok);
}
[Test]
public void TestZeroLength()
{
var beatmap = new Beatmap<ManiaHitObject>
{
HitObjects =
{
new HoldNote
{
StartTime = 1000,
Duration = 0,
Column = 0,
},
},
BeatmapInfo = { Ruleset = new ManiaRuleset().RulesetInfo },
};
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(beatmap.HitObjects[0].StartTime, ManiaAction.Key1),
new ManiaReplayFrame(beatmap.HitObjects[0].GetEndTime() + 1),
}, beatmap);
AddAssert("hold note hit", () => judgementResults.Where(j => beatmap.HitObjects[0].NestedHitObjects.Contains(j.HitObject))
.All(j => j.Type.IsHit()));
}
private void assertHeadJudgement(HitResult result)
=> AddAssert($"head judged as {result}", () => judgementResults.First(j => j.HitObject is Note).Type == result);
private void assertTailJudgement(HitResult result)
=> AddAssert($"tail judged as {result}", () => judgementResults.Single(j => j.HitObject is TailNote).Type == result);
private void assertNoteJudgement(HitResult result)
=> AddAssert($"hold note judged as {result}", () => judgementResults.Single(j => j.HitObject is HoldNote).Type == result);
private void assertTickJudgement(HitResult result)
=> AddAssert($"any tick judged as {result}", () => judgementResults.Where(j => j.HitObject is HoldNoteTick).Any(j => j.Type == result));
private void assertLastTickJudgement(HitResult result)
=> AddAssert($"last tick judged as {result}", () => judgementResults.Last(j => j.HitObject is HoldNoteTick).Type == result);
private ScoreAccessibleReplayPlayer currentPlayer;
private void performTest(List<ReplayFrame> frames, Beatmap<ManiaHitObject> beatmap = null)
{
if (beatmap == null)
{
beatmap = new Beatmap<ManiaHitObject>
{
HitObjects =
{
new HoldNote
{
StartTime = time_head,
Duration = time_tail - time_head,
Column = 0,
}
},
BeatmapInfo =
{
BaseDifficulty = new BeatmapDifficulty { SliderTickRate = 4 },
Ruleset = new ManiaRuleset().RulesetInfo
},
};
beatmap.ControlPointInfo.Add(0, new EffectControlPoint { ScrollSpeed = 0.1f });
}
AddStep("load player", () =>
{
Beatmap.Value = CreateWorkingBeatmap(beatmap);
var p = new ScoreAccessibleReplayPlayer(new Score { Replay = new Replay { Frames = frames } });
p.OnLoadComplete += _ =>
{
p.ScoreProcessor.NewJudgement += result =>
{
if (currentPlayer == p) judgementResults.Add(result);
};
};
LoadScreen(currentPlayer = p);
judgementResults = new List<JudgementResult>();
});
AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0);
AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen());
AddUntilStep("Wait for completion", () => currentPlayer.ScoreProcessor?.HasCompleted.Value == true);
}
private class ScoreAccessibleReplayPlayer : ReplayPlayer
{
public new ScoreProcessor ScoreProcessor => base.ScoreProcessor;
public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer;
protected override bool PauseOnFocusLost => false;
public ScoreAccessibleReplayPlayer(Score score)
: base(score, new PlayerConfiguration
{
AllowPause = false,
ShowResults = false,
})
{
}
}
}
}
| |
// Shatter Toolkit
// Copyright 2012 Gustav Olsson
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class ShatterTool : MonoBehaviour
{
[SerializeField]
private int generation = 1;
[SerializeField]
private int generationLimit = 3;
[SerializeField]
private int cuts = 2;
[SerializeField]
private bool fillCut = true;
[SerializeField]
private bool sendPreSplitMessage = false;
[SerializeField]
private bool sendPostSplitMessage = false;
[SerializeField]
private HullType internalHullType = HullType.FastHull;
private IHull hull;
private Vector3 center;
/// <summary>
/// Gets or sets the current generation of this ShatterTool instance.
/// By default, a game object is of generation 1. When a game object
/// is shattered using ShatterTool.Shatter() all new game objects
/// will be considered of generation 2, and so on.
/// For example, this value can be used to vary the color of a
/// game object depending on how many times it has been shattered.
/// </summary>
public int Generation
{
get { return generation; }
set { generation = Mathf.Max(value, 1); }
}
/// <summary>
/// Gets or sets the generation limit of this ShatterTool instance.
/// This value restricts how many times a game object may be shattered
/// using ShatterTool.Shatter(). A game object will only be able to shatter
/// if ShatterTool.Generation is less than ShatterTool.GenerationLimit.
/// </summary>
public int GenerationLimit
{
get { return generationLimit; }
set { generationLimit = Mathf.Max(value, 1); }
}
/// <summary>
/// Gets or sets the number of times the game object will be cut when ShatterTool.Shatter() occurs.
/// </summary>
public int Cuts
{
get { return cuts; }
set { cuts = Mathf.Max(value, 1); }
}
/// <summary>
/// Gets or sets whether the cut region should be triangulated.
/// If true, the connected UvMapper component will control the vertex properties of the filled area.
/// When the ShatterTool is used on double-sided meshes with zero thickness, such as planes, this value
/// should be false.
/// </summary>
public bool FillCut
{
get { return fillCut; }
set { fillCut = value; }
}
/// <summary>
/// Gets or sets whether a PreSplit(Plane[] planes) message should be sent to the original game object prior to a split occurs.
/// The supplied object will be the array of Planes that will be used to split the game object.
/// </summary>
public bool SendPreSplitMessage
{
get { return sendPreSplitMessage; }
set { sendPreSplitMessage = value; }
}
/// <summary>
/// Gets or sets whether a PostSplit(GameObject[] newGameObjects) message should be sent to the original game object
/// after a split has occured. The message will be sent before destroying the original game object.
/// The supplied object will be an array of all new GameObjects created during the split.
/// </summary>
public bool SendPostSplitMessage
{
get { return sendPostSplitMessage; }
set { sendPostSplitMessage = value; }
}
/// <summary>
/// Gets or sets the type of the internal hull used to shatter the mesh. The FastHull implementation is roughly 20-50% faster
/// than the LegacyHull implementation and requires no time to startup. The LegacyHull implementation is more robust in extreme
/// cases and is provided for backwards compatibility. This setting can't be changed during runtime.
/// </summary>
public HullType InternalHullType
{
get { return internalHullType; }
set { internalHullType = value; }
}
/// <summary>
/// Determines whether this game object is of the first generation. (Generation == 1)
/// </summary>
public bool IsFirstGeneration
{
get { return generation == 1; }
}
/// <summary>
/// Determines whether this game object is of the last generation. (Generation >= GenerationLimit)
/// </summary>
public bool IsLastGeneration
{
get { return generation >= generationLimit; }
}
/// <summary>
/// Gets the worldspace center of the game object. Only works during runtime.
/// </summary>
public Vector3 Center
{
get { return transform.TransformPoint(center); }
}
private void CalculateCenter()
{
// Get the localspace center of the mesh bounds
center = GetComponent<MeshFilter>().sharedMesh.bounds.center;
}
public void Start()
{
Mesh sharedMesh = GetComponent<MeshFilter>().sharedMesh;
// Initialize the first generation hull
if (hull == null)
{
if (internalHullType == HullType.FastHull)
{
hull = new FastHull(sharedMesh);
}
else if (internalHullType == HullType.LegacyHull)
{
hull = new LegacyHull(sharedMesh);
}
}
// Update properties
CalculateCenter();
}
/// <summary>
/// Shatters the game object at a point, instantiating the pieces as new
/// game objects (clones of the original) and destroying the original game object when finished.
/// If the game object has reached the generation limit, nothing will happen.
/// Apart from taking the generation into account, this is equivalent to calling
/// ShatterTool.Split() using randomly generated planes passing through the point.
/// </summary>
/// <param name="point">
/// The world-space point.
/// </param>
public void Shatter(Vector3 point)
{
if (!IsLastGeneration)
{
// Increase generation
generation++;
// Split the hull using randomly generated planes passing through the point
Plane[] planes = new Plane[cuts];
for (int i = 0; i < planes.Length; i++)
{
planes[i] = new Plane(Random.onUnitSphere, point);
}
Split(planes);
}
}
/// <summary>
/// Splits the game object using an array of planes, instantiating the pieces as new
/// game objects (clones of the original) and destroying the original game object when finished.
/// </summary>
/// <param name="planes">
/// An array of world-space planes with unit-length normals.
/// </param>
public void Split(Plane[] planes)
{
if (planes != null && planes.Length > 0 && hull != null && !hull.IsEmpty)
{
UvMapper uvMapper = GetComponent<UvMapper>();
if (uvMapper != null)
{
if (sendPreSplitMessage)
{
SendMessage("PreSplit", planes, SendMessageOptions.DontRequireReceiver);
}
Vector3[] points, normals;
ConvertPlanesToLocalspace(planes, out points, out normals);
IList<IHull> newHulls;
CreateNewHulls(uvMapper, points, normals, out newHulls);
GameObject[] newGameObjects;
CreateNewGameObjects(newHulls, out newGameObjects);
if (sendPostSplitMessage)
{
SendMessage("PostSplit", newGameObjects, SendMessageOptions.DontRequireReceiver);
}
Destroy(gameObject);
}
else
{
Debug.LogWarning(name + " has no UvMapper attached! Please attach a UvMapper to use the ShatterTool.", this);
}
}
}
private void ConvertPlanesToLocalspace(Plane[] planes, out Vector3[] points, out Vector3[] normals)
{
points = new Vector3[planes.Length];
normals = new Vector3[planes.Length];
for (int i = 0; i < planes.Length; i++)
{
Plane plane = planes[i];
Vector3 localPoint = transform.InverseTransformPoint(plane.normal * -plane.distance);
Vector3 localNormal = transform.InverseTransformDirection(plane.normal);
localNormal.Scale(transform.localScale);
localNormal.Normalize();
points[i] = localPoint;
normals[i] = localNormal;
}
}
private void CreateNewHulls(UvMapper uvMapper, Vector3[] points, Vector3[] normals, out IList<IHull> newHulls)
{
newHulls = new List<IHull>();
// Add the starting hull
newHulls.Add(hull);
for (int j = 0; j < points.Length; j++)
{
int previousHullCount = newHulls.Count;
for (int i = 0; i < previousHullCount; i++)
{
IHull previousHull = newHulls[0];
// Split the previous hull
IHull a, b;
previousHull.Split(points[j], normals[j], fillCut, uvMapper, out a, out b);
// Update the list
newHulls.Remove(previousHull);
if (!a.IsEmpty)
{
newHulls.Add(a);
}
if (!b.IsEmpty)
{
newHulls.Add(b);
}
}
}
}
private void CreateNewGameObjects(IList<IHull> newHulls, out GameObject[] newGameObjects)
{
// Get new meshes
Mesh[] newMeshes = new Mesh[newHulls.Count];
float[] newVolumes = new float[newHulls.Count];
float totalVolume = 0.0f;
for (int i = 0; i < newHulls.Count; i++)
{
Mesh mesh = newHulls[i].GetMesh();
Vector3 size = mesh.bounds.size;
float volume = size.x * size.y * size.z;
newMeshes[i] = mesh;
newVolumes[i] = volume;
totalVolume += volume;
}
// Remove mesh references to speed up instantiation
GetComponent<MeshFilter>().sharedMesh = null;
MeshCollider meshCollider = GetComponent<MeshCollider>();
if (meshCollider != null)
{
meshCollider.sharedMesh = null;
}
// Create new game objects
newGameObjects = new GameObject[newHulls.Count];
for (int i = 0; i < newHulls.Count; i++)
{
IHull newHull = newHulls[i];
Mesh newMesh = newMeshes[i];
float volume = newVolumes[i];
GameObject newGameObject = (GameObject)Instantiate(gameObject);
// Set shatter tool
ShatterTool newShatterTool = newGameObject.GetComponent<ShatterTool>();
if (newShatterTool != null)
{
newShatterTool.hull = newHull;
}
// Set mesh filter
MeshFilter newMeshFilter = newGameObject.GetComponent<MeshFilter>();
if (newMeshFilter != null)
{
newMeshFilter.sharedMesh = newMesh;
}
// Set mesh collider
MeshCollider newMeshCollider = newGameObject.GetComponent<MeshCollider>();
if (newMeshCollider != null)
{
newMeshCollider.sharedMesh = newMesh;
}
// Set rigidbody
Rigidbody newRigidbody = newGameObject.rigidbody;
if (newRigidbody != null)
{
newRigidbody.mass = rigidbody.mass * (volume / totalVolume);
if (!newRigidbody.isKinematic)
{
newRigidbody.velocity = rigidbody.GetPointVelocity(newRigidbody.worldCenterOfMass);
newRigidbody.angularVelocity = rigidbody.angularVelocity;
}
}
// Update properties
newShatterTool.CalculateCenter();
newGameObjects[i] = newGameObject;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
namespace System.Management.Automation.Help
{
/// <summary>
/// Positional parameter comparer.
/// </summary>
internal class PositionalParameterComparer : IComparer
{
/// <summary>
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y)
{
CommandParameterInfo a = x as CommandParameterInfo;
CommandParameterInfo b = y as CommandParameterInfo;
Debug.Assert(a != null && b != null);
return (a.Position - b.Position);
}
}
/// <summary>
/// The help object builder class attempts to create a full HelpInfo object from
/// a CmdletInfo object. This is used to generate the default UX when no help content
/// is present in the box. This class mimics the exact same structure as that of a MAML
/// node, so that the default UX does not introduce regressions.
/// </summary>
internal class DefaultCommandHelpObjectBuilder
{
internal static string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo";
/// <summary>
/// Generates a HelpInfo PSObject from a CmdletInfo object.
/// </summary>
/// <param name="input">Command info.</param>
/// <returns>HelpInfo PSObject.</returns>
internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input)
{
// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
// sets based on Dynamic Parameters (+ optional arguments)
CommandInfo commandInfo = input.CreateGetCommandCopy(null);
PSObject obj = new PSObject();
obj.TypeNames.Clear();
obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp);
obj.TypeNames.Add("CmdletHelpInfo");
obj.TypeNames.Add("HelpInfo");
if (commandInfo is CmdletInfo cmdletInfo)
{
bool common = false;
if (cmdletInfo.Parameters != null)
{
common = HasCommonParameters(cmdletInfo.Parameters);
}
obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
AddDetailsProperties(obj, cmdletInfo.Name, cmdletInfo.Noun, cmdletInfo.Verb, TypeNameForDefaultHelp);
AddSyntaxProperties(obj, cmdletInfo.Name, cmdletInfo.ParameterSets, common, TypeNameForDefaultHelp);
AddParametersProperties(obj, cmdletInfo.Parameters, common, TypeNameForDefaultHelp);
AddInputTypesProperties(obj, cmdletInfo.Parameters);
AddRelatedLinksProperties(obj, commandInfo.CommandMetadata.HelpUri);
try
{
AddOutputTypesProperties(obj, cmdletInfo.OutputType);
}
catch (PSInvalidOperationException)
{
AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
}
AddAliasesProperties(obj, cmdletInfo.Name, cmdletInfo.Context);
if (HasHelpInfoUri(cmdletInfo.Module, cmdletInfo.ModuleName))
{
AddRemarksProperties(obj, cmdletInfo.Name, cmdletInfo.CommandMetadata.HelpUri);
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
}
obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn));
}
else if (commandInfo is FunctionInfo funcInfo)
{
bool common = HasCommonParameters(funcInfo.Parameters);
obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
AddDetailsProperties(obj, funcInfo.Name, string.Empty, string.Empty, TypeNameForDefaultHelp);
AddSyntaxProperties(obj, funcInfo.Name, funcInfo.ParameterSets, common, TypeNameForDefaultHelp);
AddParametersProperties(obj, funcInfo.Parameters, common, TypeNameForDefaultHelp);
AddInputTypesProperties(obj, funcInfo.Parameters);
AddRelatedLinksProperties(obj, funcInfo.CommandMetadata.HelpUri);
try
{
AddOutputTypesProperties(obj, funcInfo.OutputType);
}
catch (PSInvalidOperationException)
{
AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
}
AddAliasesProperties(obj, funcInfo.Name, funcInfo.Context);
if (HasHelpInfoUri(funcInfo.Module, funcInfo.ModuleName))
{
AddRemarksProperties(obj, funcInfo.Name, funcInfo.CommandMetadata.HelpUri);
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
}
}
obj.Properties.Add(new PSNoteProperty("alertSet", null));
obj.Properties.Add(new PSNoteProperty("description", null));
obj.Properties.Add(new PSNoteProperty("examples", null));
obj.Properties.Add(new PSNoteProperty("Synopsis", commandInfo.Syntax));
obj.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName));
obj.Properties.Add(new PSNoteProperty("nonTerminatingErrors", string.Empty));
obj.Properties.Add(new PSNoteProperty("xmlns:command", "http://schemas.microsoft.com/maml/dev/command/2004/10"));
obj.Properties.Add(new PSNoteProperty("xmlns:dev", "http://schemas.microsoft.com/maml/dev/2004/10"));
obj.Properties.Add(new PSNoteProperty("xmlns:maml", "http://schemas.microsoft.com/maml/2004/10"));
return obj;
}
/// <summary>
/// Adds the details properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="name">Command name.</param>
/// <param name="noun">Command noun.</param>
/// <param name="verb">Command verb.</param>
/// <param name="typeNameForHelp">Type name for help.</param>
/// <param name="synopsis">Synopsis.</param>
internal static void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp,
string synopsis = null)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp));
mshObject.Properties.Add(new PSNoteProperty("name", name));
mshObject.Properties.Add(new PSNoteProperty("noun", noun));
mshObject.Properties.Add(new PSNoteProperty("verb", verb));
// add synopsis
if (!string.IsNullOrEmpty(synopsis))
{
PSObject descriptionObject = new PSObject();
descriptionObject.TypeNames.Clear();
descriptionObject.TypeNames.Add("MamlParaTextItem");
descriptionObject.Properties.Add(new PSNoteProperty("Text", synopsis));
mshObject.Properties.Add(new PSNoteProperty("Description", descriptionObject));
}
obj.Properties.Add(new PSNoteProperty("details", mshObject));
}
/// <summary>
/// Adds the syntax properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="cmdletName">Command name.</param>
/// <param name="parameterSets">Parameter sets.</param>
/// <param name="common">Common parameters.</param>
/// <param name="typeNameForHelp">Type name for help.</param>
internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, string typeNameForHelp)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp));
AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, typeNameForHelp);
obj.Properties.Add(new PSNoteProperty("Syntax", mshObject));
}
/// <summary>
/// Add the syntax item properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="cmdletName">Cmdlet name, you can't get this from parameterSets.</param>
/// <param name="parameterSets">A collection of parameter sets.</param>
/// <param name="common">Common parameters.</param>
/// <param name="typeNameForHelp">Type name for help.</param>
private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, string typeNameForHelp)
{
ArrayList mshObjects = new ArrayList();
foreach (CommandParameterSetInfo parameterSet in parameterSets)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp));
mshObject.Properties.Add(new PSNoteProperty("name", cmdletName));
mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common));
Collection<CommandParameterInfo> parameters = new Collection<CommandParameterInfo>();
// GenerateParameters parameters in display order
// ie., Positional followed by
// Named Mandatory (in alpha numeric) followed by
// Named (in alpha numeric)
parameterSet.GenerateParametersInDisplayOrder(parameters.Add, delegate { });
AddSyntaxParametersProperties(mshObject, parameters, common, parameterSet.Name);
mshObjects.Add(mshObject);
}
obj.Properties.Add(new PSNoteProperty("syntaxItem", mshObjects.ToArray()));
}
/// <summary>
/// Add the syntax parameters properties (these parameters are used to create the syntax section)
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="parameters">
/// a collection of parameters in display order
/// ie., Positional followed by
/// Named Mandatory (in alpha numeric) followed by
/// Named (in alpha numeric)
/// </param>
/// <param name="common">Common parameters.</param>
/// <param name="parameterSetName">Name of the parameter set for which the syntax is generated.</param>
private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable<CommandParameterInfo> parameters,
bool common, string parameterSetName)
{
ArrayList mshObjects = new ArrayList();
foreach (CommandParameterInfo parameter in parameters)
{
if (common && Cmdlet.CommonParameters.Contains(parameter.Name))
{
continue;
}
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
Collection<Attribute> attributes = new Collection<Attribute>(parameter.Attributes);
AddParameterProperties(mshObject, parameter.Name, new Collection<string>(parameter.Aliases),
parameter.IsDynamic, parameter.ParameterType, attributes, parameterSetName);
Collection<ValidateSetAttribute> validateSet = GetValidateSetAttribute(attributes);
List<string> names = new List<string>();
foreach (ValidateSetAttribute set in validateSet)
{
foreach (string value in set.ValidValues)
{
names.Add(value);
}
}
if (names.Count != 0)
{
AddParameterValueGroupProperties(mshObject, names.ToArray());
}
else
{
if (parameter.ParameterType.IsEnum && (Enum.GetNames(parameter.ParameterType) != null))
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType));
}
else if (parameter.ParameterType.IsArray)
{
if (parameter.ParameterType.GetElementType().IsEnum &&
Enum.GetNames(parameter.ParameterType.GetElementType()) != null)
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType.GetElementType()));
}
}
else if (parameter.ParameterType.IsGenericType)
{
Type[] types = parameter.ParameterType.GetGenericArguments();
if (types.Length != 0)
{
Type type = types[0];
if (type.IsEnum && (Enum.GetNames(type) != null))
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(type));
}
else if (type.IsArray)
{
if (type.GetElementType().IsEnum &&
Enum.GetNames(type.GetElementType()) != null)
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(type.GetElementType()));
}
}
}
}
}
mshObjects.Add(mshObject);
}
obj.Properties.Add(new PSNoteProperty("parameter", mshObjects.ToArray()));
}
/// <summary>
/// Adds a parameter value group (for enums)
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="values">Parameter group values.</param>
private static void AddParameterValueGroupProperties(PSObject obj, string[] values)
{
PSObject paramValueGroup = new PSObject();
paramValueGroup.TypeNames.Clear();
paramValueGroup.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
ArrayList paramValue = new ArrayList(values);
paramValueGroup.Properties.Add(new PSNoteProperty("parameterValue", paramValue.ToArray()));
obj.Properties.Add(new PSNoteProperty("parameterValueGroup", paramValueGroup));
}
/// <summary>
/// Add the parameters properties (these parameters are used to create the parameters section)
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="parameters">Parameters.</param>
/// <param name="common">Common parameters.</param>
/// <param name="typeNameForHelp">Type name for help.</param>
internal static void AddParametersProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters, bool common, string typeNameForHelp)
{
PSObject paramsObject = new PSObject();
paramsObject.TypeNames.Clear();
paramsObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameters", typeNameForHelp));
ArrayList paramObjects = new ArrayList();
ArrayList sortedParameters = new ArrayList();
if (parameters != null)
{
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
sortedParameters.Add(parameter.Key);
}
}
sortedParameters.Sort(StringComparer.Ordinal);
foreach (string parameter in sortedParameters)
{
if (common && Cmdlet.CommonParameters.Contains(parameter))
{
continue;
}
PSObject paramObject = new PSObject();
paramObject.TypeNames.Clear();
paramObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
AddParameterProperties(paramObject, parameter, parameters[parameter].Aliases,
parameters[parameter].IsDynamic, parameters[parameter].ParameterType, parameters[parameter].Attributes);
paramObjects.Add(paramObject);
}
paramsObject.Properties.Add(new PSNoteProperty("parameter", paramObjects.ToArray()));
obj.Properties.Add(new PSNoteProperty("parameters", paramsObject));
}
/// <summary>
/// Adds the parameter properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="name">Parameter name.</param>
/// <param name="aliases">Parameter aliases.</param>
/// <param name="dynamic">Is dynamic parameter?</param>
/// <param name="type">Parameter type.</param>
/// <param name="attributes">Parameter attributes.</param>
/// <param name="parameterSetName">Name of the parameter set for which the syntax is generated.</param>
private static void AddParameterProperties(PSObject obj, string name, Collection<string> aliases, bool dynamic,
Type type, Collection<Attribute> attributes, string parameterSetName = null)
{
Collection<ParameterAttribute> attribs = GetParameterAttribute(attributes);
obj.Properties.Add(new PSNoteProperty("name", name));
if (attribs.Count == 0)
{
obj.Properties.Add(new PSNoteProperty("required", string.Empty));
obj.Properties.Add(new PSNoteProperty("pipelineInput", string.Empty));
obj.Properties.Add(new PSNoteProperty("isDynamic", string.Empty));
obj.Properties.Add(new PSNoteProperty("parameterSetName", string.Empty));
obj.Properties.Add(new PSNoteProperty("description", string.Empty));
obj.Properties.Add(new PSNoteProperty("position", string.Empty));
obj.Properties.Add(new PSNoteProperty("aliases", string.Empty));
}
else
{
ParameterAttribute paramAttribute = attribs[0];
if (!string.IsNullOrEmpty(parameterSetName))
{
foreach (var attrib in attribs)
{
if (string.Equals(attrib.ParameterSetName, parameterSetName, StringComparison.OrdinalIgnoreCase))
{
paramAttribute = attrib;
break;
}
}
}
obj.Properties.Add(new PSNoteProperty("required", CultureInfo.CurrentCulture.TextInfo.ToLower(paramAttribute.Mandatory.ToString())));
obj.Properties.Add(new PSNoteProperty("pipelineInput", GetPipelineInputString(paramAttribute)));
obj.Properties.Add(new PSNoteProperty("isDynamic", CultureInfo.CurrentCulture.TextInfo.ToLower(dynamic.ToString())));
if (paramAttribute.ParameterSetName.Equals(ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase))
{
obj.Properties.Add(new PSNoteProperty("parameterSetName", StringUtil.Format(HelpDisplayStrings.AllParameterSetsName)));
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < attribs.Count; i++)
{
sb.Append(attribs[i].ParameterSetName);
if (i != (attribs.Count - 1))
{
sb.Append(", ");
}
}
obj.Properties.Add(new PSNoteProperty("parameterSetName", sb.ToString()));
}
if (paramAttribute.HelpMessage != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(paramAttribute.HelpMessage);
obj.Properties.Add(new PSNoteProperty("description", sb.ToString()));
}
// We do not show switch parameters in the syntax section
// (i.e. [-Syntax] not [-Syntax <SwitchParameter>]
if (type != typeof(SwitchParameter))
{
AddParameterValueProperties(obj, type, attributes);
}
AddParameterTypeProperties(obj, type, attributes);
if (paramAttribute.Position == int.MinValue)
{
obj.Properties.Add(new PSNoteProperty("position",
StringUtil.Format(HelpDisplayStrings.NamedParameter)));
}
else
{
obj.Properties.Add(new PSNoteProperty("position",
paramAttribute.Position.ToString(CultureInfo.InvariantCulture)));
}
if (aliases.Count == 0)
{
obj.Properties.Add(new PSNoteProperty("aliases", StringUtil.Format(
HelpDisplayStrings.None)));
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < aliases.Count; i++)
{
sb.Append(aliases[i]);
if (i != (aliases.Count - 1))
{
sb.Append(", ");
}
}
obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
}
}
}
/// <summary>
/// Adds the parameterType properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="parameterType">The type of a parameter.</param>
/// <param name="attributes">The attributes of the parameter (needed to look for PSTypeName).</param>
private static void AddParameterTypeProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
mshObject.Properties.Add(new PSNoteProperty("name", parameterTypeString));
obj.Properties.Add(new PSNoteProperty("type", mshObject));
}
/// <summary>
/// Adds the parameterValue properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="parameterType">The type of a parameter.</param>
/// <param name="attributes">The attributes of the parameter (needed to look for PSTypeName).</param>
private static void AddParameterValueProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
{
PSObject mshObject;
if (parameterType != null)
{
Type type = Nullable.GetUnderlyingType(parameterType) ?? parameterType;
var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
mshObject = new PSObject(parameterTypeString);
mshObject.Properties.Add(new PSNoteProperty("variableLength", parameterType.IsArray));
}
else
{
mshObject = new PSObject("System.Object");
mshObject.Properties.Add(new PSNoteProperty("variableLength",
StringUtil.Format(HelpDisplayStrings.FalseShort)));
}
mshObject.Properties.Add(new PSNoteProperty("required", "true"));
obj.Properties.Add(new PSNoteProperty("parameterValue", mshObject));
}
/// <summary>
/// Adds the InputTypes properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="parameters">Command parameters.</param>
internal static void AddInputTypesProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters)
{
Collection<string> inputs = new Collection<string>();
if (parameters != null)
{
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
Collection<ParameterAttribute> attribs = GetParameterAttribute(parameter.Value.Attributes);
foreach (ParameterAttribute attrib in attribs)
{
if (attrib.ValueFromPipeline ||
attrib.ValueFromPipelineByPropertyName ||
attrib.ValueFromRemainingArguments)
{
if (!inputs.Contains(parameter.Value.ParameterType.FullName))
{
inputs.Add(parameter.Value.ParameterType.FullName);
}
}
}
}
}
if (inputs.Count == 0)
{
inputs.Add(StringUtil.Format(HelpDisplayStrings.None));
}
StringBuilder sb = new StringBuilder();
foreach (string input in inputs)
{
sb.AppendLine(input);
}
PSObject inputTypesObj = new PSObject();
inputTypesObj.TypeNames.Clear();
inputTypesObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject inputTypeObj = new PSObject();
inputTypeObj.TypeNames.Clear();
inputTypeObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#inputType", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject typeObj = new PSObject();
typeObj.TypeNames.Clear();
typeObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
inputTypeObj.Properties.Add(new PSNoteProperty("type", typeObj));
inputTypesObj.Properties.Add(new PSNoteProperty("inputType", inputTypeObj));
obj.Properties.Add(new PSNoteProperty("inputTypes", inputTypesObj));
}
/// <summary>
/// Adds the OutputTypes properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="outputTypes">Output types.</param>
private static void AddOutputTypesProperties(PSObject obj, ReadOnlyCollection<PSTypeName> outputTypes)
{
PSObject returnValuesObj = new PSObject();
returnValuesObj.TypeNames.Clear();
returnValuesObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject returnValueObj = new PSObject();
returnValueObj.TypeNames.Clear();
returnValueObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#returnValue", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject typeObj = new PSObject();
typeObj.TypeNames.Clear();
typeObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
if (outputTypes.Count == 0)
{
typeObj.Properties.Add(new PSNoteProperty("name", "System.Object"));
}
else
{
StringBuilder sb = new StringBuilder();
foreach (PSTypeName outputType in outputTypes)
{
sb.AppendLine(outputType.Name);
}
typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
}
returnValueObj.Properties.Add(new PSNoteProperty("type", typeObj));
returnValuesObj.Properties.Add(new PSNoteProperty("returnValue", returnValueObj));
obj.Properties.Add(new PSNoteProperty("returnValues", returnValuesObj));
}
/// <summary>
/// Adds the aliases properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="name">Command name.</param>
/// <param name="context">Execution context.</param>
private static void AddAliasesProperties(PSObject obj, string name, ExecutionContext context)
{
StringBuilder sb = new StringBuilder();
bool found = false;
if (context != null)
{
foreach (string alias in context.SessionState.Internal.GetAliasesByCommandName(name))
{
found = true;
sb.AppendLine(alias);
}
}
if (!found)
{
sb.AppendLine(StringUtil.Format(HelpDisplayStrings.None));
}
obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
}
/// <summary>
/// Adds the remarks properties.
/// </summary>
/// <param name="obj">HelpInfo object.</param>
/// <param name="cmdletName"></param>
/// <param name="helpUri"></param>
private static void AddRemarksProperties(PSObject obj, string cmdletName, string helpUri)
{
if (string.IsNullOrEmpty(helpUri))
{
obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContentWithoutHelpUri, cmdletName)));
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContent, cmdletName, helpUri)));
}
}
/// <summary>
/// Adds the related links properties.
/// </summary>
/// <param name="obj"></param>
/// <param name="relatedLink"></param>
internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink)
{
if (!string.IsNullOrEmpty(relatedLink))
{
PSObject navigationLinkObj = new PSObject();
navigationLinkObj.TypeNames.Clear();
navigationLinkObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#navigationLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
navigationLinkObj.Properties.Add(new PSNoteProperty("uri", relatedLink));
List<PSObject> navigationLinkValues = new List<PSObject> { navigationLinkObj };
// check if obj already has relatedLinks property
PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty;
if ((relatedLinksPO != null) && (relatedLinksPO.Value != null))
{
PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value);
PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty;
if ((navigationLinkPO != null) && (navigationLinkPO.Value != null))
{
PSObject navigationLinkValue = navigationLinkPO.Value as PSObject;
if (navigationLinkValue != null)
{
navigationLinkValues.Add(navigationLinkValue);
}
else
{
PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[];
if (navigationLinkValueArray != null)
{
foreach (var psObject in navigationLinkValueArray)
{
navigationLinkValues.Add(psObject);
}
}
}
}
}
PSObject relatedLinksObj = new PSObject();
relatedLinksObj.TypeNames.Clear();
relatedLinksObj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#relatedLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
relatedLinksObj.Properties.Add(new PSNoteProperty("navigationLink", navigationLinkValues.ToArray()));
obj.Properties.Add(new PSNoteProperty("relatedLinks", relatedLinksObj));
}
}
/// <summary>
/// Gets the parameter attribute from parameter metadata.
/// </summary>
/// <param name="attributes">Parameter attributes.</param>
/// <returns>Collection of parameter attributes.</returns>
private static Collection<ParameterAttribute> GetParameterAttribute(Collection<Attribute> attributes)
{
Collection<ParameterAttribute> paramAttributes = new Collection<ParameterAttribute>();
foreach (Attribute attribute in attributes)
{
ParameterAttribute paramAttribute = (object)attribute as ParameterAttribute;
if (paramAttribute != null)
{
paramAttributes.Add(paramAttribute);
}
}
return paramAttributes;
}
/// <summary>
/// Gets the validate set attribute from parameter metadata.
/// </summary>
/// <param name="attributes">Parameter attributes.</param>
/// <returns>Collection of parameter attributes.</returns>
private static Collection<ValidateSetAttribute> GetValidateSetAttribute(Collection<Attribute> attributes)
{
Collection<ValidateSetAttribute> validateSetAttributes = new Collection<ValidateSetAttribute>();
foreach (Attribute attribute in attributes)
{
ValidateSetAttribute validateSetAttribute = (object)attribute as ValidateSetAttribute;
if (validateSetAttribute != null)
{
validateSetAttributes.Add(validateSetAttribute);
}
}
return validateSetAttributes;
}
/// <summary>
/// Gets the pipeline input type.
/// </summary>
/// <param name="paramAttrib">Parameter attribute.</param>
/// <returns>Pipeline input type.</returns>
private static string GetPipelineInputString(ParameterAttribute paramAttrib)
{
Debug.Assert(paramAttrib != null);
ArrayList values = new ArrayList();
if (paramAttrib.ValueFromPipeline)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue));
}
if (paramAttrib.ValueFromPipelineByPropertyName)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName));
}
if (paramAttrib.ValueFromRemainingArguments)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments));
}
if (values.Count == 0)
{
return StringUtil.Format(HelpDisplayStrings.FalseShort);
}
StringBuilder sb = new StringBuilder();
sb.Append(StringUtil.Format(HelpDisplayStrings.TrueShort));
sb.Append(" (");
for (int i = 0; i < values.Count; i++)
{
sb.Append((string)values[i]);
if (i != (values.Count - 1))
{
sb.Append(", ");
}
}
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// Checks if a set of parameters contains any of the common parameters.
/// </summary>
/// <param name="parameters">Parameters to check.</param>
/// <returns>True if it contains common parameters, false otherwise.</returns>
internal static bool HasCommonParameters(Dictionary<string, ParameterMetadata> parameters)
{
Collection<string> commonParams = new Collection<string>();
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
if (Cmdlet.CommonParameters.Contains(parameter.Value.Name))
{
commonParams.Add(parameter.Value.Name);
}
}
return (commonParams.Count == Cmdlet.CommonParameters.Count);
}
/// <summary>
/// Checks if the module contains HelpInfoUri.
/// </summary>
/// <param name="module"></param>
/// <param name="moduleName"></param>
/// <returns></returns>
private static bool HasHelpInfoUri(PSModuleInfo module, string moduleName)
{
// The core module is really a SnapIn, so module will be null
if (!string.IsNullOrEmpty(moduleName) && moduleName.Equals(InitialSessionState.CoreModule, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (module == null)
{
return false;
}
return !string.IsNullOrEmpty(module.HelpInfoUri);
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using CryptographicException = System.Security.Cryptography.CryptographicException;
using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags;
using SafeNCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
public static partial class crypt32
{
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out IntPtr pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")]
public static extern bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] StringBuilder pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvTypePara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, SetLastError = true)]
public static extern SafeX509ChainHandle CertDuplicateCertificateChain(IntPtr pChainContext);
[DllImport(Libraries.Crypt32, SetLastError = true)]
internal static extern SafeCertStoreHandle CertDuplicateStore(IntPtr hCertStore);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")]
public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext);
public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, string pvPara)
{
return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pvPara);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext)
{
unsafe
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
return !pCertContext.IsInvalid;
}
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle password, PfxCertStoreFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle szPassword, PFXExportFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertNameToStrW")]
public static extern int CertNameToStr(CertEncodingType dwCertEncodingType, [In] ref CRYPTOAPI_BLOB pName, CertNameStrTypeAndFlags dwStrType, StringBuilder psz, int csz);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")]
public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError);
public static bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, FormatObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, StringBuilder pbFormat, ref int pcbFormat)
{
return CryptFormatObject(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (IntPtr)lpszStructType, pbEncoded, cbEncoded, pbFormat, ref pcbFormat);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, [Out] StringBuilder pbFormat, [In, Out] ref int pcbFormat);
public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
{
return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe byte[] EncodeObject(string lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe bool CertGetCertificateChain(ChainEngine hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext)
{
return CertGetCertificateChain((IntPtr)hChainEngine, pCertContext, pTime, hStore, ref pChainPara, dwFlags, pvReserved, out ppChainContext);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStrTypeAndFlags pvPara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext)
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext);
return !pCertContext.IsInvalid;
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions);
// Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise
// identical to the wincrypt CERT_*_USAGE values.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara);
// Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern void CertFreeCertificateChain(IntPtr pChainContext);
public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus)
{
return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertFreeCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgClose(IntPtr hCryptMsg);
#if !NETNATIVE
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey);
#endif
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Management.Automation.Host;
namespace System.Management.Automation
{
/// <summary>
/// This interface defines the set of functionality that must be implemented to directly
/// execute an instance of a Cmdlet.
/// </summary>
/// <remarks>
/// When a cmdlet is instantiated and run directly, all calls to the stream APIs will be proxied
/// through to an instance of this class. For example, when a cmdlet calls WriteObject, the
/// WriteObject implementation on the instance of the class implementing this interface will be
/// called. The Monad implementation provides a default implementation of this class for use with
/// standalone cmdlets as well as the implementation provided for running in the monad engine itself.
///
/// If you do want to run Cmdlet instances standalone and capture their output with more
/// fidelity than is provided for with the default implementation, then you should create your own
/// implementation of this class and pass it to cmdlets before calling the Cmdlet Invoke() or
/// Execute() methods.
/// </remarks>
public interface ICommandRuntime
{
/// <summary>
/// Returns an instance of the PSHost implementation for this environment.
/// </summary>
PSHost Host { get; }
#region Write
/// <summary>
/// Display debug information.
/// </summary>
/// <param name="text">Debug output.</param>
/// <remarks>
/// This API is called by the cmdlet to display debug information on the inner workings
/// of the Cmdlet. An implementation of this interface should display this information in
/// an appropriately distinctive manner (e.g. through a different color or in a separate
/// status window. In simple implementations, just ignoring the text and returning is sufficient.
/// </remarks>
void WriteDebug(string text);
/// <summary>
/// Internal variant: Writes the specified error to the error pipe.
/// </summary>
/// <remarks>
/// Do not call WriteError(e.ErrorRecord).
/// The ErrorRecord contained in the ErrorRecord property of
/// an exception which implements IContainsErrorRecord
/// should not be passed directly to WriteError, since it contains
/// a <see cref="System.Management.Automation.ParentContainsErrorRecordException"/>
/// rather than the real exception.
/// </remarks>
/// <param name="errorRecord">Error.</param>
void WriteError(ErrorRecord errorRecord);
/// <summary>
/// Called to write objects to the output pipe.
/// </summary>
/// <param name="sendToPipeline">
/// The object that needs to be written. This will be written as
/// a single object, even if it is an enumeration.
/// </param>
/// <remarks>
/// When the cmdlet wants to write a single object out, it will call this
/// API. It is up to the implementation to decide what to do with these objects.
/// </remarks>
void WriteObject(object sendToPipeline);
/// <summary>
/// Called to write one or more objects to the output pipe.
/// If the object is a collection and the enumerateCollection flag
/// is true, the objects in the collection
/// will be written individually.
/// </summary>
/// <param name="sendToPipeline">
/// The object that needs to be written to the pipeline.
/// </param>
/// <param name="enumerateCollection">
/// true if the collection should be enumerated
/// </param>
/// <remarks>
/// When the cmdlet wants to write multiple objects out, it will call this
/// API. It is up to the implementation to decide what to do with these objects.
/// </remarks>
void WriteObject(object sendToPipeline, bool enumerateCollection);
/// <summary>
/// Called by the cmdlet to display progress information.
/// </summary>
/// <param name="progressRecord">Progress information.</param>
/// <remarks>
/// Use WriteProgress to display progress information about
/// the activity of your Task, when the operation of your Task
/// could potentially take a long time.
///
/// By default, progress output will
/// be displayed, although this can be configured with the
/// ProgressPreference shell variable.
///
/// The implementation of the API should display these progress records
/// in a fashion appropriate for the application. For example, a GUI application
/// would implement this as a progress bar of some sort.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteWarning(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteVerbose(string)"/>
void WriteProgress(ProgressRecord progressRecord);
/// <summary>
/// Displays progress output if enabled.
/// </summary>
/// <param name="sourceId">
/// Identifies which command is reporting progress
/// </param>
/// <param name="progressRecord">
/// Progress status to be displayed
/// </param>
/// <remarks>
/// The implementation of the API should display these progress records
/// in a fashion appropriate for the application. For example, a GUI application
/// would implement this as a progress bar of some sort.
/// </remarks>
void WriteProgress(Int64 sourceId, ProgressRecord progressRecord);
/// <summary>
/// Called when the cmdlet want to display verbose information.
/// </summary>
/// <param name="text">Verbose output.</param>
/// <remarks>
/// Cmdlets use WriteVerbose to display more detailed information about
/// the activity of the Cmdlet. By default, verbose output will
/// not be displayed, although this can be configured with the
/// VerbosePreference shell variable
/// or the -Verbose and -Debug command-line options.
///
/// The implementation of this API should display this addition information
/// in an appropriate manner e.g. in a different color in a console application
/// or in a separate window in a GUI application.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteWarning(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteProgress(ProgressRecord)"/>
void WriteVerbose(string text);
/// <summary>
/// Called by the cmdlet to display warning information.
/// </summary>
/// <param name="text">Warning output.</param>
/// <remarks>
/// Use WriteWarning to display warnings about
/// the activity of your Cmdlet. By default, warning output will
/// be displayed, although this can be configured with the
/// WarningPreference shell variable
/// or the -Verbose and -Debug command-line options.
///
/// The implementation of this API should display this addition information
/// in an appropriate manner e.g. in a different color in a console application
/// or in a separate window in a GUI application.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteVerbose(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteProgress(ProgressRecord)"/>
void WriteWarning(string text);
/// <summary>
/// Write text into pipeline execution log.
/// </summary>
/// <param name="text">Text to be written to log.</param>
/// <remarks>
/// Use WriteCommandDetail to write important information about cmdlet execution to
/// pipeline execution log.
///
/// If LogPipelineExecutionDetail is turned on, this information will be written
/// to monad log under log category "Pipeline execution detail"
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteVerbose(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteProgress(ProgressRecord)"/>
void WriteCommandDetail(string text);
#endregion Write
#region Should
/// <summary>
/// Called by the cmdlet to confirm the operation with the user. Cmdlets which make changes
/// (e.g. delete files, stop services etc.) should call ShouldProcess
/// to give the user the opportunity to confirm that the operation
/// should actually be performed.
/// </summary>
/// <param name="target">
/// Name of the target resource being acted upon. This will
/// potentially be displayed to the user.
/// </param>
/// <returns>
/// If ShouldProcess returns true, the operation should be performed.
/// If ShouldProcess returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </returns>
/// <remarks>
/// A Cmdlet should declare
/// [Cmdlet( SupportsShouldProcess = true )]
/// if-and-only-if it calls ShouldProcess before making changes.
///
/// ShouldProcess may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// ShouldProcess will take into account command-line settings
/// and preference variables in determining what it should return
/// and whether it should prompt the user.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string, out ShouldProcessReason)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string,ref bool,ref bool)"/>
bool ShouldProcess(string target);
/// <summary>
/// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes
/// (e.g. delete files, stop services etc.) should call ShouldProcess
/// to give the user the opportunity to confirm that the operation
/// should actually be performed.
///
/// This variant allows the caller to specify text for both the
/// target resource and the action.
/// </summary>
/// <param name="target">
/// Name of the target resource being acted upon. This will
/// potentially be displayed to the user.
/// </param>
/// <param name="action">
/// Name of the action which is being performed. This will
/// potentially be displayed to the user. (default is Cmdlet name)
/// </param>
/// <returns>
/// If ShouldProcess returns true, the operation should be performed.
/// If ShouldProcess returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </returns>
/// <remarks>
/// A Cmdlet should declare
/// [Cmdlet( SupportsShouldProcess = true )]
/// if-and-only-if it calls ShouldProcess before making changes.
///
/// ShouldProcess may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// ShouldProcess will take into account command-line settings
/// and preference variables in determining what it should return
/// and whether it should prompt the user.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string, out ShouldProcessReason)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string,ref bool,ref bool)"/>
bool ShouldProcess(string target, string action);
/// <summary>
/// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes
/// (e.g. delete files, stop services etc.) should call ShouldProcess
/// to give the user the opportunity to confirm that the operation
/// should actually be performed.
///
/// This variant allows the caller to specify the complete text
/// describing the operation, rather than just the name and action.
/// </summary>
/// <param name="verboseDescription">
/// Textual description of the action to be performed.
/// This is what will be displayed to the user for
/// ActionPreference.Continue.
/// </param>
/// <param name="verboseWarning">
/// Textual query of whether the action should be performed,
/// usually in the form of a question.
/// This is what will be displayed to the user for
/// ActionPreference.Inquire.
/// </param>
/// <param name="caption">
/// Caption of the window which may be displayed
/// if the user is prompted whether or not to perform the action.
/// <paramref name="caption"/> may be displayed by some hosts, but not all.
/// </param>
/// <returns>
/// If ShouldProcess returns true, the operation should be performed.
/// If ShouldProcess returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
/// </returns>
/// <remarks>
/// A Cmdlet should declare
/// [Cmdlet( SupportsShouldProcess = true )]
/// if-and-only-if it calls ShouldProcess before making changes.
///
/// ShouldProcess may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// ShouldProcess will take into account command-line settings
/// and preference variables in determining what it should return
/// and whether it should prompt the user.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string, out ShouldProcessReason)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string,ref bool,ref bool)"/>
bool ShouldProcess(string verboseDescription, string verboseWarning, string caption);
/// <summary>
/// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes
/// (e.g. delete files, stop services etc.) should call ShouldProcess
/// to give the user the opportunity to confirm that the operation
/// should actually be performed.
///
/// This variant allows the caller to specify the complete text
/// describing the operation, rather than just the name and action.
/// </summary>
/// <param name="verboseDescription">
/// Textual description of the action to be performed.
/// This is what will be displayed to the user for
/// ActionPreference.Continue.
/// </param>
/// <param name="verboseWarning">
/// Textual query of whether the action should be performed,
/// usually in the form of a question.
/// This is what will be displayed to the user for
/// ActionPreference.Inquire.
/// </param>
/// <param name="caption">
/// Caption of the window which may be displayed
/// if the user is prompted whether or not to perform the action.
/// <paramref name="caption"/> may be displayed by some hosts, but not all.
/// </param>
/// <param name="shouldProcessReason">
/// Indicates the reason(s) why ShouldProcess returned what it returned.
/// Only the reasons enumerated in
/// <see cref="System.Management.Automation.ShouldProcessReason"/>
/// are returned.
/// </param>
/// <returns>
/// If ShouldProcess returns true, the operation should be performed.
/// If ShouldProcess returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
/// </returns>
/// <remarks>
/// A Cmdlet should declare
/// [Cmdlet( SupportsShouldProcess = true )]
/// if-and-only-if it calls ShouldProcess before making changes.
///
/// ShouldProcess may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// ShouldProcess will take into account command-line settings
/// and preference variables in determining what it should return
/// and whether it should prompt the user.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string,ref bool,ref bool)"/>
bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason);
/// <summary>
/// Called by a cmdlet to confirm an operation or grouping of operations with the user.
/// This differs from ShouldProcess in that it is not affected by
/// preference settings or command-line parameters,
/// it always does the query.
/// This variant only offers Yes/No, not YesToAll/NoToAll.
/// </summary>
/// <param name="query">
/// Textual query of whether the action should be performed,
/// usually in the form of a question.
/// </param>
/// <param name="caption">
/// Caption of the window which may be displayed
/// when the user is prompted whether or not to perform the action.
/// It may be displayed by some hosts, but not all.
/// </param>
/// <returns>
/// If ShouldContinue returns true, the operation should be performed.
/// If ShouldContinue returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
/// </returns>
/// <remarks>
/// Cmdlets using ShouldContinue should also offer a "bool Force"
/// parameter which bypasses the calls to ShouldContinue
/// and ShouldProcess.
/// If this is not done, it will be difficult to use the Cmdlet
/// from scripts and non-interactive hosts.
///
/// Cmdlets using ShouldContinue must still verify operations
/// which will make changes using ShouldProcess.
/// This will assure that settings such as -WhatIf work properly.
/// You may call ShouldContinue either before or after ShouldProcess.
///
/// ShouldContinue may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// Cmdlets may have different "classes" of confirmations. For example,
/// "del" confirms whether files in a particular directory should be
/// deleted, whether read-only files should be deleted, etc.
/// Cmdlets can use ShouldContinue to store YesToAll/NoToAll members
/// for each such "class" to keep track of whether the user has
/// confirmed "delete all read-only files" etc.
/// ShouldProcess offers YesToAll/NoToAll automatically,
/// but answering YesToAll or NoToAll applies to all subsequent calls
/// to ShouldProcess for the Cmdlet instance.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string,ref bool,ref bool)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string)"/>
bool ShouldContinue(string query, string caption);
/// <summary>
/// Called to confirm an operation or grouping of operations with the user.
/// This differs from ShouldProcess in that it is not affected by
/// preference settings or command-line parameters,
/// it always does the query.
/// This variant offers Yes, No, YesToAll and NoToAll.
/// </summary>
/// <param name="query">
/// Textual query of whether the action should be performed,
/// usually in the form of a question.
/// </param>
/// <param name="caption">
/// Caption of the window which may be displayed
/// when the user is prompted whether or not to perform the action.
/// It may be displayed by some hosts, but not all.
/// </param>
/// <param name="yesToAll">
/// true iff user selects YesToAll. If this is already true,
/// ShouldContinue will bypass the prompt and return true.
/// </param>
/// <param name="noToAll">
/// true iff user selects NoToAll. If this is already true,
/// ShouldContinue will bypass the prompt and return false.
/// </param>
/// <returns>
/// If ShouldContinue returns true, the operation should be performed.
/// If ShouldContinue returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
/// </returns>
/// <remarks>
/// Cmdlets using ShouldContinue should also offer a "bool Force"
/// parameter which bypasses the calls to ShouldContinue
/// and ShouldProcess.
/// If this is not done, it will be difficult to use the Cmdlet
/// from scripts and non-interactive hosts.
///
/// Cmdlets using ShouldContinue must still verify operations
/// which will make changes using ShouldProcess.
/// This will assure that settings such as -WhatIf work properly.
/// You may call ShouldContinue either before or after ShouldProcess.
///
/// ShouldContinue may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
///
/// Cmdlets may have different "classes" of confirmations. For example,
/// "del" confirms whether files in a particular directory should be
/// deleted, whether read-only files should be deleted, etc.
/// Cmdlets can use ShouldContinue to store YesToAll/NoToAll members
/// for each such "class" to keep track of whether the user has
/// confirmed "delete all read-only files" etc.
/// ShouldProcess offers YesToAll/NoToAll automatically,
/// but answering YesToAll or NoToAll applies to all subsequent calls
/// to ShouldProcess for the Cmdlet instance.
///
/// An implementation should prompt the user in an appropriate manner
/// and return true or false. An alternative trivial implementation
/// would be to just return true all the time.
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldContinue(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.ShouldProcess(string,string,string)"/>
bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll);
#endregion Should
#region Transaction Support
/// <summary>
/// Returns true if a transaction is available and active.
/// </summary>
bool TransactionAvailable();
/// <summary>
/// Gets an object that surfaces the current PowerShell transaction.
/// When this object is disposed, PowerShell resets the active transaction.
/// </summary>
PSTransactionContext CurrentPSTransaction { get; }
#endregion Transaction Support
#region Misc
#region ThrowTerminatingError
/// <summary>
/// This interface will be called to route fatal errors from a cmdlet.
/// </summary>
/// <param name="errorRecord">
/// The error which caused the command to be terminated
/// </param>
/// <remarks>
/// <see cref="System.Management.Automation.Cmdlet.ThrowTerminatingError"/>
/// terminates the command, where
/// <see cref="System.Management.Automation.ICommandRuntime.WriteError"/>
/// allows the command to continue.
///
/// The cmdlet can also terminate the command by simply throwing
/// any exception. When the cmdlet's implementation of
/// <see cref="System.Management.Automation.Cmdlet.ProcessRecord"/>,
/// <see cref="System.Management.Automation.Cmdlet.BeginProcessing"/> or
/// <see cref="System.Management.Automation.Cmdlet.EndProcessing"/>
/// throws an exception, the Engine will always catch the exception
/// and report it as a terminating error.
/// However, it is preferred for the cmdlet to call
/// <see cref="System.Management.Automation.Cmdlet.ThrowTerminatingError"/>,
/// so that the additional information in
/// <see cref="System.Management.Automation.ErrorRecord"/>
/// is available.
///
/// It is up to the implementation of this routine to determine what
/// if any information is to be added. It should encapsulate the
/// error record into an exception and then throw that exception.
/// </remarks>
void ThrowTerminatingError(ErrorRecord errorRecord);
#endregion ThrowTerminatingError
#endregion misc
}
/// <summary>
/// This interface defines the set of functionality that must be implemented to directly
/// execute an instance of a Cmdlet. ICommandRuntime2 extends the ICommandRuntime interface
/// by adding support for the informational data stream.
/// </summary>
public interface ICommandRuntime2 : ICommandRuntime
{
/// <summary>
/// Write an informational record to the command runtime.
/// </summary>
/// <param name="informationRecord">The informational record that should be transmitted to the host or user.</param>
void WriteInformation(InformationRecord informationRecord);
/// <summary>
/// Confirm an operation or grouping of operations with the user.
/// This differs from ShouldProcess in that it is not affected by
/// preference settings or command-line parameters,
/// it always does the query.
/// This variant offers Yes, No, YesToAll and NoToAll.
/// </summary>
/// <param name="query">
/// Textual query of whether the action should be performed,
/// usually in the form of a question.
/// </param>
/// <param name="caption">
/// Caption of the window which may be displayed
/// when the user is prompted whether or not to perform the action.
/// It may be displayed by some hosts, but not all.
/// </param>
/// <param name="hasSecurityImpact">
/// true if the operation being confirmed has a security impact. If specified,
/// the default option selected in the selection menu is 'No'.
/// </param>
/// <param name="yesToAll">
/// true iff user selects YesToAll. If this is already true,
/// ShouldContinue will bypass the prompt and return true.
/// </param>
/// <param name="noToAll">
/// true iff user selects NoToAll. If this is already true,
/// ShouldContinue will bypass the prompt and return false.
/// </param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// ShouldContinue may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <returns>
/// If ShouldContinue returns true, the operation should be performed.
/// If ShouldContinue returns false, the operation should not be
/// performed, and the Cmdlet should move on to the next target resource.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll);
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
#pragma warning disable 618
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
StringAssert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
#pragma warning restore 618
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
StringAssert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Extensions.ImageExtensions;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Input;
using osu.Framework.Platform.SDL2;
using osu.Framework.Platform.Windows.Native;
using osu.Framework.Threading;
using osuTK;
using osuTK.Input;
using SDL2;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Image = SixLabors.ImageSharp.Image;
using Point = System.Drawing.Point;
using Rectangle = System.Drawing.Rectangle;
using RectangleF = osu.Framework.Graphics.Primitives.RectangleF;
using Size = System.Drawing.Size;
// ReSharper disable UnusedParameter.Local
// (Class regularly handles native events where we don't consume all parameters)
namespace osu.Framework.Platform
{
/// <summary>
/// Default implementation of a desktop window, using SDL for windowing and graphics support.
/// </summary>
public class SDL2DesktopWindow : IWindow
{
internal IntPtr SDLWindowHandle { get; private set; } = IntPtr.Zero;
private readonly IGraphicsBackend graphicsBackend;
private bool focused;
/// <summary>
/// Whether the window currently has focus.
/// </summary>
public bool Focused
{
get => focused;
private set
{
if (value == focused)
return;
isActive.Value = focused = value;
}
}
/// <summary>
/// Enables or disables vertical sync.
/// </summary>
public bool VerticalSync
{
get => graphicsBackend.VerticalSync;
set => graphicsBackend.VerticalSync = value;
}
/// <summary>
/// Returns true if window has been created.
/// Returns false if the window has not yet been created, or has been closed.
/// </summary>
public bool Exists { get; private set; }
public WindowMode DefaultWindowMode => Configuration.WindowMode.Windowed;
/// <summary>
/// Returns the window modes that the platform should support by default.
/// </summary>
protected virtual IEnumerable<WindowMode> DefaultSupportedWindowModes => Enum.GetValues(typeof(WindowMode)).OfType<WindowMode>();
private Point position;
/// <summary>
/// Returns or sets the window's position in screen space. Only valid when in <see cref="osu.Framework.Configuration.WindowMode.Windowed"/>
/// </summary>
public Point Position
{
get => position;
set
{
position = value;
ScheduleCommand(() => SDL.SDL_SetWindowPosition(SDLWindowHandle, value.X, value.Y));
}
}
private bool resizable = true;
/// <summary>
/// Returns or sets whether the window is resizable or not. Only valid when in <see cref="osu.Framework.Platform.WindowState.Normal"/>.
/// </summary>
public bool Resizable
{
get => resizable;
set
{
if (resizable == value)
return;
resizable = value;
ScheduleCommand(() => SDL.SDL_SetWindowResizable(SDLWindowHandle, value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private bool relativeMouseMode;
/// <summary>
/// Set the state of SDL2's RelativeMouseMode (https://wiki.libsdl.org/SDL_SetRelativeMouseMode).
/// On all platforms, this will lock the mouse to the window (although escaping by setting <see cref="ConfineMouseMode"/> is still possible via a local implementation).
/// On windows, this will use raw input if available.
/// </summary>
public bool RelativeMouseMode
{
get => relativeMouseMode;
set
{
if (relativeMouseMode == value)
return;
if (value && !CursorState.HasFlagFast(CursorState.Hidden))
throw new InvalidOperationException($"Cannot set {nameof(RelativeMouseMode)} to true when the cursor is not hidden via {nameof(CursorState)}.");
relativeMouseMode = value;
ScheduleCommand(() => SDL.SDL_SetRelativeMouseMode(value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private Size size = new Size(default_width, default_height);
/// <summary>
/// Returns or sets the window's internal size, before scaling.
/// </summary>
public Size Size
{
get => size;
private set
{
if (value.Equals(size)) return;
size = value;
Resized?.Invoke();
}
}
/// <summary>
/// Provides a bindable that controls the window's <see cref="CursorStateBindable"/>.
/// </summary>
public Bindable<CursorState> CursorStateBindable { get; } = new Bindable<CursorState>();
public CursorState CursorState
{
get => CursorStateBindable.Value;
set => CursorStateBindable.Value = value;
}
public Bindable<Display> CurrentDisplayBindable { get; } = new Bindable<Display>();
public Bindable<WindowMode> WindowMode { get; } = new Bindable<WindowMode>();
private readonly BindableBool isActive = new BindableBool();
public IBindable<bool> IsActive => isActive;
private readonly BindableBool cursorInWindow = new BindableBool();
public IBindable<bool> CursorInWindow => cursorInWindow;
public IBindableList<WindowMode> SupportedWindowModes { get; }
public BindableSafeArea SafeAreaPadding { get; } = new BindableSafeArea();
public virtual Point PointToClient(Point point) => point;
public virtual Point PointToScreen(Point point) => point;
private const int default_width = 1366;
private const int default_height = 768;
private const int default_icon_size = 256;
private readonly Scheduler commandScheduler = new Scheduler();
private readonly Scheduler eventScheduler = new Scheduler();
private readonly Dictionary<int, SDL2ControllerBindings> controllers = new Dictionary<int, SDL2ControllerBindings>();
private string title = string.Empty;
/// <summary>
/// Gets and sets the window title.
/// </summary>
public string Title
{
get => title;
set
{
title = value;
ScheduleCommand(() => SDL.SDL_SetWindowTitle(SDLWindowHandle, title));
}
}
private bool visible;
/// <summary>
/// Enables or disables the window visibility.
/// </summary>
public bool Visible
{
get => visible;
set
{
visible = value;
ScheduleCommand(() =>
{
if (value)
SDL.SDL_ShowWindow(SDLWindowHandle);
else
SDL.SDL_HideWindow(SDLWindowHandle);
});
}
}
private void updateCursorVisibility(bool visible) =>
ScheduleCommand(() => SDL.SDL_ShowCursor(visible ? SDL.SDL_ENABLE : SDL.SDL_DISABLE));
private void updateCursorConfined(bool confined) =>
ScheduleCommand(() => SDL.SDL_SetWindowGrab(SDLWindowHandle, confined ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
private WindowState windowState = WindowState.Normal;
private WindowState? pendingWindowState;
/// <summary>
/// Returns or sets the window's current <see cref="WindowState"/>.
/// </summary>
public WindowState WindowState
{
get => windowState;
set
{
if (pendingWindowState == null && windowState == value)
return;
pendingWindowState = value;
}
}
/// <summary>
/// Stores whether the window used to be in maximised state or not.
/// Used to properly decide what window state to pick when switching to windowed mode (see <see cref="WindowMode"/> change event)
/// </summary>
private bool windowMaximised;
/// <summary>
/// Returns the drawable area, after scaling.
/// </summary>
public Size ClientSize => new Size(Size.Width, Size.Height);
public float Scale = 1;
/// <summary>
/// Queries the physical displays and their supported resolutions.
/// </summary>
public IEnumerable<Display> Displays => Enumerable.Range(0, SDL.SDL_GetNumVideoDisplays()).Select(displayFromSDL);
/// <summary>
/// Gets the <see cref="Display"/> that has been set as "primary" or "default" in the operating system.
/// </summary>
public virtual Display PrimaryDisplay => Displays.First();
private Display currentDisplay;
private int displayIndex = -1;
/// <summary>
/// Gets or sets the <see cref="Display"/> that this window is currently on.
/// </summary>
public Display CurrentDisplay { get; private set; }
public readonly Bindable<ConfineMouseMode> ConfineMouseMode = new Bindable<ConfineMouseMode>();
private readonly Bindable<DisplayMode> currentDisplayMode = new Bindable<DisplayMode>();
/// <summary>
/// The <see cref="DisplayMode"/> for the display that this window is currently on.
/// </summary>
public IBindable<DisplayMode> CurrentDisplayMode => currentDisplayMode;
/// <summary>
/// Gets the native window handle as provided by the operating system.
/// </summary>
public IntPtr WindowHandle
{
get
{
if (SDLWindowHandle == IntPtr.Zero)
return IntPtr.Zero;
var wmInfo = getWindowWMInfo();
// Window handle is selected per subsystem as defined at:
// https://wiki.libsdl.org/SDL_SysWMinfo
switch (wmInfo.subsystem)
{
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS:
return wmInfo.info.win.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_X11:
return wmInfo.info.x11.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_DIRECTFB:
return wmInfo.info.dfb.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_COCOA:
return wmInfo.info.cocoa.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_UIKIT:
return wmInfo.info.uikit.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WAYLAND:
return wmInfo.info.wl.shell_surface;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_ANDROID:
return wmInfo.info.android.window;
default:
return IntPtr.Zero;
}
}
}
private SDL.SDL_SysWMinfo getWindowWMInfo()
{
if (SDLWindowHandle == IntPtr.Zero)
return default;
var wmInfo = new SDL.SDL_SysWMinfo();
SDL.SDL_GetWindowWMInfo(SDLWindowHandle, ref wmInfo);
return wmInfo;
}
private Rectangle windowDisplayBounds
{
get
{
SDL.SDL_GetDisplayBounds(displayIndex, out var rect);
return new Rectangle(rect.x, rect.y, rect.w, rect.h);
}
}
public bool CapsLockPressed => SDL.SDL_GetModState().HasFlagFast(SDL.SDL_Keymod.KMOD_CAPS);
private bool firstDraw = true;
private readonly BindableSize sizeFullscreen = new BindableSize();
private readonly BindableSize sizeWindowed = new BindableSize();
private readonly BindableDouble windowPositionX = new BindableDouble();
private readonly BindableDouble windowPositionY = new BindableDouble();
private readonly Bindable<DisplayIndex> windowDisplayIndexBindable = new Bindable<DisplayIndex>();
public SDL2DesktopWindow()
{
SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_GAMECONTROLLER);
graphicsBackend = CreateGraphicsBackend();
SupportedWindowModes = new BindableList<WindowMode>(DefaultSupportedWindowModes);
CursorStateBindable.ValueChanged += evt =>
{
updateCursorVisibility(!evt.NewValue.HasFlagFast(CursorState.Hidden));
updateCursorConfined(evt.NewValue.HasFlagFast(CursorState.Confined));
};
populateJoysticks();
}
/// <summary>
/// Creates the window and initialises the graphics backend.
/// </summary>
public virtual void Create()
{
SDL.SDL_WindowFlags flags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL |
SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE |
SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI |
SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | // shown after first swap to avoid white flash on startup (windows)
WindowState.ToFlags();
SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4, "1");
SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "1");
SDL.SDL_SetHint(SDL.SDL_HINT_IME_SHOW_UI, "1");
// we want text input to only be active when SDL2DesktopWindowTextInput is active.
// SDL activates it by default on some platforms: https://github.com/libsdl-org/SDL/blob/release-2.0.16/src/video/SDL_video.c#L573-L582
// so we deactivate it on startup.
SDL.SDL_StopTextInput();
SDLWindowHandle = SDL.SDL_CreateWindow(title, Position.X, Position.Y, Size.Width, Size.Height, flags);
Exists = true;
graphicsBackend.Initialise(this);
updateWindowSpecifics();
updateWindowSize();
WindowMode.TriggerChange();
}
// reference must be kept to avoid GC, see https://stackoverflow.com/a/6193914
[UsedImplicitly]
private SDL.SDL_EventFilter eventFilterDelegate;
/// <summary>
/// Starts the window's run loop.
/// </summary>
public void Run()
{
SDL.SDL_SetEventFilter(eventFilterDelegate = (_, eventPtr) =>
{
var e = Marshal.PtrToStructure<SDL.SDL_Event>(eventPtr);
OnSDLEvent?.Invoke(e);
return 1;
}, IntPtr.Zero);
// polling via SDL_PollEvent blocks on resizes (https://stackoverflow.com/a/50858339)
OnSDLEvent += e =>
{
if (e.type == SDL.SDL_EventType.SDL_WINDOWEVENT && e.window.windowEvent == SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESIZED)
{
updateWindowSize();
}
};
while (Exists)
{
commandScheduler.Update();
if (!Exists)
break;
if (pendingWindowState != null)
updateWindowSpecifics();
pollSDLEvents();
if (!cursorInWindow.Value)
pollMouse();
eventScheduler.Update();
Update?.Invoke();
}
Exited?.Invoke();
if (SDLWindowHandle != IntPtr.Zero)
SDL.SDL_DestroyWindow(SDLWindowHandle);
SDL.SDL_Quit();
}
/// <summary>
/// Updates the client size and the scale according to the window.
/// </summary>
/// <returns>Whether the window size has been changed after updating.</returns>
private void updateWindowSize()
{
SDL.SDL_GL_GetDrawableSize(SDLWindowHandle, out int w, out int h);
SDL.SDL_GetWindowSize(SDLWindowHandle, out int actualW, out int _);
Scale = (float)w / actualW;
Size = new Size(w, h);
// This function may be invoked before the SDL internal states are all changed. (as documented here: https://wiki.libsdl.org/SDL_SetEventFilter)
// Scheduling the store to config until after the event poll has run will ensure the window is in the correct state.
eventScheduler.AddOnce(storeWindowSizeToConfig);
}
/// <summary>
/// Forcefully closes the window.
/// </summary>
public void Close() => ScheduleCommand(() => Exists = false);
/// <summary>
/// Attempts to close the window.
/// </summary>
public void RequestClose() => ScheduleEvent(() =>
{
if (ExitRequested?.Invoke() != true)
Close();
});
public void SwapBuffers()
{
graphicsBackend.SwapBuffers();
if (firstDraw)
{
Visible = true;
firstDraw = false;
}
}
/// <summary>
/// Requests that the graphics backend become the current context.
/// May not be required for some backends.
/// </summary>
public void MakeCurrent() => graphicsBackend.MakeCurrent();
/// <summary>
/// Requests that the current context be cleared.
/// </summary>
public void ClearCurrent() => graphicsBackend.ClearCurrent();
private void enqueueJoystickAxisInput(JoystickAxisSource axisSource, short axisValue)
{
// SDL reports axis values in the range short.MinValue to short.MaxValue, so we scale and clamp it to the range of -1f to 1f
float clamped = Math.Clamp((float)axisValue / short.MaxValue, -1f, 1f);
JoystickAxisChanged?.Invoke(new JoystickAxis(axisSource, clamped));
}
private void enqueueJoystickButtonInput(JoystickButton button, bool isPressed)
{
if (isPressed)
JoystickButtonDown?.Invoke(button);
else
JoystickButtonUp?.Invoke(button);
}
/// <summary>
/// Attempts to set the window's icon to the specified image.
/// </summary>
/// <param name="image">An <see cref="Image{Rgba32}"/> to set as the window icon.</param>
private unsafe void setSDLIcon(Image<Rgba32> image)
{
var pixelMemory = image.CreateReadOnlyPixelMemory();
var imageSize = image.Size();
ScheduleCommand(() =>
{
var pixelSpan = pixelMemory.Span;
IntPtr surface;
fixed (Rgba32* ptr = pixelSpan)
surface = SDL.SDL_CreateRGBSurfaceFrom(new IntPtr(ptr), imageSize.Width, imageSize.Height, 32, imageSize.Width * 4, 0xff, 0xff00, 0xff0000, 0xff000000);
SDL.SDL_SetWindowIcon(SDLWindowHandle, surface);
SDL.SDL_FreeSurface(surface);
});
}
private Point previousPolledPoint = Point.Empty;
private void pollMouse()
{
SDL.SDL_GetGlobalMouseState(out int x, out int y);
if (previousPolledPoint.X == x && previousPolledPoint.Y == y)
return;
previousPolledPoint = new Point(x, y);
var pos = WindowMode.Value == Configuration.WindowMode.Windowed ? Position : windowDisplayBounds.Location;
int rx = x - pos.X;
int ry = y - pos.Y;
MouseMove?.Invoke(new Vector2(rx * Scale, ry * Scale));
}
public virtual void StartTextInput(bool allowIme) => ScheduleCommand(SDL.SDL_StartTextInput);
public void StopTextInput() => ScheduleCommand(SDL.SDL_StopTextInput);
/// <summary>
/// Resets internal state of the platform-native IME.
/// This will clear its composition text and prepare it for new input.
/// </summary>
public virtual void ResetIme() => ScheduleCommand(() =>
{
SDL.SDL_StopTextInput();
SDL.SDL_StartTextInput();
});
public void SetTextInputRect(RectangleF rect) => ScheduleCommand(() =>
{
var sdlRect = ((RectangleI)(rect / Scale)).ToSDLRect();
SDL.SDL_SetTextInputRect(ref sdlRect);
});
#region SDL Event Handling
/// <summary>
/// Adds an <see cref="Action"/> to the <see cref="Scheduler"/> expected to handle event callbacks.
/// </summary>
/// <param name="action">The <see cref="Action"/> to execute.</param>
protected void ScheduleEvent(Action action) => eventScheduler.Add(action, false);
protected void ScheduleCommand(Action action) => commandScheduler.Add(action, false);
private const int events_per_peep = 64;
private readonly SDL.SDL_Event[] events = new SDL.SDL_Event[events_per_peep];
/// <summary>
/// Poll for all pending events.
/// </summary>
private void pollSDLEvents()
{
SDL.SDL_PumpEvents();
int eventsRead;
do
{
eventsRead = SDL.SDL_PeepEvents(events, events_per_peep, SDL.SDL_eventaction.SDL_GETEVENT, SDL.SDL_EventType.SDL_FIRSTEVENT, SDL.SDL_EventType.SDL_LASTEVENT);
for (int i = 0; i < eventsRead; i++)
handleSDLEvent(events[i]);
} while (eventsRead == events_per_peep);
}
private void handleSDLEvent(SDL.SDL_Event e)
{
switch (e.type)
{
case SDL.SDL_EventType.SDL_QUIT:
case SDL.SDL_EventType.SDL_APP_TERMINATING:
handleQuitEvent(e.quit);
break;
case SDL.SDL_EventType.SDL_WINDOWEVENT:
handleWindowEvent(e.window);
break;
case SDL.SDL_EventType.SDL_KEYDOWN:
case SDL.SDL_EventType.SDL_KEYUP:
handleKeyboardEvent(e.key);
break;
case SDL.SDL_EventType.SDL_TEXTEDITING:
HandleTextEditingEvent(e.edit);
break;
case SDL.SDL_EventType.SDL_TEXTINPUT:
HandleTextInputEvent(e.text);
break;
case SDL.SDL_EventType.SDL_KEYMAPCHANGED:
handleKeymapChangedEvent();
break;
case SDL.SDL_EventType.SDL_MOUSEMOTION:
handleMouseMotionEvent(e.motion);
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
handleMouseButtonEvent(e.button);
break;
case SDL.SDL_EventType.SDL_MOUSEWHEEL:
handleMouseWheelEvent(e.wheel);
break;
case SDL.SDL_EventType.SDL_JOYAXISMOTION:
handleJoyAxisEvent(e.jaxis);
break;
case SDL.SDL_EventType.SDL_JOYBALLMOTION:
handleJoyBallEvent(e.jball);
break;
case SDL.SDL_EventType.SDL_JOYHATMOTION:
handleJoyHatEvent(e.jhat);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
handleJoyButtonEvent(e.jbutton);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
handleJoyDeviceEvent(e.jdevice);
break;
case SDL.SDL_EventType.SDL_CONTROLLERAXISMOTION:
handleControllerAxisEvent(e.caxis);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
handleControllerButtonEvent(e.cbutton);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
handleControllerDeviceEvent(e.cdevice);
break;
case SDL.SDL_EventType.SDL_FINGERDOWN:
case SDL.SDL_EventType.SDL_FINGERUP:
case SDL.SDL_EventType.SDL_FINGERMOTION:
handleTouchFingerEvent(e.tfinger);
break;
case SDL.SDL_EventType.SDL_DROPFILE:
case SDL.SDL_EventType.SDL_DROPTEXT:
case SDL.SDL_EventType.SDL_DROPBEGIN:
case SDL.SDL_EventType.SDL_DROPCOMPLETE:
handleDropEvent(e.drop);
break;
}
}
private void handleQuitEvent(SDL.SDL_QuitEvent evtQuit) => RequestClose();
private void handleDropEvent(SDL.SDL_DropEvent evtDrop)
{
switch (evtDrop.type)
{
case SDL.SDL_EventType.SDL_DROPFILE:
string str = SDL.UTF8_ToManaged(evtDrop.file, true);
if (str != null)
DragDrop?.Invoke(str);
break;
}
}
private void handleTouchFingerEvent(SDL.SDL_TouchFingerEvent evtTfinger)
{
}
private void handleControllerDeviceEvent(SDL.SDL_ControllerDeviceEvent evtCdevice)
{
switch (evtCdevice.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
addJoystick(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
SDL.SDL_GameControllerClose(controllers[evtCdevice.which].ControllerHandle);
controllers.Remove(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
if (controllers.TryGetValue(evtCdevice.which, out var state))
state.PopulateBindings();
break;
}
}
private void handleControllerButtonEvent(SDL.SDL_ControllerButtonEvent evtCbutton)
{
var button = ((SDL.SDL_GameControllerButton)evtCbutton.button).ToJoystickButton();
switch (evtCbutton.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleControllerAxisEvent(SDL.SDL_ControllerAxisEvent evtCaxis) =>
enqueueJoystickAxisInput(((SDL.SDL_GameControllerAxis)evtCaxis.axis).ToJoystickAxisSource(), evtCaxis.axisValue);
private void addJoystick(int which)
{
int instanceID = SDL.SDL_JoystickGetDeviceInstanceID(which);
// if the joystick is already opened, ignore it
if (controllers.ContainsKey(instanceID))
return;
var joystick = SDL.SDL_JoystickOpen(which);
var controller = IntPtr.Zero;
if (SDL.SDL_IsGameController(which) == SDL.SDL_bool.SDL_TRUE)
controller = SDL.SDL_GameControllerOpen(which);
controllers[instanceID] = new SDL2ControllerBindings(joystick, controller);
}
/// <summary>
/// Populates <see cref="controllers"/> with joysticks that are already connected.
/// </summary>
private void populateJoysticks()
{
for (int i = 0; i < SDL.SDL_NumJoysticks(); i++)
{
addJoystick(i);
}
}
private void handleJoyDeviceEvent(SDL.SDL_JoyDeviceEvent evtJdevice)
{
switch (evtJdevice.type)
{
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
addJoystick(evtJdevice.which);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
// if the joystick is already closed, ignore it
if (!controllers.ContainsKey(evtJdevice.which))
break;
SDL.SDL_JoystickClose(controllers[evtJdevice.which].JoystickHandle);
controllers.Remove(evtJdevice.which);
break;
}
}
private void handleJoyButtonEvent(SDL.SDL_JoyButtonEvent evtJbutton)
{
// if this button exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJbutton.which, out var state) && state.GetButtonForIndex(evtJbutton.button) != SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID)
return;
var button = JoystickButton.FirstButton + evtJbutton.button;
switch (evtJbutton.type)
{
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleJoyHatEvent(SDL.SDL_JoyHatEvent evtJhat)
{
}
private void handleJoyBallEvent(SDL.SDL_JoyBallEvent evtJball)
{
}
private void handleJoyAxisEvent(SDL.SDL_JoyAxisEvent evtJaxis)
{
// if this axis exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJaxis.which, out var state) && state.GetAxisForIndex(evtJaxis.axis) != SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_INVALID)
return;
enqueueJoystickAxisInput(JoystickAxisSource.Axis1 + evtJaxis.axis, evtJaxis.axisValue);
}
private void handleMouseWheelEvent(SDL.SDL_MouseWheelEvent evtWheel) =>
TriggerMouseWheel(new Vector2(evtWheel.x, evtWheel.y), false);
private void handleMouseButtonEvent(SDL.SDL_MouseButtonEvent evtButton)
{
MouseButton button = mouseButtonFromEvent(evtButton.button);
switch (evtButton.type)
{
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
MouseDown?.Invoke(button);
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
MouseUp?.Invoke(button);
break;
}
}
private void handleMouseMotionEvent(SDL.SDL_MouseMotionEvent evtMotion)
{
if (SDL.SDL_GetRelativeMouseMode() == SDL.SDL_bool.SDL_FALSE)
MouseMove?.Invoke(new Vector2(evtMotion.x * Scale, evtMotion.y * Scale));
else
MouseMoveRelative?.Invoke(new Vector2(evtMotion.xrel * Scale, evtMotion.yrel * Scale));
}
protected virtual unsafe void HandleTextInputEvent(SDL.SDL_TextInputEvent evtText)
{
if (!SDL2Extensions.TryGetStringFromBytePointer(evtText.text, out string text))
return;
TriggerTextInput(text);
}
protected virtual unsafe void HandleTextEditingEvent(SDL.SDL_TextEditingEvent evtEdit)
{
if (!SDL2Extensions.TryGetStringFromBytePointer(evtEdit.text, out string text))
return;
TriggerTextEditing(text, evtEdit.start, evtEdit.length);
}
private void handleKeyboardEvent(SDL.SDL_KeyboardEvent evtKey)
{
Key key = evtKey.keysym.ToKey();
if (key == Key.Unknown)
return;
switch (evtKey.type)
{
case SDL.SDL_EventType.SDL_KEYDOWN:
KeyDown?.Invoke(key);
break;
case SDL.SDL_EventType.SDL_KEYUP:
KeyUp?.Invoke(key);
break;
}
}
private void handleKeymapChangedEvent() => KeymapChanged?.Invoke();
private void handleWindowEvent(SDL.SDL_WindowEvent evtWindow)
{
updateWindowSpecifics();
switch (evtWindow.windowEvent)
{
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MOVED:
// explicitly requery as there are occasions where what SDL has provided us with is not up-to-date.
SDL.SDL_GetWindowPosition(SDLWindowHandle, out int x, out int y);
var newPosition = new Point(x, y);
if (!newPosition.Equals(Position))
{
position = newPosition;
Moved?.Invoke(newPosition);
if (WindowMode.Value == Configuration.WindowMode.Windowed)
storeWindowPositionToConfig();
}
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED:
updateWindowSize();
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_ENTER:
cursorInWindow.Value = true;
MouseEntered?.Invoke();
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_LEAVE:
cursorInWindow.Value = false;
MouseLeft?.Invoke();
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESTORED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
Focused = true;
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MINIMIZED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
Focused = false;
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_CLOSE:
break;
}
}
/// <summary>
/// Should be run on a regular basis to check for external window state changes.
/// </summary>
private void updateWindowSpecifics()
{
// don't attempt to run before the window is initialised, as Create() will do so anyway.
if (SDLWindowHandle == IntPtr.Zero)
return;
var stateBefore = windowState;
// check for a pending user state change and give precedence.
if (pendingWindowState != null)
{
windowState = pendingWindowState.Value;
pendingWindowState = null;
updateWindowStateAndSize();
}
else
{
windowState = ((SDL.SDL_WindowFlags)SDL.SDL_GetWindowFlags(SDLWindowHandle)).ToWindowState();
}
if (windowState != stateBefore)
{
WindowStateChanged?.Invoke(windowState);
updateMaximisedState();
}
int newDisplayIndex = SDL.SDL_GetWindowDisplayIndex(SDLWindowHandle);
if (displayIndex != newDisplayIndex)
{
displayIndex = newDisplayIndex;
currentDisplay = Displays.ElementAtOrDefault(displayIndex) ?? PrimaryDisplay;
CurrentDisplayBindable.Value = currentDisplay;
}
}
/// <summary>
/// Should be run after a local window state change, to propagate the correct SDL actions.
/// </summary>
private void updateWindowStateAndSize()
{
// this reset is required even on changing from one fullscreen resolution to another.
// if it is not included, the GL context will not get the correct size.
// this is mentioned by multiple sources as an SDL issue, which seems to resolve by similar means (see https://discourse.libsdl.org/t/sdl-setwindowsize-does-not-work-in-fullscreen/20711/4).
SDL.SDL_SetWindowBordered(SDLWindowHandle, SDL.SDL_bool.SDL_TRUE);
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_bool.SDL_FALSE);
switch (windowState)
{
case WindowState.Normal:
Size = (sizeWindowed.Value * Scale).ToSize();
SDL.SDL_RestoreWindow(SDLWindowHandle);
SDL.SDL_SetWindowSize(SDLWindowHandle, sizeWindowed.Value.Width, sizeWindowed.Value.Height);
SDL.SDL_SetWindowResizable(SDLWindowHandle, Resizable ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE);
readWindowPositionFromConfig();
break;
case WindowState.Fullscreen:
var closestMode = getClosestDisplayMode(sizeFullscreen.Value, currentDisplayMode.Value.RefreshRate, currentDisplay.Index);
Size = new Size(closestMode.w, closestMode.h);
SDL.SDL_SetWindowDisplayMode(SDLWindowHandle, ref closestMode);
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN);
break;
case WindowState.FullscreenBorderless:
Size = SetBorderless();
break;
case WindowState.Maximised:
SDL.SDL_RestoreWindow(SDLWindowHandle);
SDL.SDL_MaximizeWindow(SDLWindowHandle);
SDL.SDL_GL_GetDrawableSize(SDLWindowHandle, out int w, out int h);
Size = new Size(w, h);
break;
case WindowState.Minimised:
SDL.SDL_MinimizeWindow(SDLWindowHandle);
break;
}
updateMaximisedState();
if (SDL.SDL_GetWindowDisplayMode(SDLWindowHandle, out var mode) >= 0)
currentDisplayMode.Value = new DisplayMode(mode.format.ToString(), new Size(mode.w, mode.h), 32, mode.refresh_rate, displayIndex, displayIndex);
}
private void updateMaximisedState()
{
if (windowState == WindowState.Normal || windowState == WindowState.Maximised)
windowMaximised = windowState == WindowState.Maximised;
}
private void readWindowPositionFromConfig()
{
if (WindowState != WindowState.Normal)
return;
var configPosition = new Vector2((float)windowPositionX.Value, (float)windowPositionY.Value);
var displayBounds = CurrentDisplay.Bounds;
var windowSize = sizeWindowed.Value;
int windowX = (int)Math.Round((displayBounds.Width - windowSize.Width) * configPosition.X);
int windowY = (int)Math.Round((displayBounds.Height - windowSize.Height) * configPosition.Y);
Position = new Point(windowX + displayBounds.X, windowY + displayBounds.Y);
}
private void storeWindowPositionToConfig()
{
if (WindowState != WindowState.Normal)
return;
var displayBounds = CurrentDisplay.Bounds;
int windowX = Position.X - displayBounds.X;
int windowY = Position.Y - displayBounds.Y;
var windowSize = sizeWindowed.Value;
windowPositionX.Value = displayBounds.Width > windowSize.Width ? (float)windowX / (displayBounds.Width - windowSize.Width) : 0;
windowPositionY.Value = displayBounds.Height > windowSize.Height ? (float)windowY / (displayBounds.Height - windowSize.Height) : 0;
}
/// <summary>
/// Set to <c>true</c> while the window size is being stored to config to avoid bindable feedback.
/// </summary>
private bool storingSizeToConfig;
private void storeWindowSizeToConfig()
{
if (WindowState != WindowState.Normal)
return;
storingSizeToConfig = true;
sizeWindowed.Value = (Size / Scale).ToSize();
storingSizeToConfig = false;
}
/// <summary>
/// Prepare display of a borderless window.
/// </summary>
/// <returns>
/// The size of the borderless window's draw area.
/// </returns>
protected virtual Size SetBorderless()
{
// this is a generally sane method of handling borderless, and works well on macOS and linux.
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
return currentDisplay.Bounds.Size;
}
private MouseButton mouseButtonFromEvent(byte button)
{
switch ((uint)button)
{
default:
case SDL.SDL_BUTTON_LEFT:
return MouseButton.Left;
case SDL.SDL_BUTTON_RIGHT:
return MouseButton.Right;
case SDL.SDL_BUTTON_MIDDLE:
return MouseButton.Middle;
case SDL.SDL_BUTTON_X1:
return MouseButton.Button1;
case SDL.SDL_BUTTON_X2:
return MouseButton.Button2;
}
}
#endregion
protected virtual IGraphicsBackend CreateGraphicsBackend() => new SDL2GraphicsBackend();
public void SetupWindow(FrameworkConfigManager config)
{
CurrentDisplayBindable.ValueChanged += evt =>
{
windowDisplayIndexBindable.Value = (DisplayIndex)evt.NewValue.Index;
};
config.BindWith(FrameworkSetting.LastDisplayDevice, windowDisplayIndexBindable);
windowDisplayIndexBindable.BindValueChanged(evt => CurrentDisplay = Displays.ElementAtOrDefault((int)evt.NewValue) ?? PrimaryDisplay, true);
sizeFullscreen.ValueChanged += evt =>
{
if (storingSizeToConfig) return;
if (windowState != WindowState.Fullscreen) return;
pendingWindowState = windowState;
};
sizeWindowed.ValueChanged += evt =>
{
if (storingSizeToConfig) return;
if (windowState != WindowState.Normal) return;
pendingWindowState = windowState;
};
config.BindWith(FrameworkSetting.SizeFullscreen, sizeFullscreen);
config.BindWith(FrameworkSetting.WindowedSize, sizeWindowed);
config.BindWith(FrameworkSetting.WindowedPositionX, windowPositionX);
config.BindWith(FrameworkSetting.WindowedPositionY, windowPositionY);
config.BindWith(FrameworkSetting.WindowMode, WindowMode);
config.BindWith(FrameworkSetting.ConfineMouseMode, ConfineMouseMode);
WindowMode.BindValueChanged(evt =>
{
switch (evt.NewValue)
{
case Configuration.WindowMode.Fullscreen:
WindowState = WindowState.Fullscreen;
break;
case Configuration.WindowMode.Borderless:
WindowState = WindowState.FullscreenBorderless;
break;
case Configuration.WindowMode.Windowed:
WindowState = windowMaximised ? WindowState.Maximised : WindowState.Normal;
break;
}
updateConfineMode();
});
ConfineMouseMode.BindValueChanged(_ => updateConfineMode());
}
public void CycleMode()
{
var currentValue = WindowMode.Value;
do
{
switch (currentValue)
{
case Configuration.WindowMode.Windowed:
currentValue = Configuration.WindowMode.Borderless;
break;
case Configuration.WindowMode.Borderless:
currentValue = Configuration.WindowMode.Fullscreen;
break;
case Configuration.WindowMode.Fullscreen:
currentValue = Configuration.WindowMode.Windowed;
break;
}
} while (!SupportedWindowModes.Contains(currentValue) && currentValue != WindowMode.Value);
WindowMode.Value = currentValue;
}
/// <summary>
/// Update the host window manager's cursor position based on a location relative to window coordinates.
/// </summary>
/// <param name="position">A position inside the window.</param>
public void UpdateMousePosition(Vector2 position) => ScheduleCommand(() =>
SDL.SDL_WarpMouseInWindow(SDLWindowHandle, (int)(position.X / Scale), (int)(position.Y / Scale)));
public void SetIconFromStream(Stream stream)
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Position = 0;
var imageInfo = Image.Identify(ms);
if (imageInfo != null)
SetIconFromImage(Image.Load<Rgba32>(ms.GetBuffer()));
else if (IconGroup.TryParse(ms.GetBuffer(), out var iconGroup))
SetIconFromGroup(iconGroup);
}
}
internal virtual void SetIconFromGroup(IconGroup iconGroup)
{
// LoadRawIcon returns raw PNG data if available, which avoids any Windows-specific pinvokes
byte[] bytes = iconGroup.LoadRawIcon(default_icon_size, default_icon_size);
if (bytes == null)
return;
SetIconFromImage(Image.Load<Rgba32>(bytes));
}
internal virtual void SetIconFromImage(Image<Rgba32> iconImage) => setSDLIcon(iconImage);
private void updateConfineMode()
{
bool confine = false;
switch (ConfineMouseMode.Value)
{
case Input.ConfineMouseMode.Fullscreen:
confine = WindowMode.Value != Configuration.WindowMode.Windowed;
break;
case Input.ConfineMouseMode.Always:
confine = true;
break;
}
if (confine)
CursorStateBindable.Value |= CursorState.Confined;
else
CursorStateBindable.Value &= ~CursorState.Confined;
}
#region Helper functions
private SDL.SDL_DisplayMode getClosestDisplayMode(Size size, int refreshRate, int displayIndex)
{
var targetMode = new SDL.SDL_DisplayMode { w = size.Width, h = size.Height, refresh_rate = refreshRate };
if (SDL.SDL_GetClosestDisplayMode(displayIndex, ref targetMode, out var mode) != IntPtr.Zero)
return mode;
// fallback to current display's native bounds
targetMode.w = currentDisplay.Bounds.Width;
targetMode.h = currentDisplay.Bounds.Height;
targetMode.refresh_rate = 0;
if (SDL.SDL_GetClosestDisplayMode(displayIndex, ref targetMode, out mode) != IntPtr.Zero)
return mode;
// finally return the current mode if everything else fails.
// not sure this is required.
if (SDL.SDL_GetWindowDisplayMode(SDLWindowHandle, out mode) >= 0)
return mode;
throw new InvalidOperationException("couldn't retrieve valid display mode");
}
private static Display displayFromSDL(int displayIndex)
{
var displayModes = Enumerable.Range(0, SDL.SDL_GetNumDisplayModes(displayIndex))
.Select(modeIndex =>
{
SDL.SDL_GetDisplayMode(displayIndex, modeIndex, out var mode);
return displayModeFromSDL(mode, displayIndex, modeIndex);
})
.ToArray();
SDL.SDL_GetDisplayBounds(displayIndex, out var rect);
return new Display(displayIndex, SDL.SDL_GetDisplayName(displayIndex), new Rectangle(rect.x, rect.y, rect.w, rect.h), displayModes);
}
private static DisplayMode displayModeFromSDL(SDL.SDL_DisplayMode mode, int displayIndex, int modeIndex)
{
SDL.SDL_PixelFormatEnumToMasks(mode.format, out int bpp, out _, out _, out _, out _);
return new DisplayMode(SDL.SDL_GetPixelFormatName(mode.format), new Size(mode.w, mode.h), bpp, mode.refresh_rate, modeIndex, displayIndex);
}
#endregion
#region Events
/// <summary>
/// Invoked once every window event loop.
/// </summary>
public event Action Update;
/// <summary>
/// Invoked after the window has resized.
/// </summary>
public event Action Resized;
/// <summary>
/// Invoked after the window's state has changed.
/// </summary>
public event Action<WindowState> WindowStateChanged;
/// <summary>
/// Invoked when the user attempts to close the window. Return value of true will cancel exit.
/// </summary>
public event Func<bool> ExitRequested;
/// <summary>
/// Invoked when the window is about to close.
/// </summary>
public event Action Exited;
/// <summary>
/// Invoked when the mouse cursor enters the window.
/// </summary>
public event Action MouseEntered;
/// <summary>
/// Invoked when the mouse cursor leaves the window.
/// </summary>
public event Action MouseLeft;
/// <summary>
/// Invoked when the window moves.
/// </summary>
public event Action<Point> Moved;
/// <summary>
/// Invoked when the user scrolls the mouse wheel over the window.
/// </summary>
public event Action<Vector2, bool> MouseWheel;
protected void TriggerMouseWheel(Vector2 delta, bool precise) => MouseWheel?.Invoke(delta, precise);
/// <summary>
/// Invoked when the user moves the mouse cursor within the window.
/// </summary>
public event Action<Vector2> MouseMove;
/// <summary>
/// Invoked when the user moves the mouse cursor within the window (via relative / raw input).
/// </summary>
public event Action<Vector2> MouseMoveRelative;
/// <summary>
/// Invoked when the user presses a mouse button.
/// </summary>
public event Action<MouseButton> MouseDown;
/// <summary>
/// Invoked when the user releases a mouse button.
/// </summary>
public event Action<MouseButton> MouseUp;
/// <summary>
/// Invoked when the user presses a key.
/// </summary>
public event Action<Key> KeyDown;
/// <summary>
/// Invoked when the user releases a key.
/// </summary>
public event Action<Key> KeyUp;
/// <summary>
/// Invoked when the user enters text.
/// </summary>
public event Action<string> TextInput;
protected void TriggerTextInput(string text) => TextInput?.Invoke(text);
/// <summary>
/// Invoked when an IME text editing event occurs.
/// </summary>
public event TextEditingDelegate TextEditing;
protected void TriggerTextEditing(string text, int start, int length) => TextEditing?.Invoke(text, start, length);
/// <inheritdoc cref="IWindow.KeymapChanged"/>
public event Action KeymapChanged;
/// <summary>
/// Invoked when a joystick axis changes.
/// </summary>
public event Action<JoystickAxis> JoystickAxisChanged;
/// <summary>
/// Invoked when the user presses a button on a joystick.
/// </summary>
public event Action<JoystickButton> JoystickButtonDown;
/// <summary>
/// Invoked when the user releases a button on a joystick.
/// </summary>
public event Action<JoystickButton> JoystickButtonUp;
/// <summary>
/// Invoked when the user drops a file into the window.
/// </summary>
public event Action<string> DragDrop;
/// <summary>
/// Invoked on every SDL event before it's posted to the event queue.
/// </summary>
protected event Action<SDL.SDL_Event> OnSDLEvent;
#endregion
public void Dispose()
{
}
/// <summary>
/// Fired when text is edited, usually via IME composition.
/// </summary>
/// <param name="text">The composition text.</param>
/// <param name="start">The index of the selection start.</param>
/// <param name="length">The length of the selection.</param>
public delegate void TextEditingDelegate(string text, int start, int length);
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class IncomingMessageBuffer
{
private const int Kb = 1024;
private const int DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE = 1024 * Kb; // 1mg
private const int GROW_MAX_BLOCK_SIZE = 1024 * Kb; // 1mg
private static readonly ArraySegment<byte>[] EmptyBuffers = {new ArraySegment<byte>(new byte[0]), };
private readonly List<ArraySegment<byte>> readBuffer;
private readonly int maxSustainedBufferSize;
private int currentBufferSize;
private readonly byte[] lengthBuffer;
private int headerLength;
private int bodyLength;
private int receiveOffset;
private int decodeOffset;
private readonly bool supportForwarding;
private ILogger Log;
private readonly SerializationManager serializationManager;
private readonly DeserializationContext deserializationContext;
internal const int DEFAULT_RECEIVE_BUFFER_SIZE = 128 * Kb; // 128k
public IncomingMessageBuffer(
ILoggerFactory loggerFactory,
SerializationManager serializationManager,
bool supportForwarding = false,
int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE,
int maxSustainedReceiveBufferSize = DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE)
{
Log = loggerFactory.CreateLogger<IncomingMessageBuffer>();
this.serializationManager = serializationManager;
this.supportForwarding = supportForwarding;
currentBufferSize = receiveBufferSize;
maxSustainedBufferSize = maxSustainedReceiveBufferSize;
lengthBuffer = new byte[Message.LENGTH_HEADER_SIZE];
readBuffer = BufferPool.GlobalPool.GetMultiBuffer(currentBufferSize);
receiveOffset = 0;
decodeOffset = 0;
headerLength = 0;
bodyLength = 0;
deserializationContext = new DeserializationContext(this.serializationManager)
{
StreamReader = new BinaryTokenStreamReader(EmptyBuffers)
};
}
public List<ArraySegment<byte>> BuildReceiveBuffer()
{
// Opportunistic reset to start of buffer
if (decodeOffset == receiveOffset)
{
decodeOffset = 0;
receiveOffset = 0;
}
return ByteArrayBuilder.BuildSegmentList(readBuffer, receiveOffset);
}
// Copies receive buffer into read buffer for futher processing
public void UpdateReceivedData(byte[] receiveBuffer, int bytesRead)
{
var newReceiveOffset = receiveOffset + bytesRead;
while (newReceiveOffset > currentBufferSize)
{
GrowBuffer();
}
int receiveBufferOffset = 0;
var lengthSoFar = 0;
foreach (var segment in readBuffer)
{
var bytesStillToSkip = receiveOffset - lengthSoFar;
lengthSoFar += segment.Count;
if (segment.Count <= bytesStillToSkip)
{
continue;
}
if(bytesStillToSkip > 0) // This is the first buffer
{
var bytesToCopy = Math.Min(segment.Count - bytesStillToSkip, bytesRead - receiveBufferOffset);
Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, bytesStillToSkip, bytesToCopy);
receiveBufferOffset += bytesToCopy;
}
else
{
var bytesToCopy = Math.Min(segment.Count, bytesRead - receiveBufferOffset);
Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, 0, bytesToCopy);
receiveBufferOffset += Math.Min(bytesToCopy, segment.Count);
}
if (receiveBufferOffset == bytesRead)
{
break;
}
}
receiveOffset += bytesRead;
}
public void UpdateReceivedData(int bytesRead)
{
receiveOffset += bytesRead;
}
public void Reset()
{
receiveOffset = 0;
decodeOffset = 0;
headerLength = 0;
bodyLength = 0;
}
public bool TryDecodeMessage(out Message msg)
{
msg = null;
// Is there enough read into the buffer to continue (at least read the lengths?)
if (receiveOffset - decodeOffset < CalculateKnownMessageSize())
return false;
// parse lengths if needed
if (headerLength == 0 || bodyLength == 0)
{
// get length segments
List<ArraySegment<byte>> lenghts = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, decodeOffset, Message.LENGTH_HEADER_SIZE);
// copy length segment to buffer
int lengthBufferoffset = 0;
foreach (ArraySegment<byte> seg in lenghts)
{
Buffer.BlockCopy(seg.Array, seg.Offset, lengthBuffer, lengthBufferoffset, seg.Count);
lengthBufferoffset += seg.Count;
}
// read lengths
headerLength = BitConverter.ToInt32(lengthBuffer, 0);
bodyLength = BitConverter.ToInt32(lengthBuffer, 4);
}
// If message is too big for current buffer size, grow
while (decodeOffset + CalculateKnownMessageSize() > currentBufferSize)
{
GrowBuffer();
}
// Is there enough read into the buffer to read full message
if (receiveOffset - decodeOffset < CalculateKnownMessageSize())
return false;
// decode header
int headerOffset = decodeOffset + Message.LENGTH_HEADER_SIZE;
List<ArraySegment<byte>> header = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, headerOffset, headerLength);
// decode body
int bodyOffset = headerOffset + headerLength;
List<ArraySegment<byte>> body = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, bodyOffset, bodyLength);
// build message
this.deserializationContext.Reset();
this.deserializationContext.StreamReader.Reset(header);
msg = new Message
{
Headers = SerializationManager.DeserializeMessageHeaders(this.deserializationContext)
};
try
{
if (this.supportForwarding)
{
// If forwarding is supported, then deserialization will be deferred until the body value is needed.
// Need to maintain ownership of buffer, so we need to duplicate the body buffer.
msg.SetBodyBytes(this.DuplicateBuffer(body));
}
else
{
// Attempt to deserialize the body immediately.
msg.DeserializeBodyObject(this.serializationManager, body);
}
}
finally
{
MessagingStatisticsGroup.OnMessageReceive(msg, headerLength, bodyLength);
if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold)
{
Log.Info(
ErrorCode.Messaging_LargeMsg_Incoming,
"Receiving large message Size={0} HeaderLength={1} BodyLength={2}. Msg={3}",
headerLength + bodyLength,
headerLength,
bodyLength,
msg.ToString());
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Received large message {0}", msg.ToLongString());
}
// update parse receiveOffset and clear lengths
decodeOffset = bodyOffset + bodyLength;
headerLength = 0;
bodyLength = 0;
AdjustBuffer();
}
return true;
}
/// <summary>
/// This call cleans up the buffer state to make it optimal for next read.
/// The leading chunks, used by any processed messages, are removed from the front
/// of the buffer and added to the back. Decode and receiver offsets are adjusted accordingly.
/// If the buffer was grown over the max sustained buffer size (to read a large message) it is shrunken.
/// </summary>
private void AdjustBuffer()
{
// drop buffers consumed by messages and adjust offsets
// TODO: This can be optimized further. Linked lists?
int consumedBytes = 0;
int removed = 0;
for (; removed < this.readBuffer.Count; removed++)
{
ArraySegment<byte> seg = this.readBuffer[removed];
if (seg.Count <= decodeOffset - consumedBytes)
{
consumedBytes += seg.Count;
BufferPool.GlobalPool.Release(seg.Array);
}
else
{
break;
}
}
if (removed != 0) this.readBuffer.RemoveRange(0, removed);
decodeOffset -= consumedBytes;
receiveOffset -= consumedBytes;
// backfill any consumed buffers, to preserve buffer size.
if (consumedBytes != 0)
{
int backfillBytes = consumedBytes;
// If buffer is larger than max sustained size, backfill only up to max sustained buffer size.
if (currentBufferSize > maxSustainedBufferSize)
{
backfillBytes = Math.Max(consumedBytes + maxSustainedBufferSize - currentBufferSize, 0);
currentBufferSize -= consumedBytes;
currentBufferSize += backfillBytes;
}
if (backfillBytes > 0)
{
readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(backfillBytes));
}
}
}
private int CalculateKnownMessageSize()
{
return headerLength + bodyLength + Message.LENGTH_HEADER_SIZE;
}
private List<ArraySegment<byte>> DuplicateBuffer(List<ArraySegment<byte>> body)
{
var dupBody = new List<ArraySegment<byte>>(body.Count);
foreach (ArraySegment<byte> seg in body)
{
var dupSeg = new ArraySegment<byte>(BufferPool.GlobalPool.GetBuffer(), seg.Offset, seg.Count);
Buffer.BlockCopy(seg.Array, seg.Offset, dupSeg.Array, dupSeg.Offset, seg.Count);
dupBody.Add(dupSeg);
}
return dupBody;
}
private void GrowBuffer()
{
//TODO: Add configurable max message size for safety
//TODO: Review networking layer and add max size checks to all dictionaries, arrays, or other variable sized containers.
// double buffer size up to max grow block size, then only grow it in those intervals
int growBlockSize = Math.Min(currentBufferSize, GROW_MAX_BLOCK_SIZE);
readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(growBlockSize));
currentBufferSize += growBlockSize;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.Numerics;
using Windows.Foundation;
using Windows.System;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace ExampleGallery
{
//
// This example is a simple typing game that demonstrates marshaling
// keyboard events to the game loop thread.
//
public sealed partial class KeyboardInputExample : UserControl
{
LetterAttack.Game game;
public KeyboardInputExample()
{
this.InitializeComponent();
game = new LetterAttack.Game();
}
private void control_Loaded(object sender, RoutedEventArgs e)
{
// Register for keyboard events
Window.Current.CoreWindow.KeyDown += KeyDown_UIThread;
#if WINDOWS_PHONE_APP || WINDOWS_UAP
var keyboardCaps = new Windows.Devices.Input.KeyboardCapabilities();
if (keyboardCaps.KeyboardPresent == 0)
{
// If we don't have a keyboard show the input pane (aka the on-screen keyboard).
var inputPane = Windows.UI.ViewManagement.InputPane.GetForCurrentView();
inputPane.TryShow();
inputPane.Showing += inputPane_Showing;
inputPane.Hiding += inputPane_Hiding;
}
#endif
}
private void animatedControl_PointerPressed(object sender, PointerRoutedEventArgs e)
{
#if WINDOWS_PHONE_APP || WINDOWS_UAP
// Bring the on-screen keyboard back up when the user taps on the screen.
var keyboardCaps = new Windows.Devices.Input.KeyboardCapabilities();
if (keyboardCaps.KeyboardPresent == 0)
{
// There's no keyboard present, so show the input pane
var inputPane = Windows.UI.ViewManagement.InputPane.GetForCurrentView();
inputPane.TryShow();
}
#endif
}
private void control_Unloaded(object sender, RoutedEventArgs e)
{
// Unregister keyboard events
Window.Current.CoreWindow.KeyDown -= KeyDown_UIThread;
// Explicitly remove references to allow the Win2D controls to get garbage collected
animatedControl.RemoveFromVisualTree();
animatedControl = null;
}
private void KeyDown_UIThread(CoreWindow sender, KeyEventArgs args)
{
// This event runs on the UI thread. If we want to process data
// structures that are accessed on the game loop thread then we need
// to use some kind of thread synchronization to ensure that the UI
// thread and game loop thread are not accessing the same data at
// the same time.
//
// The two main options here would be to use locks / critical
// sections or to use RunOnGameLoopThreadAsync to cause code to
// execute on the game loop thread. This example uses
// RunOnGameLoopThreadAsync.
//
// Since KeyEventArgs is not agile we cannot simply pass args to the
// game loop thread. Although doing this may appear to work, it may
// have some surprising behavior. For example, calling a method on
// args may result in the method executing on the UI thread (and so
// blocking the game loop thread). There will also be surprising
// races about which thread gets to set Handled first.
//
// Instead, we do as much processing as possible on the UI thread
// before passing control to the game loop thread.
char pressedLetter = GetPressedLetter(args);
if (pressedLetter == 0)
{
// It wasn't a letter that was pressed, so we don't handle this event
return;
}
// Mark that we've handled this event. It is important to do this
// synchronously inside this event handler since the framework uses
// the Handled flag to determine whether or not to send this event
// to other handlers.
args.Handled = true;
// Now schedule code to run on the game loop thread to handle the
// pressed letter. The animated control will execute this before
// the next Update.
var action = animatedControl.RunOnGameLoopThreadAsync(() => game.ProcessPressedLetterOnGameLoopThread(pressedLetter));
}
// Convert a KeyEventArgs to the corresponding A-Z letter.
// Returns 0 if no letter was pressed.
private static char GetPressedLetter(KeyEventArgs args)
{
var key = args.VirtualKey;
char pressed = (char)0;
switch (key)
{
case VirtualKey.A: pressed = 'A'; break;
case VirtualKey.B: pressed = 'B'; break;
case VirtualKey.C: pressed = 'C'; break;
case VirtualKey.D: pressed = 'D'; break;
case VirtualKey.E: pressed = 'E'; break;
case VirtualKey.F: pressed = 'F'; break;
case VirtualKey.G: pressed = 'G'; break;
case VirtualKey.H: pressed = 'H'; break;
case VirtualKey.I: pressed = 'I'; break;
case VirtualKey.J: pressed = 'J'; break;
case VirtualKey.K: pressed = 'K'; break;
case VirtualKey.L: pressed = 'L'; break;
case VirtualKey.M: pressed = 'M'; break;
case VirtualKey.N: pressed = 'N'; break;
case VirtualKey.O: pressed = 'O'; break;
case VirtualKey.P: pressed = 'P'; break;
case VirtualKey.Q: pressed = 'Q'; break;
case VirtualKey.R: pressed = 'R'; break;
case VirtualKey.S: pressed = 'S'; break;
case VirtualKey.T: pressed = 'T'; break;
case VirtualKey.U: pressed = 'U'; break;
case VirtualKey.V: pressed = 'V'; break;
case VirtualKey.W: pressed = 'W'; break;
case VirtualKey.X: pressed = 'X'; break;
case VirtualKey.Y: pressed = 'Y'; break;
case VirtualKey.Z: pressed = 'Z'; break;
}
return pressed;
}
// When the InputPane (ie on-screen keyboard) is shown then we arrange
// so that the animated control is not obscured.
void inputPane_Showing(Windows.UI.ViewManagement.InputPane sender, Windows.UI.ViewManagement.InputPaneVisibilityEventArgs args)
{
RowObscuredByInputPane.Height = new GridLength(args.OccludedRect.Height);
}
void inputPane_Hiding(Windows.UI.ViewManagement.InputPane sender, Windows.UI.ViewManagement.InputPaneVisibilityEventArgs args)
{
// When the input pane rescale the game to fit
RowObscuredByInputPane.Height = new GridLength(0);
}
private void animatedControl_Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
{
game.Update();
}
private void animatedControl_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
{
game.Draw(args.DrawingSession, sender.Size);
}
}
namespace LetterAttack
{
class Game
{
static CanvasTextFormat scoreFormat = new CanvasTextFormat
{
HorizontalAlignment = CanvasHorizontalAlignment.Left,
VerticalAlignment = CanvasVerticalAlignment.Top
};
static CanvasTextFormat levelUpFormat = new CanvasTextFormat
{
FontSize = 40,
HorizontalAlignment = CanvasHorizontalAlignment.Center,
VerticalAlignment = CanvasVerticalAlignment.Top
};
const int initialFramesBetweenNewLetters = 60;
const float initialVerticalRegion = 0.1f;
List<Letter> letters = new List<Letter>();
int framesSinceLastNewLetter = initialFramesBetweenNewLetters;
int framesBetweenNewLetters;
float verticalRegion;
int leveledUpTimer;
int score;
int highScore = -1;
bool gameOver;
public Game()
{
ResetLevel();
if (ThumbnailGenerator.IsDrawingThumbnail)
{
for (int i = 0; i < 30; ++i)
{
letters.Add(new Letter { Pos = new Vector2(Utils.RandomBetween(0.2f, 1), Utils.RandomBetween(0, 1)) });
}
}
}
// This is called in response to a KeyDown event being received on
// the UI thread (see KeyDown_UIThread). It is invoked via
// RunOnGameLoopThreadAsync.
public void ProcessPressedLetterOnGameLoopThread(char pressedLetter)
{
foreach (var letter in letters)
{
if (!letter.IsDead && letter.Value == pressedLetter)
{
letter.Die();
++score;
if (score % 10 == 0)
{
// level up!
framesBetweenNewLetters = Math.Max(10, framesBetweenNewLetters * 5 / 6);
verticalRegion = Math.Min(0.8f, verticalRegion + 0.01f);
leveledUpTimer = 0;
}
break;
}
}
}
public void Update()
{
if (ThumbnailGenerator.IsDrawingThumbnail)
return;
++framesSinceLastNewLetter;
if (!gameOver && framesSinceLastNewLetter > framesBetweenNewLetters)
{
letters.Add(new Letter());
framesSinceLastNewLetter = 0;
}
foreach (var letter in letters)
{
letter.Update();
if (!letter.IsDead && letter.Pos.X < 0)
{
gameOver = true;
}
}
letters.RemoveAll(l => l.ShouldRemove);
if (gameOver)
{
foreach (var letter in letters)
{
if (!letter.IsDead)
{
letter.Die();
}
}
if (letters.Count == 0)
{
highScore = Math.Max(highScore, score);
ResetLevel();
}
}
++leveledUpTimer;
}
void ResetLevel()
{
letters.Clear();
leveledUpTimer = 1000;
framesSinceLastNewLetter = initialFramesBetweenNewLetters;
framesBetweenNewLetters = initialFramesBetweenNewLetters;
verticalRegion = initialVerticalRegion;
score = 0;
gameOver = false;
}
public void Draw(CanvasDrawingSession ds, Size screenSize)
{
var transform = CalculateGameToScreenTransform(screenSize);
DrawBackground(ds, transform);
foreach (var letter in letters)
{
letter.Draw(ds, transform);
}
ds.Transform = Matrix3x2.Identity;
if (!ThumbnailGenerator.IsDrawingThumbnail)
{
string scoreText = string.Format("Score: {0}", score);
if (highScore != -1)
{
scoreText += string.Format(" ({0})", highScore);
}
ds.DrawText(scoreText, 0, 0, Colors.White, scoreFormat);
}
}
private Matrix3x2 CalculateGameToScreenTransform(Size screenSize)
{
var scaleToScreen = Matrix3x2.CreateScale(screenSize.ToVector2());
var scaleVerticalRegion = Matrix3x2.CreateScale(1, verticalRegion);
var offsetVerticalRegion = Matrix3x2.CreateTranslation(0, 0.5f - (verticalRegion / 2.0f));
var transform = scaleVerticalRegion * offsetVerticalRegion * scaleToScreen;
return transform;
}
private void DrawBackground(CanvasDrawingSession ds, Matrix3x2 transform)
{
const int levelUpTime = 60;
// After levelling up we flash the screen white for a bit
Color normalColor = Colors.Blue;
Color levelUpFlashColor = Colors.White;
var flashAmount = Math.Min(1, (leveledUpTimer / (float)levelUpTime));
ds.Clear(InterpolateColors(normalColor, levelUpFlashColor, flashAmount));
var topLeft = Vector2.Transform(new Vector2(0, 0), transform);
var bottomRight = Vector2.Transform(new Vector2(1, 1), transform);
var middle = (bottomRight.X - topLeft.X) / 2 + topLeft.X;
// and display some text to let the player know what happened
if (leveledUpTimer < levelUpTime * 2)
{
ds.DrawText("Level Up!", middle, 0, Colors.White, levelUpFormat);
}
// Draw some lines to show where the top / bottom of the play area is.
var topLine = topLeft.Y - Letter.TextFormat.FontSize;
var bottomLine = bottomRight.Y + Letter.TextFormat.FontSize;
Color lineColor = levelUpFlashColor;
lineColor.A = 128;
ds.DrawLine(0, topLine, bottomRight.X, topLine, lineColor, 3);
ds.DrawLine(0, bottomLine, bottomRight.X, bottomLine, lineColor, 3);
}
private static Color InterpolateColors(Color color1, Color color2, float a)
{
var b = 1 - a;
return Color.FromArgb(
255,
(byte)(color1.R * a + color2.R * b),
(byte)(color1.G * a + color2.G * b),
(byte)(color1.B * a + color2.B * b));
}
}
// Repesents a single letter on the screen
class Letter
{
static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rng = new Random();
const float moveSpeed = 0.002f;
const int deathFrames = 30;
int deathTimer = 0;
public char Value { get; private set; }
public Vector2 Pos { get; set; } // position is normalized 0-1
public bool IsDead { get { return deathTimer > 0; } }
public bool ShouldRemove { get { return deathTimer > deathFrames; } }
public float DeadMu { get { return Math.Min(1.0f, (float)deathTimer / (float)deathFrames); } }
public static CanvasTextFormat TextFormat = new CanvasTextFormat
{
FontSize = 36,
HorizontalAlignment = CanvasHorizontalAlignment.Center,
VerticalAlignment = CanvasVerticalAlignment.Center
};
public Letter()
{
Value = chars[rng.Next(0, chars.Length)];
Pos = new Vector2(1, (float)rng.NextDouble());
deathTimer = 0;
}
public void Update()
{
if (deathTimer == 0)
{
Pos = new Vector2(Pos.X - moveSpeed, Pos.Y);
}
else
{
deathTimer++;
}
}
public void Draw(CanvasDrawingSession ds, Matrix3x2 transform)
{
var pos = Vector2.Transform(Pos, transform);
var mu = (float)Math.Sin(DeadMu * Math.PI * 0.5);
var scale = Matrix3x2.CreateScale(1.0f + mu * 10.0f);
var center = new Vector2(pos.X, pos.Y);
ds.Transform = Matrix3x2.CreateTranslation(-center) * scale * Matrix3x2.CreateTranslation(center);
Color c = Color.FromArgb((byte)((1.0f - mu) * 255.0f), 255, 255, 255);
ds.DrawText(Value.ToString(), pos, c, TextFormat);
}
public void Die()
{
if (deathTimer == 0)
deathTimer = 1;
}
}
}
}
| |
using System;
namespace Renci.SshNet.Security.Org.BouncyCastle.Crypto.Utilities
{
internal sealed class Pack
{
private Pack()
{
}
internal static void UInt16_To_BE(ushort n, byte[] bs)
{
bs[0] = (byte)(n >> 8);
bs[1] = (byte)(n);
}
internal static void UInt16_To_BE(ushort n, byte[] bs, int off)
{
bs[off] = (byte)(n >> 8);
bs[off + 1] = (byte)(n);
}
internal static ushort BE_To_UInt16(byte[] bs)
{
uint n = (uint)bs[0] << 8
| (uint)bs[1];
return (ushort)n;
}
internal static ushort BE_To_UInt16(byte[] bs, int off)
{
uint n = (uint)bs[off] << 8
| (uint)bs[off + 1];
return (ushort)n;
}
internal static byte[] UInt32_To_BE(uint n)
{
byte[] bs = new byte[4];
UInt32_To_BE(n, bs, 0);
return bs;
}
internal static void UInt32_To_BE(uint n, byte[] bs)
{
bs[0] = (byte)(n >> 24);
bs[1] = (byte)(n >> 16);
bs[2] = (byte)(n >> 8);
bs[3] = (byte)(n);
}
internal static void UInt32_To_BE(uint n, byte[] bs, int off)
{
bs[off] = (byte)(n >> 24);
bs[off + 1] = (byte)(n >> 16);
bs[off + 2] = (byte)(n >> 8);
bs[off + 3] = (byte)(n);
}
internal static byte[] UInt32_To_BE(uint[] ns)
{
byte[] bs = new byte[4 * ns.Length];
UInt32_To_BE(ns, bs, 0);
return bs;
}
internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off)
{
for (int i = 0; i < ns.Length; ++i)
{
UInt32_To_BE(ns[i], bs, off);
off += 4;
}
}
internal static uint BE_To_UInt32(byte[] bs)
{
return (uint)bs[0] << 24
| (uint)bs[1] << 16
| (uint)bs[2] << 8
| (uint)bs[3];
}
internal static uint BE_To_UInt32(byte[] bs, int off)
{
return (uint)bs[off] << 24
| (uint)bs[off + 1] << 16
| (uint)bs[off + 2] << 8
| (uint)bs[off + 3];
}
internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns)
{
for (int i = 0; i < ns.Length; ++i)
{
ns[i] = BE_To_UInt32(bs, off);
off += 4;
}
}
internal static byte[] UInt64_To_BE(ulong n)
{
byte[] bs = new byte[8];
UInt64_To_BE(n, bs, 0);
return bs;
}
internal static void UInt64_To_BE(ulong n, byte[] bs)
{
UInt32_To_BE((uint)(n >> 32), bs);
UInt32_To_BE((uint)(n), bs, 4);
}
internal static void UInt64_To_BE(ulong n, byte[] bs, int off)
{
UInt32_To_BE((uint)(n >> 32), bs, off);
UInt32_To_BE((uint)(n), bs, off + 4);
}
internal static byte[] UInt64_To_BE(ulong[] ns)
{
byte[] bs = new byte[8 * ns.Length];
UInt64_To_BE(ns, bs, 0);
return bs;
}
internal static void UInt64_To_BE(ulong[] ns, byte[] bs, int off)
{
for (int i = 0; i < ns.Length; ++i)
{
UInt64_To_BE(ns[i], bs, off);
off += 8;
}
}
internal static ulong BE_To_UInt64(byte[] bs)
{
uint hi = BE_To_UInt32(bs);
uint lo = BE_To_UInt32(bs, 4);
return ((ulong)hi << 32) | (ulong)lo;
}
internal static ulong BE_To_UInt64(byte[] bs, int off)
{
uint hi = BE_To_UInt32(bs, off);
uint lo = BE_To_UInt32(bs, off + 4);
return ((ulong)hi << 32) | (ulong)lo;
}
internal static void BE_To_UInt64(byte[] bs, int off, ulong[] ns)
{
for (int i = 0; i < ns.Length; ++i)
{
ns[i] = BE_To_UInt64(bs, off);
off += 8;
}
}
internal static void UInt16_To_LE(ushort n, byte[] bs)
{
bs[0] = (byte)(n);
bs[1] = (byte)(n >> 8);
}
internal static void UInt16_To_LE(ushort n, byte[] bs, int off)
{
bs[off] = (byte)(n);
bs[off + 1] = (byte)(n >> 8);
}
internal static ushort LE_To_UInt16(byte[] bs)
{
uint n = (uint)bs[0]
| (uint)bs[1] << 8;
return (ushort)n;
}
internal static ushort LE_To_UInt16(byte[] bs, int off)
{
uint n = (uint)bs[off]
| (uint)bs[off + 1] << 8;
return (ushort)n;
}
internal static byte[] UInt32_To_LE(uint n)
{
byte[] bs = new byte[4];
UInt32_To_LE(n, bs, 0);
return bs;
}
internal static void UInt32_To_LE(uint n, byte[] bs)
{
bs[0] = (byte)(n);
bs[1] = (byte)(n >> 8);
bs[2] = (byte)(n >> 16);
bs[3] = (byte)(n >> 24);
}
internal static void UInt32_To_LE(uint n, byte[] bs, int off)
{
bs[off] = (byte)(n);
bs[off + 1] = (byte)(n >> 8);
bs[off + 2] = (byte)(n >> 16);
bs[off + 3] = (byte)(n >> 24);
}
internal static byte[] UInt32_To_LE(uint[] ns)
{
byte[] bs = new byte[4 * ns.Length];
UInt32_To_LE(ns, bs, 0);
return bs;
}
internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off)
{
for (int i = 0; i < ns.Length; ++i)
{
UInt32_To_LE(ns[i], bs, off);
off += 4;
}
}
internal static uint LE_To_UInt32(byte[] bs)
{
return (uint)bs[0]
| (uint)bs[1] << 8
| (uint)bs[2] << 16
| (uint)bs[3] << 24;
}
internal static uint LE_To_UInt32(byte[] bs, int off)
{
return (uint)bs[off]
| (uint)bs[off + 1] << 8
| (uint)bs[off + 2] << 16
| (uint)bs[off + 3] << 24;
}
internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns)
{
for (int i = 0; i < ns.Length; ++i)
{
ns[i] = LE_To_UInt32(bs, off);
off += 4;
}
}
internal static void LE_To_UInt32(byte[] bs, int bOff, uint[] ns, int nOff, int count)
{
for (int i = 0; i < count; ++i)
{
ns[nOff + i] = LE_To_UInt32(bs, bOff);
bOff += 4;
}
}
internal static uint[] LE_To_UInt32(byte[] bs, int off, int count)
{
uint[] ns = new uint[count];
for (int i = 0; i < ns.Length; ++i)
{
ns[i] = LE_To_UInt32(bs, off);
off += 4;
}
return ns;
}
internal static byte[] UInt64_To_LE(ulong n)
{
byte[] bs = new byte[8];
UInt64_To_LE(n, bs, 0);
return bs;
}
internal static void UInt64_To_LE(ulong n, byte[] bs)
{
UInt32_To_LE((uint)(n), bs);
UInt32_To_LE((uint)(n >> 32), bs, 4);
}
internal static void UInt64_To_LE(ulong n, byte[] bs, int off)
{
UInt32_To_LE((uint)(n), bs, off);
UInt32_To_LE((uint)(n >> 32), bs, off + 4);
}
internal static byte[] UInt64_To_LE(ulong[] ns)
{
byte[] bs = new byte[8 * ns.Length];
UInt64_To_LE(ns, bs, 0);
return bs;
}
internal static void UInt64_To_LE(ulong[] ns, byte[] bs, int off)
{
for (int i = 0; i < ns.Length; ++i)
{
UInt64_To_LE(ns[i], bs, off);
off += 8;
}
}
internal static void UInt64_To_LE(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff)
{
for (int i = 0; i < nsLen; ++i)
{
UInt64_To_LE(ns[nsOff + i], bs, bsOff);
bsOff += 8;
}
}
internal static ulong LE_To_UInt64(byte[] bs)
{
uint lo = LE_To_UInt32(bs);
uint hi = LE_To_UInt32(bs, 4);
return ((ulong)hi << 32) | (ulong)lo;
}
internal static ulong LE_To_UInt64(byte[] bs, int off)
{
uint lo = LE_To_UInt32(bs, off);
uint hi = LE_To_UInt32(bs, off + 4);
return ((ulong)hi << 32) | (ulong)lo;
}
internal static void LE_To_UInt64(byte[] bs, int off, ulong[] ns)
{
for (int i = 0; i < ns.Length; ++i)
{
ns[i] = LE_To_UInt64(bs, off);
off += 8;
}
}
internal static void LE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, int nsLen)
{
for (int i = 0; i < nsLen; ++i)
{
ns[nsOff + i] = LE_To_UInt64(bs, bsOff);
bsOff += 8;
}
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Reserved instances
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class ReservedInstances
{
private string reservedInstancesIdField;
private string instanceTypeField;
private string availabilityZoneField;
private Decimal? durationField;
private string usagePriceField;
private string fixedPriceField;
private Decimal? instanceCountField;
private string productDescriptionField;
private string purchaseStateField;
private string startTimeField;
private List<Tag> tagField;
private string instanceTenancyField;
private string currencyCodeField;
private string offeringTypeField;
private List<RecurringCharges> recurringChargesField;
/// <summary>
/// The ID of the Reserved Instances.
/// </summary>
[XmlElementAttribute(ElementName = "ReservedInstancesId")]
public string ReservedInstancesId
{
get { return this.reservedInstancesIdField; }
set { this.reservedInstancesIdField = value; }
}
/// <summary>
/// Sets the ID of the Reserved Instances.
/// </summary>
/// <param name="reservedInstancesId">The ID of the Reserved Instances.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithReservedInstancesId(string reservedInstancesId)
{
this.reservedInstancesIdField = reservedInstancesId;
return this;
}
/// <summary>
/// Checks if ReservedInstancesId property is set
/// </summary>
/// <returns>true if ReservedInstancesId property is set</returns>
public bool IsSetReservedInstancesId()
{
return this.reservedInstancesIdField != null;
}
/// <summary>
/// The instance type on which the Reserved Instance can be used.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceType")]
public string InstanceType
{
get { return this.instanceTypeField; }
set { this.instanceTypeField = value; }
}
/// <summary>
/// Sets the instance type on which the Reserved Instance can be used.
/// </summary>
/// <param name="instanceType">The instance type on which the Reserved
/// Instance can be used.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithInstanceType(string instanceType)
{
this.instanceTypeField = instanceType;
return this;
}
/// <summary>
/// Checks if InstanceType property is set
/// </summary>
/// <returns>true if InstanceType property is set</returns>
public bool IsSetInstanceType()
{
return this.instanceTypeField != null;
}
/// <summary>
/// The Availability Zone in which the Reserved Instance can be used.
/// </summary>
[XmlElementAttribute(ElementName = "AvailabilityZone")]
public string AvailabilityZone
{
get { return this.availabilityZoneField; }
set { this.availabilityZoneField = value; }
}
/// <summary>
/// Sets the Availability Zone in which the Reserved Instance can be used.
/// </summary>
/// <param name="availabilityZone">The Availability Zone in which the Reserved
/// Instance can be used.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithAvailabilityZone(string availabilityZone)
{
this.availabilityZoneField = availabilityZone;
return this;
}
/// <summary>
/// Checks if AvailabilityZone property is set
/// </summary>
/// <returns>true if AvailabilityZone property is set</returns>
public bool IsSetAvailabilityZone()
{
return this.availabilityZoneField != null;
}
/// <summary>
/// The duration of the Reserved Instance, in seconds.
/// </summary>
[XmlElementAttribute(ElementName = "Duration")]
public Decimal Duration
{
get { return this.durationField.GetValueOrDefault(); }
set { this.durationField = value; }
}
/// <summary>
/// Sets the duration of the Reserved Instance, in seconds.
/// </summary>
/// <param name="duration">The duration of the Reserved Instance, in
/// seconds.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithDuration(Decimal duration)
{
this.durationField = duration;
return this;
}
/// <summary>
/// Checks if Duration property is set
/// </summary>
/// <returns>true if Duration property is set</returns>
public bool IsSetDuration()
{
return this.durationField.HasValue;
}
/// <summary>
/// The usage price of the Reserved Instance, per hour.
/// </summary>
[XmlElementAttribute(ElementName = "UsagePrice")]
public string UsagePrice
{
get { return this.usagePriceField; }
set { this.usagePriceField = value; }
}
/// <summary>
/// Sets the usage price of the Reserved Instance, per hour.
/// </summary>
/// <param name="usagePrice">The usage price of the Reserved Instance, per
/// hour.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithUsagePrice(string usagePrice)
{
this.usagePriceField = usagePrice;
return this;
}
/// <summary>
/// Checks if UsagePrice property is set
/// </summary>
/// <returns>true if UsagePrice property is set</returns>
public bool IsSetUsagePrice()
{
return this.usagePriceField != null;
}
/// <summary>
/// The purchase price of the Reserved Instance.
/// </summary>
[XmlElementAttribute(ElementName = "FixedPrice")]
public string FixedPrice
{
get { return this.fixedPriceField; }
set { this.fixedPriceField = value; }
}
/// <summary>
/// Sets the purchase price of the Reserved Instance.
/// </summary>
/// <param name="fixedPrice">The purchase price of the Reserved Instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithFixedPrice(string fixedPrice)
{
this.fixedPriceField = fixedPrice;
return this;
}
/// <summary>
/// Checks if FixedPrice property is set
/// </summary>
/// <returns>true if FixedPrice property is set</returns>
public bool IsSetFixedPrice()
{
return this.fixedPriceField != null;
}
/// <summary>
/// The number of Reserved Instances purchased.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceCount")]
public Decimal InstanceCount
{
get { return this.instanceCountField.GetValueOrDefault(); }
set { this.instanceCountField = value; }
}
/// <summary>
/// Sets the number of Reserved Instances purchased.
/// </summary>
/// <param name="instanceCount">The number of Reserved Instances purchased.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithInstanceCount(Decimal instanceCount)
{
this.instanceCountField = instanceCount;
return this;
}
/// <summary>
/// Checks if InstanceCount property is set
/// </summary>
/// <returns>true if InstanceCount property is set</returns>
public bool IsSetInstanceCount()
{
return this.instanceCountField.HasValue;
}
/// <summary>
/// The Reserved Instance description.
/// </summary>
[XmlElementAttribute(ElementName = "ProductDescription")]
public string ProductDescription
{
get { return this.productDescriptionField; }
set { this.productDescriptionField = value; }
}
/// <summary>
/// Sets the Reserved Instance description.
/// </summary>
/// <param name="productDescription">The Reserved Instance description.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithProductDescription(string productDescription)
{
this.productDescriptionField = productDescription;
return this;
}
/// <summary>
/// Checks if ProductDescription property is set
/// </summary>
/// <returns>true if ProductDescription property is set</returns>
public bool IsSetProductDescription()
{
return this.productDescriptionField != null;
}
/// <summary>
/// The state of the Reserved Instance purchase.
/// Valid Values: pending-payment | active | payment-failed | retired
/// </summary>
[XmlElementAttribute(ElementName = "PurchaseState")]
public string PurchaseState
{
get { return this.purchaseStateField; }
set { this.purchaseStateField = value; }
}
/// <summary>
/// Sets the state of the Reserved Instance purchase.
/// </summary>
/// <param name="purchaseState">The state of the Reserved Instance purchase.
/// Valid Values:
/// pending-payment | active | payment-failed | retired</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithPurchaseState(string purchaseState)
{
this.purchaseStateField = purchaseState;
return this;
}
/// <summary>
/// Checks if PurchaseState property is set
/// </summary>
/// <returns>true if PurchaseState property is set</returns>
public bool IsSetPurchaseState()
{
return this.purchaseStateField != null;
}
/// <summary>
/// The date and time the Reserved Instance started.
/// </summary>
[XmlElementAttribute(ElementName = "StartTime")]
public string StartTime
{
get { return this.startTimeField; }
set { this.startTimeField = value; }
}
/// <summary>
/// Sets the date and time the Reserved Instance started.
/// </summary>
/// <param name="startTime">The date and time the Reserved Instance
/// started.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithStartTime(string startTime)
{
this.startTimeField = startTime;
return this;
}
/// <summary>
/// Checks if StartTime property is set
/// </summary>
/// <returns>true if StartTime property is set</returns>
public bool IsSetStartTime()
{
return this.startTimeField != null;
}
/// <summary>
/// A list of tags for the ReservedInstances.
/// </summary>
[XmlElementAttribute(ElementName = "Tag")]
public List<Tag> Tag
{
get
{
if (this.tagField == null)
{
this.tagField = new List<Tag>();
}
return this.tagField;
}
set { this.tagField = value; }
}
/// <summary>
/// Sets the list of tags for the ReservedInstances.
/// </summary>
/// <param name="list">A list of tags for the ReservedInstances.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithTag(params Tag[] list)
{
foreach (Tag item in list)
{
Tag.Add(item);
}
return this;
}
/// <summary>
/// Checks if Tag property is set
/// </summary>
/// <returns>true if Tag property is set</returns>
public bool IsSetTag()
{
return (Tag.Count > 0);
}
/// <summary>
/// The Reserved Instance Offering type.
/// </summary>
[XmlElementAttribute(ElementName = "OfferingType")]
public string OfferingType
{
get { return this.offeringTypeField; }
set { this.offeringTypeField = value; }
}
/// <summary>
/// Sets the Reserved Instance Offering type.
/// </summary>
/// <returns>true if OfferingType property is set</returns>
public bool IsSetOfferingType()
{
return this.offeringTypeField != null;
}
/// <summary>
/// Sets the OfferingType property
/// </summary>
/// <param name="offeringType">The Reserved Instance Offering type</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithOfferingType(string offeringType)
{
this.offeringTypeField = offeringType;
return this;
}
/// <summary>
/// Zero or more recurring charges associated with the Reserved Instance.
/// </summary>
[XmlElementAttribute(ElementName = "RecurringCharges")]
public List<RecurringCharges> RecurringCharges
{
get
{
if (this.recurringChargesField == null)
{
this.recurringChargesField = new List<RecurringCharges>();
}
return this.recurringChargesField;
}
set { this.recurringChargesField = value; }
}
/// <summary>
/// Checks if RecurringCharges property is set
/// </summary>
/// <returns>true if RecurringCharges property is set</returns>
public bool IsSetRecurringCharges()
{
return (RecurringCharges.Count > 0);
}
/// <summary>
/// The tenancy of the reserved instance.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceTenancy")]
public string InstanceTenancy
{
get { return this.instanceTenancyField; }
set { this.instanceTenancyField = value; }
}
/// <summary>
/// Checks if InstanceTenancy property is set
/// </summary>
/// <returns>true if InstanceTenancy property is set</returns>
public bool IsSetInstanceTenancy()
{
return this.instanceTenancyField != null;
}
/// <summary>
/// Sets the tenancy of the reserved instance.
/// </summary>
/// <param name="instanceTenancy">The tenancy of the reserved instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithInstanceTenancy(string instanceTenancy)
{
this.instanceTenancyField = instanceTenancy;
return this;
}
/// <summary>
/// The currency of the Reserved Instance offering you are purchasing.
/// It's specified using ISO 4217 standard (e.g., USD, JPY).
/// </summary>
[XmlElementAttribute(ElementName = "CurrencyCode")]
public string CurrencyCode
{
get { return this.currencyCodeField; }
set { this.currencyCodeField = value; }
}
/// <summary>
/// Checks if CurrencyCode property is set
/// </summary>
/// <returns>true if InstanceTenancy property is set</returns>
public bool IsSetCurrencyCode()
{
return this.currencyCodeField != null;
}
/// <summary>
/// Sets the currency of the Reserved Instance offering you are purchasing.
/// </summary>
/// <param name="currencyCode">The ISO 4217 CurrencyCode (e.g., USD, JPY).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ReservedInstances WithCurrencyCode(string currencyCode)
{
this.currencyCodeField = currencyCode;
return this;
}
}
}
| |
public partial class Loop2000ACollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new HL(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "InformationSourceLevel",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"20")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2100ACollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 1;
SegmentDefinitions.Add(new NM1(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "PayerName",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"PR")},
SyntaxRules = new List<string>(){ "P0809","C1110","C1203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2000BCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new HL(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "InformationReceiverLevel",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"21")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2100BCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 1;
SegmentDefinitions.Add(new NM1(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "InformationReceiverName",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"41")},
SyntaxRules = new List<string>(){ "P0809","C1110","C1203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2000CCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new HL(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ServiceProviderLevel",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"19")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2100CCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 2;
SegmentDefinitions.Add(new NM1(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ProviderName",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"1P")},
SyntaxRules = new List<string>(){ "P0809","C1110","C1203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2000DCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new HL(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "SubscriberLevel",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"22")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
SegmentDefinitions.Add(new DMG(){
OwningLoopCollection = this,
SegmentDefinitionName = "SubscriberDemographicInformation",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"D8")},
SyntaxRules = new List<string>(){ "P0102","P1011","C1105" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
}
}
public partial class Loop2100DCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 1;
SegmentDefinitions.Add(new NM1(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "SubscriberName",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"IL")},
SyntaxRules = new List<string>(){ "P0809","C1110","C1203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2200DCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new TRN(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ClaimStatusTrackingNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"1")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PayerClaimControlNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"1K")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "InstitutionalBillTypeIdentification",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"BLT")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ApplicationOrLocationSystemIdentifier",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"LU")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "GroupNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"6P")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PatientControlNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"EJ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PharmacyPrescriptionNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"XZ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimIdentificationNumberForClearinghousesAnd",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"D9")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new AMT(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimSubmittedCharges",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"T3")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new DTP(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimServiceDate",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"472")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
}
}
public partial class Loop2210DCollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new SVC(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ServiceLineInformation",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"AD","ER","HC","HP","IV","N4","NU","WK")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ServiceLineItemIdentification",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"FJ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new DTP(){
OwningLoopCollection = this,
SegmentDefinitionName = "ServiceLineDate",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"472")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2000ECollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new HL(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "DependentLevel",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"23")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new DMG(){
OwningLoopCollection = this,
SegmentDefinitionName = "DependentDemographicInformation",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"D8")},
SyntaxRules = new List<string>(){ "P0102","P1011","C1105" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2100ECollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 1;
SegmentDefinitions.Add(new NM1(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "DependentName",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"QC")},
SyntaxRules = new List<string>(){ "P0809","C1110","C1203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
public partial class Loop2200ECollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new TRN(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ClaimStatusTrackingNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"1")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PayerClaimControlNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"1K")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "InstitutionalBillTypeIdentification",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"BLT")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ApplicationOrLocationSystemIdentifier",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"LU")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "GroupNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"6P")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PatientControlNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"EJ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "PharmacyPrescriptionNumber",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"XZ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimIdentificationNumberForClearinghousesAnd",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"D9")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new AMT(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimSubmittedCharges",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"T3")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new DTP(){
OwningLoopCollection = this,
SegmentDefinitionName = "ClaimServiceDate",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"472")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
}
}
public partial class Loop2210ECollection
{
public override void SetUpDefinition(){
SetUpChildDefinitions=true;
RepitionLimit = 999;
SegmentDefinitions.Add(new SVC(){
OwningLoopCollection = this,
IsLoopStarter=true,
SegmentDefinitionName = "ServiceLineInformation",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"AD","ER","HC","HP","IV","N4","NU","WK")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Optional,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new REF(){
OwningLoopCollection = this,
SegmentDefinitionName = "ServiceLineItemIdentification",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"FJ")},
SyntaxRules = new List<string>(){ "R0203" },
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.UnUsed,
FieldUsageTypeNames.UnUsed,
},
SegmentUsage = SegmentUsageTypeNames.Optional
});
SegmentDefinitions.Add(new DTP(){
OwningLoopCollection = this,
SegmentDefinitionName = "ServiceLineDate",
SegmentQualifierValues = new List<SegmentQualifiers>(){ new SegmentQualifiers(1,"472")},
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
SegmentDefinitions.Add(new TABLE(){
OwningLoopCollection = this,
SegmentDefinitionName = "TransactionSetTrailer",
FieldUsage = new List<FieldUsageTypeNames>(){
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
FieldUsageTypeNames.Mandatory,
},
SegmentUsage = SegmentUsageTypeNames.Required
});
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 452570 $
* $Date: 2006-10-03 19:00:01 +0200 (mar., 03 oct. 2006) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* 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.Collections;
using System.IO;
using System.Threading;
using IBatisNet.Common.Logging;
namespace IBatisNet.Common.Utilities
{
/// <summary>
/// Represents the method that handles calls from Configure.
/// </summary>
/// <remarks>
/// obj is a null object in a DaoManager context.
/// obj is the reconfigured sqlMap in a SqlMap context.
/// </remarks>
public delegate void ConfigureHandler(object obj);
/// <summary>
///
/// </summary>
public struct StateConfig
{
/// <summary>
/// Master Config File name.
/// </summary>
public string FileName;
/// <summary>
/// Delegate called when a file is changed, use it to rebuild.
/// </summary>
public ConfigureHandler ConfigureHandler;
}
/// <summary>
/// Class used to watch config files.
/// </summary>
/// <remarks>
/// Uses the <see cref="FileSystemWatcher"/> to monitor
/// changes to a specified file. Because multiple change notifications
/// may be raised when the file is modified, a timer is used to
/// compress the notifications into a single event. The timer
/// waits for the specified time before delivering
/// the event notification. If any further <see cref="FileSystemWatcher"/>
/// change notifications arrive while the timer is waiting it
/// is reset and waits again for the specified time to
/// elapse.
/// </remarks>
public sealed class ConfigWatcherHandler
{
#region Fields
private static readonly ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The timer used to compress the notification events.
/// </summary>
private Timer _timer = null;
/// <summary>
/// A list of configuration files to watch.
/// </summary>
private static ArrayList _filesToWatch = new ArrayList();
/// <summary>
/// The list of FileSystemWatcher.
/// </summary>
private static ArrayList _filesWatcher = new ArrayList();
/// <summary>
/// The default amount of time to wait after receiving notification
/// before reloading the config file.
/// </summary>
private const int TIMEOUT_MILLISECONDS = 500;
#endregion
#region Constructor (s) / Destructor
/// <summary>
///-
/// </summary>
/// <param name="state">
/// Represent the call context of the SqlMap or DaoManager ConfigureAndWatch method call.
/// </param>
/// <param name="onWhatchedFileChange"></param>
public ConfigWatcherHandler(TimerCallback onWhatchedFileChange, StateConfig state)
{
for (int index = 0; index < _filesToWatch.Count; index++)
{
FileInfo configFile = (FileInfo)_filesToWatch[index];
AttachWatcher(configFile);
// Create the timer that will be used to deliver events. Set as disabled
// callback : A TimerCallback delegate representing a method to be executed.
// state : An object containing information to be used by the callback method, or a null reference
// dueTime : The amount of time to delay before callback is invoked, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately
// period : The time interval between invocations of callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling
_timer = new Timer(onWhatchedFileChange, state, Timeout.Infinite, Timeout.Infinite);
}
}
#endregion
#region Methods
private void AttachWatcher(FileInfo configFile)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = configFile.DirectoryName;
watcher.Filter = configFile.Name;
// Set the notification filters
watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
watcher.Changed += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged);
watcher.Created += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged);
watcher.Deleted += new FileSystemEventHandler(ConfigWatcherHandler_OnChanged);
watcher.Renamed += new RenamedEventHandler(ConfigWatcherHandler_OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
_filesWatcher.Add(watcher);
}
/// <summary>
/// Add a file to be monitored.
/// </summary>
/// <param name="configFile"></param>
public static void AddFileToWatch(FileInfo configFile)
{
if (_logger.IsDebugEnabled)
{
// TODO: remove Path.GetFileName?
_logger.Debug("Adding file [" + Path.GetFileName(configFile.FullName) + "] to list of watched files.");
}
_filesToWatch.Add(configFile);
}
/// <summary>
/// Reset the list of files being monitored.
/// </summary>
public static void ClearFilesMonitored()
{
_filesToWatch.Clear();
// Kill all FileSystemWatcher
for (int index = 0; index < _filesWatcher.Count; index++)
{
FileSystemWatcher fileWatcher = (FileSystemWatcher)_filesWatcher[index];
fileWatcher.EnableRaisingEvents = false;
fileWatcher.Dispose();
}
}
/// <summary>
/// Event handler used by <see cref="ConfigWatcherHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// This handler reloads the configuration from the file when the event is fired.
/// </remarks>
private void ConfigWatcherHandler_OnChanged(object source, FileSystemEventArgs e)
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("ConfigWatcherHandler : " + e.ChangeType + " [" + e.Name + "]");
}
// timer will fire only once
_timer.Change(TIMEOUT_MILLISECONDS, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigWatcherHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// This handler reloads the configuration from the file when the event is fired.
/// </remarks>
private void ConfigWatcherHandler_OnRenamed(object source, RenamedEventArgs e)
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("ConfigWatcherHandler : " + e.ChangeType + " [" + e.OldName + "/" + e.Name + "]");
}
// timer will fire only once
_timer.Change(TIMEOUT_MILLISECONDS, Timeout.Infinite);
}
#endregion
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Tls
{
/// <summary>
/// TLS 1.0 DH key exchange.
/// </summary>
internal class TlsDHKeyExchange
: TlsKeyExchange
{
protected TlsClientContext context;
protected KeyExchangeAlgorithm keyExchange;
protected TlsSigner tlsSigner;
protected AsymmetricKeyParameter serverPublicKey = null;
protected DHPublicKeyParameters dhAgreeServerPublicKey = null;
protected TlsAgreementCredentials agreementCredentials;
protected DHPrivateKeyParameters dhAgreeClientPrivateKey = null;
internal TlsDHKeyExchange(TlsClientContext context, KeyExchangeAlgorithm keyExchange)
{
switch (keyExchange)
{
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DH_DSS:
this.tlsSigner = null;
break;
case KeyExchangeAlgorithm.DHE_RSA:
this.tlsSigner = new TlsRsaSigner();
break;
case KeyExchangeAlgorithm.DHE_DSS:
this.tlsSigner = new TlsDssSigner();
break;
default:
throw new ArgumentException("unsupported key exchange algorithm", "keyExchange");
}
this.context = context;
this.keyExchange = keyExchange;
}
public virtual void SkipServerCertificate()
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void ProcessServerCertificate(Certificate serverCertificate)
{
X509CertificateStructure x509Cert = serverCertificate.certs[0];
SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
try
{
this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
}
catch (Exception)
{
throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
}
if (tlsSigner == null)
{
try
{
this.dhAgreeServerPublicKey = ValidateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey);
}
catch (InvalidCastException)
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
}
else
{
if (!tlsSigner.IsValidPublicKey(this.serverPublicKey))
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
}
// TODO
/*
* Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
* signing algorithm for the certificate must be the same as the algorithm for the
* certificate key."
*/
}
public virtual void SkipServerKeyExchange()
{
// OK
}
public virtual void ProcessServerKeyExchange(Stream input)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void ValidateCertificateRequest(CertificateRequest certificateRequest)
{
ClientCertificateType[] types = certificateRequest.CertificateTypes;
foreach (ClientCertificateType type in types)
{
switch (type)
{
case ClientCertificateType.rsa_sign:
case ClientCertificateType.dss_sign:
case ClientCertificateType.rsa_fixed_dh:
case ClientCertificateType.dss_fixed_dh:
case ClientCertificateType.ecdsa_sign:
break;
default:
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
}
public virtual void SkipClientCredentials()
{
this.agreementCredentials = null;
}
public virtual void ProcessClientCredentials(TlsCredentials clientCredentials)
{
if (clientCredentials is TlsAgreementCredentials)
{
// TODO Validate client cert has matching parameters (see 'areCompatibleParameters')?
this.agreementCredentials = (TlsAgreementCredentials)clientCredentials;
}
else if (clientCredentials is TlsSignerCredentials)
{
// OK
}
else
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public virtual void GenerateClientKeyExchange(Stream output)
{
/*
* RFC 2246 7.4.7.2 If the client certificate already contains a suitable
* Diffie-Hellman key, then Yc is implicit and does not need to be sent again. In
* this case, the Client Key Exchange message will be sent, but will be empty.
*/
if (agreementCredentials != null)
{
TlsUtilities.WriteUint24(0, output);
}
else
{
GenerateEphemeralClientKeyExchange(dhAgreeServerPublicKey.Parameters, output);
}
}
public virtual byte[] GeneratePremasterSecret()
{
if (agreementCredentials != null)
{
return agreementCredentials.GenerateAgreement(dhAgreeServerPublicKey);
}
return CalculateDHBasicAgreement(dhAgreeServerPublicKey, dhAgreeClientPrivateKey);
}
protected virtual bool AreCompatibleParameters(DHParameters a, DHParameters b)
{
return a.P.Equals(b.P) && a.G.Equals(b.G);
}
protected virtual byte[] CalculateDHBasicAgreement(DHPublicKeyParameters publicKey,
DHPrivateKeyParameters privateKey)
{
DHBasicAgreement dhAgree = new DHBasicAgreement();
dhAgree.Init(dhAgreeClientPrivateKey);
BigInteger agreement = dhAgree.CalculateAgreement(dhAgreeServerPublicKey);
return BigIntegers.AsUnsignedByteArray(agreement);
}
protected virtual AsymmetricCipherKeyPair GenerateDHKeyPair(DHParameters dhParams)
{
DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator();
dhGen.Init(new DHKeyGenerationParameters(context.SecureRandom, dhParams));
return dhGen.GenerateKeyPair();
}
protected virtual void GenerateEphemeralClientKeyExchange(DHParameters dhParams, Stream output)
{
AsymmetricCipherKeyPair dhAgreeClientKeyPair = GenerateDHKeyPair(dhParams);
this.dhAgreeClientPrivateKey = (DHPrivateKeyParameters)dhAgreeClientKeyPair.Private;
BigInteger Yc = ((DHPublicKeyParameters)dhAgreeClientKeyPair.Public).Y;
byte[] keData = BigIntegers.AsUnsignedByteArray(Yc);
TlsUtilities.WriteUint24(keData.Length + 2, output);
TlsUtilities.WriteOpaque16(keData, output);
}
protected virtual DHPublicKeyParameters ValidateDHPublicKey(DHPublicKeyParameters key)
{
BigInteger Y = key.Y;
DHParameters parameters = key.Parameters;
BigInteger p = parameters.P;
BigInteger g = parameters.G;
if (!p.IsProbablePrime(2))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
if (g.CompareTo(BigInteger.Two) < 0 || g.CompareTo(p.Subtract(BigInteger.Two)) > 0)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
if (Y.CompareTo(BigInteger.Two) < 0 || Y.CompareTo(p.Subtract(BigInteger.One)) > 0)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
// TODO See RFC 2631 for more discussion of Diffie-Hellman validation
return key;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAuditingPolicyOperations _auditingPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Audit policy. Contains operations to: Create,
/// Retrieve and Update audit policy.
/// </summary>
public virtual IAuditingPolicyOperations AuditingPolicy
{
get { return this._auditingPolicy; }
}
private IDatabaseActivationOperations _databaseActivation;
/// <summary>
/// Represents all the operations for operating pertaining to
/// activation on Azure SQL Data Warehouse databases. Contains
/// operations to: Pause and Resume databases
/// </summary>
public virtual IDatabaseActivationOperations DatabaseActivation
{
get { return this._databaseActivation; }
}
private IDatabaseBackupOperations _databaseBackup;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// restore points. Contains operations to: List restore points.
/// </summary>
public virtual IDatabaseBackupOperations DatabaseBackup
{
get { return this._databaseBackup; }
}
private IDatabaseOperations _databases;
/// <summary>
/// Represents all the operations for operating on Azure SQL Databases.
/// Contains operations to: Create, Retrieve, Update, and Delete
/// databases, and also includes the ability to get the event logs for
/// a database.
/// </summary>
public virtual IDatabaseOperations Databases
{
get { return this._databases; }
}
private IDataMaskingOperations _dataMasking;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// data masking. Contains operations to: Create, Retrieve, Update,
/// and Delete data masking rules, as well as Create, Retreive and
/// Update data masking policy.
/// </summary>
public virtual IDataMaskingOperations DataMasking
{
get { return this._dataMasking; }
}
private IElasticPoolOperations _elasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Elastic Pools. Contains operations to: Create, Retrieve, Update,
/// and Delete.
/// </summary>
public virtual IElasticPoolOperations ElasticPools
{
get { return this._elasticPools; }
}
private IFirewallRuleOperations _firewallRules;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Server Firewall Rules. Contains operations to: Create, Retrieve,
/// Update, and Delete firewall rules.
/// </summary>
public virtual IFirewallRuleOperations FirewallRules
{
get { return this._firewallRules; }
}
private IRecommendedElasticPoolOperations _recommendedElasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL
/// Recommended Elastic Pools. Contains operations to: Retrieve.
/// </summary>
public virtual IRecommendedElasticPoolOperations RecommendedElasticPools
{
get { return this._recommendedElasticPools; }
}
private IRecommendedIndexOperations _recommendedIndexes;
/// <summary>
/// Represents all the operations for managing recommended indexes on
/// Azure SQL Databases. Contains operations to retrieve recommended
/// index and update state.
/// </summary>
public virtual IRecommendedIndexOperations RecommendedIndexes
{
get { return this._recommendedIndexes; }
}
private ISecureConnectionPolicyOperations _secureConnection;
/// <summary>
/// Represents all the operations for managing Azure SQL Database
/// secure connection. Contains operations to: Create, Retrieve and
/// Update secure connection policy .
/// </summary>
public virtual ISecureConnectionPolicyOperations SecureConnection
{
get { return this._secureConnection; }
}
private IServerOperations _servers;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Servers. Contains operations to: Create, Retrieve, Update, and
/// Delete servers.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
private IServerUpgradeOperations _serverUpgrades;
/// <summary>
/// Represents all the operations for Azure SQL Database Server Upgrade
/// </summary>
public virtual IServerUpgradeOperations ServerUpgrades
{
get { return this._serverUpgrades; }
}
private IServiceObjectiveOperations _serviceObjectives;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Service Objectives. Contains operations to: Retrieve service
/// objectives.
/// </summary>
public virtual IServiceObjectiveOperations ServiceObjectives
{
get { return this._serviceObjectives; }
}
private IServiceTierAdvisorOperations _serviceTierAdvisors;
/// <summary>
/// Represents all the operations for operating on service tier
/// advisors. Contains operations to: Retrieve.
/// </summary>
public virtual IServiceTierAdvisorOperations ServiceTierAdvisors
{
get { return this._serviceTierAdvisors; }
}
private ITransparentDataEncryptionOperations _transparentDataEncryption;
/// <summary>
/// Represents all the operations of Azure SQL Database Transparent
/// Data Encryption. Contains operations to: Retrieve, and Update
/// Transparent Data Encryption.
/// </summary>
public virtual ITransparentDataEncryptionOperations TransparentDataEncryption
{
get { return this._transparentDataEncryption; }
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
public SqlManagementClient()
: base()
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SqlManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SqlManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SqlManagementClient> client)
{
base.Clone(client);
if (client is SqlManagementClient)
{
SqlManagementClient clonedClient = ((SqlManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace QuantConnect.Securities.Option.StrategyMatcher
{
/// <summary>
/// Defines a lightweight structure representing a position in an option contract or underlying.
/// This type is heavily utilized by the options strategy matcher and is the parameter type of
/// option strategy definition predicates. Underlying quantities should be represented in lot sizes,
/// which is equal to the quantity of shares divided by the contract's multiplier and then rounded
/// down towards zero (truncate)
/// </summary>
public struct OptionPosition : IEquatable<OptionPosition>
{
/// <summary>
/// Gets a new <see cref="OptionPosition"/> with zero <see cref="Quantity"/>
/// </summary>
public static OptionPosition Empty(Symbol symbol)
=> new OptionPosition(symbol, 0);
/// <summary>
/// Determines whether or not this position has any quantity
/// </summary>
public bool HasQuantity => Quantity != 0;
/// <summary>
/// Determines whether or not this position is for the underlying symbol
/// </summary>
public bool IsUnderlying => !Symbol.HasUnderlying;
/// <summary>
/// Number of contracts held, can be positive or negative
/// </summary>
public int Quantity { get; }
/// <summary>
/// Option contract symbol
/// </summary>
public Symbol Symbol { get; }
/// <summary>
/// Gets the underlying symbol. If this position represents the underlying,
/// then this property is the same as the <see cref="Symbol"/> property
/// </summary>
public Symbol Underlying => IsUnderlying ? Symbol : Symbol.Underlying;
/// <summary>
/// Option contract expiration date
/// </summary>
public DateTime Expiration
{
get
{
if (Symbol.HasUnderlying)
{
return Symbol.ID.Date;
}
throw new InvalidOperationException($"{nameof(Expiration)} is not valid for underlying symbols: {Symbol}");
}
}
/// <summary>
/// Option contract strike price
/// </summary>
public decimal Strike
{
get
{
if (Symbol.HasUnderlying)
{
return Symbol.ID.StrikePrice;
}
throw new InvalidOperationException($"{nameof(Strike)} is not valid for underlying symbols: {Symbol}");
}
}
/// <summary>
/// Option contract right (put/call)
/// </summary>
public OptionRight Right
{
get
{
if (Symbol.HasUnderlying)
{
return Symbol.ID.OptionRight;
}
throw new InvalidOperationException($"{nameof(Right)} is not valid for underlying symbols: {Symbol}");
}
}
/// <summary>
/// Gets whether this position is short/long/none
/// </summary>
public PositionSide Side => (PositionSide) Math.Sign(Quantity);
/// <summary>
/// Initializes a new instance of the <see cref="OptionPosition"/> structure
/// </summary>
/// <param name="symbol">The option contract symbol</param>
/// <param name="quantity">The number of contracts held</param>
public OptionPosition(Symbol symbol, int quantity)
{
Symbol = symbol;
Quantity = quantity;
}
/// <summary>
/// Creates a new <see cref="OptionPosition"/> instance with negative <see cref="Quantity"/>
/// </summary>
public OptionPosition Negate()
{
return new OptionPosition(Symbol, -Quantity);
}
/// <summary>
/// Creates a new <see cref="OptionPosition"/> with this position's <see cref="Symbol"/>
/// and the provided <paramref name="quantity"/>
/// </summary>
public OptionPosition WithQuantity(int quantity)
{
return new OptionPosition(Symbol, quantity);
}
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
public bool Equals(OptionPosition other)
{
return Equals(Symbol, other.Symbol) && Quantity == other.Quantity;
}
/// <summary>Indicates whether this instance and a specified object are equal.</summary>
/// <param name="obj">The object to compare with the current instance. </param>
/// <returns>true if <paramref name="obj" /> and this instance are the same type and represent the same value; otherwise, false. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((OptionPosition) obj);
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
public override int GetHashCode()
{
unchecked
{
return ((Symbol != null ? Symbol.GetHashCode() : 0) * 397) ^ Quantity;
}
}
/// <summary>Returns the fully qualified type name of this instance.</summary>
/// <returns>The fully qualified type name.</returns>
public override string ToString()
{
var s = Quantity == 1 ? "" : "s";
if (Symbol.HasUnderlying)
{
return $"{Quantity} {Right.ToLower()}{s} on {Symbol.Underlying.Value} at ${Strike} expiring on {Expiration:yyyy-MM-dd}";
}
return $"{Quantity} share{s} of {Symbol.Value}";
}
/// <summary>
/// OptionPosition * Operator, will multiple quantity by given factor
/// </summary>
/// <param name="left">OptionPosition to operate on</param>
/// <param name="factor">Factor to multiply by</param>
/// <returns>Resulting OptionPosition</returns>
public static OptionPosition operator *(OptionPosition left, int factor)
{
return new OptionPosition(left.Symbol, factor * left.Quantity);
}
/// <summary>
/// OptionPosition * Operator, will multiple quantity by given factor
/// </summary>
/// <param name="right">OptionPosition to operate on</param>
/// <param name="factor">Factor to multiply by</param>
/// <returns>Resulting OptionPosition</returns>
public static OptionPosition operator *(int factor, OptionPosition right)
{
return new OptionPosition(right.Symbol, factor * right.Quantity);
}
/// <summary>
/// OptionPosition + Operator, will add quantities together if they are for the same symbol.
/// </summary>
/// <returns>Resulting OptionPosition</returns>
public static OptionPosition operator +(OptionPosition left, OptionPosition right)
{
if (!Equals(left.Symbol, right.Symbol))
{
if (left == default(OptionPosition))
{
return right;
}
if (right == default(OptionPosition))
{
return left;
}
throw new InvalidOperationException("Unable to add OptionPosition instances with different symbols");
}
return new OptionPosition(left.Symbol, left.Quantity + right.Quantity);
}
/// <summary>
/// OptionPosition - Operator, will subtract left - right quantities if they are for the same symbol.
/// </summary>
/// <returns>Resulting OptionPosition</returns>
public static OptionPosition operator -(OptionPosition left, OptionPosition right)
{
if (!Equals(left.Symbol, right.Symbol))
{
if (left == default(OptionPosition))
{
// 0 - right
return right.Negate();
}
if (right == default(OptionPosition))
{
// left - 0
return left;
}
throw new InvalidOperationException("Unable to subtract OptionPosition instances with different symbols");
}
return new OptionPosition(left.Symbol, left.Quantity - right.Quantity);
}
/// <summary>
/// Option Position == Operator
/// </summary>
/// <returns>True if they are the same</returns>
public static bool operator ==(OptionPosition left, OptionPosition right)
{
return Equals(left, right);
}
/// <summary>
/// Option Position != Operator
/// </summary>
/// <returns>True if they are not the same</returns>
public static bool operator !=(OptionPosition left, OptionPosition right)
{
return !Equals(left, right);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.