content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dms-2016-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DatabaseMigrationService.Model
{
/// <summary>
///
/// </summary>
public partial class DynamoDbSettings
{
private string _serviceAccessRoleArn;
/// <summary>
/// Gets and sets the property ServiceAccessRoleArn.
/// <para>
/// The Amazon Resource Name (ARN) used by the service access IAM role.
/// </para>
/// </summary>
public string ServiceAccessRoleArn
{
get { return this._serviceAccessRoleArn; }
set { this._serviceAccessRoleArn = value; }
}
// Check to see if ServiceAccessRoleArn property is set
internal bool IsSetServiceAccessRoleArn()
{
return this._serviceAccessRoleArn != null;
}
}
} | 29.642857 | 101 | 0.665663 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/DatabaseMigrationService/Generated/Model/DynamoDbSettings.cs | 1,660 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Diagnostics;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Math.Raw
{
internal abstract class Nat
{
private const ulong M = 0xFFFFFFFFUL;
public static uint Add(int len, uint[] x, uint[] y, uint[] z)
{
ulong c = 0;
for (int i = 0; i < len; ++i)
{
c += (ulong)x[i] + y[i];
z[i] = (uint)c;
c >>= 32;
}
return (uint)c;
}
public static uint Add33At(int len, uint x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 2));
ulong c = (ulong)z[zPos + 0] + x;
z[zPos + 0] = (uint)c;
c >>= 32;
c += (ulong)z[zPos + 1] + 1;
z[zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zPos + 2);
}
public static uint Add33At(int len, uint x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 2));
ulong c = (ulong)z[zOff + zPos] + x;
z[zOff + zPos] = (uint)c;
c >>= 32;
c += (ulong)z[zOff + zPos + 1] + 1;
z[zOff + zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 2);
}
public static uint Add33To(int len, uint x, uint[] z)
{
ulong c = (ulong)z[0] + x;
z[0] = (uint)c;
c >>= 32;
c += (ulong)z[1] + 1;
z[1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, 2);
}
public static uint Add33To(int len, uint x, uint[] z, int zOff)
{
ulong c = (ulong)z[zOff + 0] + x;
z[zOff + 0] = (uint)c;
c >>= 32;
c += (ulong)z[zOff + 1] + 1;
z[zOff + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, 2);
}
public static uint AddBothTo(int len, uint[] x, uint[] y, uint[] z)
{
ulong c = 0;
for (int i = 0; i < len; ++i)
{
c += (ulong)x[i] + y[i] + z[i];
z[i] = (uint)c;
c >>= 32;
}
return (uint)c;
}
public static uint AddBothTo(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff)
{
ulong c = 0;
for (int i = 0; i < len; ++i)
{
c += (ulong)x[xOff + i] + y[yOff + i] + z[zOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
return (uint)c;
}
public static uint AddDWordAt(int len, ulong x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 2));
ulong c = (ulong)z[zPos + 0] + (x & M);
z[zPos + 0] = (uint)c;
c >>= 32;
c += (ulong)z[zPos + 1] + (x >> 32);
z[zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zPos + 2);
}
public static uint AddDWordAt(int len, ulong x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 2));
ulong c = (ulong)z[zOff + zPos] + (x & M);
z[zOff + zPos] = (uint)c;
c >>= 32;
c += (ulong)z[zOff + zPos + 1] + (x >> 32);
z[zOff + zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 2);
}
public static uint AddDWordTo(int len, ulong x, uint[] z)
{
ulong c = (ulong)z[0] + (x & M);
z[0] = (uint)c;
c >>= 32;
c += (ulong)z[1] + (x >> 32);
z[1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, 2);
}
public static uint AddDWordTo(int len, ulong x, uint[] z, int zOff)
{
ulong c = (ulong)z[zOff + 0] + (x & M);
z[zOff + 0] = (uint)c;
c >>= 32;
c += (ulong)z[zOff + 1] + (x >> 32);
z[zOff + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, 2);
}
public static uint AddTo(int len, uint[] x, uint[] z)
{
ulong c = 0;
for (int i = 0; i < len; ++i)
{
c += (ulong)x[i] + z[i];
z[i] = (uint)c;
c >>= 32;
}
return (uint)c;
}
public static uint AddTo(int len, uint[] x, int xOff, uint[] z, int zOff)
{
ulong c = 0;
for (int i = 0; i < len; ++i)
{
c += (ulong)x[xOff + i] + z[zOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
return (uint)c;
}
public static uint AddWordAt(int len, uint x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 1));
ulong c = (ulong)x + z[zPos];
z[zPos] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zPos + 1);
}
public static uint AddWordAt(int len, uint x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 1));
ulong c = (ulong)x + z[zOff + zPos];
z[zOff + zPos] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 1);
}
public static uint AddWordTo(int len, uint x, uint[] z)
{
ulong c = (ulong)x + z[0];
z[0] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, 1);
}
public static uint AddWordTo(int len, uint x, uint[] z, int zOff)
{
ulong c = (ulong)x + z[zOff];
z[zOff] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zOff, 1);
}
public static void Copy(int len, uint[] x, uint[] z)
{
Array.Copy(x, 0, z, 0, len);
}
public static uint[] Copy(int len, uint[] x)
{
uint[] z = new uint[len];
Array.Copy(x, 0, z, 0, len);
return z;
}
public static uint[] Create(int len)
{
return new uint[len];
}
public static ulong[] Create64(int len)
{
return new ulong[len];
}
public static int Dec(int len, uint[] z)
{
for (int i = 0; i < len; ++i)
{
if (--z[i] != uint.MaxValue)
{
return 0;
}
}
return -1;
}
public static int Dec(int len, uint[] x, uint[] z)
{
int i = 0;
while (i < len)
{
uint c = x[i] - 1;
z[i] = c;
++i;
if (c != uint.MaxValue)
{
while (i < len)
{
z[i] = x[i];
++i;
}
return 0;
}
}
return -1;
}
public static int DecAt(int len, uint[] z, int zPos)
{
Debug.Assert(zPos <= len);
for (int i = zPos; i < len; ++i)
{
if (--z[i] != uint.MaxValue)
{
return 0;
}
}
return -1;
}
public static int DecAt(int len, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= len);
for (int i = zPos; i < len; ++i)
{
if (--z[zOff + i] != uint.MaxValue)
{
return 0;
}
}
return -1;
}
public static bool Eq(int len, uint[] x, uint[] y)
{
for (int i = len - 1; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static uint[] FromBigInteger(int bits, BigInteger x)
{
if (x.SignValue < 0 || x.BitLength > bits)
throw new ArgumentException();
int len = (bits + 31) >> 5;
uint[] z = Create(len);
int i = 0;
while (x.SignValue != 0)
{
z[i++] = (uint)x.IntValue;
x = x.ShiftRight(32);
}
return z;
}
public static uint GetBit(uint[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= x.Length)
{
return 0;
}
int b = bit & 31;
return (x[w] >> b) & 1;
}
public static bool Gte(int len, uint[] x, uint[] y)
{
for (int i = len - 1; i >= 0; --i)
{
uint x_i = x[i], y_i = y[i];
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static uint Inc(int len, uint[] z)
{
for (int i = 0; i < len; ++i)
{
if (++z[i] != uint.MinValue)
{
return 0;
}
}
return 1;
}
public static uint Inc(int len, uint[] x, uint[] z)
{
int i = 0;
while (i < len)
{
uint c = x[i] + 1;
z[i] = c;
++i;
if (c != 0)
{
while (i < len)
{
z[i] = x[i];
++i;
}
return 0;
}
}
return 1;
}
public static uint IncAt(int len, uint[] z, int zPos)
{
Debug.Assert(zPos <= len);
for (int i = zPos; i < len; ++i)
{
if (++z[i] != uint.MinValue)
{
return 0;
}
}
return 1;
}
public static uint IncAt(int len, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= len);
for (int i = zPos; i < len; ++i)
{
if (++z[zOff + i] != uint.MinValue)
{
return 0;
}
}
return 1;
}
public static bool IsOne(int len, uint[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < len; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static bool IsZero(int len, uint[] x)
{
if (x[0] != 0)
{
return false;
}
for (int i = 1; i < len; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static void Mul(int len, uint[] x, uint[] y, uint[] zz)
{
zz[len] = (uint)MulWord(len, x[0], y, zz);
for (int i = 1; i < len; ++i)
{
zz[i + len] = (uint)MulWordAddTo(len, x[i], y, 0, zz, i);
}
}
public static void Mul(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff)
{
zz[zzOff + len] = (uint)MulWord(len, x[xOff], y, yOff, zz, zzOff);
for (int i = 1; i < len; ++i)
{
zz[zzOff + i + len] = (uint)MulWordAddTo(len, x[xOff + i], y, yOff, zz, zzOff + i);
}
}
public static uint Mul31BothAdd(int len, uint a, uint[] x, uint b, uint[] y, uint[] z, int zOff)
{
ulong c = 0, aVal = (ulong)a, bVal = (ulong)b;
int i = 0;
do
{
c += aVal * x[i] + bVal * y[i] + z[zOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
while (++i < len);
return (uint)c;
}
public static uint MulWord(int len, uint x, uint[] y, uint[] z)
{
ulong c = 0, xVal = (ulong)x;
int i = 0;
do
{
c += xVal * y[i];
z[i] = (uint)c;
c >>= 32;
}
while (++i < len);
return (uint)c;
}
public static uint MulWord(int len, uint x, uint[] y, int yOff, uint[] z, int zOff)
{
ulong c = 0, xVal = (ulong)x;
int i = 0;
do
{
c += xVal * y[yOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
while (++i < len);
return (uint)c;
}
public static uint MulWordAddTo(int len, uint x, uint[] y, int yOff, uint[] z, int zOff)
{
ulong c = 0, xVal = (ulong)x;
int i = 0;
do
{
c += xVal * y[yOff + i] + z[zOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
while (++i < len);
return (uint)c;
}
public static uint MulWordDwordAddAt(int len, uint x, ulong y, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 3));
ulong c = 0, xVal = (ulong)x;
c += xVal * (uint)y + z[zPos + 0];
z[zPos + 0] = (uint)c;
c >>= 32;
c += xVal * (y >> 32) + z[zPos + 1];
z[zPos + 1] = (uint)c;
c >>= 32;
c += (ulong)z[zPos + 2];
z[zPos + 2] = (uint)c;
c >>= 32;
return c == 0 ? 0 : IncAt(len, z, zPos + 3);
}
public static uint ShiftDownBit(int len, uint[] z, uint c)
{
int i = len;
while (--i >= 0)
{
uint next = z[i];
z[i] = (next >> 1) | (c << 31);
c = next;
}
return c << 31;
}
public static uint ShiftDownBit(int len, uint[] z, int zOff, uint c)
{
int i = len;
while (--i >= 0)
{
uint next = z[zOff + i];
z[zOff + i] = (next >> 1) | (c << 31);
c = next;
}
return c << 31;
}
public static uint ShiftDownBit(int len, uint[] x, uint c, uint[] z)
{
int i = len;
while (--i >= 0)
{
uint next = x[i];
z[i] = (next >> 1) | (c << 31);
c = next;
}
return c << 31;
}
public static uint ShiftDownBit(int len, uint[] x, int xOff, uint c, uint[] z, int zOff)
{
int i = len;
while (--i >= 0)
{
uint next = x[xOff + i];
z[zOff + i] = (next >> 1) | (c << 31);
c = next;
}
return c << 31;
}
public static uint ShiftDownBits(int len, uint[] z, int bits, uint c)
{
Debug.Assert(bits > 0 && bits < 32);
int i = len;
while (--i >= 0)
{
uint next = z[i];
z[i] = (next >> bits) | (c << -bits);
c = next;
}
return c << -bits;
}
public static uint ShiftDownBits(int len, uint[] z, int zOff, int bits, uint c)
{
Debug.Assert(bits > 0 && bits < 32);
int i = len;
while (--i >= 0)
{
uint next = z[zOff + i];
z[zOff + i] = (next >> bits) | (c << -bits);
c = next;
}
return c << -bits;
}
public static uint ShiftDownBits(int len, uint[] x, int bits, uint c, uint[] z)
{
Debug.Assert(bits > 0 && bits < 32);
int i = len;
while (--i >= 0)
{
uint next = x[i];
z[i] = (next >> bits) | (c << -bits);
c = next;
}
return c << -bits;
}
public static uint ShiftDownBits(int len, uint[] x, int xOff, int bits, uint c, uint[] z, int zOff)
{
Debug.Assert(bits > 0 && bits < 32);
int i = len;
while (--i >= 0)
{
uint next = x[xOff + i];
z[zOff + i] = (next >> bits) | (c << -bits);
c = next;
}
return c << -bits;
}
public static uint ShiftDownWord(int len, uint[] z, uint c)
{
int i = len;
while (--i >= 0)
{
uint next = z[i];
z[i] = c;
c = next;
}
return c;
}
public static uint ShiftUpBit(int len, uint[] z, uint c)
{
for (int i = 0; i < len; ++i)
{
uint next = z[i];
z[i] = (next << 1) | (c >> 31);
c = next;
}
return c >> 31;
}
public static uint ShiftUpBit(int len, uint[] z, int zOff, uint c)
{
for (int i = 0; i < len; ++i)
{
uint next = z[zOff + i];
z[zOff + i] = (next << 1) | (c >> 31);
c = next;
}
return c >> 31;
}
public static uint ShiftUpBit(int len, uint[] x, uint c, uint[] z)
{
for (int i = 0; i < len; ++i)
{
uint next = x[i];
z[i] = (next << 1) | (c >> 31);
c = next;
}
return c >> 31;
}
public static uint ShiftUpBit(int len, uint[] x, int xOff, uint c, uint[] z, int zOff)
{
for (int i = 0; i < len; ++i)
{
uint next = x[xOff + i];
z[zOff + i] = (next << 1) | (c >> 31);
c = next;
}
return c >> 31;
}
public static ulong ShiftUpBit64(int len, ulong[] x, int xOff, ulong c, ulong[] z, int zOff)
{
for (int i = 0; i < len; ++i)
{
ulong next = x[xOff + i];
z[zOff + i] = (next << 1) | (c >> 63);
c = next;
}
return c >> 63;
}
public static uint ShiftUpBits(int len, uint[] z, int bits, uint c)
{
Debug.Assert(bits > 0 && bits < 32);
for (int i = 0; i < len; ++i)
{
uint next = z[i];
z[i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static uint ShiftUpBits(int len, uint[] z, int zOff, int bits, uint c)
{
Debug.Assert(bits > 0 && bits < 32);
for (int i = 0; i < len; ++i)
{
uint next = z[zOff + i];
z[zOff + i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static ulong ShiftUpBits64(int len, ulong[] z, int zOff, int bits, ulong c)
{
Debug.Assert(bits > 0 && bits < 64);
for (int i = 0; i < len; ++i)
{
ulong next = z[zOff + i];
z[zOff + i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static uint ShiftUpBits(int len, uint[] x, int bits, uint c, uint[] z)
{
Debug.Assert(bits > 0 && bits < 32);
for (int i = 0; i < len; ++i)
{
uint next = x[i];
z[i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static uint ShiftUpBits(int len, uint[] x, int xOff, int bits, uint c, uint[] z, int zOff)
{
Debug.Assert(bits > 0 && bits < 32);
for (int i = 0; i < len; ++i)
{
uint next = x[xOff + i];
z[zOff + i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static ulong ShiftUpBits64(int len, ulong[] x, int xOff, int bits, ulong c, ulong[] z, int zOff)
{
Debug.Assert(bits > 0 && bits < 64);
for (int i = 0; i < len; ++i)
{
ulong next = x[xOff + i];
z[zOff + i] = (next << bits) | (c >> -bits);
c = next;
}
return c >> -bits;
}
public static void Square(int len, uint[] x, uint[] zz)
{
int extLen = len << 1;
uint c = 0;
int j = len, k = extLen;
do
{
ulong xVal = (ulong)x[--j];
ulong p = xVal * xVal;
zz[--k] = (c << 31) | (uint)(p >> 33);
zz[--k] = (uint)(p >> 1);
c = (uint)p;
}
while (j > 0);
for (int i = 1; i < len; ++i)
{
c = SquareWordAdd(x, i, zz);
AddWordAt(extLen, c, zz, i << 1);
}
ShiftUpBit(extLen, zz, x[0] << 31);
}
public static void Square(int len, uint[] x, int xOff, uint[] zz, int zzOff)
{
int extLen = len << 1;
uint c = 0;
int j = len, k = extLen;
do
{
ulong xVal = (ulong)x[xOff + --j];
ulong p = xVal * xVal;
zz[zzOff + --k] = (c << 31) | (uint)(p >> 33);
zz[zzOff + --k] = (uint)(p >> 1);
c = (uint)p;
}
while (j > 0);
for (int i = 1; i < len; ++i)
{
c = SquareWordAdd(x, xOff, i, zz, zzOff);
AddWordAt(extLen, c, zz, zzOff, i << 1);
}
ShiftUpBit(extLen, zz, zzOff, x[xOff] << 31);
}
public static uint SquareWordAdd(uint[] x, int xPos, uint[] z)
{
ulong c = 0, xVal = (ulong)x[xPos];
int i = 0;
do
{
c += xVal * x[i] + z[xPos + i];
z[xPos + i] = (uint)c;
c >>= 32;
}
while (++i < xPos);
return (uint)c;
}
public static uint SquareWordAdd(uint[] x, int xOff, int xPos, uint[] z, int zOff)
{
ulong c = 0, xVal = (ulong)x[xOff + xPos];
int i = 0;
do
{
c += xVal * (x[xOff + i] & M) + (z[xPos + zOff] & M);
z[xPos + zOff] = (uint)c;
c >>= 32;
++zOff;
}
while (++i < xPos);
return (uint)c;
}
public static int Sub(int len, uint[] x, uint[] y, uint[] z)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)x[i] - y[i];
z[i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int Sub(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)x[xOff + i] - y[yOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int Sub33At(int len, uint x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 2));
long c = (long)z[zPos + 0] - x;
z[zPos + 0] = (uint)c;
c >>= 32;
c += (long)z[zPos + 1] - 1;
z[zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zPos + 2);
}
public static int Sub33At(int len, uint x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 2));
long c = (long)z[zOff + zPos] - x;
z[zOff + zPos] = (uint)c;
c >>= 32;
c += (long)z[zOff + zPos + 1] - 1;
z[zOff + zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 2);
}
public static int Sub33From(int len, uint x, uint[] z)
{
long c = (long)z[0] - x;
z[0] = (uint)c;
c >>= 32;
c += (long)z[1] - 1;
z[1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, 2);
}
public static int Sub33From(int len, uint x, uint[] z, int zOff)
{
long c = (long)z[zOff + 0] - x;
z[zOff + 0] = (uint)c;
c >>= 32;
c += (long)z[zOff + 1] - 1;
z[zOff + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, 2);
}
public static int SubBothFrom(int len, uint[] x, uint[] y, uint[] z)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)z[i] - x[i] - y[i];
z[i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int SubBothFrom(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)z[zOff + i] - x[xOff + i] - y[yOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int SubDWordAt(int len, ulong x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 2));
long c = (long)z[zPos + 0] - (long)(x & M);
z[zPos + 0] = (uint)c;
c >>= 32;
c += (long)z[zPos + 1] - (long)(x >> 32);
z[zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zPos + 2);
}
public static int SubDWordAt(int len, ulong x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 2));
long c = (long)z[zOff + zPos] - (long)(x & M);
z[zOff + zPos] = (uint)c;
c >>= 32;
c += (long)z[zOff + zPos + 1] - (long)(x >> 32);
z[zOff + zPos + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 2);
}
public static int SubDWordFrom(int len, ulong x, uint[] z)
{
long c = (long)z[0] - (long)(x & M);
z[0] = (uint)c;
c >>= 32;
c += (long)z[1] - (long)(x >> 32);
z[1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, 2);
}
public static int SubDWordFrom(int len, ulong x, uint[] z, int zOff)
{
long c = (long)z[zOff + 0] - (long)(x & M);
z[zOff + 0] = (uint)c;
c >>= 32;
c += (long)z[zOff + 1] - (long)(x >> 32);
z[zOff + 1] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, 2);
}
public static int SubFrom(int len, uint[] x, uint[] z)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)z[i] - x[i];
z[i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int SubFrom(int len, uint[] x, int xOff, uint[] z, int zOff)
{
long c = 0;
for (int i = 0; i < len; ++i)
{
c += (long)z[zOff + i] - x[xOff + i];
z[zOff + i] = (uint)c;
c >>= 32;
}
return (int)c;
}
public static int SubWordAt(int len, uint x, uint[] z, int zPos)
{
Debug.Assert(zPos <= (len - 1));
long c = (long)z[zPos] - x;
z[zPos] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zPos + 1);
}
public static int SubWordAt(int len, uint x, uint[] z, int zOff, int zPos)
{
Debug.Assert(zPos <= (len - 1));
long c = (long)z[zOff + zPos] - x;
z[zOff + zPos] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 1);
}
public static int SubWordFrom(int len, uint x, uint[] z)
{
long c = (long)z[0] - x;
z[0] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, 1);
}
public static int SubWordFrom(int len, uint x, uint[] z, int zOff)
{
long c = (long)z[zOff + 0] - x;
z[zOff + 0] = (uint)c;
c >>= 32;
return c == 0 ? 0 : DecAt(len, z, zOff, 1);
}
public static BigInteger ToBigInteger(int len, uint[] x)
{
byte[] bs = new byte[len << 2];
for (int i = 0; i < len; ++i)
{
uint x_i = x[i];
if (x_i != 0)
{
Pack.UInt32_To_BE(x_i, bs, (len - 1 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static void Zero(int len, uint[] z)
{
for (int i = 0; i < len; ++i)
{
z[i] = 0;
}
}
}
}
#endif
| 29.871456 | 112 | 0.333122 | [
"MIT"
] | czlsy009/UnityAppMVCFramework | Framework/Assets/SilenceFramework/Libs/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/raw/Nat.cs | 31,604 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using System.Windows.Forms;
using Nucs.JsonSettings.Fluent;
namespace Nucs.JsonSettings.Examples {
static class EncryptedProgram {
/// <summary>
/// The main entry point for the application.
/// </summary>
private static EncryptedSettings Settings { get; } = JsonSettings.Construct<EncryptedSettings>("mysupercomplex_password","memory.jsn").LoadNow();
public static void Run(string[] args) {
//simple app to open a file by command and browse to a new file on demand.
while (true) {
Console.WriteLine("Commands: \nopen - open a file\nbrowse - browse to a new file\nquit - closes");
Console.Write(">");
while (Console.ReadLine().ToLowerInvariant() is string r && (r == "open" || r == "browse" || r == "quit")) {
switch (r) {
case "open":
if (string.IsNullOrEmpty(Settings.LastPath))
goto _browse;
Process.Start(Settings.LastPath);
break;
case "browse":
_browse:
var dia = new OpenFileDialog() {FileName = Settings.LastPath, Multiselect = false};
if (dia.ShowDialog() == DialogResult.OK) {
Settings.LastPath = dia.FileName;
Settings.Save();
}
break;
}
Console.Write(">");
}
}
}
}
public class EncryptedSettings : JsonSettings {
public SecureString Password { get; }
public override string FileName { get; set; } = "some.default.just.in.case.jsn";
public string LastPath { get; set; }
protected override void OnConfigure() {
base.OnConfigure();
this.WithEncryption(() => Password);
}
public EncryptedSettings() { }
public EncryptedSettings(string password) : this(password, "<DEFAULT>") { }
public EncryptedSettings(string password, string fileName = "<DEFAULT>") : this(password?.ToSecureString(), fileName) { }
public EncryptedSettings(SecureString password) : this(password, "<DEFAULT>") { }
public EncryptedSettings(SecureString password, string fileName = "<DEFAULT>") : base(fileName) {
Password = password;
}
}
} | 41.323077 | 153 | 0.539464 | [
"MIT"
] | BridgerPhotonics/JsonSettings | examples/JsonSettings.Examples/EncryptedJsonSettings.cs | 2,688 | C# |
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(Attacker))]
public class Fox : MonoBehaviour {
private Attacker myAttacker;
private Animator myAnimator;
void Start () {
myAttacker = GetComponent<Attacker>();
myAnimator = GetComponent<Animator>();
}
void OnTriggerEnter2D(Collider2D collider){
GameObject collisionObject = collider.gameObject;
if(collisionObject.GetComponent<Defender>()){
if(collisionObject.GetComponent<Stone>()){
myAnimator.SetTrigger("foxJump");
}
else{
myAnimator.SetBool("isAttacking",true);
myAttacker.SetTarget(collisionObject);
}
}
}
}
| 20.03125 | 51 | 0.722309 | [
"MIT"
] | kifil/GlitchGarden | Assets/Scripts/Fox.cs | 643 | C# |
// Tree.cs
// Copyright Karel Kroeze, 2020-2020
//using Multiplayer.API;
using static FluffyResearchTree.Constants;
namespace FluffyResearchTree
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using global::ResearchTree;
using global::ResearchTree.Graph;
using RimWorld;
using UnityEngine;
using Verse;
[Serializable]
public class Tree
{
public const string ALL_TAB_NAME = "All";
public static Tree ActiveTree;
public static Tree AllTreeTab;
public static Dictionary<string, Tree> Trees = new Dictionary<string, Tree>();
public static List<ResearchTabDef> Tabs = new List<ResearchTabDef>();
private List<Edge<Node, Node>> _edges;
private bool _initializing;
private List<Node> _nodes;
private List<TechLevel> _relevantTechLevels;
private Dictionary<TechLevel, IntRange> _techLevelBounds;
public bool Initialized;
public bool OrderDirty;
public IntVec2 Size = IntVec2.Zero;
public string TabName;
public string TabLabel;
private Rect _treeRect;
public Rect TreeRect
{
get
{
if (_treeRect == default)
{
var width = Size.x * (NodeSize.x + NodeMargins.x);
var height =Size.z * (NodeSize.y + NodeMargins.y);
_treeRect = new Rect(0f, 0f, width, height);
}
return _treeRect;
}
}
public Tree(ResearchTabDef tab)
{
TabName = tab.defName;
TabLabel = (!tab.LabelCap.NullOrEmpty()?tab.LabelCap.Resolve():tab.defName);
Trees.Add(TabName, this);
Tabs.Add(tab);
// Initialize();
}
public Tree(){}
public static Tree AllTab()
{
var allTree = new Tree()
{
TabName = ALL_TAB_NAME,
TabLabel = ALL_TAB_NAME,
};
AllTreeTab = allTree;
Trees.Add(ALL_TAB_NAME, allTree);
Tabs.Add(new ResearchTabDef(){defName = ALL_TAB_NAME});
return allTree;
}
public Dictionary<TechLevel, IntRange> TechLevelBounds
{
get
{
if (_techLevelBounds == null)
throw new Exception("TechLevelBounds called before they are set.");
return _techLevelBounds;
}
}
public List<TechLevel> RelevantTechLevels
{
get
{
if (_relevantTechLevels == null)
_relevantTechLevels = Enum.GetValues(typeof(TechLevel))
.Cast<TechLevel>()
// filter down to relevant tech levels only.
.Where(
tl => (TabName==ALL_TAB_NAME?DefDatabase<ResearchProjectDef>.AllDefsListForReading:DefDatabase<ResearchProjectDef>.AllDefsListForReading.Where(def => def.tab.defName == TabName))
.Any(rp => rp.techLevel == tl))
.ToList();
return _relevantTechLevels;
}
}
public List<Node> Nodes
{
get
{
if (_nodes == null)
PopulateNodes();
return _nodes;
}
}
public List<Edge<Node, Node>> Edges
{
get
{
if (_edges == null)
throw new Exception("Trying to access edges before they are initialized.");
return _edges;
}
}
public void DrawTab(Rect visibleRect)
{
var mouseOver = Mouse.IsOver(visibleRect);
var isActive = ActiveTree.TabName == TabName;
if (Event.current.type == EventType.Repaint)
{
// researches that are completed or could be started immediately, and that have the required building(s) available
GUI.color = mouseOver ? GenUI.MouseoverColor : Assets.ColorCompleted[TechLevel.Industrial];
if (mouseOver)
GUI.DrawTexture(visibleRect, Assets.ButtonActive);
else
GUI.DrawTexture(visibleRect, Assets.Button);
var progressBarRect = visibleRect.ContractedBy(3f);
GUI.color = Assets.ColorAvailable[TechLevel.Industrial];
progressBarRect.xMin += (isActive ? 1f : 0f ) * progressBarRect.width;
GUI.DrawTexture(progressBarRect, BaseContent.WhiteTex);
GUI.color = Color.white;
Text.Anchor = TextAnchor.MiddleCenter;
Text.WordWrap = false;
Text.Font = visibleRect.width > 100?GameFont.Small:GameFont.Tiny;
Widgets.Label(visibleRect, TabLabel);
}
var btn = Widgets.ButtonInvisible(visibleRect);
if (btn)
// LMB is queue operations, RMB is info
if (Event.current.button == 0)
{
ActiveTree = Trees[TabName];
ActiveTree.Initialize();
ActiveTree.OrderDirty = true;
}
}
public Tree (Tree loadedTree)
{
_edges = loadedTree.Edges;
_nodes = loadedTree.Nodes;
_relevantTechLevels = loadedTree._relevantTechLevels;
_techLevelBounds = loadedTree._techLevelBounds;
Initialized = loadedTree.Initialized;
OrderDirty = loadedTree.OrderDirty;
Size = loadedTree.Size;
TabName = loadedTree.TabName;
TabLabel = loadedTree.TabLabel;
_treeRect = loadedTree._treeRect;
Trees[TabName] = this;
}
// [SyncMethod]
public void Initialize()
{
if (Initialized) return;
// make sure we only have one initializer running
if (_initializing)
return;
_initializing = true;
if (CacheIO.CacheShouldBeLoaded)
{
Log.Message("Loading from Cache");
var tree = CacheIO.LoadFromCache(TabName);
if (tree != null)
{
if (tree != ActiveTree)
{
ActiveTree = new Tree(tree);
ActiveTree.Initialized = true;
LongEventHandler.QueueLongEvent(Tabbed_MainTabWindow_ResearchTree.Instance.Notify_TreeInitialized,
"Fluffy.ResearchTree.RestoreQueue." + TabName, false, null);
return;
}
}
}
// setup
LongEventHandler.QueueLongEvent(CheckPrerequisites, "Fluffy.ResearchTree.PreparingTree.Setup." + TabName, false,
null);
LongEventHandler.QueueLongEvent(CreateEdges, "Fluffy.ResearchTree.PreparingTree.Setup." + TabName, false, null);
LongEventHandler.QueueLongEvent(HorizontalPositions, "Fluffy.ResearchTree.PreparingTree.Setup." + TabName, false,
null);
LongEventHandler.QueueLongEvent(NormalizeEdges, "Fluffy.ResearchTree.PreparingTree.Setup." + TabName, false, null);
#if DEBUG
LongEventHandler.QueueLongEvent(DebugStatus, "Fluffy.ResearchTree.PreparingTree.Setup." + TabName, false, null);
#endif
// crossing reduction
LongEventHandler.QueueLongEvent(Collapse, "Fluffy.ResearchTree.PreparingTree.CrossingReduction." + TabName, false,
null);
LongEventHandler.QueueLongEvent(MinimizeCrossings, "Fluffy.ResearchTree.PreparingTree.CrossingReduction." + TabName,
false, null);
#if DEBUG
LongEventHandler.QueueLongEvent(DebugStatus, "Fluffy.ResearchTree.PreparingTree.CrossingReduction." + TabName, false,
null);
#endif
// layout
LongEventHandler.QueueLongEvent(MinimizeEdgeLength, "Fluffy.ResearchTree.PreparingTree.Layout." + TabName, false,
null);
LongEventHandler.QueueLongEvent(RemoveEmptyRows, "Fluffy.ResearchTree.PreparingTree.Layout." + TabName, false, null);
#if DEBUG
LongEventHandler.QueueLongEvent(DebugStatus, "Fluffy.ResearchTree.PreparingTree.Layout." + TabName, false, null);
#endif
// done!
LongEventHandler.QueueLongEvent(() => { Initialized = true; CacheIO.SaveTab(this);}, "Fluffy.ResearchTree.PreparingTree.Layout." + TabName,
false, null);
// tell research tab we're ready
LongEventHandler.QueueLongEvent(Tabbed_MainTabWindow_ResearchTree.Instance.Notify_TreeInitialized,
"Fluffy.ResearchTree.RestoreQueue." + TabName, false, null);
}
private void RemoveEmptyRows()
{
Log.Debug("Removing empty rows");
Profiler.Start();
var y = 1;
while (y <= Size.z)
{
var row = Row(y);
if (row.NullOrEmpty())
foreach (var node in Nodes.Where(n => n.Y > y))
node.Y--;
else
y++;
}
Profiler.End();
}
private void MinimizeEdgeLength()
{
Log.Debug("Minimize edge length.");
Profiler.Start();
// move and/or swap nodes to reduce the total edge length
// perform sweeps of adjacent node reorderings
var progress = false;
int iteration = 0, burnout = 2, max_iterations = 50;
while ((!progress || burnout > 0) && iteration < max_iterations)
{
progress = EdgeLengthSweep_Local(iteration++);
if (!progress)
burnout--;
}
// sweep until we had no progress 2 times, then keep sweeping until we had progress
iteration = 0;
burnout = 2;
while (burnout > 0 && iteration < max_iterations)
{
progress = EdgeLengthSweep_Global(iteration++);
if (!progress)
burnout--;
}
Profiler.End();
}
private bool EdgeLengthSweep_Global(int iteration)
{
Profiler.Start("iteration" + iteration);
// calculate edge length before sweep
var before = EdgeLength();
// do left/right sweep, align with left/right nodes for 4 different iterations.
//if (iteration % 2 == 0)
for (var l = 2; l <= Size.x; l++)
EdgeLengthSweep_Global_Layer(l, true);
//else
// for (var l = 1; l < Size.x; l++)
// EdgeLengthSweep_Global_Layer(l, false);
// calculate edge length after sweep
var after = EdgeLength();
// return progress
Log.Debug($"EdgeLengthSweep_Global, iteration {iteration}: {before} -> {after}");
Profiler.End();
return after < before;
}
private bool EdgeLengthSweep_Local(int iteration)
{
Profiler.Start("iteration" + iteration);
// calculate edge length before sweep
var before = EdgeLength();
// do left/right sweep, align with left/right nodes for 4 different iterations.
if (iteration % 2 == 0)
for (var l = 2; l <= Size.x; l++)
EdgeLengthSweep_Local_Layer(l, true);
else
for (var l = Size.x - 1; l >= 0; l--)
EdgeLengthSweep_Local_Layer(l, false);
// calculate edge length after sweep
var after = EdgeLength();
// return progress
Log.Debug($"EdgeLengthSweep_Local, iteration {iteration}: {before} -> {after}");
Profiler.End();
return after < before;
}
private void EdgeLengthSweep_Global_Layer(int l, bool @in)
{
// The objective here is to;
// (1) move and/or swap nodes to reduce total edge length
// (2) not increase the number of crossings
var length = EdgeLength(l, @in);
var crossings = Crossings(l);
if (Math.Abs(length) < Epsilon)
return;
var layer = Layer(l, true);
foreach (var node in layer)
{
// we only need to loop over positions that might be better for this node.
// min = minimum of current position, minimum of any connected nodes current position
var neighbours = node.Nodes;
if (!neighbours.Any())
continue;
var min = Mathf.Min(node.Y, neighbours.Min(n => n.Y));
var max = Mathf.Max(node.Y, neighbours.Max(n => n.Y));
if (min == max && min == node.Y)
continue;
for (var y = min; y <= max; y++)
{
if (y == node.Y)
continue;
// is this spot occupied?
var otherNode = NodeAt(l, y);
// occupied, try swapping
if (otherNode != null)
{
Swap(node, otherNode);
var candidateCrossings = Crossings(l);
if (candidateCrossings > crossings)
{
// abort
Swap(otherNode, node);
}
else
{
var candidateLength = EdgeLength(l, @in);
if (length - candidateLength < Epsilon)
{
// abort
Swap(otherNode, node);
}
else
{
Log.Trace("\tSwapping {0} and {1}: {2} -> {3}", node, otherNode, length,
candidateLength);
length = candidateLength;
}
}
}
// not occupied, try moving
else
{
var oldY = node.Y;
node.Y = y;
var candidateCrossings = Crossings(l);
if (candidateCrossings > crossings)
{
// abort
node.Y = oldY;
}
else
{
var candidateLength = EdgeLength(l, @in);
if (length - candidateLength < Epsilon)
{
// abort
node.Y = oldY;
}
else
{
Log.Trace("\tMoving {0} -> {1}: {2} -> {3}", node, new Vector2(node.X, oldY), length,
candidateLength);
length = candidateLength;
}
}
}
}
}
}
private void EdgeLengthSweep_Local_Layer(int l, bool @in)
{
// The objective here is to;
// (1) move and/or swap nodes to reduce local edge length
// (2) not increase the number of crossings
var x = @in ? l - 1 : l + 1;
var crossings = Crossings(x);
var layer = Layer(l, true);
foreach (var node in layer)
foreach (var edge in @in ? node.InEdges : node.OutEdges)
{
// current length
var length = edge.Length;
var neighbour = @in ? edge.In : edge.Out;
if (neighbour.X != x)
Log.Warning("{0} is not at layer {1}", neighbour, x);
// we only need to loop over positions that might be better for this node.
// min = minimum of current position, node position
var min = Mathf.Min(node.Y, neighbour.Y);
var max = Mathf.Max(node.Y, neighbour.Y);
// already at only possible position
if (min == max && min == node.Y)
continue;
for (var y = min; y <= max; y++)
{
if (y == neighbour.Y)
continue;
// is this spot occupied?
var otherNode = NodeAt(x, y);
// occupied, try swapping
if (otherNode != null)
{
Swap(neighbour, otherNode);
var candidateCrossings = Crossings(x);
if (candidateCrossings > crossings)
{
// abort
Swap(otherNode, neighbour);
}
else
{
var candidateLength = edge.Length;
if (length - candidateLength < Epsilon)
{
// abort
Swap(otherNode, neighbour);
}
else
{
Log.Trace("\tSwapping {0} and {1}: {2} -> {3}", neighbour, otherNode, length,
candidateLength);
length = candidateLength;
}
}
}
// not occupied, try moving
else
{
var oldY = neighbour.Y;
neighbour.Y = y;
var candidateCrossings = Crossings(x);
if (candidateCrossings > crossings)
{
// abort
neighbour.Y = oldY;
}
else
{
var candidateLength = edge.Length;
if (length - candidateLength < Epsilon)
{
// abort
neighbour.Y = oldY;
}
else
{
Log.Trace("\tMoving {0} -> {1}: {2} -> {3}", neighbour,
new Vector2(neighbour.X, oldY), length, candidateLength);
length = candidateLength;
}
}
}
}
}
}
public void HorizontalPositions()
{
// get list of techlevels
var techlevels = RelevantTechLevels;
bool anyChange;
var iteration = 1;
var maxIterations = 50;
Log.Debug("Assigning horizontal positions.");
Profiler.Start();
// assign horizontal positions based on tech levels and prerequisites
do
{
Profiler.Start("iteration " + iteration);
var min = 1;
anyChange = false;
foreach (var techlevel in techlevels)
{
// enforce minimum x position based on techlevels
var nodes = Nodes.OfType<ResearchNode>().Where(n => n.Research.techLevel == techlevel);
if (!nodes.Any())
continue;
foreach (var node in nodes)
anyChange = node.SetDepth(min) || anyChange;
min = nodes.Max(n => n.X) + 1;
Log.Trace("\t{0}, change: {1}", techlevel, anyChange);
}
Profiler.End();
} while (anyChange && iteration++ < maxIterations);
// store tech level boundaries
_techLevelBounds = new Dictionary<TechLevel, IntRange>();
foreach (var techlevel in techlevels)
{
var nodes = Nodes.OfType<ResearchNode>().Where(n => n.Research.techLevel == techlevel);
_techLevelBounds[techlevel] = new IntRange(nodes.Min(n => n.X) - 1, nodes.Max(n => n.X));
}
Profiler.End();
}
private void NormalizeEdges()
{
Log.Debug("Normalizing edges.");
Profiler.Start();
foreach (var edge in new List<Edge<Node, Node>>(Edges.Where(e => e.Span > 1)))
{
Log.Trace("\tCreating dummy chain for {0}", edge);
// remove and decouple long edge
Edges.Remove(edge);
edge.In.OutEdges.Remove(edge);
edge.Out.InEdges.Remove(edge);
var cur = edge.In;
var yOffset = (edge.Out.Yf - edge.In.Yf) / edge.Span;
// create and hook up dummy chain
for (var x = edge.In.X + 1; x < edge.Out.X; x++)
{
var dummy = new DummyNode();
dummy.X = x;
dummy.Yf = edge.In.Yf + yOffset * (x - edge.In.X);
var dummyEdge = new Edge<Node, Node>(cur, dummy);
cur.OutEdges.Add(dummyEdge);
dummy.InEdges.Add(dummyEdge);
_nodes.Add(dummy);
Edges.Add(dummyEdge);
cur = dummy;
Log.Trace("\t\tCreated dummy {0}", dummy);
}
// hook up final dummy to out node
var finalEdge = new Edge<Node, Node>(cur, edge.Out);
cur.OutEdges.Add(finalEdge);
edge.Out.InEdges.Add(finalEdge);
Edges.Add(finalEdge);
}
Profiler.End();
}
private void CreateEdges()
{
Log.Debug("Creating edges.");
Profiler.Start();
// create links between nodes
if (_edges.NullOrEmpty()) _edges = new List<Edge<Node, Node>>();
foreach (var node in Nodes.OfType<ResearchNode>())
{
if (node.Research.prerequisites.NullOrEmpty())
continue;
foreach (var prerequisite in node.Research.prerequisites)
{
ResearchNode prerequisiteNode = prerequisite;
if (prerequisiteNode == null)
continue;
var edge = new Edge<Node, Node>(prerequisiteNode, node);
Edges.Add(edge);
node.InEdges.Add(edge);
prerequisiteNode.OutEdges.Add(edge);
Log.Trace("\tCreated edge {0}", edge);
}
}
Profiler.End();
}
private void CheckPrerequisites()
{
// check prerequisites
Log.Debug("Checking prerequisites.");
Profiler.Start();
var nodes = new Queue<ResearchNode>(Nodes.OfType<ResearchNode>());
// remove redundant prerequisites
while (nodes.Count > 0)
{
var node = nodes.Dequeue();
if (node.Research.prerequisites.NullOrEmpty())
continue;
var ancestors = node.Research.prerequisites?.SelectMany(r => r.Ancestors()).ToList();
var redundant = ancestors.Intersect(node.Research.prerequisites);
if (redundant.Any())
{
Log.Warning("\tredundant prerequisites for {0}: {1}", node.Research.LabelCap,
string.Join(", ", redundant.Select(r => r.LabelCap).ToArray()));
foreach (var redundantPrerequisite in redundant)
node.Research.prerequisites.Remove(redundantPrerequisite);
}
}
// fix bad techlevels
nodes = new Queue<ResearchNode>(Nodes.OfType<ResearchNode>());
while (nodes.Count > 0)
{
var node = nodes.Dequeue();
if (!node.Research.prerequisites.NullOrEmpty())
// warn and fix badly configured techlevels
if (node.Research.prerequisites.Any(r => r.techLevel > node.Research.techLevel))
{
Log.Warning("\t{0} has a lower techlevel than (one of) it's prerequisites",
node.Research.defName);
node.Research.techLevel = node.Research.prerequisites.Max(r => r.techLevel);
// re-enqeue all descendants
foreach (var descendant in node.Descendants.OfType<ResearchNode>())
nodes.Enqueue(descendant);
}
}
Profiler.End();
}
private void PopulateNodes()
{
Log.Debug("Populating nodes.");
Profiler.Start();
var projects = DefDatabase<ResearchProjectDef>.AllDefsListForReading;
// find hidden nodes (nodes that have themselves as a prerequisite)
var hidden = projects.Where(p => p.prerequisites?.Contains(p) ?? false);
// find locked nodes (nodes that have a hidden node as a prerequisite)
var locked = projects.Where(p => p.Ancestors().Intersect(hidden).Any());
if (TabName == ALL_TAB_NAME)
{
_nodes = new List<Node>(DefDatabase<ResearchProjectDef>.AllDefsListForReading
// .Where(def => def.tab.defName == TabName)
.Except(hidden)
.Except(locked)
.Select(def => new ResearchNode(def) as Node));
_nodes.RemoveAll(n => n == null);
}
else
{
// populate all nodes
_nodes = new List<Node>(DefDatabase<ResearchProjectDef>.AllDefsListForReading
.Where(def => def.tab.defName == TabName)
.Except(hidden)
.Except(locked)
.Select(def => new ResearchNode(def) as Node));
_nodes.RemoveAll(n => n == null);
List<Node> nodesToAdd = new List<Node>();
List<ResearchProjectDef> addedDefs = new List<ResearchProjectDef>();
foreach (var node in _nodes)
{
var missedNodes = (node as ResearchNode).Research.Ancestors().Where(n => n.tab.defName != TabName);
foreach (var researchProjectDef in missedNodes.Except(hidden).Except(locked).Except(addedDefs))
{
Verse.Log.Message("NameDef");
Verse.Log.Message(researchProjectDef.defName);
Verse.Log.Message("Tree");
Verse.Log.Message(Trees[researchProjectDef.tab.defName].TabName);
Verse.Log.Message("Nodes");
Verse.Log.Message(Trees[researchProjectDef.tab.defName].Nodes.Count.ToString());
Verse.Log.Message("Select");
var s = Trees[researchProjectDef.tab.defName].Nodes.Select(n => n as ResearchNode);
var l = s.ToList();
Verse.Log.Message("Exist");
Verse.Log.Message(l[0].Research.defName);
Verse.Log.Message(l.Exists(n => n != null && n.Research != null && n.Research.defName == researchProjectDef.defName) ? "true" : "false");
Verse.Log.Message("Find");
var r = l.Find(n => n != null && n.Research != null && n.Research.defName == researchProjectDef.defName);
Verse.Log.Message("Fake");
nodesToAdd.Add(new FakeResearchNode(r)); //.Find(n=>n.r)
}
addedDefs.AddRange(missedNodes);
}
_nodes.AddRange(nodesToAdd.Distinct());
_nodes.RemoveAll(n => n == null);
}
//foreach (var node in _nodes )
//{
// var missingNodes = (node as ResearchNode).GetMissingRequiredRecursive().Select((researchNode) => researchNode.Research);
// _nodes.AddRange(missingNodes
// .Except(hidden)
// .Except(locked)
// .Select(def => new ResearchNode(def) as Node));
// ;
//}
Log.Debug("\t{0} nodes", _nodes.Count);
Profiler.End();
}
private void Collapse()
{
Log.Debug("Collapsing nodes.");
Profiler.Start();
var pre = Size;
for (var l = 1; l <= Size.x; l++)
{
var nodes = Layer(l, true);
var Y = 1;
foreach (var node in nodes)
node.Y = Y++;
}
Log.Debug("{0} -> {1}", pre, Size);
Profiler.End();
}
//[Conditional("DEBUG")]
//internal static void DebugDraw()
//{
// foreach (var v in ActiveTree.Nodes)
// foreach (var w in v.OutNodes)
// Widgets.DrawLine(v.Right, w.Left, Color.white, 1);
//}
public void Draw(Rect visibleRect)
{
Profiler.Start("Tree.Draw");
Profiler.Start("techlevels");
foreach (var techlevel in RelevantTechLevels)
DrawTechLevel(techlevel, visibleRect);
Profiler.End();
Profiler.Start("edges");
foreach (var edge in Edges.OrderBy(e => e.DrawOrder))
edge.Draw(visibleRect);
Profiler.End();
Profiler.Start("nodes");
foreach (var node in Nodes)
node.Draw(visibleRect);
Profiler.End();
}
public void DrawTechLevel(TechLevel techlevel, Rect visibleRect)
{
if (!TechLevelBounds.ContainsKey(techlevel)) return;
// determine positions
var xMin = (NodeSize.x + NodeMargins.x) * TechLevelBounds[techlevel].min - NodeMargins.x / 2f;
var xMax = (NodeSize.x + NodeMargins.x) * TechLevelBounds[techlevel].max - NodeMargins.x / 2f;
GUI.color = Assets.TechLevelColor;
Text.Anchor = TextAnchor.MiddleCenter;
// lower bound
if (TechLevelBounds[techlevel].min > 0 && xMin > visibleRect.xMin && xMin < visibleRect.xMax)
{
// line
Widgets.DrawLine(new Vector2(xMin, visibleRect.yMin), new Vector2(xMin, visibleRect.yMax),
Assets.TechLevelColor, 1f);
// label
var labelRect = new Rect(
xMin + TechLevelLabelSize.y / 2f - TechLevelLabelSize.x / 2f,
visibleRect.center.y - TechLevelLabelSize.y / 2f,
TechLevelLabelSize.x,
TechLevelLabelSize.y);
VerticalLabel(labelRect, techlevel.ToStringHuman());
}
// upper bound
if (TechLevelBounds[techlevel].max < Size.x && xMax > visibleRect.xMin && xMax < visibleRect.xMax)
{
// label
var labelRect = new Rect(
xMax - TechLevelLabelSize.y / 2f - TechLevelLabelSize.x / 2f,
visibleRect.center.y - TechLevelLabelSize.y / 2f,
TechLevelLabelSize.x,
TechLevelLabelSize.y);
VerticalLabel(labelRect, techlevel.ToStringHuman());
}
GUI.color = Color.white;
Text.Anchor = TextAnchor.UpperLeft;
}
private void VerticalLabel(Rect rect, string text)
{
// store the scaling matrix
var matrix = GUI.matrix;
// rotate and then apply the scaling
GUI.matrix = Matrix4x4.identity;
GUIUtility.RotateAroundPivot(-90f, rect.center);
GUI.matrix = matrix * GUI.matrix;
Widgets.Label(rect, text);
// restore the original scaling matrix
GUI.matrix = matrix;
}
private Node NodeAt(int X, int Y)
{
return Nodes.FirstOrDefault(n => n.X == X && n.Y == Y);
}
public void MinimizeCrossings()
{
// initialize each layer by putting nodes with the most (recursive!) children on bottom
Log.Debug("Minimize crossings.");
Profiler.Start();
for (var X = 1; X <= Size.x; X++)
{
var nodes = Layer(X).OrderBy(n => n.Descendants.Count).ToList();
for (var i = 0; i < nodes.Count; i++)
nodes[i].Y = i + 1;
}
// up-down sweeps of mean reordering
var progress = false;
int iteration = 0, burnout = 2, max_iterations = 50;
while ((!progress || burnout > 0) && iteration < max_iterations)
{
progress = BarymetricSweep(iteration++);
if (!progress)
burnout--;
}
// greedy sweep for local optima
iteration = 0;
burnout = 2;
while (burnout > 0 && iteration < max_iterations)
{
progress = GreedySweep(iteration++);
if (!progress)
burnout--;
}
Profiler.End();
}
private bool GreedySweep(int iteration)
{
Profiler.Start("iteration " + iteration);
// count number of crossings before sweep
var before = Crossings();
// do up/down sweep on aternating iterations
if (iteration % 2 == 0)
for (var l = 1; l <= Size.x; l++)
GreedySweep_Layer(l);
else
for (var l = Size.x; l >= 1; l--)
GreedySweep_Layer(l);
// count number of crossings after sweep
var after = Crossings();
Log.Debug($"GreedySweep: {before} -> {after}");
Profiler.End();
// return progress
return after < before;
}
private void GreedySweep_Layer(int l)
{
// The objective here is twofold;
// 1: Swap nodes to reduce the number of crossings
// 2: Swap nodes so that inner edges (edges between dummies)
// avoid crossings at all costs.
//
// If I'm reasoning this out right, both objectives should be served by
// minimizing the amount of crossings between each pair of nodes.
var crossings = Crossings(l);
if (crossings == 0)
return;
var layer = Layer(l, true);
for (var i = 0; i < layer.Count - 1; i++)
for (var j = i + 1; j < layer.Count; j++)
{
// swap, then count crossings again. If lower, leave it. If higher, revert.
Swap(layer[i], layer[j]);
var candidateCrossings = Crossings(l);
if (candidateCrossings < crossings)
// update current crossings
crossings = candidateCrossings;
else
// revert change
Swap(layer[j], layer[i]);
}
}
private void Swap(Node A, Node B)
{
if (A.X != B.X)
throw new Exception("Can't swap nodes on different layers");
// swap Y positions of adjacent nodes
var tmp = A.Y;
A.Y = B.Y;
B.Y = tmp;
}
private bool BarymetricSweep(int iteration)
{
Profiler.Start("iteration " + iteration);
// count number of crossings before sweep
var before = Crossings();
// do up/down sweep on alternating iterations
if (iteration % 2 == 0)
for (var i = 2; i <= Size.x; i++)
BarymetricSweep_Layer(i, true);
else
for (var i = Size.x - 1; i > 0; i--)
BarymetricSweep_Layer(i, false);
// count number of crossings after sweep
var after = Crossings();
// did we make progress? please?
Log.Debug(
$"BarymetricSweep {iteration} ({(iteration % 2 == 0 ? "left" : "right")}): {before} -> {after}");
Profiler.End();
return after < before;
}
private void BarymetricSweep_Layer(int layer, bool left)
{
var means = Layer(layer)
.ToDictionary(n => n, n => GetBarycentre(n, left ? n.InNodes : n.OutNodes))
.OrderBy(n => n.Value);
// create groups of nodes at similar means
var cur = float.MinValue;
var groups = new Dictionary<float, List<Node>>();
foreach (var mean in means)
{
if (Math.Abs(mean.Value - cur) > Epsilon)
{
cur = mean.Value;
groups[cur] = new List<Node>();
}
groups[cur].Add(mean.Key);
}
// position nodes as close to their desired mean as possible
var Y = 1;
foreach (var group in groups)
{
var mean = group.Key;
var N = group.Value.Count;
Y = (int) Mathf.Max(Y, mean - (N - 1) / 2);
foreach (var node in group.Value)
node.Y = Y++;
}
}
private float GetBarycentre(Node node, List<Node> neighbours)
{
if (neighbours.NullOrEmpty())
return node.Yf;
return neighbours.Sum(n => n.Yf) / neighbours.Count;
}
private int Crossings()
{
var crossings = 0;
for (var layer = 1; layer < Size.x; layer++) crossings += Crossings(layer, true);
return crossings;
}
private float EdgeLength()
{
var length = 0f;
for (var layer = 1; layer < Size.x; layer++) length += EdgeLength(layer, true);
return length;
}
private int Crossings(int layer)
{
if (layer == 0)
return Crossings(layer, false);
if (layer == Size.x)
return Crossings(layer, true);
return Crossings(layer, true) + Crossings(layer, false);
}
private float EdgeLength(int layer)
{
if (layer == 0)
return EdgeLength(layer, false);
if (layer == Size.x)
return EdgeLength(layer, true);
return EdgeLength(layer, true) *
EdgeLength(layer, false); // multply to favor moving nodes closer to one endpoint
}
private int Crossings(int layer, bool @in)
{
// get in/out edges for layer
var edges = Layer(layer)
.SelectMany(n => @in ? n.InEdges : n.OutEdges)
.OrderBy(e => e.In.Y)
.ThenBy(e => e.Out.Y)
.ToList();
if (edges.Count < 2)
return 0;
// count number of inversions
var inversions = 0;
for (var i = 0; i < edges.Count - 1; i++)
for (var j = i + 1; j < edges.Count; j++)
if (edges[j].Out.Y < edges[i].Out.Y)
inversions++;
return inversions;
}
private float EdgeLength(int layer, bool @in)
{
// get in/out edges for layer
var edges = Layer(layer)
.SelectMany(n => @in ? n.InEdges : n.OutEdges)
.OrderBy(e => e.In.Y)
.ThenBy(e => e.Out.Y)
.ToList();
if (edges.NullOrEmpty())
return 0f;
return edges.Sum(e => e.Length) * (@in ? 2 : 1);
}
public List<Node> Layer(int depth, bool ordered = false)
{
if (ordered && OrderDirty)
{
_nodes = Nodes.OrderBy(n => n.X).ThenBy(n => n.Y).ToList();
OrderDirty = false;
}
return Nodes.Where(n => n.X == depth).ToList();
}
public List<Node> Row(int Y)
{
return Nodes.Where(n => n.Y == Y).ToList();
}
public new string ToString()
{
var text = new StringBuilder();
for (var l = 1; l <= Nodes.Max(n => n.X); l++)
{
text.AppendLine($"Layer {l}:");
var layer = Layer(l, true);
foreach (var n in layer)
{
text.AppendLine($"\t{n}");
text.AppendLine("\t\tAbove: " +
string.Join(", ", n.InNodes.Select(a => a.ToString()).ToArray()));
text.AppendLine("\t\tBelow: " +
string.Join(", ", n.OutNodes.Select(b => b.ToString()).ToArray()));
}
}
return text.ToString();
}
public void DebugStatus()
{
Log.Message("duplicated positions:\n " +
string.Join(
"\n",
Nodes.Where(n => Nodes.Any(n2 => n != n2 && n.X == n2.X && n.Y == n2.Y))
.Select(n => n.X + ", " + n.Y + ": " + n.Label).ToArray()));
Log.Message("out-of-bounds nodes:\n" +
string.Join(
"\n", Nodes.Where(n => n.X < 1 || n.Y < 1).Select(n => n.ToString()).ToArray()));
Log.Trace(ToString());
}
}
} | 36.443697 | 206 | 0.468456 | [
"MIT"
] | BaalEvan/ResearchTree | Source/Graph/Tree.cs | 43,368 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MHWWeaponUsage
{
public static class TaskExtensions
{
public static async void Forget(this Task task, Action<Exception> onError = null)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
try
{
if (ExecutionContext.IsFlowSuppressed() == false)
ExecutionContext.SuppressFlow();
await task;
}
catch (Exception ex)
{
if (onError != null)
onError(ex);
else
throw;
}
}
}
}
| 23.441176 | 89 | 0.513174 | [
"MIT"
] | TanukiSharp/MHWWeaponUsage | MHWWeaponUsage/TaskExtensions.cs | 799 | C# |
using System;
using System.Collections;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
namespace Bunit
{
public partial class TestServiceProviderTest
{
private class DummyService { }
private class AnotherDummyService { }
private class OneMoreDummyService { }
[Fact(DisplayName = "Provider initialized without a service collection has zero services by default")]
public void Test001()
{
using var sut = new TestServiceProvider();
sut.Count.ShouldBe(0);
}
[Fact(DisplayName = "Provider initialized with a service collection has the services form the provided collection")]
public void Test002()
{
var services = new ServiceCollection();
services.AddSingleton(new DummyService());
using var sut = new TestServiceProvider(services);
sut.Count.ShouldBe(1);
sut[0].ServiceType.ShouldBe(typeof(DummyService));
}
[Fact(DisplayName = "Services can be registered in the provider like a normal service collection")]
public void Test010()
{
using var sut = new TestServiceProvider();
sut.Add(new ServiceDescriptor(typeof(DummyService), new DummyService()));
sut.Insert(0, new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService()));
sut[1] = new ServiceDescriptor(typeof(DummyService), new DummyService());
sut.Count.ShouldBe(2);
sut[0].ServiceType.ShouldBe(typeof(AnotherDummyService));
sut[1].ServiceType.ShouldBe(typeof(DummyService));
}
[Fact(DisplayName = "Services can be removed in the provider like a normal service collection")]
public void Test011()
{
using var sut = new TestServiceProvider();
var descriptor = new ServiceDescriptor(typeof(DummyService), new DummyService());
var anotherDescriptor = new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService());
var oneMoreDescriptor = new ServiceDescriptor(typeof(OneMoreDummyService), new OneMoreDummyService());
sut.Add(descriptor);
sut.Add(anotherDescriptor);
sut.Add(oneMoreDescriptor);
sut.Remove(descriptor);
sut.Count.ShouldBe(2);
sut.RemoveAt(1);
sut.Count.ShouldBe(1);
sut.Clear();
sut.ShouldBeEmpty();
}
[Fact(DisplayName = "Misc collection methods works as expected")]
public void Test012()
{
using var sut = new TestServiceProvider();
var descriptor = new ServiceDescriptor(typeof(DummyService), new DummyService());
var copyToTarget = new ServiceDescriptor[1];
sut.Add(descriptor);
sut.IndexOf(descriptor).ShouldBe(0);
sut.Contains(descriptor).ShouldBeTrue();
sut.CopyTo(copyToTarget, 0);
copyToTarget[0].ShouldBe(descriptor);
sut.IsReadOnly.ShouldBeFalse();
((IEnumerable)sut).OfType<ServiceDescriptor>().Count().ShouldBe(1);
}
[Fact(DisplayName = "After the first service is requested, " +
"the provider does not allow changes to service collection")]
public void Test013()
{
var descriptor = new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService());
using var sut = new TestServiceProvider();
sut.AddSingleton(new DummyService());
sut.GetService<DummyService>();
// Try adding
Should.Throw<InvalidOperationException>(() => sut.Add(descriptor));
Should.Throw<InvalidOperationException>(() => sut.Insert(0, descriptor));
Should.Throw<InvalidOperationException>(() => sut[0] = descriptor);
// Try removing
Should.Throw<InvalidOperationException>(() => sut.Remove(descriptor));
Should.Throw<InvalidOperationException>(() => sut.RemoveAt(0));
Should.Throw<InvalidOperationException>(() => sut.Clear());
// Verify state
sut.IsProviderInitialized.ShouldBeTrue();
sut.IsReadOnly.ShouldBeTrue();
}
[Fact(DisplayName = "Registered services can be retrieved from the provider")]
public void Test020()
{
using var sut = new TestServiceProvider();
var expected = new DummyService();
sut.AddSingleton(expected);
var actual = sut.GetService<DummyService>();
actual.ShouldBe(expected);
}
}
}
| 31.622047 | 118 | 0.73008 | [
"MIT"
] | dyllew3/bUnit | tests/bunit.core.tests/TestServiceProviderTest.cs | 4,016 | C# |
namespace DependencyInjectionTest
{
public interface ITestInterface
{
string GetPropertyMessage();
}
}
| 15.375 | 36 | 0.691057 | [
"MIT"
] | PeteX/tomatwo-di | test/ITestInterface.cs | 123 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Container for the parameters to the GetActiveNames operation.
/// Returns the names of all active (not deleted) resources.
/// </summary>
public partial class GetActiveNamesRequest : AmazonLightsailRequest
{
private string _pageToken;
/// <summary>
/// Gets and sets the property PageToken.
/// <para>
/// The token to advance to the next page of results from your request.
/// </para>
///
/// <para>
/// To get a page token, perform an initial <code>GetActiveNames</code> request. If your
/// results are paginated, the response will return a next page token that you can specify
/// as the page token in a subsequent request.
/// </para>
/// </summary>
public string PageToken
{
get { return this._pageToken; }
set { this._pageToken = value; }
}
// Check to see if PageToken property is set
internal bool IsSetPageToken()
{
return this._pageToken != null;
}
}
} | 32.6875 | 108 | 0.630497 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/GetActiveNamesRequest.cs | 2,092 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using ArangoDriver.Protocol;
using ArangoDriver.Protocol.Responses;
namespace ArangoDriver.Client
{
public class AIndex<T> where T : class
{
private readonly RequestFactory _requestFactory;
readonly ACollection<T> _collection;
internal AIndex(RequestFactory requestFactory, ACollection<T> collection)
{
_requestFactory = requestFactory;
_collection = collection;
}
#region Actions
public IndexBuilder<T> New(AIndexType type)
{
return new IndexBuilder<T>(_requestFactory, _collection, type);
}
/// <summary>
/// Retrieves specified index.
/// </summary>
/// <exception cref="ArgumentException">Specified id value has invalid format.</exception>
public async Task<AResult<IndexCreateResponse>> Get(string id)
{
if (!Helpers.IsID(id))
{
throw new ArgumentException("Specified id value (" + id + ") has invalid format.");
}
var request = _requestFactory.Create(HttpMethod.Get, ApiBaseUri.Index, "/" + id);
var response = await _collection.Send(request);
var result = new AResult<IndexCreateResponse>(response);
switch (response.StatusCode)
{
case 200:
var body = response.ParseBody<IndexCreateResponse>();
result.Success = (body != null);
result.Value = body;
break;
case 404:
default:
// Arango error
break;
}
return result;
}
/// <summary>
/// Deletes specified index.
/// </summary>
/// <exception cref="ArgumentException">Specified id value has invalid format.</exception>
public async Task<AResult<Dictionary<string, object>>> Delete(string id)
{
if (!Helpers.IsID(id))
{
throw new ArgumentException("Specified id value (" + id + ") has invalid format.");
}
var request = _requestFactory.Create(HttpMethod.Delete, ApiBaseUri.Index, "/" + id);
var response = await _collection.Send(request);
var result = new AResult<Dictionary<string, object>>(response);
switch (response.StatusCode)
{
case 200:
var body = response.ParseBody<Dictionary<string, object>>();
result.Success = (body != null);
result.Value = body;
break;
case 400:
case 404:
default:
// Arango error
break;
}
return result;
}
#endregion
}
}
| 32.285714 | 99 | 0.502212 | [
"MIT"
] | mdm88/ArangoDriver | Client/Client/Indexes/AIndex.cs | 3,166 | C# |
using System.Collections;
using System.Collections.Generic;
using DCL.Huds.QuestsTracker;
using UnityEngine;
namespace DCL.Huds.QuestsTracker
{
public class QuestsNotificationsController : MonoBehaviour
{
internal static float NOTIFICATIONS_SEPARATION { get; set; } = 0.5f;
public static float DEFAULT_NOTIFICATION_DURATION { get; set; } = 2.5f;
internal readonly Queue<IQuestNotification> notificationsQueue = new Queue<IQuestNotification>();
private IQuestNotification currentNotification;
[SerializeField] private GameObject questCompletedPrefab;
[SerializeField] private GameObject rewardObtainedPrefab;
private bool isDestroyed = false;
internal static QuestsNotificationsController Create()
{
QuestsNotificationsController view = Instantiate(Resources.Load<GameObject>("QuestsNotificationsHUD")).GetComponent<QuestsNotificationsController>();
#if UNITY_EDITOR
view.gameObject.name = "_QuestsNotificationsHUDView";
#endif
return view;
}
private void Awake() { StartCoroutine(ProcessSectionsNotificationQueue()); }
public void ShowQuestCompleted(QuestModel quest)
{
var questNotification = Instantiate(questCompletedPrefab, transform).GetComponent<QuestNotification_QuestCompleted>();
questNotification.Populate(quest);
questNotification.gameObject.SetActive(false);
notificationsQueue.Enqueue(questNotification);
}
public void ShowRewardObtained(QuestReward reward)
{
var questNotification = Instantiate(rewardObtainedPrefab, transform).GetComponent<QuestNotification_RewardObtained>();
questNotification.Populate(reward);
questNotification.gameObject.SetActive(false);
notificationsQueue.Enqueue(questNotification);
}
public void SetVisibility(bool visible) { gameObject.SetActive(visible); }
public void Dispose()
{
if (isDestroyed)
return;
Destroy(gameObject);
}
public void ClearAllNotifications()
{
foreach ( var noti in notificationsQueue )
{
noti.Dispose();
}
if ( currentNotification != null )
currentNotification.Dispose();
}
private void OnDestroy()
{
ClearAllNotifications();
isDestroyed = true;
}
private IEnumerator ProcessSectionsNotificationQueue()
{
while (true)
{
if (notificationsQueue.Count > 0)
{
IQuestNotification notification = notificationsQueue.Dequeue();
currentNotification = notification;
notification.Show();
yield return notification.Waiter();
notification.Dispose();
currentNotification = null;
}
yield return WaitForSecondsCache.Get(NOTIFICATIONS_SEPARATION);
}
}
}
} | 34.423913 | 161 | 0.627092 | [
"Apache-2.0"
] | CarlosPolygonalMind/unity-renderer | unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/QuestsTrackerHUD/QuestsNotificationsController.cs | 3,167 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:5b24b3ee1effda8bdae46da30d1200f13d757101e828a0b7ea373c4dd5fb0705
size 72556
| 32.5 | 75 | 0.884615 | [
"MIT"
] | kenx00x/ahhhhhhhhhhhh | ahhhhhhhhhh/Library/PackageCache/com.unity.render-pipelines.high-definition@7.1.8/Editor/ShaderGraph/HDSubShaderUtilities.cs | 130 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Omack.Core.Models
{
public class CurrentGroup
{
public int Id { get; set; }
public string Name { get; set; }
}
}
| 16.923077 | 40 | 0.640909 | [
"MIT"
] | KishorTiwari/OnAirMoneyTrack | Omack.Core/Models/CurrentGroup.cs | 222 | C# |
using DbContextMappingDump.Infra.DataContracts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DbContextMappingDump.Commands
{
// ReSharper disable once ArrangeTypeModifiers
internal partial class DbContextMappingsCommand
{
protected override int Execute(string[] args)
{
var result = CreateExecutor(args).GetContextMappings();
if (_json.HasValue())
{
Reporter.NoColor = false;
Reporter.WriteDataLine("JsonResult:");
ReportJsonResult(result);
Reporter.WriteDataLine("JsonResult Done");
}
else
{
ReportResult(result);
}
return base.Execute(args);
}
private static void ReportJsonResult(DbContextMappings result)
{
Reporter.WriteDataLine("{");
Reporter.WriteDataLine(" \"MappingExtractionSucceeded\": " + Json.Literal(result.MappingExtractionSucceeded) + ",");
Reporter.WriteData(" \"ErrorDetails\": " + Json.Literal(result.ErrorDetails));
if (result.DbContexts.Any())
{
Reporter.WriteDataLine(",");
Reporter.WriteDataLine(" \"DbContexts\": ");
WriteJsonArray(result.DbContexts, false, (dbContext, writeCommaAtEnd, indentation) => WriteDbContextMapping(dbContext, writeCommaAtEnd, indentation), 2);
}
Reporter.WriteDataLine("}");
}
private static void WriteDbContextMapping(DbContextMapping dbContext, bool writeCommaAtEnd, int indentation)
{
Reporter.WriteDataLine("{", indentation);
Reporter.WriteDataLine(" \"DbContextName\": " + Json.Literal(dbContext.DbContextName) + ",", indentation);
Reporter.WriteDataLine(" \"DbContextFullName\": " + Json.Literal(dbContext.DbContextFullName) + ",", indentation);
Reporter.WriteDataLine(" \"MappingExtractionSucceeded\": " + Json.Literal(dbContext.MappingExtractionSucceeded) + ",", indentation);
Reporter.WriteData(" \"ErrorDetails\": " + Json.Literal(dbContext.ErrorDetails), indentation);
Reporter.WriteDataLine(",");
Reporter.WriteDataLine(" \"Entities\": ", indentation);
WriteJsonArray(dbContext.Entities, true, (e, writeCommaAtEnd, indent) => WriteEntityMapping(e, writeCommaAtEnd, indent), indentation + 2);
Reporter.WriteDataLine(" \"Sequences\": ", indentation);
WriteJsonArray(dbContext.Sequences, true, (e, writeCommaAtEnd, indent) => WriteSequenceMapping(e, writeCommaAtEnd, indent), indentation + 2);
Reporter.WriteDataLine(" \"DbFunctions\": ", indentation);
WriteJsonArray(dbContext.DbFunctions, false, (e, writeCommaAtEnd, indent) => WriteDbFunctionMapping(e, writeCommaAtEnd, indent), indentation + 2);
Reporter.WriteData("}", indentation);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",", indentation);
}
else
{
Reporter.WriteDataLine("", indentation);
}
}
static void WriteJsonArray<T>(IEnumerable<T> items, bool writeCommaAtEnd, Action<T, bool, int> itemWriter, int indent)
{
Reporter.WriteDataLine("[", indent);
if (items.Any())
{
var lastItem = items.Last();
foreach (var item in items.Take(items.Count() - 1))
{
itemWriter(item, true, indent + 2);
}
itemWriter(lastItem, false, indent + 2);
}
Reporter.WriteData("]", indent);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",");
}
else
{
Reporter.WriteDataLine("");
}
}
private static void WriteEntityMapping(EntityMapping entity, bool writeCommaAtEnd, int indent)
{
Reporter.WriteDataLine("{", indent);
Reporter.WriteDataLine(" \"EntityName\": " + Json.Literal(entity.EntityName) + ",", indent);
Reporter.WriteDataLine(" \"EntityFullName\": " + Json.Literal(entity.EntityFullName) + ",", indent);
Reporter.WriteDataLine(" \"Schema\": " + Json.Literal(entity.Schema) + ",", indent);
Reporter.WriteDataLine(" \"TableName\": " + Json.Literal(entity.TableName) + ",", indent);
var properties = entity.Properties;
Reporter.WriteDataLine(" \"Properties\": ", indent);
WriteJsonArray(properties, false, (p, writeCommaAtEnd, indentation) => WritePropertyMapping(p, writeCommaAtEnd, indentation), indent + 2);
Reporter.WriteData("}", indent);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",");
}
else
{
Reporter.WriteDataLine("");
}
}
private static void WritePropertyMapping(EntityPropertyMapping prop, bool writeCommaAtEnd, int indentation)
{
Reporter.WriteDataLine("{", indentation);
Reporter.WriteDataLine(" \"PropertyName\": " + Json.Literal(prop.PropertyName) + ",", indentation);
Reporter.WriteDataLine(" \"ColumnName\": " + Json.Literal(prop.ColumnName) + "", indentation);
Reporter.WriteData("}", indentation);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",");
}
else
{
Reporter.WriteDataLine("");
}
}
private static void WriteDbFunctionMapping(DbFunctionMapping dbFunction, bool writeCommaAtEnd, int indentation)
{
Reporter.WriteDataLine("{", indentation);
Reporter.WriteDataLine(" \"Name\": " + Json.Literal(dbFunction.Name) + ",", indentation);
Reporter.WriteDataLine(" \"Schema\": " + Json.Literal(dbFunction.Schema) + ",", indentation);
Reporter.WriteDataLine(" \"MappedMethodFullName\": " + Json.Literal(dbFunction.MappedMethodFullName) + "", indentation);
Reporter.WriteData("}", indentation);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",");
}
else
{
Reporter.WriteDataLine("");
}
}
private static void WriteSequenceMapping(SequencenMapping sequence, bool writeCommaAtEnd, int indentation)
{
Reporter.WriteDataLine("{", indentation);
Reporter.WriteDataLine(" \"Name\": " + Json.Literal(sequence.Name) + ",", indentation);
Reporter.WriteDataLine(" \"Schema\": " + Json.Literal(sequence.Schema) + "", indentation);
Reporter.WriteData("}", indentation);
if (writeCommaAtEnd)
{
Reporter.WriteDataLine(",");
}
else
{
Reporter.WriteDataLine("");
}
}
private static void ReportResult(DbContextMappings result)
{
Reporter.WriteDataLine($"MappingExtractionSucceeded: {result.MappingExtractionSucceeded}");
Reporter.WriteDataLine($"ErrorDetails: {result.ErrorDetails}");
foreach (var dbContext in result.DbContexts)
{
Reporter.WriteDataLine($"-----------------------------{dbContext.DbContextName}-----------------------------------");
Reporter.WriteDataLine($"DbContext: {dbContext.DbContextName}");
Reporter.WriteDataLine($"DbContextFullName: {dbContext.DbContextFullName}");
Reporter.WriteDataLine($"MappingExtractionSucceeded: {dbContext.MappingExtractionSucceeded}");
Reporter.WriteDataLine($"ErrorDetails: {dbContext.ErrorDetails}");
foreach (var mapping in dbContext.Entities)
{
Reporter.WriteDataLine($"\tEntity: {mapping.EntityName} FullName:{mapping.EntityName} Schema: {mapping.Schema} Table: {mapping.TableName}");
foreach (var propMap in mapping.Properties)
{
Reporter.WriteDataLine($"\t\tProp: {propMap.PropertyName} Column: {propMap.ColumnName}");
}
}
Reporter.WriteDataLine("");
Reporter.WriteDataLine("");
}
}
}
}
| 43.641414 | 169 | 0.566485 | [
"MIT"
] | payoneer/EFDbContextMappingsExtraction | src/DbContextMappingDump.EF/Commands/DbContextMappingsCommand.cs | 8,641 | C# |
using System;
using System.IO;
using System.Buffers.Binary;
internal class PNGSizeGrabber
{
internal static bool GetSize(string filePath, out int x, out int y)
{
x =y =0;
FileStream fs =new FileStream(filePath, FileMode.Open, FileAccess.Read);
if(fs == null)
{
return false;
}
BinaryReader br =new BinaryReader(fs);
if(br == null)
{
return false;
}
UInt64 sig =br.ReadUInt64();
if(sig != 0xA1A0A0D474E5089)
{
br.Close();
fs.Close();
return false;
}
UInt32 chunkLen =br.ReadUInt32();
//IHDR chunk
UInt32 ihdr =br.ReadUInt32();
if(ihdr != 0x52444849)
{
br.Close();
fs.Close();
return false;
}
x =br.ReadInt32();
y =br.ReadInt32();
//not sure why these are backwards
x =BinaryPrimitives.ReverseEndianness(x);
y =BinaryPrimitives.ReverseEndianness(y);
br.Close();
fs.Close();
return true;
}
} | 15.732143 | 74 | 0.646992 | [
"MIT"
] | Kharzette/Wally | PNGSizeGrabber.cs | 881 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 30.03.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_002__AS_STR.Multiply.Complete.Double.Single{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Double;
using T_DATA2 =System.Single;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_R504AAB001__param
public static class TestSet_R504AAB001__param
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=1;
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)(vv1*vv1*vv2)=="2.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=1;
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)((vv1*vv1)*vv2)=="2.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
//-----------------------------------------------------------------------
[Test]
public static void Test_003()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=1;
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)(vv1*(vv1*vv2))=="2.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003
};//class TestSet_R504AAB001__param
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_002__AS_STR.Multiply.Complete.Double.Single
| 23.456311 | 137 | 0.522558 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_002__AS_STR/Multiply/Complete/Double/Single/TestSet_R504AAB001__param.cs | 4,834 | C# |
using System;
using System.Reactive;
namespace Octokit.Reactive
{
/// <summary>
/// A client for GitHub's Collaborators on a Repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details.
/// </remarks>
public interface IObservableRepoCollaboratorsClient
{
/// <summary>
/// Gets all the collaborators on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<User> GetAll(string owner, string name);
/// <summary>
/// Gets all the collaborators on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<User> GetAll(long repositoryId);
/// <summary>
/// Gets all the collaborators on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<User> GetAll(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all the collaborators on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="options">Options for changing the API response</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<User> GetAll(long repositoryId, ApiOptions options);
/// <summary>
/// Checks if a user is a collaborator on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">Username of the prospective collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<bool> IsCollaborator(string owner, string name, string user);
/// <summary>
/// Checks if a user is a collaborator on a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#get">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the prospective collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<bool> IsCollaborator(long repositoryId, string user);
/// <summary>
/// Review a user's permission level in a repository
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">Username of the collaborator to check permission for</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<CollaboratorPermission> ReviewPermission(string owner, string name, string user);
/// <summary>
/// Review a user's permission level in a repository
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the collaborator to check permission for</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<CollaboratorPermission> ReviewPermission(long repositoryId, string user);
/// <summary>
/// Adds a new collaborator to the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<Unit> Add(string owner, string name, string user);
/// <summary>
/// Adds a new collaborator to the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<bool> Add(string owner, string name, string user, CollaboratorRequest permission);
/// <summary>
/// Adds a new collaborator to the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<Unit> Add(long repositoryId, string user);
/// <summary>
/// Adds a new collaborator to the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<bool> Add(long repositoryId, string user, CollaboratorRequest permission);
/// <summary>
/// Invites a user as a collaborator to a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">The username of the prospective collaborator</param>
IObservable<RepositoryInvitation> Invite(string owner, string name, string user);
/// <summary>
/// Invites a user as a collaborator to a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">The username of the prospective collaborator</param>
/// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param>
IObservable<RepositoryInvitation> Invite(string owner, string name, string user, CollaboratorRequest permission);
/// <summary>
/// Adds a new collaborator to the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<RepositoryInvitation> Invite(long repositoryId, string user);
/// <summary>
/// Invites a user as a collaborator to a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the new collaborator</param>
/// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<RepositoryInvitation> Invite(long repositoryId, string user, CollaboratorRequest permission);
/// <summary>
/// Deletes a collaborator from the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="user">Username of the removed collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<Unit> Delete(string owner, string name, string user);
/// <summary>
/// Deletes a collaborator from the repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/#remove-collaborator">API documentation</a> for more information.
/// </remarks>
/// <param name="repositoryId">The id of the repository</param>
/// <param name="user">Username of the removed collaborator</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
IObservable<Unit> Delete(long repositoryId, string user);
}
} | 55.21267 | 158 | 0.633011 | [
"MIT"
] | 7enderhead/octokit.net | Octokit.Reactive/Clients/IObservableRepoCollaboratorsClient.cs | 12,204 | C# |
using System.Text;
namespace B18_EX02
{
public class Cell
{
private const int k_LegalNumberOfInput = 2;
private byte m_CellRow;
private byte m_CellCol;
private eSign m_CellSign;
public Cell(byte i_CellRow, byte i_CellCol, eSign i_CellSign)
{
m_CellRow = i_CellRow;
m_CellCol = i_CellCol;
m_CellSign = i_CellSign;
}
public eSign CellSign { get => m_CellSign; set => m_CellSign = value; }
public byte CellRow { get => m_CellRow; set => m_CellRow = value; }
public byte CellCol { get => m_CellCol; set => m_CellCol = value; }
public static bool Parse(string i_Input, out Cell o_ParsedCell)
{
bool isValidInput = false;
o_ParsedCell = null;
if (i_Input.Length == k_LegalNumberOfInput)
{
if (char.IsUpper(i_Input[0]) && char.IsLower(i_Input[1]))
{
o_ParsedCell = new Cell((byte)(i_Input[1] - 'a'), (byte)(i_Input[0] - 'A'), eSign.Empty);
isValidInput = true;
}
}
return isValidInput;
}
public string GetCellStr()
{
StringBuilder cellStr = new StringBuilder();
cellStr.Append((char)(m_CellCol + 'A'));
cellStr.Append((char)(m_CellRow + 'a'));
return cellStr.ToString();
}
}
}
| 28.686275 | 109 | 0.533835 | [
"MIT"
] | Mitelka/English-draughts | B18_EX02/Cell.cs | 1,463 | C# |
using Swtor.Dps.LogParser.Combat;
namespace Swtor.Dps.StatOptimizer.ViewModel
{
public class CombatViewModel
{
public Combat Combat { get; }
public CombatViewModel(Combat combat)
{
Combat = combat;
}
}
}
| 14.733333 | 43 | 0.719457 | [
"Apache-2.0"
] | Vhaerlein/swtor.playground | src/Swtor.Dps.StatOptimizer/ViewModel/CombatViewModel.cs | 223 | C# |
namespace Perpetuum.Zones.PBS
{
public interface IPBSEventHandler
{
void HandlePBSEvent(IPBSObject sender, PBSEventArgs e);
}
} | 18.5 | 63 | 0.702703 | [
"MIT"
] | LoyalServant/PerpetuumServerCore | Perpetuum/Zones/PBS/IPBSEventHandler.cs | 148 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using MySql.Data.MySqlClient;
using Steeltoe.Connector.Services;
using System;
using Xunit;
namespace Steeltoe.Connector.MySql.Test
{
public class MySqlProviderConnectorFactoryTest
{
[Fact]
public void Constructor_ThrowsIfConfigNull()
{
// Arrange
MySqlProviderConnectorOptions config = null;
MySqlServiceInfo si = null;
// Act and Assert
var ex = Assert.Throws<ArgumentNullException>(() => new MySqlProviderConnectorFactory(si, config, typeof(MySqlConnection)));
Assert.Contains(nameof(config), ex.Message);
}
[Fact]
public void Create_ReturnsMySqlConnection()
{
var config = new MySqlProviderConnectorOptions()
{
Server = "localhost",
Port = 3306,
Password = "password",
Username = "username",
Database = "database"
};
var si = new MySqlServiceInfo("MyId", "mysql://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:3306/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355");
var factory = new MySqlProviderConnectorFactory(si, config, typeof(MySqlConnection));
var connection = factory.Create(null);
Assert.NotNull(connection);
}
}
}
| 35.204545 | 153 | 0.62621 | [
"Apache-2.0"
] | Chatina73/steeltoe | src/Connectors/test/ConnectorBase.Test/MySql/MySqlProviderConnectorFactoryTest.cs | 1,551 | C# |
using Letter.IO;
namespace Letter.Kcp
{
public interface IKcpBootstrap : IBootstrap<KcpOptions, IKcpSession, IKcpChannel>
{
void ConfigurationGlobalThread(IKcpScheduler scheduler);
}
} | 22.888889 | 85 | 0.737864 | [
"MIT"
] | gedo4547/letter | src/Letter.Kcp/IKcpBootstrap.cs | 208 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Class of extension rule for Intermediate.Conformance.100705
/// </summary>
[Export(typeof(ExtensionRule))]
public class IntermediateConformance100705 : ConformanceIntermediateExtensionRule
{
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Intermediate.Conformance.100705";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "7.5. SHOULD support $filter on expanded entities (section 11.2.4.2.1)";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string V4SpecificationSection
{
get
{
return "13.1.2";
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Should;
}
}
/// <summary>
/// Verifies the extension rule.
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
List<string> expectedTypes = new List<string>() { "Edm.String", "Edm.Int32", "Edm.Int16", "Edm.Single", "Edm.Double", "Edm.Boolean", "Edm.DateTimeOffset", "Edm.Guid" };
ExtensionRuleResultDetail detail1 = new ExtensionRuleResultDetail(this.Name);
var restrictions = AnnotationsHelper.GetRestrictions(
context.MetadataDocument,
context.VocCapabilities,
new List<Func<string, string, string, List<NormalProperty>, List<NavigProperty>, bool>>() { AnnotationsHelper.GetExpandRestrictions, AnnotationsHelper.GetFilterRestrictions },
null,
NavigationRoughType.CollectionValued);
if (string.IsNullOrEmpty(restrictions.Item1) ||
null == restrictions.Item2 || !restrictions.Item2.Any() ||
null == restrictions.Item3 || !restrictions.Item3.Any())
{
detail1.ErrorMessage = "Cannot find an appropriate entity-set which supports $expand, $filter system query options in the service.";
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
string entitySet = restrictions.Item1;
string navigPropName = string.Empty;
string navigPropType = string.Empty;
foreach (var np in restrictions.Item3)
{
if (NavigationRoughType.CollectionValued == np.NavigationRoughType)
{
navigPropName = np.NavigationPropertyName;
navigPropType = np.NavigationPropertyType;
}
}
string entityType = navigPropType.RemoveCollectionFlag().GetLastSegment();
var tmp = MetadataHelper.GetPropertiesWithSpecifiedTypeFromEntityType(entityType, context.MetadataDocument, expectedTypes);
if (null == tmp && !tmp.Any())
{
detail1.ErrorMessage = "Cannot find an appropriate primitive properties of entity type in the service.";
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
var str = tmp.First().Split(',');
string primitivePropertyName = str[0];
string primitivePropertyType = str[1];
if (string.IsNullOrEmpty(entitySet))
{
detail1.ErrorMessage = "Cannot find an appropriate entity-set which supports $expand system query option.";
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
if (string.IsNullOrEmpty(navigPropName) || string.IsNullOrEmpty(navigPropType))
{
detail1.ErrorMessage = "Cannot get expanded entities because cannot get collection type of navigation property from metadata";
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
if (string.IsNullOrEmpty(primitivePropertyName) || string.IsNullOrEmpty(primitivePropertyType))
{
detail1.ErrorMessage = "Cannot get an appropriate primitive property from navigation properties.";
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
Uri uri = new Uri(string.Format("{0}/{1}?$expand={2}", context.ServiceBaseUri, entitySet, navigPropName));
var response = WebHelper.Get(uri, Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
if (HttpStatusCode.OK != response.StatusCode)
{
passed = false;
detail1.ErrorMessage = JsonParserHelper.GetErrorMessage(response.ResponsePayload);
info = new ExtensionRuleViolationInfo(uri, response.ResponsePayload, detail1);
return passed;
}
JObject feed;
response.ResponsePayload.TryToJObject(out feed);
if (feed != null && JTokenType.Object == feed.Type)
{
var entities = JsonParserHelper.GetEntries(feed);
var navigProp = entities[0][navigPropName] as JArray;
if (navigProp != null && navigProp.Count != 0)
{
string propVal = navigProp[0][primitivePropertyName].ToString();
string compareVal = propVal;
if (primitivePropertyType.Equals("Edm.String"))
{
compareVal = "'" + propVal + "'";
}
string url = string.Format("{0}/{1}?$expand={2}($filter={3} eq {4})", context.ServiceBaseUri, entitySet, navigPropName, primitivePropertyName, compareVal);
var resp = WebHelper.Get(new Uri(url), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
detail1 = new ExtensionRuleResultDetail(this.Name, url, "GET", StringHelper.MergeHeaders(Constants.AcceptHeaderJson, context.RequestHeaders), resp);
if (resp.StatusCode == HttpStatusCode.OK)
{
JObject jObj;
resp.ResponsePayload.TryToJObject(out jObj);
if (jObj != null && JTokenType.Object == jObj.Type)
{
var entries = JsonParserHelper.GetEntries(jObj).ToList();
foreach (var entry in entries)
{
if (entry[navigPropName] != null && ((JArray)entry[navigPropName]).Count == 0)
{
continue;
}
else if (entry[navigPropName] != null && ((JArray)entry[navigPropName]).Count > 0)
{
var temp = entry[navigPropName].ToList()
.FindAll(en => propVal == en[primitivePropertyName].ToString())
.Select(en => en);
if (entry[navigPropName].ToList().Count == temp.Count())
{
passed = true;
}
else
{
passed = false;
detail1.ErrorMessage = string.Format("The service does not execute an accurate result on system query option '$filter' (Actual Value: {0}, Expected Value: {1}).", entry[navigPropName].ToList().Count, temp.Count());
break;
}
}
}
}
}
else
{
passed = false;
detail1.ErrorMessage = "The service does not support system query option '$filter' on expanded entities.";
}
}
}
info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
return passed;
}
}
}
| 43.728814 | 255 | 0.527616 | [
"MIT"
] | OData/ValidationTool | src/CodeRules/Conformance/IntermediateConformance100705.cs | 10,322 | C# |
namespace XmlUnit {
using System.IO;
using System.Text;
using System.Xml.XPath;
public class XPath {
private readonly string _xPathExpression;
public XPath(string anXPathExpression) {
_xPathExpression = anXPathExpression;
}
public bool XPathExists(string forSomeXml) {
return XPathExists(new XmlInput(forSomeXml));
}
public bool XPathExists(XmlInput forInput) {
XPathNodeIterator iterator = GetNodeIterator(forInput);
return (iterator.Count > 0);
}
private XPathNodeIterator GetNodeIterator(XmlInput forXmlInput) {
XPathNavigator xpathNavigator = GetNavigator(forXmlInput);
return xpathNavigator.Select(_xPathExpression);
}
private XPathNavigator GetNavigator(XmlInput forXmlInput) {
XPathDocument xpathDocument =
new XPathDocument(forXmlInput.CreateXmlReader());
return xpathDocument.CreateNavigator();
}
public string EvaluateXPath(string forSomeXml) {
return EvaluateXPath(new XmlInput(forSomeXml));
}
public string EvaluateXPath(XmlInput forXmlInput) {
XPathNavigator xpathNavigator = GetNavigator(forXmlInput);
XPathExpression xPathExpression = xpathNavigator.Compile(_xPathExpression);
if (xPathExpression.ReturnType == XPathResultType.NodeSet) {
return EvaluateXPath(xpathNavigator);
} else {
return xpathNavigator.Evaluate(xPathExpression).ToString();
}
}
private string EvaluateXPath(XPathNavigator forXPathNavigator) {
XPathNodeIterator iterator = forXPathNavigator.Select(_xPathExpression);
StringBuilder stringBuilder = new StringBuilder();
XPathNavigator xpathNavigator;
while (iterator.MoveNext()) {
xpathNavigator = iterator.Current;
stringBuilder.Insert(stringBuilder.Length, xpathNavigator.Value);
}
return stringBuilder.ToString();
}
}
}
| 37.442623 | 87 | 0.601138 | [
"BSD-3-Clause"
] | wallymathieu/XmlUnit | src/csharp/XPath.cs | 2,284 | C# |
using System;
using System.Globalization;
using KlotosLib.StringTools;
namespace KlotosLib.Angles
{
/// <summary>
/// Инкапсулирует один геометрический угол, включая его величину и единицу измерения. Поддерживает угол в рамках одного оборота.
/// Поддерживает геометрические операции над углами. Поддерживает конвертацию угловой величины в разные единицы измерений.
/// Неизменяемый значимый тип.
/// </summary>
/// <remarks>Для сохранения точности величины угла экземпляр содержит её в той единице измерения, в которой экземпляр был создан.
/// Выполняет преобразования в необходимые единицы на лету, не изменяя изначально запомненную единицу измерения.</remarks>
[Serializable()]
public struct GeometricAngle : IEquatable<GeometricAngle>, IComparable<GeometricAngle>, IComparable, ICloneable, IFormattable
{
#region Constants
private const Double _threshold = 0.000001;
private const String _errorMesMuNotInit = "Specified measurement unit is not initialized";
private const String _errorTemplateMuValueUnknown = "Current value '{0}' of the 'measurementUnit' parameter is not supported";
private const String _errorMesInvalidNumber = "Input angle value number is NaN or infinity";
#endregion Constants
#region Fields
/// <summary>
/// Величина угла. Должна быть неотрицательной и не превышать один полный оборот.
/// </summary>
private readonly Double _value;
/// <summary>
/// Единица измерения угла
/// </summary>
private readonly MeasurementUnit _measurementUnit;
#endregion Fields
#region Constructors
private GeometricAngle(GeometricAngle other)
{
this._value = other._value;
this._measurementUnit = other._measurementUnit;
}
private GeometricAngle(Double value, MeasurementUnit measurementUnit)
{
this._value = value;
this._measurementUnit = measurementUnit;
}
#endregion Constructors
#region Private helpers
private static Double NormalizeMeasurementValue(Double inputValue, Double maxValue, Double threshold)
{
if (NumericTools.AreEqual(threshold, inputValue, 0.0))
{
return 0.0;
}
else if (NumericTools.AreEqual(threshold, inputValue, maxValue))
{
return maxValue;
}
else if (NumericTools.AreEqual(threshold, inputValue, -maxValue))
{
return maxValue;
}
else if (inputValue > 0.0 && inputValue < maxValue)
{
return inputValue;
}
else if (inputValue > maxValue)
{
Double remainder = inputValue % maxValue;
if (NumericTools.AreEqual(threshold, remainder, 0.0))
{
return maxValue;
}
else
{
return remainder;
}
}
else if (inputValue < 0 && inputValue > -maxValue) //-maxValue < inputValue < 0
{
return (maxValue + inputValue);
}
else//if(inputValue < -maxValue)
{
return (maxValue + (inputValue % maxValue));
}
}
#endregion Private helpers
#region Static factories
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в указанной единице измерения углов
/// </summary>
/// <param name="inputValue">Величина угла. Если отрицательная или превышает один полный оборот в заданных единицах измерения углов —
/// будет нормализирована.</param>
/// <param name="measurementUnit">Единица измерения углов, в которой указана величина <paramref name="inputValue"/>.</param>
/// <returns></returns>
public static GeometricAngle FromSpecifiedUnit(Double inputValue, MeasurementUnit measurementUnit)
{
if (Double.IsNaN(inputValue) || Double.IsInfinity(inputValue))
{
throw new ArgumentOutOfRangeException("inputValue", inputValue, _errorMesInvalidNumber);
}
if (NumericTools.IsZero(inputValue) && measurementUnit.IsInitialized == false)
{
return new GeometricAngle(0.0, measurementUnit);
}
if (measurementUnit.IsInitialized == false)
{
throw new ArgumentException(_errorMesMuNotInit, "measurementUnit");
}
return new GeometricAngle(NormalizeMeasurementValue(inputValue, measurementUnit.PositionsInOneTurn, _threshold), measurementUnit);
}
/// <summary>
/// Возвращает новый экземпляр угла, имеющий такую величину, как в указанном именованном угле, и в указанной единице измерения углов
/// </summary>
/// <param name="namedAngle">Именованный угол, значение которого будет использовано</param>
/// <param name="measurementUnit">Единица измерения углов, которая будет применена для представления величины именованного угла</param>
/// <returns></returns>
public static GeometricAngle FromNamedAngle(NamedAngles namedAngle, MeasurementUnit measurementUnit)
{
if (Enum.IsDefined(namedAngle.GetType(), namedAngle) == false)
{
throw new System.ComponentModel.InvalidEnumArgumentException("namedAngle", (Int32)namedAngle, namedAngle.GetType());
}
if (measurementUnit.IsInitialized == false)
{
throw new ArgumentException(_errorMesMuNotInit, "measurementUnit");
}
switch (namedAngle)
{
case NamedAngles.Zero:
return new GeometricAngle(0, measurementUnit);
case NamedAngles.HalfQuarter:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(45.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(32.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(0.125, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI / 4.0, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(0.5, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(0.75, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(50.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
case NamedAngles.Right:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(90.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(64.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(0.25, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI / 2.0, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(1.0, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(1.5, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(100.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
case NamedAngles.TripleHalfQuarter:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(135.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(96.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(0.375, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI * 0.75, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(1.5, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(2.25, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(150.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
case NamedAngles.Straight:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(180.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(128.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(0.5, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(2, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(3, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(200.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
case NamedAngles.TripleQuarters:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(270.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(192.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(0.75, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI * 1.5, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(3, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(4.5, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(300.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
case NamedAngles.Full:
if (measurementUnit == MeasurementUnit.Degrees)
{
return new GeometricAngle(360.0, MeasurementUnit.Degrees);
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return new GeometricAngle(256.0, MeasurementUnit.BinaryDegrees);
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return new GeometricAngle(1.0, MeasurementUnit.Turns);
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return new GeometricAngle(Math.PI * 2.0, MeasurementUnit.Radians);
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return new GeometricAngle(4, MeasurementUnit.Quadrants);
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return new GeometricAngle(6, MeasurementUnit.Sextants);
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return new GeometricAngle(400.0, MeasurementUnit.Grads);
}
else
{
throw new InvalidOperationException(String.Format(_errorTemplateMuValueUnknown, measurementUnit.Name));
}
default:
throw new InvalidOperationException(String.Format("Current 'NamedAngles' value ('{0}') is not supported", namedAngle));
}
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в оборотах
/// </summary>
/// <param name="turns"></param>
/// <returns></returns>
public static GeometricAngle FromTurns(Double turns)
{
if (Double.IsNaN(turns) || Double.IsInfinity(turns))
{
throw new ArgumentOutOfRangeException("turns", turns, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(turns, MeasurementUnit.Turns.PositionsInOneTurn, _threshold),
MeasurementUnit.Turns);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в радианах
/// </summary>
/// <param name="radians"></param>
/// <returns></returns>
public static GeometricAngle FromRadians(Double radians)
{
if (Double.IsNaN(radians) || Double.IsInfinity(radians))
{
throw new ArgumentOutOfRangeException("radians", radians, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(radians, MeasurementUnit.Radians.PositionsInOneTurn, _threshold),
MeasurementUnit.Radians);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в градусах
/// </summary>
/// <param name="degrees"></param>
/// <returns></returns>
public static GeometricAngle FromDegrees(Double degrees)
{
if (Double.IsNaN(degrees) || Double.IsInfinity(degrees))
{
throw new ArgumentOutOfRangeException("degrees", degrees, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(degrees, MeasurementUnit.Degrees.PositionsInOneTurn, _threshold),
MeasurementUnit.Degrees);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в двоичных градусах
/// </summary>
/// <param name="binaryDegrees"></param>
/// <returns></returns>
public static GeometricAngle FromBinaryDegrees(Double binaryDegrees)
{
if (Double.IsNaN(binaryDegrees) || Double.IsInfinity(binaryDegrees))
{
throw new ArgumentOutOfRangeException("binaryDegrees", binaryDegrees, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(binaryDegrees, MeasurementUnit.BinaryDegrees.PositionsInOneTurn, _threshold),
MeasurementUnit.BinaryDegrees);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в квадрантах
/// </summary>
/// <param name="quadrants"></param>
/// <returns></returns>
public static GeometricAngle FromQuadrants(Double quadrants)
{
if (Double.IsNaN(quadrants) || Double.IsInfinity(quadrants))
{
throw new ArgumentOutOfRangeException("quadrants", quadrants, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(quadrants, MeasurementUnit.Quadrants.PositionsInOneTurn, _threshold),
MeasurementUnit.Quadrants);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в секстантах
/// </summary>
/// <param name="sextants"></param>
/// <returns></returns>
public static GeometricAngle FromSextants(Double sextants)
{
if (Double.IsNaN(sextants) || Double.IsInfinity(sextants))
{
throw new ArgumentOutOfRangeException("sextants", sextants, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(sextants, MeasurementUnit.Sextants.PositionsInOneTurn, _threshold),
MeasurementUnit.Sextants);
}
/// <summary>
/// Возвращает новый экземпляр угла, заданный указанным значением в градах (градианах, гонах)
/// </summary>
/// <param name="grads"></param>
/// <returns></returns>
public static GeometricAngle FromGrads(Double grads)
{
if (Double.IsNaN(grads) || Double.IsInfinity(grads))
{
throw new ArgumentOutOfRangeException("grads", grads, _errorMesInvalidNumber);
}
return new GeometricAngle(NormalizeMeasurementValue(grads, MeasurementUnit.Grads.PositionsInOneTurn, _threshold),
MeasurementUnit.Grads);
}
/// <summary>
/// Возвращает нулевой угол без величины (угол по умолчанию, он же безразмерный ноль)
/// </summary>
public static readonly GeometricAngle Zero = GeometricAngle.FromSpecifiedUnit(0.0, MeasurementUnit.Uninitialized);
#endregion Static factories
#region Instance properties
/// <summary>
/// Показывает, содержит ли данный угол безразмерный ноль, т.е. является нулевым и при этом без определённой единицы измерения.
/// Получить подобный экземпляр угла можно при помощи поля <see cref="Zero"/> или вызвав пустой конструктор по-умолчанию.
/// </summary>
public Boolean IsUnitlessZero { get { return NumericTools.IsZero(this._value) && this._measurementUnit.IsInitialized == false; } }
/// <summary>
/// Определяет, является ли данный угол нулевым
/// </summary>
public Boolean IsZero { get { return NumericTools.IsZero(this._value); } }
/// <summary>
/// Возвращает единицу измерения данного угла
/// </summary>
public MeasurementUnit Unit {get { return this._measurementUnit; } }
/// <summary>
/// Возвращает величину данного угла
/// </summary>
public Double Value {get { return this._value; }}
/// <summary>
/// Возвращает величину данного угла в оборотах
/// </summary>
public Double InTurns
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Turns, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в радианах
/// </summary>
public Double InRadians
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Radians, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в градусах
/// </summary>
public Double InDegrees
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Degrees, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в двоичных градусах
/// </summary>
public Double InBinaryDegrees
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.BinaryDegrees, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в квадрантах
/// </summary>
public Double InQuadrants
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Quadrants, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в секстантах
/// </summary>
public Double InSextants
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Sextants, this._value);
}
}
}
/// <summary>
/// Возвращает величину данного угла в градах (градианах, гонах)
/// </summary>
public Double InGrads
{
get
{
if (this.IsZero)
{
return this._value;
}
else
{
return MeasurementUnit.ConvertFromTo(this._measurementUnit, MeasurementUnit.Grads, this._value);
}
}
}
/// <summary>
/// Возвращает диапазон, к которому относится данный угол
/// </summary>
public AngleRanges InRange
{
get
{
if (this.IsZero)
{
return AngleRanges.Zero;
}
GeometricAngle right = GeometricAngle.FromNamedAngle(NamedAngles.Right, this._measurementUnit);
if (this._value < right.Value)
{
return AngleRanges.Acute;
}
if (NumericTools.AreEqual(_threshold, this._value, right.Value))
{
return AngleRanges.Right;
}
GeometricAngle straight = GeometricAngle.FromNamedAngle(NamedAngles.Straight, this._measurementUnit);
if (this._value < straight.Value)
{
return AngleRanges.Obtuse;
}
if (NumericTools.AreEqual(_threshold, this._value, straight.Value))
{
return AngleRanges.Straight;
}
GeometricAngle full = GeometricAngle.FromNamedAngle(NamedAngles.Full, this._measurementUnit);
if (this._value < full.Value)
{
return AngleRanges.Reflex;
}
if (NumericTools.AreEqual(_threshold, this._value, full.Value))
{
return AngleRanges.Full;
}
throw new UnreachableCodeException();
}
}
#endregion Instance properties
#region Instance methods
/// <summary>
/// Возвращает величину данного угла в указанных единицах измерения
/// </summary>
/// <param name="measurementUnit"></param>
/// <returns></returns>
public Double GetValueInUnit(MeasurementUnit measurementUnit)
{
if (this.IsZero)
{
return this._value;
}
else if (measurementUnit == MeasurementUnit.Turns)
{
return this.InTurns;
}
else if (measurementUnit == MeasurementUnit.Radians)
{
return this.InRadians;
}
else if (measurementUnit == MeasurementUnit.Degrees)
{
return this.InDegrees;
}
else if (measurementUnit == MeasurementUnit.BinaryDegrees)
{
return this.InBinaryDegrees;
}
else if (measurementUnit == MeasurementUnit.Quadrants)
{
return this.InQuadrants;
}
else if (measurementUnit == MeasurementUnit.Sextants)
{
return this.InSextants;
}
else if (measurementUnit == MeasurementUnit.Grads)
{
return this.InGrads;
}
else
{
throw new ArgumentException(_errorMesMuNotInit, "measurementUnit");
}
}
/// <summary>
/// Возвращает для данного угла дополнительный угол, т.е. такой, сумма которого с текущим равна 90°.
/// Если текущий угол больше 90°, т.е. дополнительный угол не может быть взят, выбрасывает исключение.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public GeometricAngle GetComplementaryAngle()
{
if (this._measurementUnit.IsInitialized == false)
{
return GeometricAngle.FromNamedAngle(NamedAngles.Right, MeasurementUnit.Degrees);
}
GeometricAngle right = GeometricAngle.FromNamedAngle(NamedAngles.Right, this._measurementUnit);
if (this._value > right._value)
{
throw new InvalidOperationException(string.Format(
"Текущий угол равен {0}, что превышает величину прямого угла {1}, и поэтому смежный угол не может быть взят", this, right));
}
return GeometricAngle.FromSpecifiedUnit(right._value - this._value, this._measurementUnit);
}
/// <summary>
/// Возвращает для данного угла смежный угол, т.е. такой, сумма которого с текущим равна 180°.
/// Если текущий угол больше 180°, т.е. смежный угол не может быть взят, выбрасывает исключение.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public GeometricAngle GetSupplementaryAngle()
{
if (this._measurementUnit.IsInitialized == false)
{
return GeometricAngle.FromNamedAngle(NamedAngles.Straight, MeasurementUnit.Degrees);
}
GeometricAngle straight = GeometricAngle.FromNamedAngle(NamedAngles.Straight, this._measurementUnit);
if (this._value > straight._value)
{
throw new InvalidOperationException(string.Format(
"Текущий угол равен {0}, что превышает величину развёрнутого угла {1}, и поэтому смежный угол не может быть взят", this, straight));
}
return GeometricAngle.FromSpecifiedUnit(straight._value - this._value, this._measurementUnit);
}
/// <summary>
/// Возвращает для данного угла сопряженный угол, т.е. такой, сумма которого с текущим равна 360°.
/// Если текущий угол равен 360°, возвращает нулевой угол.
/// </summary>
/// <returns></returns>
public GeometricAngle GetExplementaryAngle()
{
if (this._measurementUnit.IsInitialized == false)
{
return GeometricAngle.FromNamedAngle(NamedAngles.Full, MeasurementUnit.Degrees);
}
GeometricAngle full = GeometricAngle.FromNamedAngle(NamedAngles.Full, this._measurementUnit);
if (this._value > full._value)
{
throw new InvalidOperationException(string.Format(
"Текущий угол равен {0}, что превышает величину полного угла {1}, и поэтому смежный угол не может быть взят", this, full));
}
return GeometricAngle.FromSpecifiedUnit(full._value - this._value, this._measurementUnit);
}
#endregion Instance methods
#region Comparable and Equatable
/// <summary>
/// Определяет, равны ли два указанных угла, вне зависимости от того, в каких единицах измерения углов представлены их величины
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean AreEqual(GeometricAngle first, GeometricAngle second)
{
Boolean firstIsZero = first.IsZero;
Boolean secondIsZero = second.IsZero;
Boolean result;
if (firstIsZero == true && secondIsZero == true)
{
result = true;
}
else if (firstIsZero == true || secondIsZero == true)
{
result = false;
}
else if (first._measurementUnit == second._measurementUnit)
{
result = NumericTools.AreEqual(_threshold, first._value, second._value);
}
else
{
result = NumericTools.AreEqual(_threshold, first._value, second.GetValueInUnit(first._measurementUnit));
}
return result;
}
/// <summary>
/// Определяет, равны ли между собой все указанные углы, вне зависимости от того, в каких единицах измерения углов представлены их величины
/// </summary>
/// <param name="geometricAngles">Набор углов для оценки равенства. Не может быть NULL, пустым или содержать только один угол.</param>
/// <returns></returns>
public static Boolean AreEqual(params GeometricAngle[] geometricAngles)
{
if (geometricAngles == null) { throw new ArgumentNullException("geometricAngles"); }
if (geometricAngles.Length == 0) { throw new ArgumentException("Набор углов не может быть пуст", "geometricAngles"); }
if (geometricAngles.Length == 1) { throw new ArgumentException("Набор углов не может содержать только один угол", "geometricAngles"); }
if (geometricAngles.Length == 2) { return GeometricAngle.AreEqual(geometricAngles[0], geometricAngles[1]); }
for (Int32 firstIndex = 0, secondIndex = firstIndex + 1; secondIndex < geometricAngles.Length; firstIndex++, secondIndex++)
{
if (GeometricAngle.AreEqual(geometricAngles[firstIndex], geometricAngles[secondIndex]) == false)
{ return false; }
}
return true;
}
/// <summary>
/// Сравнивает между собой два угла вне зависимости от того, в каких единицах измерения углов представлены их величины,
/// и определяет, какой из них больше, меньше, или же они равны.
/// </summary>
/// <param name="first">Первый сравниваемый угол</param>
/// <param name="second">Второй сравниваемый угол</param>
/// <returns>'1' - первый угол больше второго; '-1' - первый угол меньше второго; '0' - оба угла равны между собой</returns>
public static Int32 Compare(GeometricAngle first, GeometricAngle second)
{
Boolean firstIsZero = first.IsZero;
Boolean secondIsZero = second.IsZero;
if (firstIsZero == true && secondIsZero == true)
{
return 0;
}
else if (firstIsZero == true && secondIsZero == false)
{
return -1;
}
else if (firstIsZero == false && secondIsZero == true)
{
return 1;
}
else if (first._measurementUnit == second._measurementUnit)
{
return first._value.CompareTo(second._value);
}
else
{
return first._value.CompareTo(second.GetValueInUnit(first._measurementUnit));
}
}
/// <summary>
/// Возвращает хэш-код данного геометрического угла
/// </summary>
/// <returns></returns>
public override Int32 GetHashCode()
{
unchecked
{
Int32 hashCode = this._value.GetHashCode();
hashCode = (hashCode * 397) ^ this._measurementUnit.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Определяет равенство данного экземпляра угла с указанным, предварительно пытаясь привести его к данному типу
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public override Boolean Equals(Object other)
{
if (Object.ReferenceEquals(null, other)) { return false; }
if (other.GetType() != typeof(GeometricAngle)) { return false; }
return GeometricAngle.AreEqual(this, (GeometricAngle)other);
}
/// <summary>
/// Определяет равенство данного экземпляра угла с указанным
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public Boolean Equals(GeometricAngle other)
{
return GeometricAngle.AreEqual(this, other);
}
/// <summary>
/// Сравнивает данный угол с указанным и определяет, какой из них больше, меньше, или же они равны.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public Int32 CompareTo(GeometricAngle other)
{
return GeometricAngle.Compare(this, other);
}
/// <summary>
/// Пытается привести указанный экземпляр неизвестного типа Object к данному типу, а затем
/// сравнивает данный угол с указанным и определяет, какой из них больше, меньше, или же они равны.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public Int32 CompareTo(Object other)
{
if (Object.ReferenceEquals(other, null) == true)
{
throw new ArgumentNullException("other", "Нельзя сравнить угол с NULL");
}
if (other.GetType() != this.GetType())
{
throw new InvalidOperationException("Нельзя сравнить угол с другим типом");
}
return GeometricAngle.Compare(this, (GeometricAngle)other);
}
#endregion Comparable and Equatable
#region Operators
/// <summary>
/// Определяет, равны ли два указанных экземпляра углов между собой
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator ==(GeometricAngle first, GeometricAngle second)
{
return GeometricAngle.AreEqual(first, second);
}
/// <summary>
/// Определяет, не равны ли два указанных экземпляра углов между собой
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator !=(GeometricAngle first, GeometricAngle second)
{
return !GeometricAngle.AreEqual(first, second);
}
/// <summary>
/// Определяет, строго больше ли величина первого угла по сравнению с величиной второго
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator >(GeometricAngle first, GeometricAngle second)
{
return GeometricAngle.Compare(first, second) == 1;
}
/// <summary>
/// Определяет, строго меньше ли величина первого угла по сравнению с величиной второго
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator <(GeometricAngle first, GeometricAngle second)
{
return GeometricAngle.Compare(first, second) == -1;
}
/// <summary>
/// Определяет, больше или равна величина первого угла по сравнению с величиной второго
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator >=(GeometricAngle first, GeometricAngle second)
{
return GeometricAngle.Compare(first, second) >= 0;
}
/// <summary>
/// Определяет, меньше или равна величина первого угла по сравнению с величиной второго
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Boolean operator <=(GeometricAngle first, GeometricAngle second)
{
return GeometricAngle.Compare(first, second) <= 0;
}
/// <summary>
/// Возвращает угол, являющийся суммой указанных двух углов.
/// Если результат сложения величин будет превышать величину полного угла, будет сделан перевод на новый оборот.
/// Единица измерения результирующего угла будет такой, как у первого угла.
/// </summary>
/// <param name="first">Первый слагаемый угол</param>
/// <param name="second">Второй слагаемый угол</param>
/// <example>30° + 30° = 60°; 270° + 180° (= 450° = 360° + 90°) = 90°</example>
/// <returns></returns>
public static GeometricAngle operator +(GeometricAngle first, GeometricAngle second)
{
if (first._measurementUnit == second._measurementUnit)
{
return GeometricAngle.FromSpecifiedUnit(first._value + second._value, first._measurementUnit);
}
return GeometricAngle.FromSpecifiedUnit(first._value + second.GetValueInUnit(first._measurementUnit), first._measurementUnit);
}
/// <summary>
/// Возвращает угол, являющийся разностью уменьшаемого и вычитаемого углов.
/// Если результат вычитания является отрицательным, будет сделан перевод на новый оборот.
/// Единица измерения результирующего угла будет такой, как у первого угла.
/// Не-ассоциативная и антикоммуникативная операция.
/// </summary>
/// <param name="first">Первый уменьшаемый угол</param>
/// <param name="second">Второй вычитаемый угол</param>
/// <example>180° - 270° (= 0° - 90° = 360° - 90°) = 270°; 90° - 270° (= 0° - 180° = 360° - 180°) = 180°</example>
/// <returns></returns>
public static GeometricAngle operator -(GeometricAngle first, GeometricAngle second)
{
if (first._measurementUnit == second._measurementUnit)
{
return GeometricAngle.FromSpecifiedUnit(first._value - second._value, first._measurementUnit);
}
return GeometricAngle.FromSpecifiedUnit(first._value - second.GetValueInUnit(first._measurementUnit), first._measurementUnit);
}
#endregion Operators
#region Cloning
/// <summary>
/// Возвращает глубокую копию текущего экземпляра угла
/// </summary>
/// <returns></returns>
public GeometricAngle Clone()
{
return new GeometricAngle(this);
}
Object ICloneable.Clone()
{
return this.Clone();
}
#endregion Cloning
#region ToString
/// <summary>
/// Возвращает строковое представление величины и единицы измерения данного угла
/// </summary>
/// <returns></returns>
public override String ToString()
{
return String.Format("{0} {1}", this._value.ToString(System.Globalization.CultureInfo.InvariantCulture), this._measurementUnit.ToString());
}
/// <summary>
/// Возвращает строковое представление величины и единицы измерения данного угла
/// с использованием указанного формата и сведений об особенностях форматирования
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public String ToString(String format, IFormatProvider formatProvider)
{
return String.Format("{0} {1}", this._value.ToString(format, formatProvider), this._measurementUnit.ToString());
}
#endregion ToString
#region Parsing
/// <summary>
/// Пытается распарсить входную строку как геометрический угол с учётом указанных сведений о форматировании числа
/// и возвращает его в случае успешного парсинга
/// </summary>
/// <param name="input">Входная строка, которая предположительно содержит один геометрический угол</param>
/// <param name="provider">Сведения о форматировании числа, представляющего величину угла</param>
/// <param name="result">Распарсенный угол в случае успешного парсинга или безразмерный ноль в случае неуспешного</param>
/// <returns>Результат операции парсинга</returns>
public static Boolean TryParse(String input, IFormatProvider provider, out GeometricAngle result)
{
result = GeometricAngle.Zero;
if (input.HasAlphaNumericChars() == false)
{
return false;
}
String temp = input.Trim();
String number = null;
String unit = null;
for (Int32 i = 0; i < temp.Length; i++)
{
Char c = temp[i];
if (Char.IsWhiteSpace(c))
{
number = temp.Substring(0, i);
unit = temp.Substring(i + 1);
break;
}
if (Char.IsLetter(c) || c == '°')
{
number = temp.Substring(0, i);
unit = temp.Substring(i);
break;
}
}
if (unit.IsStringNullEmptyWs() || number.IsStringNullEmptyWs())
{
return false;
}
MeasurementUnit parsedUnit;
Boolean unitParsingResult = MeasurementUnit.TryParse(unit, out parsedUnit);
if (unitParsingResult == false)
{
return false;
}
Double parsedNumber;
Boolean numberParsingResult = Double
.TryParse(number, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, provider, out parsedNumber);
if (numberParsingResult == false)
{
return false;
}
result = FromSpecifiedUnit(parsedNumber, parsedUnit);
return true;
}
/// <summary>
/// Пытается распарсить входную строку как геометрический угол и возвращает его в случае успешного парсинга
/// </summary>
/// <param name="input">Входная строка, которая предположительно содержит один геометрический угол</param>
/// <param name="result">Распарсенный угол в случае успешного парсинга или безразмерный ноль в случае неуспешного</param>
/// <returns>Результат операции парсинга</returns>
public static Boolean TryParse(String input, out GeometricAngle result)
{
return TryParse(input, CultureInfo.InvariantCulture, out result);
}
#endregion Parsing
}
} | 42.254011 | 152 | 0.548925 | [
"MIT"
] | Klotos/KlotosLib | KlotosLib/Angles/GeometricAngle.cs | 53,131 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the mediaconnect-2018-11-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.MediaConnect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteFlow operation
/// </summary>
public class DeleteFlowResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteFlowResponse response = new DeleteFlowResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("flowArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.FlowArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Status = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException"))
{
return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException"))
{
return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonMediaConnectException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteFlowResponseUnmarshaller _instance = new DeleteFlowResponseUnmarshaller();
internal static DeleteFlowResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteFlowResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.551471 | 196 | 0.613874 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/MediaConnect/Generated/Model/Internal/MarshallTransformations/DeleteFlowResponseUnmarshaller.cs | 5,651 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace LinkyLink
{
public static partial class LinkOperations
{
[FunctionName(nameof(UpdateList))]
public static async Task<IActionResult> UpdateList(
[HttpTrigger(AuthorizationLevel.Function, "PATCH", Route = "links/{vanityUrl}")] HttpRequest req,
[CosmosDB(
databaseName: "linkylinkdb",
collectionName: "linkbundles",
ConnectionStringSetting = "LinkLinkConnection",
SqlQuery = "SELECT * FROM linkbundles lb WHERE LOWER(lb.vanityUrl) = LOWER({vanityUrl})"
)] IEnumerable<LinkBundle> documents,
[CosmosDB(ConnectionStringSetting = "LinkLinkConnection")] IDocumentClient docClient,
string vanityUrl,
ILogger log)
{
string handle = GetTwitterHandle(req);
if (string.IsNullOrEmpty(handle)) return new UnauthorizedResult();
if (!documents.Any())
{
log.LogInformation($"Bundle for {vanityUrl} not found.");
return new NotFoundResult();
}
try
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
if (string.IsNullOrEmpty(requestBody))
{
log.LogError("Request body is empty.");
return new BadRequestResult();
}
JsonPatchDocument<LinkBundle> patchDocument = JsonConvert.DeserializeObject<JsonPatchDocument<LinkBundle>>(requestBody);
if (!patchDocument.Operations.Any())
{
log.LogError("Request body contained no operations.");
return new NoContentResult();
}
LinkBundle bundle = documents.Single();
patchDocument.ApplyTo(bundle);
Uri collUri = UriFactory.CreateDocumentCollectionUri("linkylinkdb", "linkbundles");
RequestOptions reqOptions = new RequestOptions { PartitionKey = new PartitionKey(vanityUrl) };
await docClient.UpsertDocumentAsync(collUri, bundle, reqOptions);
}
catch (JsonSerializationException ex)
{
log.LogError(ex, ex.Message);
return new BadRequestResult();
}
catch (Exception ex)
{
log.LogError(ex, ex.Message);
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
return new NoContentResult();
}
}
} | 37.95 | 136 | 0.603096 | [
"MIT"
] | softchris/the-urlist | backend/src/LinkyLink/UpdateList.cs | 3,036 | C# |
using CSharpSpeed;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace InstrumentedLibrary
{
/// <summary>
/// The interpolate cubic bezier1d tests class.
/// </summary>
[DisplayName("Cubic Bezier Interpolate 1D Tests")]
[Description("Find a point on a 1D Cubic Bezier curve.")]
[SourceCodeLocationProvider]
public static class InterpolateBezierCubic1DTests
{
/// <summary>
/// The interpolate cubic bezier1d test.
/// </summary>
/// <returns>The <see cref="List{T}"/>.</returns>
[DisplayName(nameof(InterpolateBezierCubic1DTests))]
public static List<SpeedTester> TestHarness()
{
var trials = 10000;
var tests = new Dictionary<object[], TestCaseResults> {
{ new object[] { 0.5d, 0d, 1d, 2d, 3d }, new TestCaseResults(description: "", trials: trials, expectedReturnValue:1.5d, epsilon: double.Epsilon) },
{ new object[] { 0.5d, 0d, 3d, 6d, 7d }, new TestCaseResults(description: "", trials: trials, expectedReturnValue:4.25d, epsilon: double.Epsilon) },
};
var results = new List<SpeedTester>();
foreach (var method in HelperExtensions.ListStaticMethodsWithAttribute(MethodBase.GetCurrentMethod().DeclaringType, typeof(SourceCodeLocationProviderAttribute)))
{
var methodDescription = ((DescriptionAttribute)method.GetCustomAttribute(typeof(DescriptionAttribute)))?.Description;
results.Add(new SpeedTester(method, methodDescription, tests));
}
return results;
}
/// <summary>
///
/// </summary>
/// <param name="t"></param>
/// <param name="v0"></param>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <param name="v3"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Signature]
public static double CubicBezier(double t, double v0, double v1, double v2, double v3)
=> CubicBezier1(t, v0, v1, v2, v3);
/// <summary>
/// The cubic bezier.
/// </summary>
/// <param name="t">The t.</param>
/// <param name="v0">The v0.</param>
/// <param name="v1">The v1.</param>
/// <param name="v2">The v2.</param>
/// <param name="v3">The v3.</param>
/// <returns>The <see cref="double"/>.</returns>
/// <acknowledgment>
/// http://paulbourke.net/geometry/bezier/index.html
/// </acknowledgment>
[DisplayName("Cubic Bezier Interpolate 1")]
[Description("Simple Cubic Bezier Interpolation.")]
[Acknowledgment("http://paulbourke.net/geometry/bezier/index.html")]
[SourceCodeLocationProvider]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double CubicBezier1(double t, double v0, double v1, double v2, double v3)
{
// The inverse of t.
var ti = 1d - t;
// The inverse of t cubed.
var ti3 = ti * ti * ti;
// The t cubed.
var t3 = t * t * t;
return (ti3 * v0) + (3d * t * ti * ti * v1) + (3d * t * t * ti * v2) + (t3 * v3);
}
/// <summary>
///
/// </summary>
/// <param name="t"></param>
/// <param name="A"></param>
/// <param name="B"></param>
/// <param name="C"></param>
/// <param name="D"></param>
/// <returns></returns>
/// <acknowledgment>
/// https://blog.demofox.org/2015/07/05/the-de-casteljeau-algorithm-for-evaluating-bezier-curves/
/// </acknowledgment>
[DisplayName("Cubic Bezier Interpolate 1")]
[Description("Simple Cubic Bezier Interpolation.")]
[Acknowledgment("https://blog.demofox.org/2015/07/05/the-de-casteljeau-algorithm-for-evaluating-bezier-curves/")]
[SourceCodeLocationProvider]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double BezierCubic(double t, double A, double B, double C, double D)
{
var ABC = InterpolateBezierQuadratic1DTests.BezierQuadratic(t, A, B, C);
var BCD = InterpolateBezierQuadratic1DTests.BezierQuadratic(t, B, C, D);
return InterpolateLinear1DTests.BezierLinear(t, ABC, BCD);
}
/// <summary>
/// The EvalBez method.
/// </summary>
/// <param name="t">The t.</param>
/// <param name="p0">The p0.</param>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <param name="p3">The p3.</param>
/// <returns>The <see cref="double"/>.</returns>
/// <acknowledgment>
/// http://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve
/// http://floris.briolas.nl/floris/2009/10/bounding-box-of-cubic-bezier/
/// http://jsfiddle.net/SalixAlba/QQnvm/4/
/// </acknowledgment>
[DisplayName("Cubic Interpolate EvalBez")]
[Description("Simple Cubic Interpolation.")]
[Acknowledgment("http://stackoverflow.com/questions/24809978/calculating-the-bounding-box-of-cubic-bezier-curve", "http://floris.briolas.nl/floris/2009/10/bounding-box-of-cubic-bezier/", "http://jsfiddle.net/SalixAlba/QQnvm/4/")]
[SourceCodeLocationProvider]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double EvalBez(double t, double p0, double p1, double p2, double p3)
{
return (p0 * (1 - t) * (1 - t) * (1 - t)) + (3 * p1 * t * (1 - t) * (1 - t)) + (3 * p2 * t * t * (1 - t)) + (p3 * t * t * t);
}
}
}
| 43.576642 | 237 | 0.584422 | [
"MIT"
] | Shkyrockett/CSharpSpeed | InstrumentedLibrary/Geometry/Interpolation/Bezier/InterpolateBezierCubic1DTests.cs | 5,972 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Framework
{
public class UIActionStatusMessage
{
#region constructors
/// <summary>
/// default constructor
/// </summary>
public UIActionStatusMessage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UIActionStatusMessage"/> class.
/// </summary>
/// <param name="sourceTypeFullName">Full name of the source type.</param>
/// <param name="senderView">The sender view.</param>
/// <param name="uIAction">The u i action.</param>
/// <param name="uIActionStatus">The u i action status.</param>
public UIActionStatusMessage(
System.String sourceTypeFullName,
System.String senderView,
UIAction uIAction,
UIActionStatus uIActionStatus)
: this(sourceTypeFullName, senderView, uIAction, uIActionStatus, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UIActionStatusMessage"/> class.
/// </summary>
/// <param name="sourceTypeFullName">Full name of the source type.</param>
/// <param name="senderView">The sender view.</param>
/// <param name="uIAction">The u i action.</param>
/// <param name="uIActionStatus">The u i action status.</param>
/// <param name="errorMessage">The error message.</param>
public UIActionStatusMessage(
System.String sourceTypeFullName,
System.String senderView,
UIAction uIAction,
UIActionStatus uIActionStatus,
string errorMessage
)
{
this.ErrorMessage = errorMessage;
this.SourceTypeFullName = sourceTypeFullName;
this.SenderView = senderView;
this.UIAction = uIAction;
this.UIActionStatus = uIActionStatus;
}
#endregion constructors
/// <summary>
/// Gets or sets the full name of the source type.
/// </summary>
/// <value>
/// The full name of the source type.
/// </value>
public string SourceTypeFullName { get; set; }
/// <summary>
/// Gets or sets the sender.
/// </summary>
/// <value>
/// The sender.
/// </value>
public string SenderView { get; set; }
/// <summary>
/// Gets or sets the UI action.
/// </summary>
/// <value>
/// The UI action.
/// </value>
public UIAction UIAction { get; set; }
/// <summary>
/// Gets or sets the UI action status.
/// </summary>
/// <value>
/// The UI action status.
/// </value>
public UIActionStatus UIActionStatus { get; set; }
public string ErrorMessage { get; set; }
#region override string ToString()
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("SourceTypeFullName:{0};SenderView:{1};UIAction:{2};UIActionStatus:{3};ErrorMessage:{4}", this.SourceTypeFullName, this.SenderView, this.UIActionStatus, this.UIActionStatus, this.ErrorMessage);
}
#endregion override string ToString()
}
}
| 32.080357 | 226 | 0.563874 | [
"MIT"
] | ntierontime/Log4Net | Frameworks/Framework/UIActionStatusMessage.cs | 3,593 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Globalization;
using System.Windows.Forms.ButtonInternal;
using System.Windows.Forms.Layout;
using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;
using static Interop;
namespace System.Windows.Forms
{
[DesignTimeVisible(false)]
[Designer("System.Windows.Forms.Design.ToolStripItemDesigner, " + AssemblyRef.SystemDesign)]
[DefaultEvent(nameof(Click))]
[ToolboxItem(false)]
[DefaultProperty(nameof(Text))]
public abstract class ToolStripItem : Component,
IDropTarget,
ISupportOleDropSource,
IArrangedElement,
IKeyboardToolTip
{
#if DEBUG
internal static readonly TraceSwitch MouseDebugging = new TraceSwitch("MouseDebugging", "Debug ToolStripItem mouse debugging code");
#else
internal static readonly TraceSwitch MouseDebugging;
#endif
private Rectangle bounds = Rectangle.Empty;
private PropertyStore propertyStore;
private ToolStripItemAlignment alignment = ToolStripItemAlignment.Left;
private ToolStrip parent = null;
private ToolStrip owner = null;
private ToolStripItemOverflow overflow = ToolStripItemOverflow.AsNeeded;
private ToolStripItemPlacement placement = ToolStripItemPlacement.None;
private ContentAlignment imageAlign = ContentAlignment.MiddleCenter;
private ContentAlignment textAlign = ContentAlignment.MiddleCenter;
private TextImageRelation textImageRelation = TextImageRelation.ImageBeforeText;
private ToolStripItemImageIndexer imageIndexer = null;
private ToolStripItemInternalLayout toolStripItemInternalLayout = null;
private BitVector32 state = new BitVector32();
private string toolTipText = null;
private Color imageTransparentColor = Color.Empty;
private ToolStripItemImageScaling imageScaling = ToolStripItemImageScaling.SizeToFit;
private Size cachedTextSize = Size.Empty;
private static readonly Padding defaultMargin = new Padding(0, 1, 0, 2);
private static readonly Padding defaultStatusStripMargin = new Padding(0, 2, 0, 0);
private Padding scaledDefaultMargin = defaultMargin;
private Padding scaledDefaultStatusStripMargin = defaultStatusStripMargin;
private ToolStripItemDisplayStyle displayStyle = ToolStripItemDisplayStyle.ImageAndText;
private static readonly ArrangedElementCollection EmptyChildCollection = new ArrangedElementCollection();
///
/// Adding a new event?? Make sure you dont need to add to ToolStripControlHost.cs
///
internal static readonly object EventMouseDown = new object();
internal static readonly object EventMouseEnter = new object();
internal static readonly object EventMouseLeave = new object();
internal static readonly object EventMouseHover = new object();
internal static readonly object EventMouseMove = new object();
internal static readonly object EventMouseUp = new object();
internal static readonly object EventMouseWheel = new object();
internal static readonly object EventClick = new object();
internal static readonly object EventDoubleClick = new object();
internal static readonly object EventDragDrop = new object();
internal static readonly object EventDragEnter = new object();
internal static readonly object EventDragLeave = new object();
internal static readonly object EventDragOver = new object();
internal static readonly object EventDisplayStyleChanged = new object();
internal static readonly object EventEnabledChanged = new object();
internal static readonly object EventInternalEnabledChanged = new object();
internal static readonly object EventFontChanged = new object();
internal static readonly object EventForeColorChanged = new object();
internal static readonly object EventBackColorChanged = new object();
internal static readonly object EventGiveFeedback = new object();
internal static readonly object EventQueryContinueDrag = new object();
internal static readonly object EventQueryAccessibilityHelp = new object();
internal static readonly object EventMove = new object();
internal static readonly object EventResize = new object();
internal static readonly object EventLayout = new object();
internal static readonly object EventLocationChanged = new object();
internal static readonly object EventRightToLeft = new object();
internal static readonly object EventVisibleChanged = new object();
internal static readonly object EventAvailableChanged = new object();
internal static readonly object EventOwnerChanged = new object();
internal static readonly object EventPaint = new object();
internal static readonly object EventText = new object();
internal static readonly object EventSelectedChanged = new object();
///
/// Adding a new event?? Make sure you dont need to add to ToolStripControlHost.cs
///
// Property store keys for properties. The property store allocates most efficiently
// in groups of four, so we try to lump properties in groups of four based on how
// likely they are going to be used in a group.
private static readonly int PropName = PropertyStore.CreateKey();
private static readonly int PropText = PropertyStore.CreateKey();
private static readonly int PropBackColor = PropertyStore.CreateKey();
private static readonly int PropForeColor = PropertyStore.CreateKey();
private static readonly int PropImage = PropertyStore.CreateKey();
private static readonly int PropFont = PropertyStore.CreateKey();
private static readonly int PropRightToLeft = PropertyStore.CreateKey();
private static readonly int PropTag = PropertyStore.CreateKey();
private static readonly int PropAccessibility = PropertyStore.CreateKey();
private static readonly int PropAccessibleName = PropertyStore.CreateKey();
private static readonly int PropAccessibleRole = PropertyStore.CreateKey();
private static readonly int PropAccessibleHelpProvider = PropertyStore.CreateKey();
private static readonly int PropAccessibleDefaultActionDescription = PropertyStore.CreateKey();
private static readonly int PropAccessibleDescription = PropertyStore.CreateKey();
private static readonly int PropTextDirection = PropertyStore.CreateKey();
private static readonly int PropMirroredImage = PropertyStore.CreateKey();
private static readonly int PropBackgroundImage = PropertyStore.CreateKey();
private static readonly int PropBackgroundImageLayout = PropertyStore.CreateKey();
private static readonly int PropMergeAction = PropertyStore.CreateKey();
private static readonly int PropMergeIndex = PropertyStore.CreateKey();
private static readonly int stateAllowDrop = BitVector32.CreateMask();
private static readonly int stateVisible = BitVector32.CreateMask(stateAllowDrop);
private static readonly int stateEnabled = BitVector32.CreateMask(stateVisible);
private static readonly int stateMouseDownAndNoDrag = BitVector32.CreateMask(stateEnabled);
private static readonly int stateAutoSize = BitVector32.CreateMask(stateMouseDownAndNoDrag);
private static readonly int statePressed = BitVector32.CreateMask(stateAutoSize);
private static readonly int stateSelected = BitVector32.CreateMask(statePressed);
private static readonly int stateContstructing = BitVector32.CreateMask(stateSelected);
private static readonly int stateDisposed = BitVector32.CreateMask(stateContstructing);
private static readonly int stateCurrentlyAnimatingImage = BitVector32.CreateMask(stateDisposed);
private static readonly int stateDoubleClickEnabled = BitVector32.CreateMask(stateCurrentlyAnimatingImage);
private static readonly int stateAutoToolTip = BitVector32.CreateMask(stateDoubleClickEnabled);
private static readonly int stateSupportsRightClick = BitVector32.CreateMask(stateAutoToolTip);
private static readonly int stateSupportsItemClick = BitVector32.CreateMask(stateSupportsRightClick);
private static readonly int stateRightToLeftAutoMirrorImage = BitVector32.CreateMask(stateSupportsItemClick);
private static readonly int stateInvalidMirroredImage = BitVector32.CreateMask(stateRightToLeftAutoMirrorImage);
private static readonly int stateSupportsSpaceKey = BitVector32.CreateMask(stateInvalidMirroredImage);
private static readonly int stateMouseDownAndUpMustBeInSameItem = BitVector32.CreateMask(stateSupportsSpaceKey);
private static readonly int stateSupportsDisabledHotTracking = BitVector32.CreateMask(stateMouseDownAndUpMustBeInSameItem);
private static readonly int stateUseAmbientMargin = BitVector32.CreateMask(stateSupportsDisabledHotTracking);
private static readonly int stateDisposing = BitVector32.CreateMask(stateUseAmbientMargin);
private long lastClickTime = 0;
private int deviceDpi = DpiHelper.DeviceDpi;
internal Font defaultFont = ToolStripManager.DefaultFont;
/// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItem.ToolStripItem"]/*' />
/// <devdoc>
/// Constructor
/// </summary>
protected ToolStripItem()
{
if (DpiHelper.IsScalingRequirementMet)
{
scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin);
scaledDefaultStatusStripMargin = DpiHelper.LogicalToDeviceUnits(defaultStatusStripMargin);
}
state[stateEnabled | stateAutoSize | stateVisible | stateContstructing | stateSupportsItemClick | stateInvalidMirroredImage | stateMouseDownAndUpMustBeInSameItem | stateUseAmbientMargin] = true;
state[stateAllowDrop | stateMouseDownAndNoDrag | stateSupportsRightClick | statePressed | stateSelected | stateDisposed | stateDoubleClickEnabled | stateRightToLeftAutoMirrorImage | stateSupportsSpaceKey] = false;
SetAmbientMargin();
Size = DefaultSize;
DisplayStyle = DefaultDisplayStyle;
CommonProperties.SetAutoSize(this, true);
state[stateContstructing] = false;
AutoToolTip = DefaultAutoToolTip;
}
protected ToolStripItem(string text, Image image, EventHandler onClick) : this(text, image, onClick, null)
{
}
protected ToolStripItem(string text, Image image, EventHandler onClick, string name) : this()
{
Text = text;
Image = image;
if (onClick != null)
{
Click += onClick;
}
Name = name;
}
/// <summary>
/// The Accessibility Object for this Control
/// </summary>
[
Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.ToolStripItemAccessibilityObjectDescr))
]
public AccessibleObject AccessibilityObject
{
get
{
AccessibleObject accessibleObject = (AccessibleObject)Properties.GetObject(PropAccessibility);
if (accessibleObject == null)
{
accessibleObject = CreateAccessibilityInstance();
Properties.SetObject(PropAccessibility, accessibleObject);
}
return accessibleObject;
}
}
/// <summary>
/// The default action description of the control
/// </summary>
[
SRCategory(nameof(SR.CatAccessibility)),
Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.ToolStripItemAccessibleDefaultActionDescr))
]
public string AccessibleDefaultActionDescription
{
get
{
return (string)Properties.GetObject(PropAccessibleDefaultActionDescription);
}
set
{
Properties.SetObject(PropAccessibleDefaultActionDescription, value);
OnAccessibleDefaultActionDescriptionChanged(EventArgs.Empty);
}
}
/// <summary>
/// The accessible description of the control
/// </summary>
[
SRCategory(nameof(SR.CatAccessibility)),
DefaultValue(null),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemAccessibleDescriptionDescr))
]
public string AccessibleDescription
{
get
{
return (string)Properties.GetObject(PropAccessibleDescription);
}
set
{
Properties.SetObject(PropAccessibleDescription, value);
OnAccessibleDescriptionChanged(EventArgs.Empty);
}
}
/// <summary>
/// The accessible name of the control
/// </summary>
[
SRCategory(nameof(SR.CatAccessibility)),
DefaultValue(null),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemAccessibleNameDescr))
]
public string AccessibleName
{
get
{
return (string)Properties.GetObject(PropAccessibleName);
}
set
{
Properties.SetObject(PropAccessibleName, value);
OnAccessibleNameChanged(EventArgs.Empty);
}
}
/// <summary>
/// The accessible role of the control
/// </summary>
[
SRCategory(nameof(SR.CatAccessibility)),
DefaultValue(AccessibleRole.Default),
SRDescription(nameof(SR.ToolStripItemAccessibleRoleDescr))
]
public AccessibleRole AccessibleRole
{
get
{
int role = Properties.GetInteger(PropAccessibleRole, out bool found);
if (found)
{
return (AccessibleRole)role;
}
else
{
return AccessibleRole.Default;
}
}
set
{
//valid values are 0xffffffff to 0x40
if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AccessibleRole));
}
Properties.SetInteger(PropAccessibleRole, (int)value);
OnAccessibleRoleChanged(EventArgs.Empty);
}
}
/// <summary>
/// Determines if the item aligns towards the beginning or end of the ToolStrip.
/// </summary>
[
DefaultValue(ToolStripItemAlignment.Left),
SRCategory(nameof(SR.CatLayout)),
SRDescription(nameof(SR.ToolStripItemAlignmentDescr))
]
public ToolStripItemAlignment Alignment
{
get
{
return alignment;
}
set
{
//valid values are 0x0 to 0x1
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemAlignment.Left, (int)ToolStripItemAlignment.Right))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemAlignment));
}
if (alignment != value)
{
alignment = value;
if ((ParentInternal != null) && ParentInternal.IsHandleCreated)
{
ParentInternal.PerformLayout();
}
}
}
}
/// <summary>
/// Determines if this item can be dragged.
/// This is EXACTLY like Control.AllowDrop - setting this to true WILL call
/// the droptarget handlers. The ToolStripDropTargetManager is the one that
/// handles the routing of DropTarget events to the ToolStripItem's IDropTarget
/// methods.
/// </summary>
[
SRCategory(nameof(SR.CatDragDrop)),
DefaultValue(false),
SRDescription(nameof(SR.ToolStripItemAllowDropDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public virtual bool AllowDrop
{
get
{
return state[stateAllowDrop];
}
set
{
if (value != state[stateAllowDrop])
{
EnsureParentDropTargetRegistered();
state[stateAllowDrop] = value;
}
}
}
/// <summary>
/// Determines whether we set the ToolStripItem to its preferred size
/// </summary>
[DefaultValue(true)]
[SRCategory(nameof(SR.CatBehavior))]
[RefreshProperties(RefreshProperties.All)]
[Localizable(true)]
[SRDescription(nameof(SR.ToolStripItemAutoSizeDescr))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool AutoSize
{
get
{
return state[stateAutoSize];
}
set
{
if (state[stateAutoSize] != value)
{
state[stateAutoSize] = value;
CommonProperties.SetAutoSize(this, value);
InvalidateItemLayout(PropertyNames.AutoSize);
}
}
}
/// <summary>
/// !!!!This property ONLY works when toolStrip.ShowItemToolTips = true!!!!
/// if AutoToolTip is set to true we use the Text, if false, we use ToolTipText.
///</summary>
[DefaultValue(false)]
[SRDescription(nameof(SR.ToolStripItemAutoToolTipDescr))]
[SRCategory(nameof(SR.CatBehavior))]
public bool AutoToolTip
{
get
{
return state[stateAutoToolTip];
}
set
{
state[stateAutoToolTip] = value;
}
}
/// <summary>
/// as opposed to Visible, which returns whether or not the item and its parent are Visible
/// Available returns whether or not the item will be shown. Setting Available sets Visible and Vice/Versa
///</summary>
[
Browsable(false),
SRDescription(nameof(SR.ToolStripItemAvailableDescr)),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool Available
{
get
{
// MainMenu compat:
// the only real diff is the getter - this returns what the item really thinks,
// as opposed to whether or not the parent is also Visible. Visible behavior is the same
// so that it matches Control behavior (we dont have to do special things for control hosts, etc etc).
return state[stateVisible];
}
set
{
SetVisibleCore(value);
}
}
[
Browsable(false),
SRCategory(nameof(SR.CatPropertyChanged)),
SRDescription(nameof(SR.ToolStripItemOnAvailableChangedDescr))
]
public event EventHandler AvailableChanged
{
add => Events.AddHandler(EventAvailableChanged, value);
remove => Events.RemoveHandler(EventAvailableChanged, value);
}
/// <summary>
/// Gets or sets the image that is displayed on a <see cref='Label'/>.
/// </summary>
[
Localizable(true),
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemImageDescr)),
DefaultValue(null)
]
public virtual Image BackgroundImage
{
get
{
return Properties.GetObject(PropBackgroundImage) as Image;
}
set
{
if (BackgroundImage != value)
{
Properties.SetObject(PropBackgroundImage, value);
Invalidate();
}
}
}
// Every ToolStripItem needs to cache its last/current Parent's DeviceDpi
// for PerMonitorV2 scaling purposes.
internal virtual int DeviceDpi
{
get
{
return deviceDpi;
}
set
{
deviceDpi = value;
}
}
[
SRCategory(nameof(SR.CatAppearance)),
DefaultValue(ImageLayout.Tile),
Localizable(true),
SRDescription(nameof(SR.ControlBackgroundImageLayoutDescr))
]
public virtual ImageLayout BackgroundImageLayout
{
get
{
bool found = Properties.ContainsObject(PropBackgroundImageLayout);
if (!found)
{
return ImageLayout.Tile;
}
else
{
return ((ImageLayout)Properties.GetObject(PropBackgroundImageLayout));
}
}
set
{
if (BackgroundImageLayout != value)
{
//valid values are 0x0 to 0x4
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ImageLayout.None, (int)ImageLayout.Zoom))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ImageLayout));
}
Properties.SetObject(PropBackgroundImageLayout, value);
Invalidate();
}
}
}
/// <summary>
/// The BackColor of the item
/// </summary>
[
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemBackColorDescr))
]
public virtual Color BackColor
{
get
{
Color c = RawBackColor; // inheritedProperties.BackColor
if (!c.IsEmpty)
{
return c;
}
Control p = ParentInternal;
if (p != null)
{
return p.BackColor;
}
return Control.DefaultBackColor;
}
set
{
Color c = BackColor;
if (!value.IsEmpty || Properties.ContainsObject(PropBackColor))
{
Properties.SetColor(PropBackColor, value);
}
if (!c.Equals(BackColor))
{
OnBackColorChanged(EventArgs.Empty);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnBackColorChangedDescr))]
public event EventHandler BackColorChanged
{
add => Events.AddHandler(EventBackColorChanged, value);
remove => Events.RemoveHandler(EventBackColorChanged, value);
}
/// <summary>
/// The bounds of the item
/// </summary>
[Browsable(false)]
public virtual Rectangle Bounds
{
get
{
return bounds;
}
}
// Zero-based rectangle, same concept as ClientRect
internal Rectangle ClientBounds
{
get
{
Rectangle client = bounds;
client.Location = Point.Empty;
return client;
}
}
[Browsable(false)]
public Rectangle ContentRectangle
{
get
{
Rectangle content = LayoutUtils.InflateRect(InternalLayout.ContentRectangle, Padding);
content.Size = LayoutUtils.UnionSizes(Size.Empty, content.Size);
return content;
}
}
/// <summary>
/// Determines whether or not the item can be selected.
/// </summary>
[Browsable(false)]
public virtual bool CanSelect
{
get
{
return true;
}
}
// usually the same as can select, but things like the control box in an MDI window are exceptions
internal virtual bool CanKeyboardSelect
{
get
{
return CanSelect;
}
}
/// <summary>
/// Occurs when the control is clicked.
/// </summary>
[
SRCategory(nameof(SR.CatAction)),
SRDescription(nameof(SR.ToolStripItemOnClickDescr))
]
public event EventHandler Click
{
add => Events.AddHandler(EventClick, value);
remove => Events.RemoveHandler(EventClick, value);
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
DefaultValue(CommonProperties.DefaultAnchor)
]
public AnchorStyles Anchor
{
get
{
// since we dont support DefaultLayout go directly against the CommonProperties
return CommonProperties.xGetAnchor(this);
}
set
{
// flags enum - dont check for validity....
if (value != Anchor)
{
// since we dont support DefaultLayout go directly against the CommonProperties
CommonProperties.xSetAnchor(this, value);
if (ParentInternal != null)
{
LayoutTransaction.DoLayout(this, ParentInternal, PropertyNames.Anchor);
}
}
}
}
/// <summary> This does not show up in the property grid because it only applies to flow and table layouts </summary>
[
Browsable(false),
DefaultValue(CommonProperties.DefaultDock)
]
public DockStyle Dock
{
get
{
// since we dont support DefaultLayout go directly against the CommonProperties
return CommonProperties.xGetDock(this);
}
set
{
//valid values are 0x0 to 0x5
if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DockStyle));
}
if (value != Dock)
{
// since we dont support DefaultLayout go directly against the CommonProperties
CommonProperties.xSetDock(this, value);
if (ParentInternal != null)
{
LayoutTransaction.DoLayout(this, ParentInternal, PropertyNames.Dock);
}
}
}
}
/// <summary>default setting of auto tooltip when this object is created</summary>
protected virtual bool DefaultAutoToolTip
{
get
{
return false;
}
}
/// <summary>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </summary>
protected internal virtual Padding DefaultMargin
{
get
{
if (Owner != null && Owner is StatusStrip)
{
return scaledDefaultStatusStripMargin;
}
else
{
return scaledDefaultMargin;
}
}
}
/// <summary>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </summary>
protected virtual Padding DefaultPadding
{
get
{
return Padding.Empty;
}
}
/// <summary>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected virtual Size DefaultSize
{
get
{
return DpiHelper.IsPerMonitorV2Awareness ?
DpiHelper.LogicalToDeviceUnits(new Size(23, 23), DeviceDpi) :
new Size(23, 23);
}
}
protected virtual ToolStripItemDisplayStyle DefaultDisplayStyle
{
get
{
return ToolStripItemDisplayStyle.ImageAndText;
}
}
/// <summary>
/// specifies the default behavior of these items on ToolStripDropDowns when clicked.
/// </summary>
internal protected virtual bool DismissWhenClicked
{
get
{
return true;
}
}
/// <summary>
/// DisplayStyle specifies whether the image and text are rendered. This is not on the base
/// item class because different derived things will have different enumeration needs.
/// </summary>
[
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemDisplayStyleDescr))
]
public virtual ToolStripItemDisplayStyle DisplayStyle
{
get
{
return displayStyle;
}
set
{
if (displayStyle != value)
{
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemDisplayStyle.None, (int)ToolStripItemDisplayStyle.ImageAndText))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemDisplayStyle));
}
displayStyle = value;
if (!state[stateContstructing])
{
InvalidateItemLayout(PropertyNames.DisplayStyle);
OnDisplayStyleChanged(EventArgs.Empty);
}
}
}
}
/// <summary>
/// Occurs when the display style has changed
/// </summary>
public event EventHandler DisplayStyleChanged
{
add => Events.AddHandler(EventDisplayStyleChanged, value);
remove => Events.RemoveHandler(EventDisplayStyleChanged, value);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
private RightToLeft DefaultRightToLeft
{
get
{
return RightToLeft.Inherit;
}
}
/// <summary>
/// Occurs when the control is double clicked.
/// </summary>
[SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnDoubleClickDescr))]
public event EventHandler DoubleClick
{
add => Events.AddHandler(EventDoubleClick, value);
remove => Events.RemoveHandler(EventDoubleClick, value);
}
[
DefaultValue(false),
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.ToolStripItemDoubleClickedEnabledDescr))
]
public bool DoubleClickEnabled
{
get
{
return state[stateDoubleClickEnabled];
}
set
{
state[stateDoubleClickEnabled] = value;
}
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnDragDropDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event DragEventHandler DragDrop
{
add => Events.AddHandler(EventDragDrop, value);
remove => Events.RemoveHandler(EventDragDrop, value);
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnDragEnterDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event DragEventHandler DragEnter
{
add => Events.AddHandler(EventDragEnter, value);
remove => Events.RemoveHandler(EventDragEnter, value);
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnDragOverDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event DragEventHandler DragOver
{
add => Events.AddHandler(EventDragOver, value);
remove => Events.RemoveHandler(EventDragOver, value);
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnDragLeaveDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event EventHandler DragLeave
{
add => Events.AddHandler(EventDragLeave, value);
remove => Events.RemoveHandler(EventDragLeave, value);
}
/// <summary>
/// ToolStripItem.DropSource
///
/// This represents what we're actually going to drag. If the parent has set AllowItemReorder to true,
/// then the item should call back on the private OnQueryContinueDrag/OnGiveFeedback that is implemented
/// in the parent ToolStrip.
///
/// Else if the parent does not support reordering of items (Parent.AllowItemReorder = false) -
/// then call back on the ToolStripItem's OnQueryContinueDrag/OnGiveFeedback methods.
/// </summary>
private DropSource DropSource
{
get
{
if ((ParentInternal != null) && (ParentInternal.AllowItemReorder) && (ParentInternal.ItemReorderDropSource != null))
{
return new DropSource(ParentInternal.ItemReorderDropSource);
}
return new DropSource(this);
}
}
/// <summary>
/// Occurs when the control is clicked.
/// </summary>
[
SRCategory(nameof(SR.CatBehavior)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemEnabledDescr)),
DefaultValue(true)
]
public virtual bool Enabled
{
get
{
bool parentEnabled = true;
if (Owner != null)
{
parentEnabled = Owner.Enabled;
}
return state[stateEnabled] && parentEnabled;
}
set
{
// flip disabled bit.
if (state[stateEnabled] != value)
{
state[stateEnabled] = value;
if (!state[stateEnabled])
{
bool wasSelected = state[stateSelected];
// clear all the other states.
state[stateSelected | statePressed] = false;
if (wasSelected)
{
KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this);
}
}
OnEnabledChanged(EventArgs.Empty);
Invalidate();
}
OnInternalEnabledChanged(EventArgs.Empty);
}
}
[
SRDescription(nameof(SR.ToolStripItemEnabledChangedDescr))
]
public event EventHandler EnabledChanged
{
add => Events.AddHandler(EventEnabledChanged, value);
remove => Events.RemoveHandler(EventEnabledChanged, value);
}
internal event EventHandler InternalEnabledChanged
{
add => Events.AddHandler(EventInternalEnabledChanged, value);
remove => Events.RemoveHandler(EventInternalEnabledChanged, value);
}
private void EnsureParentDropTargetRegistered()
{
if (ParentInternal != null)
{
ParentInternal.DropTargetManager.EnsureRegistered(this);
}
}
/// <summary>
/// Retrieves the current font for this item. This will be the font used
/// by default for painting and text in the control.
/// </summary>
[
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemForeColorDescr))
]
public virtual Color ForeColor
{
get
{
Color foreColor = Properties.GetColor(PropForeColor);
if (!foreColor.IsEmpty)
{
return foreColor;
}
Control p = ParentInternal;
if (p != null)
{
return p.ForeColor;
}
return Control.DefaultForeColor;
}
set
{
Color c = ForeColor;
if (!value.IsEmpty || Properties.ContainsObject(PropForeColor))
{
Properties.SetColor(PropForeColor, value);
}
if (!c.Equals(ForeColor))
{
OnForeColorChanged(EventArgs.Empty);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnForeColorChangedDescr))]
public event EventHandler ForeColorChanged
{
add => Events.AddHandler(EventForeColorChanged, value);
remove => Events.RemoveHandler(EventForeColorChanged, value);
}
/// <summary>
/// Retrieves the current font for this control. This will be the font used
/// by default for painting and text in the control.
/// </summary>
[
SRCategory(nameof(SR.CatAppearance)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemFontDescr))
]
public virtual Font Font
{
get
{
Font font = (Font)Properties.GetObject(PropFont);
if (font != null)
{
return font;
}
Font f = GetOwnerFont();
if (f != null)
{
return f;
}
return DpiHelper.IsPerMonitorV2Awareness ?
defaultFont :
ToolStripManager.DefaultFont;
}
set
{
Font local = (Font)Properties.GetObject(PropFont);
if ((local != value))
{
Properties.SetObject(PropFont, value);
OnFontChanged(EventArgs.Empty);
}
}
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnGiveFeedbackDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event GiveFeedbackEventHandler GiveFeedback
{
add => Events.AddHandler(EventGiveFeedback, value);
remove => Events.RemoveHandler(EventGiveFeedback, value);
}
/// <summary>
/// The height of this control
/// </summary>
[
SRCategory(nameof(SR.CatLayout)),
Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Height
{
get
{
return Bounds.Height;
}
set
{
Rectangle currentBounds = Bounds;
SetBounds(currentBounds.X, currentBounds.Y, currentBounds.Width, value);
}
}
/// <summary>
/// ToolStripItems do not have children. For perf reasons always return a static empty collection.
/// Consider creating readonly collection.
/// </summary>
ArrangedElementCollection IArrangedElement.Children
{
get
{
return ToolStripItem.EmptyChildCollection;
}
}
/// <summary>
/// Should not be exposed as this returns an unexposed type.
/// </summary>
IArrangedElement IArrangedElement.Container
{
get
{
if (ParentInternal == null)
{
return Owner;
}
return ParentInternal;
}
}
Rectangle IArrangedElement.DisplayRectangle
{
get
{
return Bounds;
}
}
bool IArrangedElement.ParticipatesInLayout
{
get
{
// this can be different than "Visible" property as "Visible" takes into account whether or not you
// are parented and your parent is visible.
return state[stateVisible];
}
}
PropertyStore IArrangedElement.Properties
{
get
{
return Properties;
}
}
// Sets the bounds for an element.
void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified)
{
// in this case the parent is telling us to refresh our bounds - dont
// call PerformLayout
SetBounds(bounds);
}
void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName)
{
return;
}
/// <summary>
/// Gets or sets the alignment of the image on the label control.
/// </summary>
[
DefaultValue(ContentAlignment.MiddleCenter),
Localizable(true),
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemImageAlignDescr))
]
public ContentAlignment ImageAlign
{
get
{
return imageAlign;
}
set
{
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment));
}
if (imageAlign != value)
{
imageAlign = value;
InvalidateItemLayout(PropertyNames.ImageAlign);
}
}
}
/// <summary>
/// Gets or sets the image that is displayed on a <see cref='Label'/>.
/// </summary>
[
Localizable(true),
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemImageDescr))
]
public virtual Image Image
{
get
{
Image image = (Image)Properties.GetObject(PropImage);
if (image == null && (Owner != null) && (Owner.ImageList != null) && ImageIndexer.ActualIndex >= 0)
{
if (ImageIndexer.ActualIndex < Owner.ImageList.Images.Count)
{
// CACHE (by design). If we fetched out of the image list every time it would dramatically hit perf.
image = Owner.ImageList.Images[ImageIndexer.ActualIndex];
state[stateInvalidMirroredImage] = true;
Properties.SetObject(PropImage, image);
return image;
}
}
else
{
return image;
}
return null;
}
set
{
if (Image != value)
{
StopAnimate();
if (value is Bitmap bmp && ImageTransparentColor != Color.Empty)
{
if (bmp.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(bmp))
{
bmp.MakeTransparent(ImageTransparentColor);
}
value = bmp;
}
if (value != null)
{
ImageIndex = -1;
}
Properties.SetObject(PropImage, value);
state[stateInvalidMirroredImage] = true;
Animate();
InvalidateItemLayout(PropertyNames.Image);
}
}
}
[
Localizable(true),
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemImageTransparentColorDescr))
]
public Color ImageTransparentColor
{
get
{
return imageTransparentColor;
}
set
{
if (imageTransparentColor != value)
{
imageTransparentColor = value;
if (Image is Bitmap currentImage && value != Color.Empty)
{
if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage))
{
currentImage.MakeTransparent(imageTransparentColor);
}
}
Invalidate();
}
}
}
/// <summary>
/// Returns the ToolStripItem's currently set image index
/// Here for compat only - this is NOT to be visible at DT.
/// </summary>
[
SRDescription(nameof(SR.ToolStripItemImageIndexDescr)),
Localizable(true),
SRCategory(nameof(SR.CatBehavior)),
RefreshProperties(RefreshProperties.Repaint),
TypeConverter(typeof(NoneExcludedImageIndexConverter)),
Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
Browsable(false),
RelatedImageList("Owner.ImageList")
]
public int ImageIndex
{
get
{
if ((Owner != null) && ImageIndexer.Index != -1 && Owner.ImageList != null && ImageIndexer.Index >= Owner.ImageList.Images.Count)
{
return Owner.ImageList.Images.Count - 1;
}
return ImageIndexer.Index;
}
set
{
if (value < -1)
{
throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1));
}
ImageIndexer.Index = value;
state[stateInvalidMirroredImage] = true;
// Set the Image Property to null
Properties.SetObject(PropImage, null);
InvalidateItemLayout(PropertyNames.ImageIndex);
}
}
internal ToolStripItemImageIndexer ImageIndexer
{
get
{
if (imageIndexer == null)
{
imageIndexer = new ToolStripItemImageIndexer(this);
}
return imageIndexer;
}
}
/// <summary>
/// Returns the ToolStripItem's currently set image index
/// Here for compat only - this is NOT to be visible at DT.
/// </summary>
[
SRDescription(nameof(SR.ToolStripItemImageKeyDescr)),
SRCategory(nameof(SR.CatBehavior)),
Localizable(true),
TypeConverter(typeof(ImageKeyConverter)),
RefreshProperties(RefreshProperties.Repaint),
Editor("System.Windows.Forms.Design.ToolStripImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
Browsable(false),
RelatedImageList("Owner.ImageList")
]
public string ImageKey
{
get
{
return ImageIndexer.Key;
}
set
{
ImageIndexer.Key = value;
state[stateInvalidMirroredImage] = true;
Properties.SetObject(PropImage, null);
InvalidateItemLayout(PropertyNames.ImageKey);
}
}
[
SRCategory(nameof(SR.CatAppearance)),
DefaultValue(ToolStripItemImageScaling.SizeToFit),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemImageScalingDescr))
]
public ToolStripItemImageScaling ImageScaling
{
get
{
return imageScaling;
}
set
{
//valid values are 0x0 to 0x1
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemImageScaling.None, (int)ToolStripItemImageScaling.SizeToFit))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemImageScaling));
}
if (imageScaling != value)
{
imageScaling = value;
InvalidateItemLayout(PropertyNames.ImageScaling);
}
}
}
/// <summary>
/// This object helps determine where the image and text should be drawn.
/// </summary>
internal ToolStripItemInternalLayout InternalLayout
{
get
{
if (toolStripItemInternalLayout == null)
{
toolStripItemInternalLayout = CreateInternalLayout();
}
return toolStripItemInternalLayout;
}
}
internal bool IsForeColorSet
{
get
{
Color color = Properties.GetColor(PropForeColor);
if (!color.IsEmpty)
{
return true;
}
else
{
Control parent = ParentInternal;
if (parent != null)
{
return parent.ShouldSerializeForeColor();
}
}
return false;
}
}
/// <summary>
/// This is used by ToolStrip to pass on the mouseMessages for ActiveDropDown.
/// </summary>
internal bool IsInDesignMode
{
get
{
return DesignMode;
}
}
[Browsable(false)]
public bool IsDisposed
{
get
{
return state[stateDisposed];
}
}
[Browsable(false)]
public bool IsOnDropDown
{
get
{
if (ParentInternal != null)
{
return ParentInternal.IsDropDown;
}
else if (Owner != null && Owner.IsDropDown)
{
return true;
}
return false;
}
}
/// returns whether the item placement is set to overflow.
[Browsable(false)]
public bool IsOnOverflow
{
get
{
return (Placement == ToolStripItemPlacement.Overflow);
}
}
/// <summary>
/// Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing).
/// </summary>
internal virtual bool IsMnemonicsListenerAxSourced
{
get
{
return true;
}
}
/// <summary>
/// Occurs when the location of the ToolStripItem has been updated -- usually by layout by its
/// owner of ToolStrips
/// </summary>
[SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ToolStripItemOnLocationChangedDescr))]
public event EventHandler LocationChanged
{
add => Events.AddHandler(EventLocationChanged, value);
remove => Events.RemoveHandler(EventLocationChanged, value);
}
/// <summary>
/// Specifies the external spacing between this item and any other item or the ToolStrip.
/// </summary>
[
SRDescription(nameof(SR.ToolStripItemMarginDescr)),
SRCategory(nameof(SR.CatLayout))
]
public Padding Margin
{
get { return CommonProperties.GetMargin(this); }
set
{
if (Margin != value)
{
state[stateUseAmbientMargin] = false;
CommonProperties.SetMargin(this, value);
}
}
}
/// <summary>
/// Specifies the merge action when merging two ToolStrip.
/// </summary>
[
SRDescription(nameof(SR.ToolStripMergeActionDescr)),
DefaultValue(MergeAction.Append),
SRCategory(nameof(SR.CatLayout))
]
public MergeAction MergeAction
{
get
{
int action = Properties.GetInteger(PropMergeAction, out bool found);
if (found)
{
return (MergeAction)action;
}
else
{
// default value
return MergeAction.Append;
}
}
set
{
//valid values are 0x0 to 0x4
if (!ClientUtils.IsEnumValid(value, (int)value, (int)MergeAction.Append, (int)MergeAction.MatchOnly))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(MergeAction));
}
Properties.SetInteger(PropMergeAction, (int)value);
}
}
/// <summary>
/// Specifies the merge action when merging two ToolStrip.
/// </summary>
[
SRDescription(nameof(SR.ToolStripMergeIndexDescr)),
DefaultValue(-1),
SRCategory(nameof(SR.CatLayout))
]
public int MergeIndex
{
get
{
int index = Properties.GetInteger(PropMergeIndex, out bool found);
if (found)
{
return index;
}
else
{
// default value
return -1;
}
}
set
{
Properties.SetInteger(PropMergeIndex, value);
}
}
// required for menus
internal bool MouseDownAndUpMustBeInSameItem
{
get { return state[stateMouseDownAndUpMustBeInSameItem]; }
set { state[stateMouseDownAndUpMustBeInSameItem] = value; }
}
/// <summary>
/// Occurs when the mouse pointer is over the control and a mouse button is
/// pressed.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseDownDescr))
]
public event MouseEventHandler MouseDown
{
add => Events.AddHandler(EventMouseDown, value);
remove => Events.RemoveHandler(EventMouseDown, value);
}
/// <summary>
/// Occurs when the mouse pointer enters the control.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseEnterDescr))
]
public event EventHandler MouseEnter
{
add => Events.AddHandler(EventMouseEnter, value);
remove => Events.RemoveHandler(EventMouseEnter, value);
}
/// <summary>
/// Occurs when the mouse pointer leaves the control.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseLeaveDescr))
]
public event EventHandler MouseLeave
{
add => Events.AddHandler(EventMouseLeave, value);
remove => Events.RemoveHandler(EventMouseLeave, value);
}
/// <summary>
/// Occurs when the mouse pointer hovers over the contro.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseHoverDescr))
]
public event EventHandler MouseHover
{
add => Events.AddHandler(EventMouseHover, value);
remove => Events.RemoveHandler(EventMouseHover, value);
}
/// <summary>
/// Occurs when the mouse pointer is moved over the control.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseMoveDescr))
]
public event MouseEventHandler MouseMove
{
add => Events.AddHandler(EventMouseMove, value);
remove => Events.RemoveHandler(EventMouseMove, value);
}
/// <summary>
/// Occurs when the mouse pointer is over the control and a mouse button is released.
/// </summary>
[
SRCategory(nameof(SR.CatMouse)),
SRDescription(nameof(SR.ToolStripItemOnMouseUpDescr))
]
public event MouseEventHandler MouseUp
{
add => Events.AddHandler(EventMouseUp, value);
remove => Events.RemoveHandler(EventMouseUp, value);
}
/// <summary>
/// Name of this control. The designer will set this to the same
/// as the programatic Id "(name)" of the control. The name can be
/// used as a key into the ControlCollection.
/// </summary>
[
Browsable(false),
DefaultValue(null)
]
public string Name
{
get
{
return WindowsFormsUtils.GetComponentName(this, (string)Properties.GetObject(ToolStripItem.PropName));
}
set
{
if (DesignMode) //InDesignMode the Extender property will set it to the right value.
{
return;
}
Properties.SetObject(ToolStripItem.PropName, value);
}
}
/// <summary>
/// The owner of this ToolStripItem. The owner is essentially a backpointer to
/// the ToolStrip who contains this item in it's item collection. Handy for getting
/// to things such as the ImageList, which would be defined on the ToolStrip.
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public ToolStrip Owner
{
get
{
return owner;
}
set
{
if (owner != value)
{
if (owner != null)
{
owner.Items.Remove(this);
}
if (value != null)
{
value.Items.Add(this);
}
}
}
}
/// <summary> returns the "parent" item on the preceeding menu which has spawned this item.
/// e.g. File->Open the OwnerItem of Open is File. </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public ToolStripItem OwnerItem
{
get
{
ToolStripDropDown currentParent = null;
if (ParentInternal != null)
{
currentParent = ParentInternal as ToolStripDropDown;
}
else if (Owner != null)
{
// parent may be null, but we may be "owned" by a collection.
currentParent = Owner as ToolStripDropDown;
}
if (currentParent != null)
{
return currentParent.OwnerItem;
}
return null;
}
}
[
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.ToolStripItemOwnerChangedDescr))
]
public event EventHandler OwnerChanged
{
add => Events.AddHandler(EventOwnerChanged, value);
remove => Events.RemoveHandler(EventOwnerChanged, value);
}
[
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemOnPaintDescr))
]
public event PaintEventHandler Paint
{
add => Events.AddHandler(EventPaint, value);
remove => Events.RemoveHandler(EventPaint, value);
}
/// <summary>
/// The parent of this ToolStripItem. This can be distinct from the owner because
/// the item can fall onto another window (overflow). In this case the overflow
/// would be the parent but the original ToolStrip would be the Owner. The "parent"
/// ToolStrip will be firing things like paint events - where as the "owner" ToolStrip
/// will be containing shared data like image lists. Typically the only one who should
/// set the parent property is the layout manager on the ToolStrip.
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
internal protected ToolStrip Parent
{
get
{
// we decided that there is no "parent" protection for toolstripitems.
// since toolstrip and toolstripitem are tightly coupled.
return ParentInternal;
}
set
{
ParentInternal = value;
}
}
/// <summary>
/// Specifies whether or not the item is glued to the ToolStrip or overflow or
/// can float between the two.
/// </summary>
[
DefaultValue(ToolStripItemOverflow.AsNeeded),
SRDescription(nameof(SR.ToolStripItemOverflowDescr)),
SRCategory(nameof(SR.CatLayout))
]
public ToolStripItemOverflow Overflow
{
get
{
return overflow;
}
set
{
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemOverflow.Never, (int)ToolStripItemOverflow.AsNeeded))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripGripStyle));
}
if (overflow != value)
{
overflow = value;
if (Owner != null)
{
LayoutTransaction.DoLayout(Owner, Owner, "Overflow");
}
}
}
}
/// <summary>
/// Specifies the internal spacing between the contents and the edges of the item
/// </summary>
[
SRDescription(nameof(SR.ToolStripItemPaddingDescr)),
SRCategory(nameof(SR.CatLayout))
]
public virtual Padding Padding
{
get { return CommonProperties.GetPadding(this, DefaultPadding); }
set
{
if (Padding != value)
{
CommonProperties.SetPadding(this, value);
InvalidateItemLayout(PropertyNames.Padding);
}
}
}
/// <summary>
/// This is explicitly a ToolStrip, because only ToolStrips know how to manage ToolStripitems
/// </summary>
internal ToolStrip ParentInternal
{
get
{
return parent;
}
set
{
if (parent != value)
{
ToolStrip oldParent = parent;
parent = value;
OnParentChanged(oldParent, value);
}
}
}
/// <summary>
/// Where the item actually ended up.
/// </summary>
[Browsable(false)]
public ToolStripItemPlacement Placement
{
get
{
return placement;
}
}
internal Size PreferredImageSize
{
get
{
if ((DisplayStyle & ToolStripItemDisplayStyle.Image) != ToolStripItemDisplayStyle.Image)
{
return Size.Empty;
}
Image image = (Image)Properties.GetObject(PropImage);
bool usingImageList = ((Owner != null) && (Owner.ImageList != null) && (ImageIndexer.ActualIndex >= 0));
if (ImageScaling == ToolStripItemImageScaling.SizeToFit)
{
ToolStrip ownerToolStrip = Owner;
if (ownerToolStrip != null && (image != null || usingImageList))
{
return ownerToolStrip.ImageScalingSize;
}
}
Size imageSize = Size.Empty;
if (usingImageList)
{
imageSize = Owner.ImageList.ImageSize;
}
else
{
imageSize = (image == null) ? Size.Empty : image.Size;
}
return imageSize;
}
}
/// <summary>
/// Retrieves our internal property storage object. If you have a property
/// whose value is not always set, you should store it in here to save
/// space.
/// </summary>
internal PropertyStore Properties
{
get
{
if (propertyStore == null)
{
propertyStore = new PropertyStore();
}
return propertyStore;
}
}
/// <summary>
/// Returns true if the state of the item is pushed
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Pressed
{
get
{
return CanSelect && state[statePressed];
}
}
[
SRCategory(nameof(SR.CatDragDrop)),
SRDescription(nameof(SR.ToolStripItemOnQueryContinueDragDescr)),
EditorBrowsable(EditorBrowsableState.Advanced),
Browsable(false)
]
public event QueryContinueDragEventHandler QueryContinueDrag
{
add => Events.AddHandler(EventQueryContinueDrag, value);
remove => Events.RemoveHandler(EventQueryContinueDrag, value);
}
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripItemOnQueryAccessibilityHelpDescr))]
public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp
{
add => Events.AddHandler(EventQueryAccessibilityHelp, value);
remove => Events.RemoveHandler(EventQueryAccessibilityHelp, value);
}
// Returns the value of the backColor field -- no asking the parent with its color is, etc.
internal Color RawBackColor
{
get
{
return Properties.GetColor(PropBackColor);
}
}
internal ToolStripRenderer Renderer
{
get
{
if (Owner != null)
{
return Owner.Renderer;
}
return ParentInternal?.Renderer;
}
}
/// <summary>
/// This is used for international applications where the language
/// is written from RightToLeft. When this property is true,
/// control placement and text will be from right to left.
/// </summary>
[
SRCategory(nameof(SR.CatAppearance)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemRightToLeftDescr))
]
public virtual RightToLeft RightToLeft
{
get
{
int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found);
if (!found)
{
rightToLeft = (int)RightToLeft.Inherit;
}
if (((RightToLeft)rightToLeft) == RightToLeft.Inherit)
{
if (Owner != null)
{
rightToLeft = (int)Owner.RightToLeft;
}
else if (ParentInternal != null)
{
// case for Overflow & Grip
rightToLeft = (int)ParentInternal.RightToLeft;
}
else
{
rightToLeft = (int)DefaultRightToLeft;
}
}
return (RightToLeft)rightToLeft;
}
set
{
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(RightToLeft));
}
RightToLeft oldValue = RightToLeft;
if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit)
{
Properties.SetInteger(PropRightToLeft, (int)value);
}
if (oldValue != RightToLeft)
{
OnRightToLeftChanged(EventArgs.Empty);
}
}
}
///<summary>
/// Mirrors the image when RTL.Yes.
/// Note we do not change what is returned back from the Image property as this would cause problems with serialization.
/// Instead we only change what is painted - there's an internal MirroredImage property which fills in as
/// e.Image in the ToolStripItemImageRenderEventArgs if the item is RTL.Yes and AutoMirrorImage is turned on.
///</summary>
[
DefaultValue(false),
SRCategory(nameof(SR.CatAppearance)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemRightToLeftAutoMirrorImageDescr))
]
public bool RightToLeftAutoMirrorImage
{
get
{
return state[stateRightToLeftAutoMirrorImage];
}
set
{
if (state[stateRightToLeftAutoMirrorImage] != value)
{
state[stateRightToLeftAutoMirrorImage] = value;
Invalidate();
}
}
}
internal Image MirroredImage
{
get
{
if (state[stateInvalidMirroredImage])
{
Image image = Image;
if (image != null)
{
Image mirroredImage = image.Clone() as Image;
mirroredImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
Properties.SetObject(PropMirroredImage, mirroredImage);
state[stateInvalidMirroredImage] = false;
return mirroredImage;
}
else
{
return null;
}
}
return Properties.GetObject(PropMirroredImage) as Image;
}
}
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnRightToLeftChangedDescr))]
public event EventHandler RightToLeftChanged
{
add => Events.AddHandler(EventRightToLeft, value);
remove => Events.RemoveHandler(EventRightToLeft, value);
}
/// <summary>
/// if the item is selected we return true.
///
/// FAQ: Why dont we have a Hot or MouseIsOver property?
/// After going through the scenarios, we've decided NOT to add a separate MouseIsOver or Hot flag to ToolStripItem. The thing to use is 'Selected'.
/// Why? While the selected thing can be different than the moused over item, the selected item is ALWAYS the one you want to paint differently
///
/// Scenario 1: Keyboard select an item then select a different item with the mouse.
/// - Do Alt+F to expand your File menu, keyboard down several items.
/// - Mouse over a different item
/// - Notice how two things are never painted hot at the same time, and how the selection changes from the keyboard selected item to the one selected with the mouse. In this case the selection should move with the mouse selection.
/// - Notice how if you hit enter when the mouse is over it, it executes the item. That's selection.
/// Scenario 2: Put focus into a combo box, then mouse over a different item
/// - Notice how all the other items you mouse over do not change the way they are painted, if you hit enter, that goes to the combobox, rather than executing the current item.
///
/// At first look "MouseIsOver" or "Hot" seems to be the thing people want, but its almost never the desired behavior. A unified selection model is simpler and seems to meet the scenarios.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Selected
{
get
{
return CanSelect && !DesignMode && (state[stateSelected] ||
(ParentInternal != null && ParentInternal.IsSelectionSuspended &&
ParentInternal.LastMouseDownedItem == this));
}
}
internal protected virtual bool ShowKeyboardCues
{
get
{
if (!DesignMode)
{
return ToolStripManager.ShowMenuFocusCues;
}
// default to true.
return true;
}
}
/// <summary>The size of the item</summary>
[
SRCategory(nameof(SR.CatLayout)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemSizeDescr))
]
public virtual Size Size
{
get
{
return Bounds.Size;
}
set
{
Rectangle currentBounds = Bounds;
currentBounds.Size = value;
SetBounds(currentBounds);
}
}
internal bool SupportsRightClick
{
get
{
return state[stateSupportsRightClick];
}
set
{
state[stateSupportsRightClick] = value;
}
}
internal bool SupportsItemClick
{
get
{
return state[stateSupportsItemClick];
}
set
{
state[stateSupportsItemClick] = value;
}
}
internal bool SupportsSpaceKey
{
get
{
return state[stateSupportsSpaceKey];
}
set
{
state[stateSupportsSpaceKey] = value;
}
}
internal bool SupportsDisabledHotTracking
{
get
{
return state[stateSupportsDisabledHotTracking];
}
set
{
state[stateSupportsDisabledHotTracking] = value;
}
}
/// <summary>Summary for Tag</summary>
[DefaultValue(null),
SRCategory(nameof(SR.CatData)),
Localizable(false),
Bindable(true),
SRDescription(nameof(SR.ToolStripItemTagDescr)),
TypeConverter(typeof(StringConverter))
]
public object Tag
{
get
{
if (Properties.ContainsObject(ToolStripItem.PropTag))
{
return propertyStore.GetObject(ToolStripItem.PropTag);
}
return null;
}
set
{
Properties.SetObject(ToolStripItem.PropTag, value);
}
}
/// <summary>The text of the item</summary>
[
DefaultValue(""),
SRCategory(nameof(SR.CatAppearance)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemTextDescr))
]
public virtual string Text
{
get
{
if (Properties.ContainsObject(ToolStripItem.PropText))
{
return (string)Properties.GetObject(ToolStripItem.PropText);
}
return "";
}
set
{
if (value != Text)
{
Properties.SetObject(ToolStripItem.PropText, value);
OnTextChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the alignment of the text on the label control.
/// </summary>
[
DefaultValue(ContentAlignment.MiddleCenter),
Localizable(true),
SRCategory(nameof(SR.CatAppearance)),
SRDescription(nameof(SR.ToolStripItemTextAlignDescr))
]
public virtual ContentAlignment TextAlign
{
get
{
return textAlign;
}
set
{
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment));
}
if (textAlign != value)
{
textAlign = value;
InvalidateItemLayout(PropertyNames.TextAlign);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnTextChangedDescr))]
public event EventHandler TextChanged
{
add => Events.AddHandler(EventText, value);
remove => Events.RemoveHandler(EventText, value);
}
[
SRDescription(nameof(SR.ToolStripTextDirectionDescr)),
SRCategory(nameof(SR.CatAppearance))
]
public virtual ToolStripTextDirection TextDirection
{
get
{
ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit;
if (Properties.ContainsObject(ToolStripItem.PropTextDirection))
{
textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection);
}
if (textDirection == ToolStripTextDirection.Inherit)
{
if (ParentInternal != null)
{
// in the case we're on a ToolStripOverflow
textDirection = ParentInternal.TextDirection;
}
else
{
textDirection = (Owner == null) ? ToolStripTextDirection.Horizontal : Owner.TextDirection;
}
}
return textDirection;
}
set
{
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripTextDirection));
}
Properties.SetObject(ToolStripItem.PropTextDirection, value);
InvalidateItemLayout("TextDirection");
}
}
[DefaultValue(TextImageRelation.ImageBeforeText)]
[Localizable(true)]
[SRDescription(nameof(SR.ToolStripItemTextImageRelationDescr))]
[SRCategory(nameof(SR.CatAppearance))]
public TextImageRelation TextImageRelation
{
get => textImageRelation;
set
{
if (!ClientUtils.IsEnumValid(value, (int)value, (int)TextImageRelation.Overlay, (int)TextImageRelation.TextBeforeImage, 1))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TextImageRelation));
}
if (value != TextImageRelation)
{
textImageRelation = value;
InvalidateItemLayout(PropertyNames.TextImageRelation);
}
}
}
/// <summary>
/// !!!!This property ONLY works when toolStrip.ShowItemToolTips = true!!!!
/// if AutoToolTip is set to true we return the Text as the ToolTipText.
/// </summary>
[SRDescription(nameof(SR.ToolStripItemToolTipTextDescr))]
[SRCategory(nameof(SR.CatBehavior))]
[Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[Localizable(true)]
public string ToolTipText
{
get
{
if (AutoToolTip && string.IsNullOrEmpty(toolTipText))
{
string toolText = Text;
if (WindowsFormsUtils.ContainsMnemonic(toolText))
{
// this shouldnt be called a lot so we can take the perf hit here.
toolText = string.Join("", toolText.Split('&'));
}
return toolText;
}
return toolTipText;
}
set
{
toolTipText = value;
}
}
/// <summary>Whether or not the item is visible</summary>
[
SRCategory(nameof(SR.CatBehavior)),
Localizable(true),
SRDescription(nameof(SR.ToolStripItemVisibleDescr))
]
public bool Visible
{
get
{
return (ParentInternal != null) && (ParentInternal.Visible) && Available;
}
set
{
SetVisibleCore(value);
}
}
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnVisibleChangedDescr))]
public event EventHandler VisibleChanged
{
add => Events.AddHandler(EventVisibleChanged, value);
remove => Events.RemoveHandler(EventVisibleChanged, value);
}
/// <summary>
/// The width of this ToolStripItem.
/// </summary>
[
SRCategory(nameof(SR.CatLayout)),
Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Width
{
get
{
return Bounds.Width;
}
set
{
Rectangle currentBounds = Bounds;
SetBounds(currentBounds.X, currentBounds.Y, value, currentBounds.Height);
}
}
//
// Methods for ToolStripItem
//
internal void AccessibilityNotifyClients(AccessibleEvents accEvent)
{
if (ParentInternal != null)
{
int index = ParentInternal.DisplayedItems.IndexOf(this);
ParentInternal.AccessibilityNotifyClients(accEvent, index);
}
}
private void Animate()
{
Animate(!DesignMode && Visible && Enabled && ParentInternal != null);
}
private void StopAnimate()
{
Animate(false);
}
private void Animate(bool animate)
{
if (animate != state[stateCurrentlyAnimatingImage])
{
if (animate)
{
if (Image != null)
{
ImageAnimator.Animate(Image, new EventHandler(OnAnimationFrameChanged));
state[stateCurrentlyAnimatingImage] = animate;
}
}
else
{
if (Image != null)
{
ImageAnimator.StopAnimate(Image, new EventHandler(OnAnimationFrameChanged));
state[stateCurrentlyAnimatingImage] = animate;
}
}
}
}
internal bool BeginDragForItemReorder()
{
if (Control.ModifierKeys == Keys.Alt)
{
if (ParentInternal.Items.Contains(this) && ParentInternal.AllowItemReorder)
{
// we only drag
ToolStripItem item = this as ToolStripItem;
DoDragDrop(item, DragDropEffects.Move);
return true;
}
}
return false;
}
/// <summary>
/// constructs the new instance of the accessibility object for this ToolStripItem. Subclasses
/// should not call base.CreateAccessibilityObject.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual AccessibleObject CreateAccessibilityInstance()
{
return new ToolStripItemAccessibleObject(this);
}
/// <summary>
/// Creates an instance of the object that defines how image and text
/// gets laid out in the ToolStripItem
/// </summary>
internal virtual ToolStripItemInternalLayout CreateInternalLayout()
{
return new ToolStripItemInternalLayout(this);
}
/// <summary>
/// Disposes this ToolStrip item...
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
state[stateDisposing] = true;
if (Owner != null)
{
StopAnimate();
Debug.Assert(Owner.Items.Contains(this), "How can there be a owner and not be in the collection?");
Owner.Items.Remove(this);
toolStripItemInternalLayout = null;
state[stateDisposed] = true;
}
}
base.Dispose(disposing);
if (disposing)
{
// need to call base() first since the Component.Dispose(_) is listened to by the ComponentChangeService
// which Serializes the object in Undo-Redo transactions.
Properties.SetObject(PropMirroredImage, null);
Properties.SetObject(PropImage, null);
state[stateDisposing] = false;
}
}
internal static long DoubleClickTicks
{
// (DoubleClickTime in ms) * 1,000,000 ns/1ms * 1 Tick / 100ns = XXX in Ticks.
// Therefore: (DoubleClickTime) * 1,000,000/100 = xxx in Ticks.
get { return SystemInformation.DoubleClickTime * 10000; }
}
/// <summary>
/// Begins a drag operation. The allowedEffects determine which
/// drag operations can occur. If the drag operation needs to interop
/// with applications in another process, data should either be
/// a base managed class (String, Bitmap, or Metafile) or some Object
/// that implements System.Runtime.Serialization.ISerializable. data can also be any Object that
/// implements System.Windows.Forms.IDataObject.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects)
{
Ole32.IDropSource dropSource = DropSource;
IComDataObject dataObject = null;
dataObject = data as IComDataObject;
if (dataObject == null)
{
DataObject iwdata = null;
if (data is IDataObject idataObject)
{
iwdata = new DataObject(idataObject);
}
else if (data is ToolStripItem)
{
// it seems that the DataObject does string comparison
// on the type, so you can't ask for GetDataPresent of
// a base type (e.g. ToolStripItem) when you are really
// looking at a ToolStripButton. The alternative is
// to set the format string expressly to a string matching
// the type of ToolStripItem
iwdata = new DataObject();
iwdata.SetData(typeof(ToolStripItem).ToString(), data);
}
else
{
iwdata = new DataObject();
iwdata.SetData(data);
}
dataObject = (IComDataObject)iwdata;
}
HRESULT hr = Ole32.DoDragDrop(dataObject, dropSource, (Ole32.DROPEFFECT)allowedEffects, out Ole32.DROPEFFECT finalEffect);
if (!hr.Succeeded())
{
return DragDropEffects.None;
}
return (DragDropEffects)finalEffect;
}
internal void FireEvent(ToolStripItemEventType met)
{
FireEvent(EventArgs.Empty, met);
}
internal void FireEvent(EventArgs e, ToolStripItemEventType met)
{
switch (met)
{
case ToolStripItemEventType.LocationChanged:
OnLocationChanged(e);
break;
case ToolStripItemEventType.Paint:
HandlePaint(e as PaintEventArgs);
break;
case ToolStripItemEventType.MouseHover:
// disabled toolstrip items should show tooltips.
// we wont raise mouse events though.
if (!Enabled && ParentInternal != null && !string.IsNullOrEmpty(ToolTipText))
{
ParentInternal.UpdateToolTip(this);
}
else
{
FireEventInteractive(e, met);
}
break;
case ToolStripItemEventType.MouseEnter:
HandleMouseEnter(e);
break;
case ToolStripItemEventType.MouseLeave:
// disabled toolstrip items should also clear tooltips.
// we wont raise mouse events though.
if (!Enabled && ParentInternal != null)
{
ParentInternal.UpdateToolTip(null);
}
else
{
HandleMouseLeave(e);
}
break;
case ToolStripItemEventType.MouseMove:
// Disabled items typically dont get mouse move
// but they should be allowed to re-order if the ALT key is pressed
if (!Enabled && ParentInternal != null)
{
BeginDragForItemReorder();
}
else
{
FireEventInteractive(e, met);
}
break;
default:
FireEventInteractive(e, met);
break;
}
}
internal void FireEventInteractive(EventArgs e, ToolStripItemEventType met)
{
if (Enabled)
{
switch (met)
{
case ToolStripItemEventType.MouseMove:
HandleMouseMove(e as MouseEventArgs);
break;
case ToolStripItemEventType.MouseHover:
HandleMouseHover(e as EventArgs);
break;
case ToolStripItemEventType.MouseUp:
HandleMouseUp(e as MouseEventArgs);
break;
case ToolStripItemEventType.MouseDown:
HandleMouseDown(e as MouseEventArgs);
break;
case ToolStripItemEventType.Click:
HandleClick(e);
break;
case ToolStripItemEventType.DoubleClick:
HandleDoubleClick(e);
break;
default:
Debug.Assert(false, "Invalid event type.");
break;
}
}
}
private Font GetOwnerFont()
{
if (Owner != null)
{
return Owner.Font;
}
return null;
}
/// <summary> we dont want a public settable property... and usually owner will work
/// except for things like the overflow button</summary>
public ToolStrip GetCurrentParent()
{
return Parent;
}
internal ToolStripDropDown GetCurrentParentDropDown()
{
if (ParentInternal != null)
{
return ParentInternal as ToolStripDropDown;
}
else
{
return Owner as ToolStripDropDown;
}
}
public virtual Size GetPreferredSize(Size constrainingSize)
{
// Switch Size.Empty to maximum possible values
constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize);
return InternalLayout.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size;
}
internal Size GetTextSize()
{
if (string.IsNullOrEmpty(Text))
{
return Size.Empty;
}
else if (cachedTextSize == Size.Empty)
{
cachedTextSize = TextRenderer.MeasureText(Text, Font);
}
return cachedTextSize;
}
/// <summary>
/// Invalidates the ToolStripItem
/// </summary>
public void Invalidate()
{
if (ParentInternal != null)
{
ParentInternal.Invalidate(Bounds, true);
}
}
/// <summary>
/// invalidates a rectangle within the ToolStripItem's bounds
/// </summary>
public void Invalidate(Rectangle r)
{
// the only value add to this over calling invalidate on the ToolStrip is that
// you can specify the rectangle with coordinates relative to the upper left hand
// corner of the ToolStripItem.
Point rectangleLocation = TranslatePoint(r.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ToolStripCoords);
if (ParentInternal != null)
{
ParentInternal.Invalidate(new Rectangle(rectangleLocation, r.Size), true);
}
}
internal void InvalidateItemLayout(string affectedProperty, bool invalidatePainting)
{
toolStripItemInternalLayout = null;
if (Owner != null)
{
LayoutTransaction.DoLayout(Owner, this, affectedProperty);
}
if (invalidatePainting && Owner != null)
{
Owner.Invalidate();
}
}
internal void InvalidateItemLayout(string affectedProperty)
{
InvalidateItemLayout(affectedProperty, /*invalidatePainting*/true);
}
internal void InvalidateImageListImage()
{
// invalidate the cache.
if (ImageIndexer.ActualIndex >= 0)
{
Properties.SetObject(PropImage, null);
InvalidateItemLayout(PropertyNames.Image);
}
}
internal void InvokePaint()
{
if (ParentInternal != null)
{
ParentInternal.InvokePaintItem(this);
}
}
protected internal virtual bool IsInputKey(Keys keyData)
{
return false;
}
protected internal virtual bool IsInputChar(char charCode)
{
return false;
}
//
// Private handlers which are the equivilant of Control.Wm<Message>
//
private void HandleClick(EventArgs e)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleClick");
try
{
if (!DesignMode)
{
state[statePressed] = true;
}
// force painting w/o using message loop here because it may be quite a long
// time before it gets pumped again.
InvokePaint();
if (SupportsItemClick && Owner != null)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleItemClick");
Owner.HandleItemClick(this);
}
OnClick(e);
if (SupportsItemClick && Owner != null)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleItemClicked");
Owner.HandleItemClicked(this);
}
}
finally
{
state[statePressed] = false;
}
// when we get around to it, paint unpressed.
Invalidate();
}
private void HandleDoubleClick(EventArgs e)
{
OnDoubleClick(e);
}
private void HandlePaint(PaintEventArgs e)
{
Animate();
ImageAnimator.UpdateFrames(Image);
OnPaint(e);
RaisePaintEvent(EventPaint, e);
}
private void HandleMouseEnter(EventArgs e)
{
if (!DesignMode)
{
if (ParentInternal != null
&& ParentInternal.CanHotTrack
&& ParentInternal.ShouldSelectItem())
{
if (Enabled)
{
// calling select can dismiss a child dropdown which would break auto-expansion.
// save off auto expand and restore it.
bool autoExpand = ParentInternal.MenuAutoExpand;
if (ParentInternal.LastMouseDownedItem == this)
{
// Same as Control.MouseButtons == MouseButtons.Left, but slightly more efficient.
if (User32.GetKeyState((int)Keys.LButton) < 0)
{
Push(true);
}
}
Select();
ParentInternal.MenuAutoExpand = autoExpand;
}
else if (SupportsDisabledHotTracking)
{
Select();
}
}
}
KeyboardToolTipStateMachine.Instance.NotifyAboutMouseEnter(this);
if (Enabled)
{
OnMouseEnter(e);
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseEnter");
RaiseEvent(EventMouseEnter, e);
}
}
private void HandleMouseMove(MouseEventArgs mea)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseMove");
if (Enabled && CanSelect && !Selected)
{
if (ParentInternal != null
&& ParentInternal.CanHotTrack
&& ParentInternal.ShouldSelectItem())
{
// this is the case where we got a mouse enter, but ShouldSelectItem
// returned false.
// typically occus when a window first opens - we get a mouse enter on the item
// the cursor is hovering over - but we dont actually want to change selection to it.
Select();
}
}
OnMouseMove(mea);
RaiseMouseEvent(EventMouseMove, mea);
}
private void HandleMouseHover(EventArgs e)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseHover");
OnMouseHover(e);
RaiseEvent(EventMouseHover, e);
}
private void HandleLeave()
{
if (state[stateMouseDownAndNoDrag] || state[statePressed] || state[stateSelected])
{
state[stateMouseDownAndNoDrag | statePressed | stateSelected] = false;
KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this);
Invalidate();
}
}
private void HandleMouseLeave(EventArgs e)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseLeave");
HandleLeave();
if (Enabled)
{
OnMouseLeave(e);
RaiseEvent(EventMouseLeave, e);
}
}
private void HandleMouseDown(MouseEventArgs e)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseDown");
state[stateMouseDownAndNoDrag] = !BeginDragForItemReorder();
if (state[stateMouseDownAndNoDrag])
{
if (e.Button == MouseButtons.Left)
{
Push(true);
}
//
OnMouseDown(e);
RaiseMouseEvent(EventMouseDown, e);
}
}
private void HandleMouseUp(MouseEventArgs e)
{
Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseUp");
bool fireMouseUp = (ParentInternal.LastMouseDownedItem == this);
if (!fireMouseUp && !MouseDownAndUpMustBeInSameItem)
{
// in the case of menus, you can mouse down on one item and mouse up
// on another. We do need to be careful
// that the mouse has actually moved from when a dropdown has been opened -
// otherwise we may accidentally click what's underneath the mouse at the time
// the dropdown is opened.
fireMouseUp = ParentInternal.ShouldSelectItem();
}
if (state[stateMouseDownAndNoDrag] || fireMouseUp)
{
Push(false);
if (e.Button == MouseButtons.Left || (e.Button == MouseButtons.Right && state[stateSupportsRightClick]))
{
bool shouldFireDoubleClick = false;
if (DoubleClickEnabled)
{
long newTime = DateTime.Now.Ticks;
long deltaTicks = newTime - lastClickTime;
lastClickTime = newTime;
// use >= for cases where the delta is so fast DateTime cannot pick up the delta.
Debug.Assert(deltaTicks >= 0, "why are deltaticks less than zero? thats some mighty fast clicking");
// if we've seen a mouse up less than the double click time ago, we should fire.
if (deltaTicks >= 0 && deltaTicks < DoubleClickTicks)
{
shouldFireDoubleClick = true;
}
}
if (shouldFireDoubleClick)
{
HandleDoubleClick(EventArgs.Empty);
// If we actually fired DoubleClick - reset the lastClickTime.
lastClickTime = 0;
}
else
{
HandleClick(EventArgs.Empty);
}
}
OnMouseUp(e);
RaiseMouseEvent(EventMouseUp, e);
}
}
internal virtual void OnAccessibleDescriptionChanged(EventArgs e)
{
}
internal virtual void OnAccessibleNameChanged(EventArgs e)
{
}
internal virtual void OnAccessibleDefaultActionDescriptionChanged(EventArgs e)
{
}
internal virtual void OnAccessibleRoleChanged(EventArgs e)
{
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnBackColorChanged(EventArgs e)
{
Invalidate();
RaiseEvent(EventBackColorChanged, e);
}
protected virtual void OnBoundsChanged()
{
LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds);
InternalLayout.PerformLayout();
}
protected virtual void OnClick(EventArgs e)
{
RaiseEvent(EventClick, e);
}
protected internal virtual void OnLayout(LayoutEventArgs e)
{
}
///
/// Explicit support of DropTarget
///
void IDropTarget.OnDragEnter(DragEventArgs dragEvent)
{
OnDragEnter(dragEvent);
}
void IDropTarget.OnDragOver(DragEventArgs dragEvent)
{
OnDragOver(dragEvent);
}
void IDropTarget.OnDragLeave(EventArgs e)
{
OnDragLeave(e);
}
void IDropTarget.OnDragDrop(DragEventArgs dragEvent)
{
OnDragDrop(dragEvent);
}
///
/// Explicit support of DropSource
///
void ISupportOleDropSource.OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEventArgs)
{
OnGiveFeedback(giveFeedbackEventArgs);
}
void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEventArgs)
{
OnQueryContinueDrag(queryContinueDragEventArgs);
}
private void OnAnimationFrameChanged(object o, EventArgs e)
{
ToolStrip parent = ParentInternal;
if (parent != null)
{
if (parent.Disposing || parent.IsDisposed)
{
return;
}
if (parent.IsHandleCreated && parent.InvokeRequired)
{
parent.BeginInvoke(new EventHandler(OnAnimationFrameChanged), new object[] { o, e });
return;
}
Invalidate();
}
}
protected virtual void OnAvailableChanged(EventArgs e)
{
RaiseEvent(EventAvailableChanged, e);
}
/// <summary>
/// Raises the <see cref='ToolStripItem.Enter'/> event.
/// Inheriting classes should override this method to handle this event.
/// Call base.onEnter to send this event to any registered event listeners.
/// </summary>
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onDragEnter to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDragEnter(DragEventArgs dragEvent)
{
RaiseDragEvent(EventDragEnter, dragEvent);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onDragOver to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDragOver(DragEventArgs dragEvent)
{
RaiseDragEvent(EventDragOver, dragEvent);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onDragLeave to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDragLeave(EventArgs e)
{
RaiseEvent(EventDragLeave, e);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onDragDrop to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDragDrop(DragEventArgs dragEvent)
{
RaiseDragEvent(EventDragDrop, dragEvent);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDisplayStyleChanged(EventArgs e)
{
RaiseEvent(EventDisplayStyleChanged, e);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onGiveFeedback to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
// PM review done
protected virtual void OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEvent)
{
((GiveFeedbackEventHandler)Events[EventGiveFeedback])?.Invoke(this, giveFeedbackEvent);
}
internal virtual void OnImageScalingSizeChanged(EventArgs e)
{
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// Call base.onQueryContinueDrag to send this event to any registered event listeners.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
// PM review done
protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEvent)
{
RaiseQueryContinueDragEvent(EventQueryContinueDrag, queryContinueDragEvent);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnDoubleClick(EventArgs e)
{
RaiseEvent(EventDoubleClick, e);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnEnabledChanged(EventArgs e)
{
RaiseEvent(EventEnabledChanged, e);
Animate();
}
internal void OnInternalEnabledChanged(EventArgs e)
{
RaiseEvent(EventInternalEnabledChanged, e);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnForeColorChanged(EventArgs e)
{
Invalidate();
RaiseEvent(EventForeColorChanged, e);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnFontChanged(EventArgs e)
{
cachedTextSize = Size.Empty;
// PERF - only invalidate if we actually care about the font
if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text)
{
InvalidateItemLayout(PropertyNames.Font);
}
else
{
toolStripItemInternalLayout = null;
}
RaiseEvent(EventFontChanged, e);
}
protected virtual void OnLocationChanged(EventArgs e)
{
RaiseEvent(EventLocationChanged, e);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseEnter(EventArgs e)
{
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseMove(MouseEventArgs mea)
{
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseHover(EventArgs e)
{
if (ParentInternal != null && !string.IsNullOrEmpty(ToolTipText))
{
ParentInternal.UpdateToolTip(this);
}
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseLeave(EventArgs e)
{
if (ParentInternal != null)
{
ParentInternal.UpdateToolTip(null);
}
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseDown(MouseEventArgs e)
{
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnMouseUp(MouseEventArgs e)
{
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnPaint(PaintEventArgs e)
{
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnParentBackColorChanged(EventArgs e)
{
Color backColor = Properties.GetColor(PropBackColor);
if (backColor.IsEmpty)
{
OnBackColorChanged(e);
}
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnParentChanged(ToolStrip oldParent, ToolStrip newParent)
{
SetAmbientMargin();
if ((oldParent != null) && (oldParent.DropTargetManager != null))
{
oldParent.DropTargetManager.EnsureUnRegistered(this);
}
if (AllowDrop && (newParent != null))
{
EnsureParentDropTargetRegistered();
}
Animate();
}
/// <summary>
/// Occurs when this.Parent.Enabled changes.
/// </summary>
protected internal virtual void OnParentEnabledChanged(EventArgs e)
{
OnEnabledChanged(EventArgs.Empty);
}
/// <summary>
/// Occurs when the font property has changed on the parent - used to notify inheritors of the font property that
/// the font has changed
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal protected virtual void OnOwnerFontChanged(EventArgs e)
{
if (Properties.GetObject(PropFont) == null)
{
OnFontChanged(e);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnParentForeColorChanged(EventArgs e)
{
Color foreColor = Properties.GetColor(PropForeColor);
if (foreColor.IsEmpty)
{
OnForeColorChanged(e);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual void OnParentRightToLeftChanged(EventArgs e)
{
if (!Properties.ContainsInteger(PropRightToLeft) || ((RightToLeft)Properties.GetInteger(PropRightToLeft)) == RightToLeft.Inherit)
{
OnRightToLeftChanged(e);
}
}
/// <summary>
/// Occurs when the owner of an item changes.
/// </summary>
protected virtual void OnOwnerChanged(EventArgs e)
{
RaiseEvent(EventOwnerChanged, e);
SetAmbientMargin();
if (Owner != null)
{
// check if we need to fire OnRightToLeftChanged
int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found);
if (!found)
{
rightToLeft = (int)RightToLeft.Inherit;
}
if ((rightToLeft == (int)RightToLeft.Inherit) && RightToLeft != DefaultRightToLeft)
{
OnRightToLeftChanged(EventArgs.Empty);
}
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal void OnOwnerTextDirectionChanged()
{
ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit;
if (Properties.ContainsObject(ToolStripItem.PropTextDirection))
{
textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection);
}
if (textDirection == ToolStripTextDirection.Inherit)
{
InvalidateItemLayout("TextDirection");
}
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnRightToLeftChanged(EventArgs e)
{
InvalidateItemLayout(PropertyNames.RightToLeft);
RaiseEvent(EventRightToLeft, e);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnTextChanged(EventArgs e)
{
cachedTextSize = Size.Empty;
// Make sure we clear the cache before we perform the layout.
InvalidateItemLayout(PropertyNames.Text);
RaiseEvent(EventText, e);
}
/// <summary>
/// Inheriting classes should override this method to handle this event.
/// </summary>
protected virtual void OnVisibleChanged(EventArgs e)
{
if (Owner != null && !(Owner.IsDisposed || Owner.Disposing))
{
Owner.OnItemVisibleChanged(new ToolStripItemEventArgs(this), /*performLayout*/true);
}
RaiseEvent(EventVisibleChanged, e);
Animate();
}
public void PerformClick()
{
if (Enabled && Available)
{
FireEvent(ToolStripItemEventType.Click);
}
}
/// <summary>
/// Pushes the button.
/// </summary>
internal void Push(bool push)
{
if (!CanSelect || !Enabled || DesignMode)
{
return;
}
if (state[statePressed] != push)
{
state[statePressed] = push;
if (Available)
{
Invalidate();
}
}
}
/// <summary>
/// See Control.ProcessDialogKey for more info.
/// </summary>
protected internal virtual bool ProcessDialogKey(Keys keyData)
{
//
if (keyData == Keys.Enter || (state[stateSupportsSpaceKey] && keyData == Keys.Space))
{
FireEvent(ToolStripItemEventType.Click);
if (ParentInternal != null && !ParentInternal.IsDropDown && Enabled)
{
ParentInternal.RestoreFocusInternal();
}
return true;
}
return false;
}
/// <summary>
/// See Control.ProcessCmdKey for more info.
/// </summary>
protected internal virtual bool ProcessCmdKey(ref Message m, Keys keyData)
{
return false;
}
protected internal virtual bool ProcessMnemonic(char charCode)
{
// checking IsMnemonic is not necessary - control does this for us.
FireEvent(ToolStripItemEventType.Click);
return true;
}
internal void RaiseCancelEvent(object key, CancelEventArgs e)
{
((CancelEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseDragEvent(object key, DragEventArgs e)
{
((DragEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseEvent(object key, EventArgs e)
{
((EventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseKeyEvent(object key, KeyEventArgs e)
{
((KeyEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e)
{
((KeyPressEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseMouseEvent(object key, MouseEventArgs e)
{
((MouseEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaisePaintEvent(object key, PaintEventArgs e)
{
((PaintEventHandler)Events[key])?.Invoke(this, e);
}
internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e)
{
((QueryContinueDragEventHandler)Events[key])?.Invoke(this, e);
}
private void ResetToolTipText()
{
toolTipText = null;
}
// This will only be called in PerMonitorV2 scenarios.
internal virtual void ToolStrip_RescaleConstants(int oldDpi, int newDpi)
{
DeviceDpi = newDpi;
RescaleConstantsInternal(newDpi);
OnFontChanged(EventArgs.Empty);
}
internal void RescaleConstantsInternal(int newDpi)
{
ToolStripManager.CurrentDpi = newDpi;
defaultFont = ToolStripManager.DefaultFont;
scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin, deviceDpi);
scaledDefaultStatusStripMargin = DpiHelper.LogicalToDeviceUnits(defaultStatusStripMargin, deviceDpi);
}
/// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItem.Select"]/*' />
/// <devdoc>
/// Selects the item
/// </summary>
public void Select()
{
#if DEBUG
// let's not snap the stack trace unless we're debugging selection.
if (ToolStrip.SelectionDebug.TraceVerbose)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Select: {0} \r\n{1}\r\n", ToString(), new StackTrace().ToString().Substring(0, 200)));
}
#endif
if (!CanSelect)
{
return;
}
if (Owner != null && Owner.IsCurrentlyDragging)
{
// make sure we dont select during a drag operation.
return;
}
if (ParentInternal != null && ParentInternal.IsSelectionSuspended)
{
Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[Selection DBG] BAILING, selection is currently suspended");
return;
}
if (!Selected)
{
state[stateSelected] = true;
if (ParentInternal != null)
{
ParentInternal.NotifySelectionChange(this);
Debug.Assert(state[stateSelected], "calling notify selection change changed the selection state of this item");
}
if (IsOnDropDown)
{
if (OwnerItem != null && OwnerItem.IsOnDropDown)
{
// ensure the selection is moved back to our owner item.
OwnerItem.Select();
}
}
KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(this);
if (AccessibilityObject is ToolStripItemAccessibleObject)
{
((ToolStripItemAccessibleObject)AccessibilityObject).RaiseFocusChanged();
}
}
}
internal void SetOwner(ToolStrip newOwner)
{
if (owner != newOwner)
{
Font f = this.Font;
if (owner != null)
{
owner.rescaleConstsCallbackDelegate -= ToolStrip_RescaleConstants;
}
owner = newOwner;
if (owner != null)
{
owner.rescaleConstsCallbackDelegate += ToolStrip_RescaleConstants;
}
// clear the parent if the owner is null...
//
if (newOwner == null)
{
this.ParentInternal = null;
}
if (!state[stateDisposing] && !IsDisposed)
{
OnOwnerChanged(EventArgs.Empty);
if (f != Font)
{
OnFontChanged(EventArgs.Empty);
}
}
}
}
protected virtual void SetVisibleCore(bool visible)
{
if (state[stateVisible] != visible)
{
state[stateVisible] = visible;
Unselect();
Push(false);
OnAvailableChanged(EventArgs.Empty);
OnVisibleChanged(EventArgs.Empty);
}
}
/// <summary>
/// Sets the bounds of the item
/// </summary>
internal protected virtual void SetBounds(Rectangle bounds)
{
Rectangle oldBounds = this.bounds;
this.bounds = bounds;
if (!state[stateContstructing])
{
// Dont fire while we're in the base constructor as the inherited
// class may not have had a chance to initialize yet.
if (this.bounds != oldBounds)
{
OnBoundsChanged();
}
if (this.bounds.Location != oldBounds.Location)
{
OnLocationChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Sets the bounds of the item
/// </summary>
internal void SetBounds(int x, int y, int width, int height)
{
SetBounds(new Rectangle(x, y, width, height));
}
/// <summary>
/// Sets the placement of the item
/// </summary>
internal void SetPlacement(ToolStripItemPlacement placement)
{
this.placement = placement;
}
// Some implementations of DefaultMargin check which container they
// are on. They need to be re-evaluated when the containership changes.
// DefaultMargin will stop being honored the moment someone sets the Margin property.
internal void SetAmbientMargin()
{
if (state[stateUseAmbientMargin] && Margin != DefaultMargin)
{
CommonProperties.SetMargin(this, DefaultMargin);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeImageTransparentColor()
{
return ImageTransparentColor != Color.Empty;
}
/// <summary>
/// Returns true if the backColor should be persisted in code gen.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal virtual bool ShouldSerializeBackColor()
{
Color backColor = Properties.GetColor(PropBackColor);
return !backColor.IsEmpty;
}
private bool ShouldSerializeDisplayStyle()
{
return DisplayStyle != DefaultDisplayStyle;
}
private bool ShouldSerializeToolTipText()
{
return !string.IsNullOrEmpty(toolTipText);
}
/// <summary>
/// Returns true if the foreColor should be persisted in code gen.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal virtual bool ShouldSerializeForeColor()
{
Color foreColor = Properties.GetColor(PropForeColor);
return !foreColor.IsEmpty;
}
/// <summary>
/// Returns true if the font should be persisted in code gen.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal virtual bool ShouldSerializeFont()
{
object font = Properties.GetObject(PropFont, out bool found);
return (found && font != null);
}
/// <summary>
/// Determines if the <see cref='Padding'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializePadding()
{
return (Padding != DefaultPadding);
}
/// <summary>
/// Determines if the <see cref='Margin'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeMargin()
{
return (Margin != DefaultMargin);
}
/// <summary>
/// Determines if the <see cref='Visible'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeVisible()
{
return !state[stateVisible]; // only serialize if someone turned off visiblilty
}
/// <summary>
/// Determines if the <see cref='Image'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeImage()
{
return (Image != null) && (ImageIndexer.ActualIndex < 0);
}
/// <summary>
/// Determines if the <see cref='Image'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeImageKey()
{
return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Key != null && ImageIndexer.Key.Length != 0);
}
/// <summary>
/// Determines if the <see cref='Image'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeImageIndex()
{
return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Index != -1);
}
/// <summary>
/// Determines if the <see cref='RightToLeft'/> property needs to be persisted.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal virtual bool ShouldSerializeRightToLeft()
{
int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found);
if (!found)
{
return false;
}
return (rightToLeft != (int)DefaultRightToLeft);
}
private bool ShouldSerializeTextDirection()
{
ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit;
if (Properties.ContainsObject(ToolStripItem.PropTextDirection))
{
textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection);
}
return textDirection != ToolStripTextDirection.Inherit;
}
/// <summary>
/// Resets the back color to be based on the parent's back color.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetBackColor()
{
BackColor = Color.Empty;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetDisplayStyle()
{
DisplayStyle = DefaultDisplayStyle;
}
/// <summary>
/// Resets the fore color to be based on the parent's fore color.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetForeColor()
{
ForeColor = Color.Empty;
}
/// <summary>
/// Resets the Font to be based on the parent's Font.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetFont()
{
Font = null;
}
/// <summary>
/// Resets the back color to be based on the parent's back color.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetImage()
{
Image = null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
private void ResetImageTransparentColor()
{
ImageTransparentColor = Color.Empty;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetMargin()
{
state[stateUseAmbientMargin] = true;
SetAmbientMargin();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ResetPadding()
{
CommonProperties.ResetPadding(this);
}
/// <summary>
/// Resets the RightToLeft to be the default.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetRightToLeft()
{
RightToLeft = RightToLeft.Inherit;
}
/// <summary>
/// Resets the TextDirection to be the default.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ResetTextDirection()
{
TextDirection = ToolStripTextDirection.Inherit;
}
/// <summary>
/// Translates a point from one coordinate system to another
/// </summary>
internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, ToolStripPointType toPointType)
{
ToolStrip parent = ParentInternal;
if (parent == null)
{
parent = (IsOnOverflow && Owner != null) ? Owner.OverflowButton.DropDown : Owner;
}
if (parent == null)
{
// should not throw here as it's an internal function call.
return fromPoint;
}
if (fromPointType == toPointType)
{
return fromPoint;
}
Point toPoint = Point.Empty;
Point currentToolStripItemLocation = Bounds.Location;
// From: Screen
// To: ToolStrip or ToolStripItem
if (fromPointType == ToolStripPointType.ScreenCoords)
{
// Convert ScreenCoords --> ToolStripCoords
toPoint = parent.PointToClient(fromPoint);
// Convert ToolStripCoords --> ToolStripItemCoords
if (toPointType == ToolStripPointType.ToolStripItemCoords)
{
toPoint.X += currentToolStripItemLocation.X;
toPoint.Y += currentToolStripItemLocation.Y;
}
}
// From: ToolStrip or ToolStripItem
// To: Screen or ToolStripItem
else
{
// Convert "fromPoint" ToolStripItemCoords --> ToolStripCoords
if (fromPointType == ToolStripPointType.ToolStripItemCoords)
{
fromPoint.X += currentToolStripItemLocation.X;
fromPoint.Y += currentToolStripItemLocation.Y;
}
// At this point, fromPoint is now in ToolStrip coordinates.
// Convert ToolStripCoords --> ScreenCoords
if (toPointType == ToolStripPointType.ScreenCoords)
{
toPoint = parent.PointToScreen(fromPoint);
}
// Convert ToolStripCoords --> ToolStripItemCoords
else if (toPointType == ToolStripPointType.ToolStripItemCoords)
{
fromPoint.X -= currentToolStripItemLocation.X;
fromPoint.Y -= currentToolStripItemLocation.Y;
toPoint = fromPoint;
}
else
{
Debug.Assert((toPointType == ToolStripPointType.ToolStripCoords), "why are we here! - investigate");
toPoint = fromPoint;
}
}
return toPoint;
}
internal ToolStrip RootToolStrip
{
get
{
ToolStripItem item = this;
while (item.OwnerItem != null)
{
item = item.OwnerItem;
}
return item.ParentInternal;
}
}
/// <summary>
/// ToString support
/// </summary>
public override string ToString()
{
if (Text != null && Text.Length != 0)
{
return Text;
}
return base.ToString();
}
/// <summary>
/// removes selection bits from item state
/// </summary>
internal void Unselect()
{
Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Unselect: {0}", ToString()));
if (state[stateSelected])
{
state[stateSelected] = false;
if (Available)
{
Invalidate();
if (ParentInternal != null)
{
ParentInternal.NotifySelectionChange(this);
}
KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this);
}
}
}
#region IKeyboardToolTip implementation
bool IKeyboardToolTip.CanShowToolTipsNow()
{
return Visible && parent != null && ((IKeyboardToolTip)parent).AllowsChildrenToShowToolTips();
}
Rectangle IKeyboardToolTip.GetNativeScreenRectangle()
{
return AccessibilityObject.Bounds;
}
IList<Rectangle> IKeyboardToolTip.GetNeighboringToolsRectangles()
{
List<Rectangle> neighbors = new List<Rectangle>(3);
if (parent != null)
{
ToolStripItemCollection items = parent.DisplayedItems;
int i = 0, count = items.Count;
bool found = false;
while (!found && i < count)
{
found = Object.ReferenceEquals(items[i], this);
if (found)
{
int previousIndex = i - 1;
if (previousIndex >= 0)
{
neighbors.Add(((IKeyboardToolTip)items[previousIndex]).GetNativeScreenRectangle());
}
int nextIndex = i + 1;
if (nextIndex < count)
{
neighbors.Add(((IKeyboardToolTip)items[nextIndex]).GetNativeScreenRectangle());
}
}
else
{
i++;
}
}
Debug.Assert(i < count, "Item has a parent set but the parent doesn't own the item");
}
if (parent is ToolStripDropDown dropDown && dropDown.OwnerItem != null)
{
neighbors.Add(((IKeyboardToolTip)dropDown.OwnerItem).GetNativeScreenRectangle());
}
return neighbors;
}
bool IKeyboardToolTip.IsHoveredWithMouse()
{
return ((IKeyboardToolTip)this).GetNativeScreenRectangle().Contains(Control.MousePosition);
}
bool IKeyboardToolTip.HasRtlModeEnabled()
{
return parent != null && ((IKeyboardToolTip)parent).HasRtlModeEnabled();
}
bool IKeyboardToolTip.AllowsToolTip()
{
return true;
}
IWin32Window IKeyboardToolTip.GetOwnerWindow()
{
Debug.Assert(ParentInternal != null, "Tool Strip Item Parent is null");
return ParentInternal;
}
void IKeyboardToolTip.OnHooked(ToolTip toolTip)
{
OnKeyboardToolTipHook(toolTip);
}
void IKeyboardToolTip.OnUnhooked(ToolTip toolTip)
{
OnKeyboardToolTipUnhook(toolTip);
}
string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip)
{
return ToolTipText;
}
bool IKeyboardToolTip.ShowsOwnToolTip()
{
return true;
}
bool IKeyboardToolTip.IsBeingTabbedTo()
{
return IsBeingTabbedTo();
}
bool IKeyboardToolTip.AllowsChildrenToShowToolTips()
{
return true;
}
#endregion
internal virtual void OnKeyboardToolTipHook(ToolTip toolTip)
{
}
internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip)
{
}
internal virtual bool IsBeingTabbedTo()
{
return ToolStrip.AreCommonNavigationalKeysDown();
}
/// <summary>
/// An implementation of AccessibleChild for use with ToolStripItems
/// </summary>
[Runtime.InteropServices.ComVisible(true)]
public class ToolStripItemAccessibleObject : AccessibleObject
{
// Member variables
private readonly ToolStripItem ownerItem = null; // The associated ToolStripItem for this AccessibleChild (if any)
private AccessibleStates additionalState = AccessibleStates.None; // Test hook for the designer
private int[] runtimeId = null; // Used by UIAutomation
// constructors
public ToolStripItemAccessibleObject(ToolStripItem ownerItem)
{
this.ownerItem = ownerItem ?? throw new ArgumentNullException(nameof(ownerItem));
}
public override string DefaultAction
{
get
{
string defaultAction = ownerItem.AccessibleDefaultActionDescription;
if (defaultAction != null)
{
return defaultAction;
}
else
{
return SR.AccessibleActionPress;
}
}
}
public override string Description
{
get
{
string description = ownerItem.AccessibleDescription;
if (description != null)
{
return description;
}
else
{
return base.Description;
}
}
}
public override string Help
{
get
{
QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[ToolStripItem.EventQueryAccessibilityHelp];
if (handler != null)
{
QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs();
handler(Owner, args);
return args.HelpString;
}
else
{
return base.Help;
}
}
}
public override string KeyboardShortcut
{
get
{
// This really is the Mnemonic - NOT the shortcut. E.g. in notepad Edit->Replace is Control+H
// but the KeyboardShortcut comes up as the mnemonic 'r'.
char mnemonic = WindowsFormsUtils.GetMnemonic(ownerItem.Text, false);
if (ownerItem.IsOnDropDown)
{
// no ALT on dropdown
return (mnemonic == (char)0) ? string.Empty : mnemonic.ToString();
}
return (mnemonic == (char)0) ? string.Empty : ("Alt+" + mnemonic);
}
}
internal override int[] RuntimeId
{
get
{
if (runtimeId == null)
{
// we need to provide a unique ID
// others are implementing this in the same manner
// first item should be UiaAppendRuntimeId since this is not a top-level element of the fragment.
// second item can be anything, but here it is a hash. For toolstrip hash is unique even with child controls. Hwnd is not.
runtimeId = new int[2];
runtimeId[0] = NativeMethods.UiaAppendRuntimeId;
runtimeId[1] = ownerItem.GetHashCode();
}
return runtimeId;
}
}
/// <summary>
/// Gets the accessible property value.
/// </summary>
/// <param name="propertyID">The accessible property ID.</param>
/// <returns>The accessible property value.</returns>
internal override object GetPropertyValue(UiaCore.UIA propertyID)
{
switch (propertyID)
{
case UiaCore.UIA.NamePropertyId:
return Name;
case UiaCore.UIA.IsExpandCollapsePatternAvailablePropertyId:
return (object)IsPatternSupported(UiaCore.UIA.ExpandCollapsePatternId);
case UiaCore.UIA.IsEnabledPropertyId:
return ownerItem.Enabled;
case UiaCore.UIA.IsOffscreenPropertyId:
return ownerItem.Placement != ToolStripItemPlacement.Main;
case UiaCore.UIA.IsKeyboardFocusablePropertyId:
return ownerItem.CanSelect;
case UiaCore.UIA.HasKeyboardFocusPropertyId:
return ownerItem.Selected;
case UiaCore.UIA.AccessKeyPropertyId:
return KeyboardShortcut;
case UiaCore.UIA.IsPasswordPropertyId:
return false;
case UiaCore.UIA.HelpTextPropertyId:
return Help ?? string.Empty;
}
return base.GetPropertyValue(propertyID);
}
public override string Name
{
get
{
string name = ownerItem.AccessibleName;
if (name != null)
{
return name;
}
string baseName = base.Name;
if (baseName == null || baseName.Length == 0)
{
return WindowsFormsUtils.TextWithoutMnemonics(ownerItem.Text);
}
return baseName;
}
set
{
ownerItem.AccessibleName = value;
}
}
internal ToolStripItem Owner
{
get
{
return ownerItem;
}
}
public override AccessibleRole Role
{
get
{
AccessibleRole role = ownerItem.AccessibleRole;
if (role != AccessibleRole.Default)
{
return role;
}
else
{
return AccessibleRole.PushButton;
}
}
}
public override AccessibleStates State
{
get
{
if (!ownerItem.CanSelect)
{
return base.State | additionalState;
}
if (!ownerItem.Enabled)
{
if (ownerItem.Selected && ownerItem is ToolStripMenuItem)
{
return AccessibleStates.Unavailable | additionalState | AccessibleStates.Focused;
}
// Disabled menu items that are selected must have focus
// state so that Narrator can announce them.
if (ownerItem.Selected && ownerItem is ToolStripMenuItem)
{
return AccessibleStates.Focused;
}
return AccessibleStates.Unavailable | additionalState;
}
AccessibleStates accState = AccessibleStates.Focusable | additionalState;
//
/*if (HasDropDownItems) {
accState |= AccessibleState.HasPopup;
}*/
if (ownerItem.Selected || ownerItem.Pressed)
{
accState |= AccessibleStates.Focused | AccessibleStates.HotTracked;
}
if (ownerItem.Pressed)
{
accState |= AccessibleStates.Pressed;
}
return accState;
}
}
public override void DoDefaultAction()
{
if (Owner != null)
{
((ToolStripItem)Owner).PerformClick();
}
}
public override int GetHelpTopic(out string fileName)
{
int topic = 0;
QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[ToolStripItem.EventQueryAccessibilityHelp];
if (handler != null)
{
QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs();
handler(Owner, args);
fileName = args.HelpNamespace;
try
{
topic = int.Parse(args.HelpKeyword, CultureInfo.InvariantCulture);
}
catch
{
}
return topic;
}
else
{
return base.GetHelpTopic(out fileName);
}
}
public override AccessibleObject Navigate(AccessibleNavigation navigationDirection)
{
ToolStripItem nextItem = null;
if (Owner != null)
{
ToolStrip parent = Owner.ParentInternal;
if (parent == null)
{
return null;
}
bool forwardInCollection = (parent.RightToLeft == RightToLeft.No);
switch (navigationDirection)
{
case AccessibleNavigation.FirstChild:
nextItem = parent.GetNextItem(null, ArrowDirection.Right, /*RTLAware=*/true);
break;
case AccessibleNavigation.LastChild:
nextItem = parent.GetNextItem(null, ArrowDirection.Left,/*RTLAware=*/true);
break;
case AccessibleNavigation.Previous:
case AccessibleNavigation.Left:
nextItem = parent.GetNextItem(Owner, ArrowDirection.Left, /*RTLAware=*/true);
break;
case AccessibleNavigation.Next:
case AccessibleNavigation.Right:
nextItem = parent.GetNextItem(Owner, ArrowDirection.Right, /*RTLAware=*/true);
break;
case AccessibleNavigation.Up:
nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Up) :
parent.GetNextItem(Owner, ArrowDirection.Left, /*RTLAware=*/true);
break;
case AccessibleNavigation.Down:
nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Down) :
parent.GetNextItem(Owner, ArrowDirection.Right, /*RTLAware=*/true);
break;
}
}
if (nextItem != null)
{
return nextItem.AccessibilityObject;
}
return null;
}
public void AddState(AccessibleStates state)
{
if (state == AccessibleStates.None)
{
additionalState = state;
}
else
{
additionalState |= state;
}
}
public override string ToString()
{
if (Owner != null)
{
return "ToolStripItemAccessibleObject: Owner = " + Owner.ToString();
}
else
{
return "ToolStripItemAccessibleObject: Owner = null";
}
}
/// <summary>
/// Gets the bounds of the accessible object, in screen coordinates.
/// </summary>
public override Rectangle Bounds
{
get
{
Rectangle bounds = Owner.Bounds;
if (Owner.ParentInternal != null &&
Owner.ParentInternal.Visible)
{
return new Rectangle(Owner.ParentInternal.PointToScreen(bounds.Location), bounds.Size);
}
return Rectangle.Empty;
}
}
/// <summary>
/// When overridden in a derived class, gets or sets the parent of an accessible object.
/// </summary>
public override AccessibleObject Parent
{
get
{
if (Owner.IsOnDropDown)
{
// Return the owner item as the accessible parent.
ToolStripDropDown dropDown = Owner.GetCurrentParentDropDown();
return dropDown.AccessibilityObject;
}
return (Owner.Parent != null) ? Owner.Parent.AccessibilityObject : base.Parent;
}
}
/// <summary>
/// Gets the top level element.
/// </summary>
internal override UiaCore.IRawElementProviderFragmentRoot FragmentRoot
{
get
{
return ownerItem.RootToolStrip?.AccessibilityObject;
}
}
/// <summary>
/// Returns the element in the specified direction.
/// </summary>
/// <param name="direction">Indicates the direction in which to navigate.</param>
/// <returns>Returns the element in the specified direction.</returns>
internal override UiaCore.IRawElementProviderFragment FragmentNavigate(UiaCore.NavigateDirection direction)
{
switch (direction)
{
case UiaCore.NavigateDirection.Parent:
return Parent;
case UiaCore.NavigateDirection.NextSibling:
case UiaCore.NavigateDirection.PreviousSibling:
int index = GetChildFragmentIndex();
if (index == -1)
{
Debug.Fail("No item matched the index?");
return null;
}
int increment = direction == UiaCore.NavigateDirection.NextSibling ? 1 : -1;
AccessibleObject sibling = null;
index += increment;
int itemsCount = GetChildFragmentCount();
if (index >= 0 && index < itemsCount)
{
sibling = GetChildFragment(index);
}
return sibling;
}
return base.FragmentNavigate(direction);
}
private AccessibleObject GetChildFragment(int index)
{
if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent)
{
return toolStripParent.GetChildFragment(index);
}
// ToolStripOverflowButtonAccessibleObject is derived from ToolStripDropDownItemAccessibleObject
// and we should not process ToolStripOverflowButton as a ToolStripDropDownItem here so check for
// the ToolStripOverflowButton firstly as more specific condition.
if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent)
{
if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent)
{
return toolStripGrandParent.GetChildFragment(index, true);
}
}
if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent)
{
return dropDownItemParent.GetChildFragment(index);
}
return null;
}
private int GetChildFragmentCount()
{
if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent)
{
return toolStripParent.GetChildFragmentCount();
}
if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent)
{
if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent)
{
return toolStripGrandParent.GetChildOverflowFragmentCount();
}
}
if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent)
{
return dropDownItemParent.GetChildCount();
}
return -1;
}
private int GetChildFragmentIndex()
{
if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent)
{
return toolStripParent.GetChildFragmentIndex(this);
}
if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent)
{
if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent)
{
return toolStripGrandParent.GetChildFragmentIndex(this);
}
}
if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent)
{
return dropDownItemParent.GetChildFragmentIndex(this);
}
return -1;
}
internal override void SetFocus()
{
Owner.Select();
}
internal void RaiseFocusChanged()
{
ToolStrip root = ownerItem.RootToolStrip;
if (root != null && root.SupportsUiaProviders)
{
RaiseAutomationEvent(UiaCore.UIA.AutomationFocusChangedEventId);
}
}
}
}
// We need a special way to defer to the ToolStripItem's image
// list for indexing purposes.
internal class ToolStripItemImageIndexer : ImageList.Indexer
{
private readonly ToolStripItem item;
public ToolStripItemImageIndexer(ToolStripItem item)
{
this.item = item;
}
public override ImageList ImageList
{
get
{
if ((item != null) && (item.Owner != null))
{
return item.Owner.ImageList;
}
return null;
}
set { Debug.Assert(false, "We should never set the image list"); }
}
}
/// <summary>
/// This class helps determine where the image and text should be drawn.
/// </summary>
internal class ToolStripItemInternalLayout
{
private ToolStripItemLayoutOptions currentLayoutOptions;
private readonly ToolStripItem ownerItem;
private ButtonBaseAdapter.LayoutData layoutData;
private const int BORDER_WIDTH = 2;
private const int BORDER_HEIGHT = 3;
private readonly static Size INVALID_SIZE = new Size(int.MinValue, int.MinValue);
private Size lastPreferredSize = INVALID_SIZE;
private ToolStripLayoutData parentLayoutData = null;
public ToolStripItemInternalLayout(ToolStripItem ownerItem)
{
this.ownerItem = ownerItem ?? throw new ArgumentNullException(nameof(ownerItem));
}
// the thing that we fetch properties off of -- this can be different than ownerItem - e.g. case of split button.
protected virtual ToolStripItem Owner
{
get { return ownerItem; }
}
public virtual Rectangle ImageRectangle
{
get
{
Rectangle imageRect = LayoutData.imageBounds;
imageRect.Intersect(layoutData.field);
return imageRect;
}
}
internal ButtonBaseAdapter.LayoutData LayoutData
{
get
{
EnsureLayout();
return layoutData;
}
}
public Size PreferredImageSize
{
get
{
return Owner.PreferredImageSize;
}
}
protected virtual ToolStrip ParentInternal
{
get
{
return ownerItem?.ParentInternal;
}
}
public virtual Rectangle TextRectangle
{
get
{
Rectangle textRect = LayoutData.textBounds;
textRect.Intersect(layoutData.field);
return textRect;
}
}
public virtual Rectangle ContentRectangle
{
get
{
return LayoutData.field;
}
}
public virtual TextFormatFlags TextFormat
{
get
{
if (currentLayoutOptions != null)
{
return currentLayoutOptions.gdiTextFormatFlags;
}
return CommonLayoutOptions().gdiTextFormatFlags;
}
}
internal static TextFormatFlags ContentAlignToTextFormat(ContentAlignment alignment, bool rightToLeft)
{
TextFormatFlags textFormat = TextFormatFlags.Default;
if (rightToLeft)
{
//We specifically do not want to turn on TextFormatFlags.Right.
textFormat |= TextFormatFlags.RightToLeft;
}
// Calculate Text Positioning
textFormat |= ControlPaint.TranslateAlignmentForGDI(alignment);
textFormat |= ControlPaint.TranslateLineAlignmentForGDI(alignment);
return textFormat;
}
protected virtual ToolStripItemLayoutOptions CommonLayoutOptions()
{
ToolStripItemLayoutOptions layoutOptions = new ToolStripItemLayoutOptions();
Rectangle bounds = new Rectangle(Point.Empty, ownerItem.Size);
layoutOptions.client = bounds;
layoutOptions.growBorderBy1PxWhenDefault = false;
layoutOptions.borderSize = BORDER_WIDTH;
layoutOptions.paddingSize = 0;
layoutOptions.maxFocus = true;
layoutOptions.focusOddEvenFixup = false;
layoutOptions.font = ownerItem.Font;
layoutOptions.text = ((Owner.DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) ? Owner.Text : string.Empty;
layoutOptions.imageSize = PreferredImageSize;
layoutOptions.checkSize = 0;
layoutOptions.checkPaddingSize = 0;
layoutOptions.checkAlign = ContentAlignment.TopLeft;
layoutOptions.imageAlign = Owner.ImageAlign;
layoutOptions.textAlign = Owner.TextAlign;
layoutOptions.hintTextUp = false;
layoutOptions.shadowedText = !ownerItem.Enabled;
layoutOptions.layoutRTL = RightToLeft.Yes == Owner.RightToLeft;
layoutOptions.textImageRelation = Owner.TextImageRelation;
//set textImageInset to 0 since we don't draw 3D border for ToolStripItems.
layoutOptions.textImageInset = 0;
layoutOptions.everettButtonCompat = false;
// Support RTL
layoutOptions.gdiTextFormatFlags = ContentAlignToTextFormat(Owner.TextAlign, Owner.RightToLeft == RightToLeft.Yes);
// Hide underlined &File unless ALT is pressed
layoutOptions.gdiTextFormatFlags = (Owner.ShowKeyboardCues) ? layoutOptions.gdiTextFormatFlags : layoutOptions.gdiTextFormatFlags | TextFormatFlags.HidePrefix;
return layoutOptions;
}
private bool EnsureLayout()
{
if (layoutData == null || parentLayoutData == null || !parentLayoutData.IsCurrent(ParentInternal))
{
PerformLayout();
return true;
}
return false;
}
private ButtonBaseAdapter.LayoutData GetLayoutData()
{
currentLayoutOptions = CommonLayoutOptions();
if (Owner.TextDirection != ToolStripTextDirection.Horizontal)
{
currentLayoutOptions.verticalText = true;
}
ButtonBaseAdapter.LayoutData data = currentLayoutOptions.Layout();
return data;
}
public virtual Size GetPreferredSize(Size constrainingSize)
{
Size preferredSize = Size.Empty;
EnsureLayout();
// we would prefer not to be larger than the ToolStrip itself.
// so we'll ask the ButtonAdapter layout guy what it thinks
// its preferred size should be - and we'll tell it to be no
// bigger than the ToolStrip itself. Note this is "Parent" not
// "Owner" because we care in this instance what we're currently displayed on.
if (ownerItem != null)
{
lastPreferredSize = currentLayoutOptions.GetPreferredSizeCore(constrainingSize);
return lastPreferredSize;
}
return Size.Empty;
}
internal void PerformLayout()
{
layoutData = GetLayoutData();
ToolStrip parent = ParentInternal;
if (parent != null)
{
parentLayoutData = new ToolStripLayoutData(parent);
}
else
{
parentLayoutData = null;
}
}
internal class ToolStripItemLayoutOptions : ButtonBaseAdapter.LayoutOptions
{
Size cachedSize = LayoutUtils.InvalidSize;
Size cachedProposedConstraints = LayoutUtils.InvalidSize;
// override GetTextSize to provide simple text caching.
protected override Size GetTextSize(Size proposedConstraints)
{
if (cachedSize != LayoutUtils.InvalidSize
&& (cachedProposedConstraints == proposedConstraints
|| cachedSize.Width <= proposedConstraints.Width))
{
return cachedSize;
}
else
{
cachedSize = base.GetTextSize(proposedConstraints);
cachedProposedConstraints = proposedConstraints;
}
return cachedSize;
}
}
private class ToolStripLayoutData
{
private readonly ToolStripLayoutStyle layoutStyle;
private readonly bool autoSize;
private Size size;
public ToolStripLayoutData(ToolStrip toolStrip)
{
layoutStyle = toolStrip.LayoutStyle;
autoSize = toolStrip.AutoSize;
size = toolStrip.Size;
}
public bool IsCurrent(ToolStrip toolStrip)
{
if (toolStrip == null)
{
return false;
}
return (toolStrip.Size == size && toolStrip.LayoutStyle == layoutStyle && toolStrip.AutoSize == autoSize);
}
}
}
}
| 34.912442 | 250 | 0.526835 | [
"MIT"
] | AArnott/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs | 174,250 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Storage {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class ResourceV2 {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ResourceV2() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.Storage.custom.Dataplane.v2.ResourceV2", typeof(ResourceV2).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to [Anonymous].
/// </summary>
internal static string AnonymousAccountName {
get {
return ResourceManager.GetString("AnonymousAccountName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} begin processing without ParameterSet..
/// </summary>
internal static string BeginProcessingWithoutParameterSetLog {
get {
return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'..
/// </summary>
internal static string BeginProcessingWithParameterSetLog {
get {
return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob '{0}' in container '{1}' already exists..
/// </summary>
internal static string BlobAlreadyExists {
get {
return ResourceManager.GetString("BlobAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob End Point: {0}..
/// </summary>
internal static string BlobEndPointTips {
get {
return ResourceManager.GetString("BlobEndPointTips", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can't read the blob properties..
/// </summary>
internal static string BlobIsNotReadable {
get {
return ResourceManager.GetString("BlobIsNotReadable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find blob name or container name..
/// </summary>
internal static string BlobNameNotFound {
get {
return ResourceManager.GetString("BlobNameNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob name should be empty when uploading multiple files..
/// </summary>
internal static string BlobNameShouldBeEmptyWhenUploading {
get {
return ResourceManager.GetString("BlobNameShouldBeEmptyWhenUploading", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find blob '{0}' in container '{1}', or the blob type is unsupported..
/// </summary>
internal static string BlobNotFound {
get {
return ResourceManager.GetString("BlobNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob type mismatched, the current blob type of '{0}' is {1}..
/// </summary>
internal static string BlobTypeMismatch {
get {
return ResourceManager.GetString("BlobTypeMismatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find blob '{0}', or the blob type is unsupported..
/// </summary>
internal static string BlobUriNotFound {
get {
return ResourceManager.GetString("BlobUriNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified blob '{0}' is already a snapshot with snapshot time {1}. Can't use "DeleteSnapshot" option for it..
/// </summary>
internal static string CannotDeleteSnapshotForSnapshot {
get {
return ResourceManager.GetString("CannotDeleteSnapshotForSnapshot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not get storage account from subscription. Please check the subscription settings using "Get-AzSubscription"..
/// </summary>
internal static string CannotGetSotrageAccountFromSubscription {
get {
return ResourceManager.GetString("CannotGetSotrageAccountFromSubscription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not get storage account from environment variable 'AZURE_STORAGE_CONNECTION_STRING'. Please check whether this environment variable is valid..
/// </summary>
internal static string CannotGetStorageAccountFromEnvironmentVariable {
get {
return ResourceManager.GetString("CannotGetStorageAccountFromEnvironmentVariable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not upload the directory '{0}' to azure. If you want to upload directory, please use "ls -File -Recurse | Set-AzStorageBlobContent -Container containerName"..
/// </summary>
internal static string CannotSendDirectory {
get {
return ResourceManager.GetString("CannotSendDirectory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Azure-Storage-PowerShell-{0}.
/// </summary>
internal static string ClientRequestIdFormat {
get {
return ResourceManager.GetString("ClientRequestIdFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified cloud file '{0}' already exists. If you want to overwrite this file, use -Force option..
/// </summary>
internal static string CloudFileConflict {
get {
return ResourceManager.GetString("CloudFileConflict", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}-{1}.
/// </summary>
internal static string CmdletFormat {
get {
return ResourceManager.GetString("CmdletFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to blob '{0}' in container '{1}' with CopyId {2}..
/// </summary>
internal static string ConfirmAbortCopyOperation {
get {
return ResourceManager.GetString("ConfirmAbortCopyOperation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to file '{0}' with CopyId {1}..
/// </summary>
internal static string ConfirmAbortFileCopyOperation {
get {
return ResourceManager.GetString("ConfirmAbortFileCopyOperation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Confirm.
/// </summary>
internal static string ConfirmCaption {
get {
return ResourceManager.GetString("ConfirmCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The blob '{0}' in container '{1}' has snapshots..
/// </summary>
internal static string ConfirmRemoveBlobWithSnapshot {
get {
return ResourceManager.GetString("ConfirmRemoveBlobWithSnapshot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure to remove container '{0}'?.
/// </summary>
internal static string ConfirmRemoveContainer {
get {
return ResourceManager.GetString("ConfirmRemoveContainer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Confirm to remove azure container..
/// </summary>
internal static string ConfirmRemoveContainerCaption {
get {
return ResourceManager.GetString("ConfirmRemoveContainerCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Container '{0}' already exists..
/// </summary>
internal static string ContainerAlreadyExists {
get {
return ResourceManager.GetString("ContainerAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find the container '{0}'..
/// </summary>
internal static string ContainerNotFound {
get {
return ResourceManager.GetString("ContainerNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Context cannot be null. Please log in using Connect-AzAccount..
/// </summary>
internal static string ContextCannotBeNull {
get {
return ResourceManager.GetString("ContextCannotBeNull", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy Blob..
/// </summary>
internal static string CopyBlobActivity {
get {
return ResourceManager.GetString("CopyBlobActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' copy to blob '{1}' in container '{2}' from '{3}'..
/// </summary>
internal static string CopyBlobStatus {
get {
return ResourceManager.GetString("CopyBlobStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy Blob Status Summary..
/// </summary>
internal static string CopyBlobSummaryActivity {
get {
return ResourceManager.GetString("CopyBlobSummaryActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total: {0}. Successful: {1}. Active: {2}. Failed: {3}..
/// </summary>
internal static string CopyBlobSummaryCount {
get {
return ResourceManager.GetString("CopyBlobSummaryCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Successfully start copy blob '{0}' in container '{1}' to blob '{2}' in container '{3}'..
/// </summary>
internal static string CopyBlobToBlobSuccessfully {
get {
return ResourceManager.GetString("CopyBlobToBlobSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy request to blob '{0}' in container '{1}' has been scheduled with copyId {2}..
/// </summary>
internal static string CopyDestinationBlobPending {
get {
return ResourceManager.GetString("CopyDestinationBlobPending", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy File..
/// </summary>
internal static string CopyFileActivity {
get {
return ResourceManager.GetString("CopyFileActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' copy to file '{1}' in share '{2}' from '{3}'..
/// </summary>
internal static string CopyFileStatus {
get {
return ResourceManager.GetString("CopyFileStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CopyId can not be empty..
/// </summary>
internal static string CopyIdCannotBeEmpty {
get {
return ResourceManager.GetString("CopyIdCannotBeEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CopyId mismatch on blob '{0}' in container '{1}'. Expected:{2}. User supplied: {3}..
/// </summary>
internal static string CopyIdMismatch {
get {
return ResourceManager.GetString("CopyIdMismatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Percent:{0}%. BytesCopied: {1}Bytes. TotalBytes: {2}Bytes..
/// </summary>
internal static string CopyPendingStatus {
get {
return ResourceManager.GetString("CopyPendingStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find copy task on the specified blob '{0}' in container '{1}'..
/// </summary>
internal static string CopyTaskNotFound {
get {
return ResourceManager.GetString("CopyTaskNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Successfully start copy '{0}' to blob '{1}' in container '{2}'..
/// </summary>
internal static string CopyUriToBlobSuccessfully {
get {
return ResourceManager.GetString("CopyUriToBlobSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CORS rules setting is invalid. Please reference to "https://msdn.microsoft.com/en-us/library/azure/dn535601.aspx" to get detailed information..
/// </summary>
internal static string CORSRuleError {
get {
return ResourceManager.GetString("CORSRuleError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current Storage Account not found in subscription '{0}'. Please set it use "Set-AzSubscription"..
/// </summary>
internal static string CurrentStorageAccountNameNotFound {
get {
return ResourceManager.GetString("CurrentStorageAccountNameNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not found current storage account '{0}' of subsciption '{1}' on azure, please check whether the specified storage account exists..
/// </summary>
internal static string CurrentStorageAccountNotFoundOnAzure {
get {
return ResourceManager.GetString("CurrentStorageAccountNotFoundOnAzure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to core.windows.net.
/// </summary>
internal static string DefaultDomain {
get {
return ResourceManager.GetString("DefaultDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find your azure storage credential. Please set current storage account using "Set-AzSubscription" or set the "AZURE_STORAGE_CONNECTION_STRING" environment variable..
/// </summary>
internal static string DefaultStorageCredentialsNotFound {
get {
return ResourceManager.GetString("DefaultStorageCredentialsNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to core.windows.net.
/// </summary>
internal static string DefaultStorageEndPointDomain {
get {
return ResourceManager.GetString("DefaultStorageEndPointDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User specified blob type does not match the blob type of the existing destination blob..
/// </summary>
internal static string DestinationBlobTypeNotMatch {
get {
return ResourceManager.GetString("DestinationBlobTypeNotMatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Directory '{0}' doesn't exist..
/// </summary>
internal static string DirectoryNotExists {
get {
return ResourceManager.GetString("DirectoryNotExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading blob '{0}' in container '{1}' is cancelled..
/// </summary>
internal static string DownloadBlobCancelled {
get {
return ResourceManager.GetString("DownloadBlobCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot download the blob '{0}' in container '{1}' into local file '{2}'. Error: {3}.
/// </summary>
internal static string DownloadBlobFailed {
get {
return ResourceManager.GetString("DownloadBlobFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download blob '{0}' successful..
/// </summary>
internal static string DownloadBlobSuccessful {
get {
return ResourceManager.GetString("DownloadBlobSuccessful", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Endpk must accompany Endrk..
/// </summary>
internal static string EndpkMustAccomanyEndrk {
get {
return ResourceManager.GetString("EndpkMustAccomanyEndrk", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} end processing, Start {1} remote calls. Finish {2} remote calls. Elapsed time {3:0.00} ms. Client operation id: {4}..
/// </summary>
internal static string EndProcessingLog {
get {
return ResourceManager.GetString("EndProcessingLog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to AZURE_STORAGE_CONNECTION_STRING.
/// </summary>
internal static string EnvConnectionString {
get {
return ResourceManager.GetString("EnvConnectionString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exception cannot be null or empty..
/// </summary>
internal static string ExceptionCannotEmpty {
get {
return ResourceManager.GetString("ExceptionCannotEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The expiry time of the specified access policy should be greater than start time. Expiry time : {0}. Start time: {1}..
/// </summary>
internal static string ExpiryTimeGreatThanStartTime {
get {
return ResourceManager.GetString("ExpiryTimeGreatThanStartTime", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Parameter -ExpiryTime and -NoExpiryTime are mutually exclusive.
/// </summary>
internal static string ExpiryTimeParameterConflict {
get {
return ResourceManager.GetString("ExpiryTimeParameterConflict", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File '{0}' already exists..
/// </summary>
internal static string FileAlreadyExists {
get {
return ResourceManager.GetString("FileAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find copy task on the specified file '{0}'..
/// </summary>
internal static string FileCopyTaskNotFound {
get {
return ResourceManager.GetString("FileCopyTaskNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File name can not be empty..
/// </summary>
internal static string FileNameCannotEmpty {
get {
return ResourceManager.GetString("FileNameCannotEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} ({1}){2}.
/// </summary>
internal static string FileNameFormatForSnapShot {
get {
return ResourceManager.GetString("FileNameFormatForSnapShot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given file name '{0}' is not valid since a file name could not end with a '/' forward slash..
/// </summary>
internal static string FileNameShouldNotEndWithSlash {
get {
return ResourceManager.GetString("FileNameShouldNotEndWithSlash", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find the specified file '{0}'..
/// </summary>
internal static string FileNotFound {
get {
return ResourceManager.GetString("FileNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to It doesn't support logging in Microsoft Azure File service..
/// </summary>
internal static string FileNotSupportLogging {
get {
return ResourceManager.GetString("FileNotSupportLogging", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Percent : {0}%..
/// </summary>
internal static string FileTransmitStatus {
get {
return ResourceManager.GetString("FileTransmitStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finish remote call for {0} with status code {1}({2}) and service request id {3}. Elapsed time {4:0.00} ms..
/// </summary>
internal static string FinishRemoteCall {
get {
return ResourceManager.GetString("FinishRemoteCall", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Get-AzStorageContainerAcl.
/// </summary>
internal static string GetAzureStorageContainerAclCmdletName {
get {
return ResourceManager.GetString("GetAzureStorageContainerAclCmdletName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Get-AzStorageContainer.
/// </summary>
internal static string GetAzureStorageContainerCmdletName {
get {
return ResourceManager.GetString("GetAzureStorageContainerCmdletName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fetch Permission for container '{0}' failed. Exception: {1}.
/// </summary>
internal static string GetContainerPermissionException {
get {
return ResourceManager.GetString("GetContainerPermissionException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Get storage account from environment variable 'AZURE_STORAGE_CONNECTION_STRING'..
/// </summary>
internal static string GetStorageAccountFromEnvironmentVariable {
get {
return ResourceManager.GetString("GetStorageAccountFromEnvironmentVariable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://{0}.blob.{1}/.
/// </summary>
internal static string HttpBlobEndPointFormat {
get {
return ResourceManager.GetString("HttpBlobEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://{0}.file.{1}/.
/// </summary>
internal static string HttpFileEndPointFormat {
get {
return ResourceManager.GetString("HttpFileEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://.
/// </summary>
internal static string HTTPPrefix {
get {
return ResourceManager.GetString("HTTPPrefix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://{0}.queue.{1}/.
/// </summary>
internal static string HttpQueueEndPointFormat {
get {
return ResourceManager.GetString("HttpQueueEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://{0}.blob.{1}/.
/// </summary>
internal static string HttpsBlobEndPointFormat {
get {
return ResourceManager.GetString("HttpsBlobEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://{0}.file.{1}/.
/// </summary>
internal static string HttpsFileEndPointFormat {
get {
return ResourceManager.GetString("HttpsFileEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://.
/// </summary>
internal static string HTTPSPrefix {
get {
return ResourceManager.GetString("HTTPSPrefix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://{0}.queue.{1}/.
/// </summary>
internal static string HttpsQueueEndPointFormat {
get {
return ResourceManager.GetString("HttpsQueueEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://{0}.table.{1}/.
/// </summary>
internal static string HttpsTableEndPointFormat {
get {
return ResourceManager.GetString("HttpsTableEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://{0}.table.{1}/.
/// </summary>
internal static string HttpTableEndPointFormat {
get {
return ResourceManager.GetString("HttpTableEndPointFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}bytes.
/// </summary>
internal static string HumanReadableSizeFormat_Bytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_Bytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}EB.
/// </summary>
internal static string HumanReadableSizeFormat_ExaBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_ExaBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}GB.
/// </summary>
internal static string HumanReadableSizeFormat_GigaBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_GigaBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}KB.
/// </summary>
internal static string HumanReadableSizeFormat_KiloBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_KiloBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}MB.
/// </summary>
internal static string HumanReadableSizeFormat_MegaBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_MegaBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}PB.
/// </summary>
internal static string HumanReadableSizeFormat_PetaBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_PetaBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0:0.##}TB.
/// </summary>
internal static string HumanReadableSizeFormat_TeraBytes {
get {
return ResourceManager.GetString("HumanReadableSizeFormat_TeraBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Init service channel from current subscription..
/// </summary>
internal static string InitChannelFromSubscription {
get {
return ResourceManager.GetString("InitChannelFromSubscription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Init Operation Context for '{0}' with client request id {1}. If you want to get more details, please add "-Debug" to your command..
/// </summary>
internal static string InitOperationContextLog {
get {
return ResourceManager.GetString("InitOperationContextLog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid access permission '{0}'..
/// </summary>
internal static string InvalidAccessPermission {
get {
return ResourceManager.GetString("InvalidAccessPermission", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid access policy '{0}'..
/// </summary>
internal static string InvalidAccessPolicy {
get {
return ResourceManager.GetString("InvalidAccessPolicy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Access policy name '{0}' is invalid. Valid names should be 1 through 64 characters long..
/// </summary>
internal static string InvalidAccessPolicyName {
get {
return ResourceManager.GetString("InvalidAccessPolicyName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Access policy type is invalid, only SharedAccessBlobPolicy, SharedAccessQueuePolicy, and SharedAccessTablePolicy are supported.
/// </summary>
internal static string InvalidAccessPolicyType {
get {
return ResourceManager.GetString("InvalidAccessPolicyType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to invalid parameter combination, please see the command help..
/// </summary>
internal static string InvalidAccountParameterCombination {
get {
return ResourceManager.GetString("InvalidAccountParameterCombination", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob name '{0}' is invalid. Valid names should be 1 through 1024 characters long and should not end with a . or /..
/// </summary>
internal static string InvalidBlobName {
get {
return ResourceManager.GetString("InvalidBlobName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob properties '{0}' with value '{1}' is invalid.
/// </summary>
internal static string InvalidBlobProperties {
get {
return ResourceManager.GetString("InvalidBlobProperties", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blob type '{0}' of blob '{1}' is not supported..
/// </summary>
internal static string InvalidBlobType {
get {
return ResourceManager.GetString("InvalidBlobType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CloudBlob "{0}" should contain container properties..
/// </summary>
internal static string InvalidBlobWithoutContainer {
get {
return ResourceManager.GetString("InvalidBlobWithoutContainer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Container name '{0}' is invalid. Valid names start and end with a lower case letter or a number and has in between a lower case letter, number or dash with no consecutive dashes and is 3 through 63 characters long..
/// </summary>
internal static string InvalidContainerName {
get {
return ResourceManager.GetString("InvalidContainerName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid enum name {0}..
/// </summary>
internal static string InvalidEnumName {
get {
return ResourceManager.GetString("InvalidEnumName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid expiry time '{0}'..
/// </summary>
internal static string InvalidExpiryTime {
get {
return ResourceManager.GetString("InvalidExpiryTime", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File name "{0}" is invalid..
/// </summary>
internal static string InvalidFileName {
get {
return ResourceManager.GetString("InvalidFileName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is an invalid HTTP method..
/// </summary>
internal static string InvalidHTTPMethod {
get {
return ResourceManager.GetString("InvalidHTTPMethod", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The page blob size must be a multiple of 512 bytes. But the size of local file '{0}' is {1}..
/// </summary>
internal static string InvalidPageBlobSize {
get {
return ResourceManager.GetString("InvalidPageBlobSize", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Queue name '{0}' is invalid. Valid names start and end with a lower case letter or a number and has in between a lower case letter, number or dash with no consecutive dashes and is 3 through 63 characters long..
/// </summary>
internal static string InvalidQueueName {
get {
return ResourceManager.GetString("InvalidQueueName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified path does not represent any resource on the server..
/// </summary>
internal static string InvalidResource {
get {
return ResourceManager.GetString("InvalidResource", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The minimum value of retention days is 1, the largest value is 365 (one year). -1 means turn off the retention policy. Current is {0}..
/// </summary>
internal static string InvalidRetentionDay {
get {
return ResourceManager.GetString("InvalidRetentionDay", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid start time '{0}'..
/// </summary>
internal static string InvalidStartTime {
get {
return ResourceManager.GetString("InvalidStartTime", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid storage end point '{0}'..
/// </summary>
internal static string InvalidStorageEndPoint {
get {
return ResourceManager.GetString("InvalidStorageEndPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Storage service type should be one of Blob,Table,Queue..
/// </summary>
internal static string InvalidStorageServiceType {
get {
return ResourceManager.GetString("InvalidStorageServiceType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Table name '{0}' is invalid. Valid names are case insensitive, start with a letter and is followed by letters or numbers and is 3 through 63 characters long..
/// </summary>
internal static string InvalidTableName {
get {
return ResourceManager.GetString("InvalidTableName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified timeout value ({0}) was out of range. The timeout accepted is in seconds and can only be a positive integer or -1..
/// </summary>
internal static string InvalidTimeoutValue {
get {
return ResourceManager.GetString("InvalidTimeoutValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to New-Alias.
/// </summary>
internal static string NewAlias {
get {
return ResourceManager.GetString("NewAlias", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name.
/// </summary>
internal static string NewAliasName {
get {
return ResourceManager.GetString("NewAliasName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Value.
/// </summary>
internal static string NewAliasValue {
get {
return ResourceManager.GetString("NewAliasValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None or All operation can't be used with other operations..
/// </summary>
internal static string NoneAndAllOperationShouldBeAlone {
get {
return ResourceManager.GetString("NoneAndAllOperationShouldBeAlone", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Object '{0}' cannot be null..
/// </summary>
internal static string ObjectCannotBeNull {
get {
return ResourceManager.GetString("ObjectCannotBeNull", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only support to copy from azure file to a block blob..
/// </summary>
internal static string OnlyCopyFromBlockBlobToAzureFile {
get {
return ResourceManager.GetString("OnlyCopyFromBlockBlobToAzureFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must supply only one permission in Off/Blob/Container for container..
/// </summary>
internal static string OnlyOnePermissionForContainer {
get {
return ResourceManager.GetString("OnlyOnePermissionForContainer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure to overwrite '{0}'?.
/// </summary>
internal static string OverwriteConfirmation {
get {
return ResourceManager.GetString("OverwriteConfirmation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given path/prefix '{0}' is not a valid name for a file or directory or does match the requirement for Microsoft Azure File Service REST API..
/// </summary>
internal static string PathInvalid {
get {
return ResourceManager.GetString("PathInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The length of the given path/prefix '{0}' exceeded the max allowed length {1} for Microsoft Azure File Service REST API..
/// </summary>
internal static string PathTooLong {
get {
return ResourceManager.GetString("PathTooLong", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Policy '{0}' already exists..
/// </summary>
internal static string PolicyAlreadyExists {
get {
return ResourceManager.GetString("PolicyAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find policy '{0}'..
/// </summary>
internal static string PolicyNotFound {
get {
return ResourceManager.GetString("PolicyNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Prepare to download blob..
/// </summary>
internal static string PrepareDownloadingBlob {
get {
return ResourceManager.GetString("PrepareDownloadingBlob", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Prepare to download file..
/// </summary>
internal static string PrepareDownloadingFile {
get {
return ResourceManager.GetString("PrepareDownloadingFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Prepare to upload blob..
/// </summary>
internal static string PrepareUploadingBlob {
get {
return ResourceManager.GetString("PrepareUploadingBlob", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Prepare to upload file..
/// </summary>
internal static string PrepareUploadingFile {
get {
return ResourceManager.GetString("PrepareUploadingFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Queue '{0}' already exists..
/// </summary>
internal static string QueueAlreadyExists {
get {
return ResourceManager.GetString("QueueAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find queue '{0}'..
/// </summary>
internal static string QueueNotFound {
get {
return ResourceManager.GetString("QueueNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download blob '{0}' into '{1}'..
/// </summary>
internal static string ReceiveAzureBlobActivity {
get {
return ResourceManager.GetString("ReceiveAzureBlobActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download file '{0}' into '{1}'..
/// </summary>
internal static string ReceiveAzureFileActivity {
get {
return ResourceManager.GetString("ReceiveAzureFileActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remove operation of blob '{0}' in container '{1}' is cancelled..
/// </summary>
internal static string RemoveBlobCancelled {
get {
return ResourceManager.GetString("RemoveBlobCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed blob '{0}' in container '{1}' successfully..
/// </summary>
internal static string RemoveBlobSuccessfully {
get {
return ResourceManager.GetString("RemoveBlobSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remove operation of container '{0}' has been cancelled..
/// </summary>
internal static string RemoveContainerCancelled {
get {
return ResourceManager.GetString("RemoveContainerCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed container '{0}' successfully..
/// </summary>
internal static string RemoveContainerSuccessfully {
get {
return ResourceManager.GetString("RemoveContainerSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remove operation of policy '{0}' has been cancelled..
/// </summary>
internal static string RemovePolicyCancelled {
get {
return ResourceManager.GetString("RemovePolicyCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed policy '{0}' successfully..
/// </summary>
internal static string RemovePolicySuccessfully {
get {
return ResourceManager.GetString("RemovePolicySuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remove operation of queue '{0}' has been cancelled..
/// </summary>
internal static string RemoveQueueCancelled {
get {
return ResourceManager.GetString("RemoveQueueCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed queue '{0}' successfully..
/// </summary>
internal static string RemoveQueueSuccessfully {
get {
return ResourceManager.GetString("RemoveQueueSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remove operation of table '{0}' has been cancelled..
/// </summary>
internal static string RemoveTableCancelled {
get {
return ResourceManager.GetString("RemoveTableCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed table '{0}' successfully..
/// </summary>
internal static string RemoveTableSuccessfully {
get {
return ResourceManager.GetString("RemoveTableSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to [SasToken].
/// </summary>
internal static string SasTokenAccountName {
get {
return ResourceManager.GetString("SasTokenAccountName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload file '{0}' to blob '{1}' in container '{2}'..
/// </summary>
internal static string SendAzureBlobActivity {
get {
return ResourceManager.GetString("SendAzureBlobActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload file '{0}' to blob '{1}' cancelled..
/// </summary>
internal static string SendAzureBlobCancelled {
get {
return ResourceManager.GetString("SendAzureBlobCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload file '{0}' to '{1}' in share '{2}'..
/// </summary>
internal static string SendAzureFileActivity {
get {
return ResourceManager.GetString("SendAzureFileActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The given share name/prefix '{0}' is not a valid name for a file share of Microsoft Azure File Service; refer to https://msdn.microsoft.com/library/azure/dn167011.aspx for details..
/// </summary>
internal static string ShareNameInvalid {
get {
return ResourceManager.GetString("ShareNameInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This expiry time field must be omitted if it has been specified in an associated stored access policy..
/// </summary>
internal static string SignedExpiryTimeMustBeOmitted {
get {
return ResourceManager.GetString("SignedExpiryTimeMustBeOmitted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This permission field must be omitted if it has been specified in an associated stored access policy..
/// </summary>
internal static string SignedPermissionsMustBeOmitted {
get {
return ResourceManager.GetString("SignedPermissionsMustBeOmitted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This start time field must be omitted if it has been specified in an associated stored access policy..
/// </summary>
internal static string SignedStartTimeMustBeOmitted {
get {
return ResourceManager.GetString("SignedStartTimeMustBeOmitted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skip to download blob '{0}' with snapshot time '{0}'..
/// </summary>
internal static string SkipDownloadSnapshot {
get {
return ResourceManager.GetString("SkipDownloadSnapshot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified source file '{0}' was not found..
/// </summary>
internal static string SourceFileNotFound {
get {
return ResourceManager.GetString("SourceFileNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ignore mismatch source storage context.. The source uri is {0}, the end point is {1}..
/// </summary>
internal static string StartCopySourceContextMismatch {
get {
return ResourceManager.GetString("StartCopySourceContextMismatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start to download blob '{0}' to '{1}'..
/// </summary>
internal static string StartDownloadBlob {
get {
return ResourceManager.GetString("StartDownloadBlob", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Startpk must accompany startrk..
/// </summary>
internal static string StartpkMustAccomanyStartrk {
get {
return ResourceManager.GetString("StartpkMustAccomanyStartrk", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start {0}th remote call, method: {1}, destination: {2}..
/// </summary>
internal static string StartRemoteCall {
get {
return ResourceManager.GetString("StartRemoteCall", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Parameter -StartTime and -NoStartTime are mutually exclusive.
/// </summary>
internal static string StartTimeParameterConflict {
get {
return ResourceManager.GetString("StartTimeParameterConflict", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start to upload '{0}' to blob '{1}'..
/// </summary>
internal static string StartUploadFile {
get {
return ResourceManager.GetString("StartUploadFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Stopped the copy task on blob '{0}' in container '{1}' successfully..
/// </summary>
internal static string StopCopyBlobSuccessfully {
get {
return ResourceManager.GetString("StopCopyBlobSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Stopped the copy task on file '{0}' successfully..
/// </summary>
internal static string StopCopyFileSuccessfully {
get {
return ResourceManager.GetString("StopCopyFileSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The stop copy operation on blob '{0}' in container '{1}' is cancelled..
/// </summary>
internal static string StopCopyOperationCancelled {
get {
return ResourceManager.GetString("StopCopyOperationCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} stop processing, Use {1} remote calls. Elapsed time {2:0.00} ms. Client operation id: {3}..
/// </summary>
internal static string StopProcessingLog {
get {
return ResourceManager.GetString("StopProcessingLog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error Message {0}. HTTP Status Code: {1} - HTTP Error Message: {2}.
/// </summary>
internal static string StorageExceptionDetails {
get {
return ResourceManager.GetString("StorageExceptionDetails", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Table '{0}' already exists..
/// </summary>
internal static string TableAlreadyExists {
get {
return ResourceManager.GetString("TableAlreadyExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not find table '{0}'..
/// </summary>
internal static string TableNotFound {
get {
return ResourceManager.GetString("TableNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transfer Summary
///--------------------------------
///Total: {0}.
///Successful: {1}.
///Failed: {2}..
/// </summary>
internal static string TransferSummary {
get {
return ResourceManager.GetString("TransferSummary", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total: {0}. Successful: {1}. Failed: {2}. Active: {3}..
/// </summary>
internal static string TransmitActiveSummary {
get {
return ResourceManager.GetString("TransmitActiveSummary", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} task status :.
/// </summary>
internal static string TransmitActivity {
get {
return ResourceManager.GetString("TransmitActivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transmit cancelled by user..
/// </summary>
internal static string TransmitCancelled {
get {
return ResourceManager.GetString("TransmitCancelled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transmit failed. Exception: {0}..
/// </summary>
internal static string TransmitFailed {
get {
return ResourceManager.GetString("TransmitFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transmit successfully..
/// </summary>
internal static string TransmitSuccessfully {
get {
return ResourceManager.GetString("TransmitSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown blob..
/// </summary>
internal static string UnknownBlob {
get {
return ResourceManager.GetString("UnknownBlob", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not upload file to azure blob. Error: {0}..
/// </summary>
internal static string Upload2BlobFailed {
get {
return ResourceManager.GetString("Upload2BlobFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload file '{0}' failed. Error: '{1}'..
/// </summary>
internal static string UploadFileFailed {
get {
return ResourceManager.GetString("UploadFileFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload file '{0}' successfully..
/// </summary>
internal static string UploadFileSuccessfully {
get {
return ResourceManager.GetString("UploadFileSuccessfully", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use current storage account '{0}' from subscription '{1}'..
/// </summary>
internal static string UseCurrentStorageAccountFromSubscription {
get {
return ResourceManager.GetString("UseCurrentStorageAccountFromSubscription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use storage account '{0}' from storage context..
/// </summary>
internal static string UseStorageAccountFromContext {
get {
return ResourceManager.GetString("UseStorageAccountFromContext", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Valid environment names are: '{0}' and '{1}'.
/// </summary>
internal static string ValidEnvironmentName {
get {
return ResourceManager.GetString("ValidEnvironmentName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} {1}..
/// </summary>
internal static string VerboseLogFormat {
get {
return ResourceManager.GetString("VerboseLogFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Write to file '{0}' is denied..
/// </summary>
internal static string WritePermissionDenied {
get {
return ResourceManager.GetString("WritePermissionDenied", resourceCulture);
}
}
}
}
| 41.135071 | 279 | 0.551688 | [
"MIT"
] | bganapa/azure-powershell | src/Storage/custom/Dataplane.v2/ResourceV2.Designer.cs | 67,751 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.AccessApi
{
///<summary>
/// DispatchInterface _NavigationControl
/// SupportByVersion Access, 14,15
///</summary>
[SupportByVersionAttribute("Access", 14,15)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class _NavigationControl : NetOffice.OfficeApi.IAccessible
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_NavigationControl);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public _NavigationControl(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _NavigationControl(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822469.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.AccessApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.Application.LateBindingApiWrapperType) as NetOffice.AccessApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835973.aspx
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835390.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public object OldValue
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OldValue", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195251.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Properties Properties
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Properties", paramsArray);
NetOffice.AccessApi.Properties newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.Properties.LateBindingApiWrapperType) as NetOffice.AccessApi.Properties;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195260.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Children Controls
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Controls", paramsArray);
NetOffice.AccessApi.Children newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.Children.LateBindingApiWrapperType) as NetOffice.AccessApi.Children;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192112.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi._Hyperlink Hyperlink
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Hyperlink", paramsArray);
NetOffice.AccessApi._Hyperlink newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.AccessApi._Hyperlink;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845896.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.FormatConditions FormatConditions
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "FormatConditions", paramsArray);
NetOffice.AccessApi.FormatConditions newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.FormatConditions.LateBindingApiWrapperType) as NetOffice.AccessApi.FormatConditions;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff198282.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public object Value
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Value", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Value", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835034.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string EventProcPrefix
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "EventProcPrefix", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "EventProcPrefix", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string _Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "_Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "_Name", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822813.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte ControlType
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ControlType", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ControlType", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197345.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string StatusBarText
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "StatusBarText", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "StatusBarText", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197643.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public bool Visible
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Visible", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835678.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte DisplayWhen
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "DisplayWhen", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "DisplayWhen", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194929.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public bool Enabled
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Enabled", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Enabled", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff823039.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte FilterLookup
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "FilterLookup", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "FilterLookup", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192703.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public bool AutoTab
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AutoTab", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AutoTab", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192878.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public bool TabStop
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "TabStop", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "TabStop", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192261.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 TabIndex
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "TabIndex", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "TabIndex", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192730.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 Left
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Left", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Left", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196002.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 Top
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Top", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Top", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192486.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 Width
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Width", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Width", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822786.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 Height
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Height", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Height", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845838.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte BackStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BackStyle", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BackStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835065.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 BackColor
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BackColor", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BackColor", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821470.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte SpecialEffect
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "SpecialEffect", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "SpecialEffect", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197622.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte BorderStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderStyle", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194298.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte OldBorderStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OldBorderStyle", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OldBorderStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196470.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 BorderColor
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderColor", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderColor", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff820774.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte BorderWidth
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderWidth", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderWidth", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public byte BorderLineStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderLineStyle", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderLineStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197085.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string ShortcutMenuBar
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShortcutMenuBar", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ShortcutMenuBar", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192529.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string ControlTipText
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ControlTipText", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ControlTipText", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822084.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 HelpContextId
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "HelpContextId", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "HelpContextId", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195229.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 Section
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Section", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Section", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string ControlName
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ControlName", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ControlName", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195482.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string Tag
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Tag", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Tag", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195169.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public bool IsVisible
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "IsVisible", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "IsVisible", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197757.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool InSelection
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "InSelection", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "InSelection", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194936.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnGotFocus
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnGotFocus", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnGotFocus", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845848.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnLostFocus
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnLostFocus", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnLostFocus", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192893.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnClick
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnClick", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnClick", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845655.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnDblClick
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnDblClick", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnDblClick", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff823167.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnMouseDown
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseDown", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseDown", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845388.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnMouseMove
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseMove", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseMove", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff837196.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnMouseUp
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseUp", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseUp", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197363.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnKeyDown
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyDown", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyDown", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821490.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnKeyUp
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyUp", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyUp", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194738.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string OnKeyPress
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyPress", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyPress", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836320.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public byte ReadingOrder
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ReadingOrder", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ReadingOrder", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194460.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte KeyboardLanguage
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "KeyboardLanguage", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "KeyboardLanguage", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public byte AllowedText
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AllowedText", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AllowedText", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822408.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte ScrollBarAlign
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ScrollBarAlign", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ScrollBarAlign", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845881.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte NumeralShapes
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "NumeralShapes", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "NumeralShapes", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845214.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Name", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822780.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 LineSpacing
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "LineSpacing", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "LineSpacing", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835941.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi._SmartTags SmartTags
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "SmartTags", paramsArray);
NetOffice.AccessApi._SmartTags newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.AccessApi._SmartTags;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836263.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Enums.AcLayoutType Layout
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Layout", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.AccessApi.Enums.AcLayoutType)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845088.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 LeftPadding
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "LeftPadding", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "LeftPadding", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194235.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 TopPadding
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "TopPadding", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "TopPadding", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197331.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 RightPadding
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "RightPadding", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "RightPadding", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff837170.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int16 BottomPadding
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BottomPadding", paramsArray);
return NetRuntimeSystem.Convert.ToInt16(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BottomPadding", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195206.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineStyleLeft
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineStyleLeft", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineStyleLeft", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193991.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineStyleTop
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineStyleTop", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineStyleTop", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197059.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineStyleRight
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineStyleRight", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineStyleRight", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff198068.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineStyleBottom
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineStyleBottom", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineStyleBottom", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197052.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineWidthLeft
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineWidthLeft", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineWidthLeft", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836077.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineWidthTop
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineWidthTop", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineWidthTop", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845523.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineWidthRight
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineWidthRight", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineWidthRight", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193841.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public byte GridlineWidthBottom
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineWidthBottom", paramsArray);
return NetRuntimeSystem.Convert.ToByte(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineWidthBottom", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845904.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 GridlineColor
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineColor", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineColor", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192238.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Enums.AcHorizontalAnchor HorizontalAnchor
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "HorizontalAnchor", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.AccessApi.Enums.AcHorizontalAnchor)intReturnItem;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "HorizontalAnchor", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff844719.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Enums.AcVerticalAnchor VerticalAnchor
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "VerticalAnchor", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.AccessApi.Enums.AcVerticalAnchor)intReturnItem;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "VerticalAnchor", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnGotFocusMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnGotFocusMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnGotFocusMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnLostFocusMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnLostFocusMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnLostFocusMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnClickMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnClickMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnClickMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnDblClickMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnDblClickMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnDblClickMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnMouseDownMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseDownMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseDownMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnMouseMoveMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseMoveMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseMoveMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnMouseUpMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnMouseUpMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnMouseUpMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnKeyDownMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyDownMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyDownMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnKeyUpMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyUpMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyUpMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string OnKeyPressMacro
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "OnKeyPressMacro", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "OnKeyPressMacro", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192262.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 LayoutID
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "LayoutID", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string Target
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Target", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Target", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196463.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 BackThemeColorIndex
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BackThemeColorIndex", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BackThemeColorIndex", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834358.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single BackTint
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BackTint", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BackTint", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192682.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single BackShade
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BackShade", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BackShade", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff198253.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 BorderThemeColorIndex
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderThemeColorIndex", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderThemeColorIndex", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197368.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single BorderTint
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderTint", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderTint", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194107.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single BorderShade
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BorderShade", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "BorderShade", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194329.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Int32 GridlineThemeColorIndex
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineThemeColorIndex", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineThemeColorIndex", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff837332.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single GridlineTint
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineTint", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineTint", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836553.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public Single GridlineShade
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "GridlineShade", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "GridlineShade", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836071.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public string SubForm
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "SubForm", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "SubForm", paramsArray);
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821405.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Children Tabs
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Tabs", paramsArray);
NetOffice.AccessApi.Children newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.Children.LateBindingApiWrapperType) as NetOffice.AccessApi.Children;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff197379.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.NavigationButton SelectedTab
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "SelectedTab", paramsArray);
NetOffice.AccessApi.NavigationButton newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.AccessApi.NavigationButton.LateBindingApiWrapperType) as NetOffice.AccessApi.NavigationButton;
return newObject;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// Get/Set
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff820835.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public NetOffice.AccessApi.Enums.AcNavigationSpan Span
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Span", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.AccessApi.Enums.AcNavigationSpan)intReturnItem;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Span", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834747.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public void Undo()
{
object[] paramsArray = null;
Invoker.Method(this, "Undo", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195267.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public void SizeToFit()
{
object[] paramsArray = null;
Invoker.Method(this, "SizeToFit", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194868.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public void Requery()
{
object[] paramsArray = null;
Invoker.Method(this, "Requery", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
///
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersionAttribute("Access", 14,15)]
public void Goto()
{
object[] paramsArray = null;
Invoker.Method(this, "Goto", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195869.aspx
/// </summary>
[SupportByVersionAttribute("Access", 14,15)]
public void SetFocus()
{
object[] paramsArray = null;
Invoker.Method(this, "SetFocus", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
///
/// </summary>
/// <param name="bstrExpr">string bstrExpr</param>
/// <param name="ppsa">optional object[] ppsa</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersionAttribute("Access", 14,15)]
public object _Evaluate(string bstrExpr, object[] ppsa)
{
object[] paramsArray = Invoker.ValidateParamsArray(bstrExpr, (object)ppsa);
object returnItem = Invoker.MethodReturn(this, "_Evaluate", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
///
/// </summary>
/// <param name="bstrExpr">string bstrExpr</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[CustomMethodAttribute]
[SupportByVersionAttribute("Access", 14,15)]
public object _Evaluate(string bstrExpr)
{
object[] paramsArray = Invoker.ValidateParamsArray(bstrExpr);
object returnItem = Invoker.MethodReturn(this, "_Evaluate", paramsArray);
if((null != returnItem) && (returnItem is MarshalByRefObject))
{
COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem);
return newObject;
}
else
{
return returnItem;
}
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822712.aspx
/// </summary>
/// <param name="left">object Left</param>
/// <param name="top">optional object Top</param>
/// <param name="width">optional object Width</param>
/// <param name="height">optional object Height</param>
[SupportByVersionAttribute("Access", 14,15)]
public void Move(object left, object top, object width, object height)
{
object[] paramsArray = Invoker.ValidateParamsArray(left, top, width, height);
Invoker.Method(this, "Move", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822712.aspx
/// </summary>
/// <param name="left">object Left</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Access", 14,15)]
public void Move(object left)
{
object[] paramsArray = Invoker.ValidateParamsArray(left);
Invoker.Method(this, "Move", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822712.aspx
/// </summary>
/// <param name="left">object Left</param>
/// <param name="top">optional object Top</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Access", 14,15)]
public void Move(object left, object top)
{
object[] paramsArray = Invoker.ValidateParamsArray(left, top);
Invoker.Method(this, "Move", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822712.aspx
/// </summary>
/// <param name="left">object Left</param>
/// <param name="top">optional object Top</param>
/// <param name="width">optional object Width</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Access", 14,15)]
public void Move(object left, object top, object width)
{
object[] paramsArray = Invoker.ValidateParamsArray(left, top, width);
Invoker.Method(this, "Move", paramsArray);
}
/// <summary>
/// SupportByVersion Access 14, 15
///
/// </summary>
/// <param name="dispid">Int32 dispid</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersionAttribute("Access", 14,15)]
public bool IsMemberSafe(Int32 dispid)
{
object[] paramsArray = Invoker.ValidateParamsArray(dispid);
object returnItem = Invoker.MethodReturn(this, "IsMemberSafe", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
#endregion
#pragma warning restore
}
} | 30.236111 | 212 | 0.667246 | [
"MIT"
] | NetOffice/NetOffice | Source/Access/DispatchInterfaces/_NavigationControl.cs | 69,664 | C# |
using Shouldly.Tests.Strings;
using Xunit;
namespace Shouldly.Tests.ShouldNotBeEmpty
{
public class ArrayScenario
{
[Fact]
public void ArrayScenarioShouldFail()
{
Verify.ShouldFail(() =>
new int[0].ShouldNotBeEmpty("Some additional context"),
errorWithSource:
@"new int[0]
should not be empty but was
Additional Info:
Some additional context",
errorWithoutSource:
@"[]
should not be empty but was
Additional Info:
Some additional context");
}
[Fact]
public void ShouldPass()
{
new[] {1}.ShouldNotBeEmpty();
}
}
} | 16.444444 | 55 | 0.662162 | [
"BSD-3-Clause"
] | EvilMindz/shouldly | src/Shouldly.Tests/ShouldNotBeEmpty/ArrayScenario.cs | 594 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using FT = MS.Internal.Xml.XPath.Function.FunctionType;
namespace MS.Internal.Xml.XPath
{
internal sealed class NodeFunctions : ValueQuery
{
private Query _arg = null;
private FT _funcType;
private XsltContext _xsltContext;
public NodeFunctions(FT funcType, Query arg)
{
_funcType = funcType;
_arg = arg;
}
public override void SetXsltContext(XsltContext context)
{
_xsltContext = context.Whitespace ? context : null;
if (_arg != null)
{
_arg.SetXsltContext(context);
}
}
private XPathNavigator EvaluateArg(XPathNodeIterator context)
{
if (_arg == null)
{
return context.Current;
}
_arg.Evaluate(context);
return _arg.Advance();
}
public override object Evaluate(XPathNodeIterator context)
{
XPathNavigator argVal;
switch (_funcType)
{
case FT.FuncPosition:
return (double)context.CurrentPosition;
case FT.FuncLast:
return (double)context.Count;
case FT.FuncNameSpaceUri:
argVal = EvaluateArg(context);
if (argVal != null)
{
return argVal.NamespaceURI;
}
break;
case FT.FuncLocalName:
argVal = EvaluateArg(context);
if (argVal != null)
{
return argVal.LocalName;
}
break;
case FT.FuncName:
argVal = EvaluateArg(context);
if (argVal != null)
{
return argVal.Name;
}
break;
case FT.FuncCount:
_arg.Evaluate(context);
int count = 0;
if (_xsltContext != null)
{
XPathNavigator nav;
while ((nav = _arg.Advance()) != null)
{
if (nav.NodeType != XPathNodeType.Whitespace || _xsltContext.PreserveWhitespace(nav))
{
count++;
}
}
}
else
{
while (_arg.Advance() != null)
{
count++;
}
}
return (double)count;
}
return string.Empty;
}
public override XPathResultType StaticType { get { return Function.ReturnTypes[(int)_funcType]; } }
public override XPathNodeIterator Clone()
{
NodeFunctions method = new NodeFunctions(_funcType, Clone(_arg));
method._xsltContext = _xsltContext;
return method;
}
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
w.WriteAttributeString("name", _funcType.ToString());
if (_arg != null)
{
_arg.PrintQuery(w);
}
w.WriteEndElement();
}
}
}
| 31.316667 | 113 | 0.445716 | [
"MIT"
] | 690486439/corefx | src/System.Xml.XPath/src/System/Xml/XPath/Internal/NodeFunctions.cs | 3,758 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoT.Model
{
/// <summary>
/// This is the response object from the ListThingGroups operation.
/// </summary>
public partial class ListThingGroupsResponse : AmazonWebServiceResponse
{
private string _nextToken;
private List<GroupNameAndArn> _thingGroups = new List<GroupNameAndArn>();
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token used to get the next set of results, or <b>null</b> if there are no additional
/// results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ThingGroups.
/// <para>
/// The thing groups.
/// </para>
/// </summary>
public List<GroupNameAndArn> ThingGroups
{
get { return this._thingGroups; }
set { this._thingGroups = value; }
}
// Check to see if ThingGroups property is set
internal bool IsSetThingGroups()
{
return this._thingGroups != null && this._thingGroups.Count > 0;
}
}
} | 30.038961 | 101 | 0.623 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/ListThingGroupsResponse.cs | 2,313 | C# |
using System;
using FluentNHibernate.Testing;
using NUnit.Framework;
using StickEmApp.Dal;
using StickEmApp.Entities;
namespace StickEmApp.UnitTest.Dal.Mapping
{
[TestFixture]
public class VendorMappingTestFixture : UnitOfWorkAwareTestFixture
{
[Test]
public void TestMap()
{
new PersistenceSpecification<Vendor>(UnitOfWorkManager.Session)
.CheckProperty(c => c.Name, "foo")
.CheckProperty(c => c.StartedAt, new DateTime(2016, 4, 12, 10, 30, 0))
.CheckProperty(c => c.FinishedAt, new DateTime(2016, 4, 12, 15, 00, 0))
.CheckProperty(c => c.ChangeReceived, new Money(55))
.CheckProperty(c => c.NumberOfStickersReceived, 10)
.CheckProperty(c => c.NumberOfStickersReturned, 5)
.CheckProperty(c => c.AmountReturned.FiveHundreds, 1)
.CheckProperty(c => c.AmountReturned.TwoHundreds, 1)
.CheckProperty(c => c.AmountReturned.Hundreds, 1)
.CheckProperty(c => c.AmountReturned.Fifties, 1)
.CheckProperty(c => c.AmountReturned.Twenties, 1)
.CheckProperty(c => c.AmountReturned.Tens, 1)
.CheckProperty(c => c.AmountReturned.Fives, 1)
.CheckProperty(c => c.AmountReturned.Twos, 1)
.CheckProperty(c => c.AmountReturned.Ones, 1)
.CheckProperty(c => c.AmountReturned.FiftyCents, 1)
.CheckProperty(c => c.AmountReturned.TwentyCents, 1)
.CheckProperty(c => c.AmountReturned.TenCents, 1)
.CheckProperty(c => c.AmountReturned.FiveCents, 1)
.CheckProperty(c => c.AmountReturned.TwoCents, 1)
.CheckProperty(c => c.AmountReturned.OneCents, 1)
.CheckProperty(c => c.Status, VendorStatus.Removed)
.VerifyTheMappings();
}
}
} | 44.829268 | 83 | 0.624048 | [
"MIT"
] | jdt/StickEmApp | Source/StickEmApp/StickEmApp.UnitTest/Dal/Mapping/VendorMappingTestFixture.cs | 1,840 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NEXCORE.Common;
using NEXCORE.Common.Data;
using System.Collections;
namespace SK.WMS.INV50.CON.UI
{
public partial class CON5030 : SKUserControlBase
{
public CON5030()
{
InitializeComponent();
}
}
}
| 19.130435 | 52 | 0.706818 | [
"MIT"
] | hsi79/SK.WMS | 60.UI Layer/SK.WMS.INV50.CON.UI/CON5030.cs | 442 | C# |
//=======================================================================
// Copyright (C) 2010-2013 William Hallahan
//
// 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.
//=======================================================================
//======================================================================
// Generic Class: Sparse4DMatrix
// Author: Bill Hallahan
// Date: April 12, 2010
//======================================================================
using System;
using System.Collections.Generic;
namespace SparseCollections
{
/// <summary>
/// This class implements a sparse 4 dimensional matrix.
/// </summary>
/// <typeparam name="TKey0">The first key type used to index the array items</typeparam>
/// <typeparam name="TKey1">The second key type used to index the array items</typeparam>
/// <typeparam name="TKey2">The third key type used to index the array items</typeparam>
/// <typeparam name="TKey3">The fourth key type used to index the array items</typeparam>
/// <typeparam name="TValue">The type of the array values</typeparam>
[Serializable]
public class Sparse4DMatrix<TKey0, TKey1, TKey2, TKey3, TValue> : IEnumerable<KeyValuePair<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue>>
where TKey0 : IComparable<TKey0>
where TKey1 : IComparable<TKey1>
where TKey2 : IComparable<TKey2>
where TKey3 : IComparable<TKey3>
{
private Dictionary<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue> m_dictionary;
/// <summary>
/// This property stores the default value that is returned if the keys don't exist in the array.
/// </summary>
public TValue DefaultValue
{
get;
set;
}
/// <summary>
/// Property to get the count of items in the sparse array.
/// </summary>
public int Count
{
get
{
return m_dictionary.Count;
}
}
#region Constructors
/// <summary>
/// Constructor - creates an empty sparse array instance.
/// </summary>
public Sparse4DMatrix()
{
InitializeDictionary();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="defaultValue">A default value to return if the key is not present.</param>
public Sparse4DMatrix(TValue defaultValue)
{
InitializeDictionary();
DefaultValue = defaultValue;
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="sparse4DMatrix">The sparse array instance to be copied</param>
public Sparse4DMatrix(Sparse4DMatrix<TKey0, TKey1, TKey2, TKey3, TValue> sparse4DMatrix)
{
InitializeDictionary();
Initialize(sparse4DMatrix);
DefaultValue = sparse4DMatrix.DefaultValue;
}
#endregion
/// <summary>
/// Initialize the dictionary to compare items based on key values.
/// </summary>
private void InitializeDictionary()
{
ComparableTuple4EqualityComparer<TKey0, TKey1, TKey2, TKey3> equalityComparer = new ComparableTuple4EqualityComparer<TKey0, TKey1, TKey2, TKey3>();
m_dictionary = new Dictionary<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue>(equalityComparer);
}
/// <summary>
/// Method to copy the data in another Sparse4DMatrix instance to this instance.
/// </summary>
/// <param name="sparse4DMatrix">An instance of the Sparse4DMatrix class.</param>
private void Initialize(Sparse4DMatrix<TKey0, TKey1, TKey2, TKey3, TValue> sparse4DMatrix)
{
m_dictionary.Clear();
// Copy each key value pair to the dictionary.
foreach (KeyValuePair<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue> pair in sparse4DMatrix)
{
ComparableTuple4<TKey0, TKey1, TKey2, TKey3> newCombinedKey = new ComparableTuple4<TKey0, TKey1, TKey2, TKey3>(pair.Key);
m_dictionary.Add(newCombinedKey, pair.Value);
}
}
/// <summary>
/// Method to copy the data in this Sparse4DMatrix instance to another instance.
/// </summary>
/// <param name="sparse4DMatrix">An instance of the Sparse4DMatrix class.</param>
public void CopyTo(Sparse4DMatrix<TKey0, TKey1, TKey2, TKey3, TValue> sparse4DMatrix)
{
sparse4DMatrix.m_dictionary.Clear();
// Copy each key value pair to the dictionary.
foreach (KeyValuePair<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue> pair in m_dictionary)
{
ComparableTuple4<TKey0, TKey1, TKey2, TKey3> newCombinedKey = new ComparableTuple4<TKey0, TKey1, TKey2, TKey3>(pair.Key);
sparse4DMatrix.m_dictionary.Add(newCombinedKey, pair.Value);
}
}
/// <summary>
/// Property []
/// </summary>
/// <param name="key0">The first key used to index the value</param>
/// <param name="key1">The second key used to index the value</param>
/// <param name="key2">The third key used to index the value</param>
/// <param name="key3">The fourth key used to index the value</param>
/// <returns>The 'get' property returns the value at the current key</returns>
public TValue this[TKey0 key0, TKey1 key1, TKey2 key2, TKey3 key3]
{
get
{
TValue value;
if (!m_dictionary.TryGetValue(CombineKeys(key0, key1, key2, key3), out value))
{
value = DefaultValue;
}
return value;
}
set
{
m_dictionary[CombineKeys(key0, key1, key2, key3)] = value;
}
}
/// <summary>
/// Determines whether this matrix contains the specified keys.
/// </summary>
/// <param name="key0">The first key used to index the value</param>
/// <param name="key1">The second key used to index the value</param>
/// <param name="key2">The third key used to index the value</param>
/// <param name="key3">The fourth key used to index the value</param>
/// <returns>Returns the value 'true' if and only if the keys exists in this matrix</returns>
public bool ContainsKey(TKey0 key0, TKey1 key1, TKey2 key2, TKey3 key3)
{
return m_dictionary.ContainsKey(CombineKeys(key0, key1, key2, key3));
}
/// <summary>
/// Determines whether this matrix contains the specified value.
/// </summary>
/// <param name="value">A value</param>
/// <returns>Returns the value 'true' if and only if the value exists in this matrix</returns>
public bool ContainsValue(TValue value)
{
return m_dictionary.ContainsValue(value);
}
/// <summary>
/// Gets the value for the associated keys.
/// </summary>
/// <param name="key0">The first key used to index the value</param>
/// <param name="key1">The second key used to index the value</param>
/// <param name="key2">The third key used to index the value</param>
/// <param name="key3">The fourth key used to index the value</param>
/// <param name="value">An out parameter that contains the value if the key exists</param>
/// <returns>Returns the value 'true' if and only if the key exists in this matrix</returns>
public bool TryGetValue(TKey0 key0, TKey1 key1, TKey2 key2, TKey3 key3, out TValue value)
{
return m_dictionary.TryGetValue(CombineKeys(key0, key1, key2, key3), out value);
}
/// <summary>
/// Removes the value with the specified key from this sparse matrix instance.
/// </summary>
/// <param name="key0">The first key of the element to remove</param>
/// <param name="key1">The second key of the element to remove</param>
/// <param name="key2">The third key used to index the value</param>
/// <param name="key3">The fourth key used to index the value</param>
/// <returns>The value 'true' if and only if the element is successfully found and removed.</returns>
public bool Remove(TKey0 key0, TKey1 key1, TKey2 key2, TKey3 key3)
{
return m_dictionary.Remove(CombineKeys(key0, key1, key2, key3));
}
/// <summary>
/// Method to clear all values in the sparse array.
/// </summary>
public void Clear()
{
m_dictionary.Clear();
}
/// <summary>
/// This method must be overridden by the caller to combine the keys.
/// </summary>
/// <param name="key0">The first key</param>
/// <param name="key1">The second key</param>
/// <param name="key2">The third key</param>
/// <param name="key3">The fourth key</param>
/// <returns>A value that combines the keys in a unique fashion</returns>
public ComparableTuple4<TKey0, TKey1, TKey2, TKey3> CombineKeys(TKey0 key0, TKey1 key1, TKey2 key2, TKey3 key3)
{
return new ComparableTuple4<TKey0, TKey1, TKey2, TKey3>(key0, key1, key2, key3);
}
/// <summary>
/// This method must be overridden by the caller to separate a combined key into the two original keys.
/// </summary>
/// <param name="combinedKey">A value that combines the keys in a unique fashion</param>
/// <param name="key0">A reference to the first key</param>
/// <param name="key1">A reference to the second key</param>
/// <param name="key2">A reference to the third key</param>
/// <param name="key3">A reference to the fourth key</param>
public void SeparateCombinedKeys(ComparableTuple4<TKey0, TKey1, TKey2, TKey3> combinedKey,
ref TKey0 key0,
ref TKey1 key1,
ref TKey2 key2,
ref TKey3 key3)
{
key0 = combinedKey.Item0;
key1 = combinedKey.Item1;
key2 = combinedKey.Item2;
key3 = combinedKey.Item3;
}
#region IEnumerable<KeyValuePair<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue>> Members
/// <summary>
/// The Generic IEnumerator<> GetEnumerator method
/// </summary>
/// <returns>An enumerator to iterate over all key-value pairs in this sparse array</returns>
public IEnumerator<KeyValuePair<ComparableTuple4<TKey0, TKey1, TKey2, TKey3>, TValue>> GetEnumerator()
{
return this.m_dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// The non-generic IEnumerator<> GetEnumerator method
/// </summary>
/// <returns>An enumerator to iterate over all key-value pairs in this sparse array</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.m_dictionary.GetEnumerator();
}
#endregion
}
}
| 42.962199 | 159 | 0.593825 | [
"MIT"
] | WorkingRobot/WorldExplorer | WorldExplorer/SparseCollections/Sparse4DMatrix.cs | 12,504 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Strawberrey.API
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
} | 22.16 | 57 | 0.723827 | [
"MIT"
] | Nufflee/Strawberrey | src/Strawberrey.API/Program.cs | 556 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServiceFabric.ServiceBus.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceFabric.ServiceBus.Services")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0c1ad577-93e3-437c-a0c7-5918e0f4d575")]
| 42.708333 | 84 | 0.782439 | [
"MIT"
] | gdodd1977/ServiceFabric.ServiceBus | ServiceFabric.ServiceBus.Services/Properties/AssemblyInfo.cs | 1,028 | C# |
// * **************************************************************************
// * Copyright (c) Clinton Sheppard <sheppard@cs.unm.edu>
// *
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// *
// * source repository: https://github.com/handcraftsman/Afluistic
// * **************************************************************************
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Afluistic.Services
{
public interface IJsonSerializer
{
T DeserializeFromFile<T>(string path);
void SerializeToFile<T>(string path, T obj);
}
public class JsonSerializer : IJsonSerializer
{
private readonly IFileSystemService _fileSystemService;
public JsonSerializer(IFileSystemService fileSystemService)
{
_fileSystemService = fileSystemService;
}
public T DeserializeFromFile<T>(string path)
{
var serializer = Newtonsoft.Json.JsonSerializer.Create(new JsonSerializerSettings());
serializer.Converters.Add(new NamedConstantJsonConverter());
using (var reader = _fileSystemService.GetStreamReader(path))
{
var content = (T)serializer.Deserialize(reader, typeof(T));
return content;
}
}
public void SerializeToFile<T>(string path, T obj)
{
var serializer = new Newtonsoft.Json.JsonSerializer
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.Converters.Add(new NamedConstantJsonConverter());
using (var streamWriter = _fileSystemService.GetStreamWriter(path))
{
using (var jsonTextWriter = new JsonTextWriter(streamWriter))
{
jsonTextWriter.Formatting = Formatting.Indented;
using (var writer = jsonTextWriter)
{
serializer.Serialize(writer, obj);
}
}
}
}
}
} | 38.235294 | 97 | 0.575769 | [
"MIT"
] | handcraftsman/Afluistic | src/Afluistic/Services/JsonSerializer.cs | 2,600 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.KeyVault.V20200401Preview.Inputs
{
/// <summary>
/// Properties of the vault
/// </summary>
public sealed class VaultPropertiesArgs : Pulumi.ResourceArgs
{
[Input("accessPolicies")]
private InputList<Inputs.AccessPolicyEntryArgs>? _accessPolicies;
/// <summary>
/// An array of 0 to 1024 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access policies are required.
/// </summary>
public InputList<Inputs.AccessPolicyEntryArgs> AccessPolicies
{
get => _accessPolicies ?? (_accessPolicies = new InputList<Inputs.AccessPolicyEntryArgs>());
set => _accessPolicies = value;
}
/// <summary>
/// The vault's create mode to indicate whether the vault need to be recovered or not.
/// </summary>
[Input("createMode")]
public Input<Pulumi.AzureNative.KeyVault.V20200401Preview.CreateMode>? CreateMode { get; set; }
/// <summary>
/// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - that is, the property does not accept false as its value.
/// </summary>
[Input("enablePurgeProtection")]
public Input<bool>? EnablePurgeProtection { get; set; }
/// <summary>
/// Property that controls how data actions are authorized. When true, the key vault will use Role Based Access Control (RBAC) for authorization of data actions, and the access policies specified in vault properties will be ignored (warning: this is a preview feature). When false, the key vault will use the access policies specified in vault properties, and any policy stored on Azure Resource Manager will be ignored. If null or not specified, the vault is created with the default value of false. Note that management actions are always authorized with RBAC.
/// </summary>
[Input("enableRbacAuthorization")]
public Input<bool>? EnableRbacAuthorization { get; set; }
/// <summary>
/// Property to specify whether the 'soft delete' functionality is enabled for this key vault. If it's not set to any value(true or false) when creating new key vault, it will be set to true by default. Once set to true, it cannot be reverted to false.
/// </summary>
[Input("enableSoftDelete")]
public Input<bool>? EnableSoftDelete { get; set; }
/// <summary>
/// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.
/// </summary>
[Input("enabledForDeployment")]
public Input<bool>? EnabledForDeployment { get; set; }
/// <summary>
/// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.
/// </summary>
[Input("enabledForDiskEncryption")]
public Input<bool>? EnabledForDiskEncryption { get; set; }
/// <summary>
/// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.
/// </summary>
[Input("enabledForTemplateDeployment")]
public Input<bool>? EnabledForTemplateDeployment { get; set; }
/// <summary>
/// Rules governing the accessibility of the key vault from specific network locations.
/// </summary>
[Input("networkAcls")]
public Input<Inputs.NetworkRuleSetArgs>? NetworkAcls { get; set; }
/// <summary>
/// Provisioning state of the vault.
/// </summary>
[Input("provisioningState")]
public InputUnion<string, Pulumi.AzureNative.KeyVault.V20200401Preview.VaultProvisioningState>? ProvisioningState { get; set; }
/// <summary>
/// SKU details
/// </summary>
[Input("sku", required: true)]
public Input<Inputs.SkuArgs> Sku { get; set; } = null!;
/// <summary>
/// softDelete data retention days. It accepts >=7 and <=90.
/// </summary>
[Input("softDeleteRetentionInDays")]
public Input<int>? SoftDeleteRetentionInDays { get; set; }
/// <summary>
/// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.
/// </summary>
[Input("tenantId", required: true)]
public Input<string> TenantId { get; set; } = null!;
/// <summary>
/// The URI of the vault for performing operations on keys and secrets.
/// </summary>
[Input("vaultUri")]
public Input<string>? VaultUri { get; set; }
public VaultPropertiesArgs()
{
EnableRbacAuthorization = false;
EnableSoftDelete = true;
SoftDeleteRetentionInDays = 90;
}
}
}
| 48.258621 | 571 | 0.658985 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/KeyVault/V20200401Preview/Inputs/VaultPropertiesArgs.cs | 5,598 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace CodeSnippets.UnitTests
{
[Trait("代码片段", "异常操作测试")]
public class ExceptionOperationTest
{
}
}
| 14.428571 | 39 | 0.707921 | [
"MIT"
] | zhaobingwang/sample | test/CodeSnippets.UnitTests/ExceptionOperationTest.cs | 224 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************
using System.Collections.Generic;
using System;
using CustomDeviceAccess;
namespace SDKTemplate
{
public partial class MainPage
{
// Change the string below to reflect the name of your sample.
// This is used on the main page as the title of the sample.
public const string FEATURE_NAME = "CustomDeviceAccess";
// Change the array below to reflect the name of your scenarios.
// This will be used to populate the list of scenarios on the main page with
// which the user will choose the specific scenario that they are interested in.
// These should be in the form: "Navigating to a web page".
// The code in MainPage will take care of turning this into: "1) Navigating to a web page"
List<Scenario> scenarios = new List<Scenario>
{
new Scenario() { Title = "Connecting to the Fx2 Device", ClassType = typeof(CustomDeviceAccess.DeviceConnect) },
new Scenario() { Title = "Sending IOCTLs to and from the device", ClassType = typeof(CustomDeviceAccess.DeviceIO) },
new Scenario() { Title = "Handling asynchronous device events", ClassType = typeof(CustomDeviceAccess.DeviceEvents) },
new Scenario() { Title = "Read and Write operations", ClassType = typeof(CustomDeviceAccess.DeviceReadWrite) },
};
}
public class Scenario
{
public string Title { get; set; }
public Type ClassType { get; set; }
public override string ToString()
{
return Title;
}
}
}
| 40.2 | 136 | 0.586512 | [
"MIT"
] | mfloresn90/CSharpSources | Custom driver access sample/C#/Constants.cs | 1,809 | C# |
using System;
namespace EasyDeploy.Core.Logger
{
public class ConsoleLogger : ILogger
{
public void Exception(Exception exception)
{
Log(exception.Message); // TODO: better :-)
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
}
| 18.555556 | 55 | 0.556886 | [
"MIT"
] | frostieDE/easy-deploy | EasyDeploy.Core/Logger/ConsoleLogger.cs | 336 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// You already have a snapshot with the given name.
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public partial class SnapshotAlreadyExistsException : AmazonElastiCacheException
{
/// <summary>
/// Constructs a new SnapshotAlreadyExistsException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public SnapshotAlreadyExistsException(string message)
: base(message) {}
/// <summary>
/// Construct instance of SnapshotAlreadyExistsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public SnapshotAlreadyExistsException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of SnapshotAlreadyExistsException
/// </summary>
/// <param name="innerException"></param>
public SnapshotAlreadyExistsException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of SnapshotAlreadyExistsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public SnapshotAlreadyExistsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of SnapshotAlreadyExistsException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public SnapshotAlreadyExistsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the SnapshotAlreadyExistsException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected SnapshotAlreadyExistsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.887097 | 178 | 0.683563 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/SnapshotAlreadyExistsException.cs | 5,938 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace StoreDL.Migrations
{
public partial class EMM : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 17.833333 | 71 | 0.657321 | [
"Unlicense"
] | 211004-Reston-NET/Angel-Santos-P1 | StoreDL/Migrations/20211213232439_EMM.cs | 323 | C# |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2017
// by DotNetNuke Corporation
//
// 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
#region Usings
using System.Text.RegularExpressions;
#endregion
namespace DotNetNuke.Services.Localization
{
public static class LocalizationExtensions
{
public const string ResxFileLocaleRegex = "(?i)(.*)\\.((\\w\\w-)?\\w{2,3}-\\w{2,3})(\\.resx)$(?-i)";
private static readonly Regex FileNameMatchRegex = new Regex(ResxFileLocaleRegex, RegexOptions.Compiled);
/// <summary>
/// Gets the name of the locale code from a resource file.
/// E.g. My file with.fancy-characters.fr-FR.resx should return "fr-FR".
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>Microsoft compatible locale code</returns>
public static string GetLocaleCodeFromFileName(this string fileName)
{
var m = FileNameMatchRegex.Match(fileName);
return m.Success ? m.Groups[2].Value : string.Empty;
}
/// <summary>
/// Gets the file name part from localized resource file.
/// E.g. My file with.fancy-characters.fr-FR.resx should return "My file with.fancy-characters".
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>File name stripped of culture code or extension</returns>
public static string GetFileNameFromLocalizedResxFile(this string fileName)
{
var m = FileNameMatchRegex.Match(fileName);
return m.Success ? m.Groups[1].Value : string.Empty;
}
}
}
| 46.135593 | 116 | 0.688464 | [
"MIT"
] | Expasys/Expasys.Web.Platform | DNN Platform/Library/Services/Localization/LocalizationExtensions.cs | 2,725 | C# |
using System;
using PrimeFuncPack.UnitTest;
using Xunit;
using static PrimeFuncPack.UnitTest.TestData;
namespace PrimeFuncPack.Tests;
partial class TwoDependencyTest
{
[Fact]
public void From_Resolver_FirstIsNull_ExpectArgumentNullException()
{
var second = ZeroIdRefType;
var ex = Assert.Throws<ArgumentNullException>(
() => _ = Dependency<StructType, RefType>.From(
null!,
_ => second));
Assert.Equal("first", ex.ParamName);
}
[Fact]
public void From_Resolver_SecondIsNull_ExpectArgumentNullException()
{
var first = SomeString;
var ex = Assert.Throws<ArgumentNullException>(
() => _ = Dependency<string?, RecordType>.From(
_ => first,
null!));
Assert.Equal("second", ex.ParamName);
}
[Theory]
[MemberData(nameof(TestEntitySource.RefTypes), MemberType = typeof(TestEntitySource))]
public void From_Resolver_ResolversAreNotNull_ExpectResolvedValuesAreEqualToSource(
RefType? sourceSecond)
{
var sourceFirst = new { Name = SomeString };
var actual = Dependency<object, RefType?>.From(
_ => sourceFirst,
_ => sourceSecond);
var actualValue = actual.Resolve();
var expectedValue = (sourceFirst, sourceSecond);
Assert.Equal(expectedValue, actualValue);
}
}
| 26.886792 | 90 | 0.633684 | [
"MIT"
] | pfpack/pfpack-dependency-pipeline | src/dependency-core/Core.Tests/Tests.Dependency.02/Factory/From.Resolver.cs | 1,425 | C# |
using JPBotelho;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class FlyCam : MonoBehaviour
{
[SerializeField]
private float speed = 10;
[SerializeField]
private float positionDampTime = 0.2f;
[SerializeField]
private float tangentDampTime = 4;
[SerializeField]
private float farDetectionRange = 25;
[SerializeField]
private float obstacleDetectionRange = 2;
[SerializeField]
private float advanceFrameRatio = 0.5f;
[SerializeField]
private int splineResolution = 20;
private const int mask = 1 << 8;
private const int controlPointCount = 6;
private int maxIndex;
private int index;
private float t;
private Frame frame;
private CaveSystem cave;
private CatmullRom spline;
private CatmullRom.CatmullRomPoint[] splinePoints;
private Queue<Vector3> controlPoints;
private bool waitForCaveReady = true;
private Vector3 position;
private Vector3 posDampVelo;
private Vector3 tangent;
private Vector3 tanDampVelo;
void Start()
{
cave = FindObjectOfType<CaveSystem>();
cave.Initialize(transform);
cave.OnReset();
frame = new Frame(transform);
spline = new CatmullRom(splineResolution);
controlPoints = new Queue<Vector3>(controlPointCount);
controlPoints.Enqueue(frame.origin);
maxIndex = splineResolution * 3 - 1;
}
private void LateUpdate()
{
if (!waitForCaveReady)
{
WalkSpline();
}
else if (cave.AllChunksActive())
{
waitForCaveReady = false;
UpdateSpline();
}
}
private void WalkSpline()
{
if (t < 1f)
{
t += speed * Time.deltaTime;
}
else
{
t -= 1f;
if (index < maxIndex)
{
index++;
}
else
{
index = splineResolution * 2;
controlPoints.Dequeue();
UpdateSpline();
}
}
var a = splinePoints[index];
var b = splinePoints[index + 1];
Vector3 pos = Vector3.Lerp(a.position, b.position, t);
Vector3 tan = Vector3.Lerp(a.tangent, b.tangent, t);
pos += GetCentroid(transform, obstacleDetectionRange);
position = Vector3.SmoothDamp(position, pos, ref posDampVelo, positionDampTime);
tangent = Vector3.SmoothDamp(tangent, tan, ref tanDampVelo, tangentDampTime);
transform.position = position;
transform.rotation = Quaternion.LookRotation(tangent);
// spline.DrawSpline(Color.white);
}
private void UpdateSpline()
{
while (controlPoints.Count < controlPointCount)
{
frame.origin += GetFarthest(frame, farDetectionRange) * advanceFrameRatio;
controlPoints.Enqueue(frame.origin);
}
spline.Update(controlPoints);
splinePoints = spline.GetPoints();
}
private static Vector3 GetFarthest(Frame frame, float range, float angle = 45, float resolution = 6)
{
Ray[] rays = frame.GetRays(angle);
Vector3 delta = Vector3.zero;
for (int i = 0; i < rays.Length; i++)
{
if (Physics.Raycast(rays[i], out RaycastHit hit, range, mask))
{
if (hit.distance > delta.magnitude)
{
delta = hit.point - rays[i].origin;
}
}
else
{
delta = rays[i].direction * range;
break;
}
}
if (angle < resolution)
{
// 5.625 (45/8) degree resolution in 4th iteration, 17 raycasts total.
return delta;
}
frame.Update(delta.normalized);
return GetFarthest(frame, range, angle * 0.5f, resolution);
}
public static Vector3 GetCentroid(Transform origin, float range)
{
Vector3 c = Vector3.zero;
Vector3 p = origin.position;
Quaternion r = origin.rotation;
for (int i = 0; i < sphere.Length; i++)
{
Vector3 d = r * sphere[i];
c += Physics.Raycast(p, d, out RaycastHit hit, range, mask)
? hit.point - p
: d * range;
}
return c / (float)sphere.Length;
}
private static Vector3[] sphere = CalcFibonacciSphere(32);
private static Vector3[] CalcFibonacciSphere(int n)
{
Vector3[] v = new Vector3[n];
float phi = Mathf.PI * (3f - Mathf.Sqrt(5f));
for (int i = 0; i < n; i++)
{
float y = 1 - (i / (n - 1f)) * 2;
float theta = phi * i;
float r = Mathf.Sqrt(1 - y * y);
float x = Mathf.Cos(theta) * r;
float z = Mathf.Sin(theta) * r;
v[i] = new Vector3(x, y, z);
}
return v;
}
}
public class Frame
{
public Vector3 origin;
public Vector3 right;
public Vector3 up;
public Vector3 forward;
public Frame(Transform transform) : this(transform.position, transform.forward, transform.up)
{
}
public Frame(Vector3 origin, Vector3 forward, Vector3 up)
{
this.origin = origin;
Update(forward, up);
}
public void Update(Vector3 forward, Vector3 up)
{
this.forward = forward;
this.right = Vector3.Cross(forward, -up);
this.up = Vector3.Cross(forward, right);
}
public void Update(Vector3 forward)
{
Update(forward, up);
}
public Ray[] GetRays(float angle)
{
return angle < 45
? new Ray[4]
{
new Ray(origin, Quaternion.AngleAxis(angle, up) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, -up) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, right) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, -right) * forward)
}
: new Ray[5]
{
new Ray(origin, forward), // only needed for 1st iteration
new Ray(origin, Quaternion.AngleAxis(angle, up) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, -up) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, right) * forward),
new Ray(origin, Quaternion.AngleAxis(angle, -right) * forward)
};
}
public void Draw()
{
Debug.DrawRay(origin, right, Color.red);
Debug.DrawRay(origin, up, Color.green);
Debug.DrawRay(origin, forward, Color.blue);
}
} | 28.782979 | 104 | 0.554701 | [
"MIT"
] | mbaske/procedural-cave | Assets/DemoScene/FlyCam.cs | 6,766 | C# |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Data;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class ForeignKeyConstraint_Equals_O : GHTBase
{
[Test] public void Main()
{
ForeignKeyConstraint_Equals_O tc = new ForeignKeyConstraint_Equals_O();
Exception exp = null;
try
{
tc.BeginTest("ForeignKeyConstraint_Equals_O");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
DataSet ds = new DataSet();
DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable();
DataTable dtChild = GHTUtils.DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
dtParent.PrimaryKey = new DataColumn[] {dtParent.Columns[0]};
ds.EnforceConstraints = true;
ForeignKeyConstraint fc1,fc2;
fc1 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);
fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[1]);
try
{
BeginCase("different columnn");
Compare(fc1.Equals(fc2),false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
try
{
BeginCase("same column");
fc2 = new ForeignKeyConstraint(dtParent.Columns[0],dtChild.Columns[0]);
Compare(fc1.Equals(fc2),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
}
}
} | 30.028037 | 86 | 0.727669 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Data/Test/System.Data.Tests.Mainsoft/System.Data/ForeignKeyConstraint/ForeignKeyConstraint_Equals_O.cs | 3,213 | C# |
namespace BurnSystems.Collections
{
/// <summary>
/// This interface has to be implemented by all objects, having a certain
/// key-object and wants to be used the advantages of the autodictionary
/// for example.
/// </summary>
public interface IHasKey
{
/// <summary>
/// Gets the name of the key of the instance
/// </summary>
string Key
{
get;
}
}
}
| 22.4 | 77 | 0.555804 | [
"MIT"
] | mbrenn/burnsystems | src/BurnSystems/Collections/IHasKey.cs | 450 | C# |
using System;
namespace Epam.Task3.Game
{
public class Player : Objects, IAction, IDraw
{
public void Circumvent()
{
}
public void TakeBonus()
{
}
public override void Draw()
{
throw new NotImplementedException();
}
void IAction.Move()
{
}
void IAction.Attack()
{
}
void IAction.Die()
{
}
}
}
| 14.181818 | 49 | 0.442308 | [
"MIT"
] | VeronicaDedova/XT-2018Q4 | Task3/Epam.Task3.Game/Objects/Player.cs | 470 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using VaporStore.Data.Models.Enums;
namespace VaporStore.DataProcessor.Dto.Import
{
public class ImportCardJsonDto
{
[RegularExpression(@"(\d{4}) (\d{4}) (\d{4}) (\d{4})")]
[Required]
public string Number { get; set; }
[RegularExpression(@"(\d{3})")]
[Required]
public string CVC { get; set; }
[Required]
public string Type { get; set; }
}
}
| 23.173913 | 63 | 0.617261 | [
"MIT"
] | aalishov/SoftUni | 06-Entity-Framework-Core-June-2020/Exams/Exam/01. Model Definition_Skeleton + Datasets/VaporStore/DataProcessor/Dto/Import/ImportCardJsonDto.cs | 535 | C# |
using System;
namespace CqrsMovie.SharedKernel.Domain.Ids
{
public class MovieId : DomainId
{
public MovieId(Guid value) : base(value)
{
}
}
}
| 13.583333 | 44 | 0.656442 | [
"MIT"
] | Iridio/CQRS-ES_testing_workshop | CqrsMovie.SharedKernel/Domain/Ids/MovieId.cs | 165 | C# |
using Netboot.Utility.Cache.Domains;
using System;
namespace Netboot.Utility.Cache.Extensions
{
public static class DistributedCacheOptionsExtensions
{
public static DistributedCacheOptions UseSerialization(
this DistributedCacheOptions options,
Func<object, byte[]> serializer,
Func<byte[], Type, object> deserializer)
{
options.Serializer = serializer;
options.Deserializer = deserializer;
return options;
}
}
} | 27.578947 | 63 | 0.648855 | [
"MIT"
] | NetbootCommunity/Dotnet-Cache | Src/Netboot.Utility.Cache/Extensions/DistributedCacheOptionsExtensions.cs | 526 | C# |
using LoanApi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LoanApi.Repository
{
public class SmsRepository : GenericRepository<Sms>, ISmsRepository
{
public SmsRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public IQueryable<Sms> GetAll()
{
return _dbContext.Sms.Include(x => x.Account).Include(x => x.Customer).AsQueryable();
}
public IQueryable<SmsBoardcast> GetBroadcast()
{
return _dbContext.SmsBoardcast.AsQueryable();
}
public async Task<SmsBoardcast> InsertBroadcast(SmsBoardcast sms)
{
_dbContext.SmsBoardcast.Add(sms);
await _dbContext.SaveChangesAsync();
return sms;
}
}
}
| 25.685714 | 97 | 0.629588 | [
"MIT"
] | anwarul/loanapi | LoanApi/Repository/SmsRepository.cs | 901 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Atm")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("oriana")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 35.107143 | 81 | 0.735504 | [
"MIT"
] | OrianaCadavid/real-time-programming | Atm/Atm/Properties/AssemblyInfo.cs | 985 | C# |
// <auto-generated />
using System;
using FileExample.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FileExample.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20200407151409_AddedUploadedImageTable")]
partial class AddedUploadedImageTable
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("FileExample.Models.UploadedImage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<DateTime>("DateUploaded")
.HasColumnType("timestamp without time zone");
b.Property<string>("ImageUrl")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("UploadImages");
});
#pragma warning restore 612, 618
}
}
}
| 36.333333 | 128 | 0.634862 | [
"MIT"
] | suncoast-devs/cohort-17 | week-08/FileExample/Migrations/20200407151409_AddedUploadedImageTable.Designer.cs | 1,637 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public partial class CommandLineProjectTests : TestBase
{
[Fact]
public void TestCreateWithoutRequiredServices()
{
string commandLine = @"goo.cs";
Assert.Throws<InvalidOperationException>(delegate
{
var ws = new AdhocWorkspace(); // only includes portable services
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory", ws);
});
}
[Fact]
public void TestCreateWithRequiredServices()
{
string commandLine = @"goo.cs";
var ws = new AdhocWorkspace(DesktopMefHostServices.DefaultServices); // includes non-portable services too
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory", ws);
}
[Fact]
public void TestUnrootedPathInsideProjectCone()
{
string commandLine = @"goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(0, docInfo.Folders.Count);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestUnrootedSubPathInsideProjectCone()
{
string commandLine = @"subdir\goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(1, docInfo.Folders.Count);
Assert.Equal("subdir", docInfo.Folders[0]);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestRootedPathInsideProjectCone()
{
string commandLine = @"c:\ProjectDirectory\goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(0, docInfo.Folders.Count);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestRootedSubPathInsideProjectCone()
{
string commandLine = @"c:\projectDirectory\subdir\goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(1, docInfo.Folders.Count);
Assert.Equal("subdir", docInfo.Folders[0]);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestRootedPathOutsideProjectCone()
{
string commandLine = @"C:\SomeDirectory\goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(0, docInfo.Folders.Count);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestUnrootedPathOutsideProjectCone()
{
string commandLine = @"..\goo.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var docInfo = info.Documents.First();
Assert.Equal(0, docInfo.Folders.Count);
Assert.Equal("goo.cs", docInfo.Name);
}
[Fact]
public void TestAdditionalFiles()
{
string commandLine = @"goo.cs /additionalfile:bar.cs";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var firstDoc = info.Documents.Single();
var secondDoc = info.AdditionalDocuments.Single();
Assert.Equal("goo.cs", firstDoc.Name);
Assert.Equal("bar.cs", secondDoc.Name);
}
[Fact]
public void TestAnalyzerReferences()
{
var pathToAssembly = typeof(object).Assembly.Location;
var assemblyBaseDir = Path.GetDirectoryName(pathToAssembly);
var relativePath = Path.Combine(".", Path.GetFileName(pathToAssembly));
string commandLine = @"goo.cs /a:" + relativePath;
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, assemblyBaseDir);
var firstDoc = info.Documents.Single();
var analyzerRef = info.AnalyzerReferences.First();
Assert.Equal("goo.cs", firstDoc.Name);
Assert.Equal(pathToAssembly, analyzerRef.FullPath);
}
}
}
| 40.037879 | 161 | 0.628004 | [
"Apache-2.0"
] | AdamSpeight2008/roslyn-1 | src/Workspaces/CoreTest/WorkspaceTests/CommandLineProjectTests.cs | 5,287 | C# |
//-----------------------------------------------------------------------
// <copyright file="ExampleUnit.cs" company="Junle Li">
// Copyright (c) Junle Li. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Vsxmd.Units
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
/// <summary>
/// Example unit.
/// </summary>
internal class ExampleUnit : BaseUnit
{
/// <summary>
/// Initializes a new instance of the <see cref="ExampleUnit"/> class.
/// </summary>
/// <param name="element">The example XML element.</param>
/// <exception cref="ArgumentException">Throw if XML element name is not <c>example</c>.</exception>
internal ExampleUnit(XElement element)
: base(element, "example")
{
}
/// <inheritdoc />
public override IEnumerable<string> ToMarkdown() =>
new[]
{
"### Ejemplo de código",
"<CodeBlock slots='heading, code' repeat='3' languages='C#' /> ",
"\n",
"#### Code",
$"```",
$"{this.ElementContent}",
$"```",
"\n",
};
/// <summary>
/// Convert the example XML element to Markdown safely.
/// If element is <value>null</value>, return empty string.
/// </summary>
/// <param name="element">The example XML element.</param>
/// <returns>The generated Markdown.</returns>
internal static IEnumerable<string> ToMarkdown(XElement element) =>
element != null
? new ExampleUnit(element).ToMarkdown()
: Enumerable.Empty<string>();
}
}
| 33.690909 | 108 | 0.481382 | [
"MIT"
] | trifenix/Vsxmd | Vsxmd/Units/ExampleUnit.cs | 1,856 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace mvc_conventions
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 30.637931 | 143 | 0.61058 | [
"MIT"
] | jeremybytes/mvc-conventions-aspnet | Startup.cs | 1,777 | C# |
#region Using Statements
using System;
using System.Threading;
using System.Globalization;
using RogueEssence.Content;
using RogueEssence.Data;
using RogueEssence.Dev;
using RogueEssence.Dungeon;
using RogueEssence.Script;
using RogueEssence;
using PMDC.Dev;
using System.Reflection;
using Microsoft.Xna.Framework;
using Avalonia;
using RogueEssence.Ground;
using SDL2;
using RogueElements;
using System.IO;
#endregion
namespace PMDC
{
/// <summary>
/// The main class.
/// </summary>
public static class Program
{
//[System.Runtime.InteropServices.DllImport("user32.dll")]
//static extern bool SetProcessDPIAware();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
InitDllMap();
//SetProcessDPIAware();
//TODO: figure out how to set this switch in appconfig
AppContext.SetSwitch("Switch.System.Runtime.Serialization.SerializationGuard.AllowFileWrites", true);
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
string[] args = Environment.GetCommandLineArgs();
PathMod.InitExePath(args[0]);
DiagManager.InitInstance();
DiagManager.Instance.CurSettings = DiagManager.Instance.LoadSettings();
DiagManager.Instance.UpgradeBinder = new UpgradeBinder();
try
{
DiagManager.Instance.LogInfo("=========================================");
DiagManager.Instance.LogInfo(String.Format("SESSION STARTED: {0}", String.Format("{0:yyyy/MM/dd HH:mm:ss}", DateTime.Now)));
DiagManager.Instance.LogInfo("Version: " + Versioning.GetVersion().ToString());
DiagManager.Instance.LogInfo(Versioning.GetDotNetInfo());
DiagManager.Instance.LogInfo("=========================================");
bool logInput = true;
bool guideBook = false;
GraphicsManager.AssetType convertAssets = GraphicsManager.AssetType.None;
DataManager.DataType convertIndices = DataManager.DataType.None;
DataManager.DataType reserializeIndices = DataManager.DataType.None;
string langArgs = "";
bool dev = false;
string mod = "";
bool buildMod = false;
string playInputs = null;
for (int ii = 1; ii < args.Length; ii++)
{
if (args[ii] == "-dev")
dev = true;
else if (args[ii] == "-play" && args.Length > ii + 1)
{
playInputs = args[ii + 1];
ii++;
}
else if (args[ii] == "-lang" && args.Length > ii + 1)
{
langArgs = args[ii + 1];
ii++;
}
else if (args[ii] == "-nolog")
logInput = false;
else if (args[ii] == "-guide")
guideBook = true;
else if (args[ii] == "-asset")
{
PathMod.ASSET_PATH = Path.GetFullPath(args[ii + 1]);
ii++;
}
else if (args[ii] == "-raw")
{
PathMod.DEV_PATH = Path.GetFullPath(args[ii + 1]);
ii++;
}
else if (args[ii] == "-mod")
{
mod = args[ii + 1];
ii++;
}
else if (args[ii] == "-build")
{
buildMod = true;
ii++;
}
else if (args[ii] == "-convert")
{
int jj = 1;
while (args.Length > ii + jj)
{
GraphicsManager.AssetType conv = GraphicsManager.AssetType.None;
foreach (GraphicsManager.AssetType type in Enum.GetValues(typeof(GraphicsManager.AssetType)))
{
if (args[ii + jj].ToLower() == type.ToString().ToLower())
{
conv = type;
break;
}
}
if (conv != GraphicsManager.AssetType.None)
convertAssets |= conv;
else
break;
jj++;
}
ii += jj - 1;
}
else if (args[ii] == "-index")
{
int jj = 1;
while (args.Length > ii + jj)
{
DataManager.DataType conv = DataManager.DataType.None;
foreach (DataManager.DataType type in Enum.GetValues(typeof(DataManager.DataType)))
{
if (args[ii + jj].ToLower() == type.ToString().ToLower())
{
conv = type;
break;
}
}
if (conv != DataManager.DataType.None)
convertIndices |= conv;
else
break;
jj++;
}
ii += jj - 1;
}
else if (args[ii] == "-reserialize")
{
int jj = 1;
while (args.Length > ii + jj)
{
DataManager.DataType conv = DataManager.DataType.None;
foreach (DataManager.DataType type in Enum.GetValues(typeof(DataManager.DataType)))
{
if (args[ii + jj].ToLower() == type.ToString().ToLower())
{
conv = type;
break;
}
}
if (conv != DataManager.DataType.None)
reserializeIndices |= conv;
else
break;
jj++;
}
ii += jj - 1;
}
}
DiagManager.Instance.SetupGamepad();
GraphicsManager.InitParams();
DiagManager.Instance.DevMode = dev;
if (mod != "")
{
if (Directory.Exists(Path.Combine(PathMod.MODS_PATH, mod)))
{
PathMod.Mod = PathMod.MODS_FOLDER + mod;
DiagManager.Instance.LogInfo(String.Format("Loaded mod \"{0}\".", mod));
}
else
DiagManager.Instance.LogInfo(String.Format("Cannot find mod \"{0}\" in {1}. Falling back to base game.", mod, PathMod.MODS_PATH));
}
if (playInputs != null)
DiagManager.Instance.LoadInputs(playInputs);
Text.Init();
if (langArgs != "" && DiagManager.Instance.CurSettings.Language == "")
{
if (langArgs.Length > 0)
{
DiagManager.Instance.CurSettings.Language = langArgs.ToLower();
Text.SetCultureCode(langArgs.ToLower());
}
else
DiagManager.Instance.CurSettings.Language = "en";
}
Text.SetCultureCode(DiagManager.Instance.CurSettings.Language == "" ? "" : DiagManager.Instance.CurSettings.Language.ToString());
if (buildMod)
{
if (PathMod.Mod == "")
{
DiagManager.Instance.LogInfo("No mod specified to build.");
return;
}
RogueEssence.Dev.DevHelper.MergeMod(mod);
return;
}
if (convertAssets != GraphicsManager.AssetType.None)
{
//run conversions
using (GameBase game = new GameBase())
{
GraphicsManager.InitSystem(game.GraphicsDevice);
GraphicsManager.RunConversions(convertAssets);
}
return;
}
if (reserializeIndices != DataManager.DataType.None)
{
DiagManager.Instance.LogInfo("Beginning Reserialization");
//we need the datamanager for this, but only while data is hardcoded
//TODO: remove when data is no longer hardcoded
LuaEngine.InitInstance();
DataManager.InitInstance();
DataManager.InitDataDirs(PathMod.ModPath(""));
RogueEssence.Dev.DevHelper.ReserializeBase();
DiagManager.Instance.LogInfo("Reserializing main data");
RogueEssence.Dev.DevHelper.Reserialize(reserializeIndices);
DiagManager.Instance.LogInfo("Reserializing map data");
if ((reserializeIndices & DataManager.DataType.Zone) != DataManager.DataType.None)
{
RogueEssence.Dev.DevHelper.ReserializeData<Map>(DataManager.DATA_PATH + "Map/", DataManager.MAP_EXT);
RogueEssence.Dev.DevHelper.ReserializeData<GroundMap>(DataManager.DATA_PATH + "Ground/", DataManager.GROUND_EXT);
}
DiagManager.Instance.LogInfo("Reserializing indices");
RogueEssence.Dev.DevHelper.RunIndexing(reserializeIndices);
DataManager.Instance.UniversalData = (TypeDict<BaseData>)RogueEssence.Dev.DevHelper.LoadWithLegacySupport(PathMod.ModPath(DataManager.MISC_PATH + "Index.bin"), typeof(TypeDict<BaseData>));
RogueEssence.Dev.DevHelper.RunExtraIndexing(reserializeIndices);
return;
}
if (convertIndices != DataManager.DataType.None)
{
//we need the datamanager for this, but only while data is hardcoded
//TODO: remove when data is no longer hardcoded
LuaEngine.InitInstance();
DataManager.InitInstance();
DiagManager.Instance.LogInfo("Reserializing indices");
DataManager.InitDataDirs(PathMod.ModPath(""));
RogueEssence.Dev.DevHelper.RunIndexing(convertIndices);
DataManager.Instance.UniversalData = (TypeDict<BaseData>)RogueEssence.Dev.DevHelper.LoadWithLegacySupport(PathMod.ModPath(DataManager.MISC_PATH + "Index.bin"), typeof(TypeDict<BaseData>));
RogueEssence.Dev.DevHelper.RunExtraIndexing(convertIndices);
return;
}
if (guideBook)
{
//print the guidebook in the chosen language
//we need the datamanager for this
LuaEngine.InitInstance();
DataManager.InitInstance();
DataManager.Instance.InitData();
//just print a guidebook and exit
StrategyGuide.PrintMoveGuide();
StrategyGuide.PrintItemGuide();
StrategyGuide.PrintAbilityGuide();
StrategyGuide.PrintEncounterGuide();
return;
}
//Dev.ImportManager.PrintMoveUsers(PathMod.DEV_PATH+"moves.txt");
//Dev.ImportManager.PrintAbilityUsers(PathMod.DEV_PATH+"abilities.txt");
logInput = false; //this feature is disabled for now...
if (DiagManager.Instance.ActiveDebugReplay == null && logInput)
DiagManager.Instance.BeginInput();
if (DiagManager.Instance.DevMode)
{
InitDataEditor();
AppBuilder builder = RogueEssence.Dev.Program.BuildAvaloniaApp();
builder.StartWithClassicDesktopLifetime(args);
}
else
{
DiagManager.Instance.DevEditor = new EmptyEditor();
using (GameBase game = new GameBase())
game.Run();
}
}
catch (Exception ex)
{
DiagManager.Instance.LogError(ex);
throw;
}
}
// We used to have to map dlls manually, but FNA has a provisional solution now.
// Keep these comments for clarity
public static void InitDllMap()
{
//CoreDllMap.Init();
//Assembly fnaAssembly = Assembly.GetAssembly(typeof(Game));
//CoreDllMap.Register(fnaAssembly);
//load SDL first before FNA3D to sidestep multiple dylibs problem
SDL.SDL_GetPlatform();
}
public static void InitDataEditor()
{
DataEditor.Init();
DataEditor.AddEditor(new StatusEffectEditor());
DataEditor.AddEditor(new MapStatusEditor());
DataEditor.AddEditor(new MoneySpawnZoneStepEditor());
//DataEditor.AddConverter(new AutoTileBaseConverter());
DataEditor.AddEditor(new DataFolderEditor());
DataEditor.AddEditor(new AnimDataEditor());
DataEditor.AddEditor(new SoundEditor());
DataEditor.AddEditor(new MusicEditor());
DataEditor.AddEditor(new EntryDataEditor());
DataEditor.AddEditor(new FrameTypeEditor());
DataEditor.AddEditor(new MapItemEditor());
DataEditor.AddEditor(new MultiStepSpawnerEditor());
DataEditor.AddEditor(new PickerSpawnerEditor());
DataEditor.AddEditor(new ContextSpawnerEditor());
DataEditor.AddEditor(new TeamStepSpawnerEditor());
DataEditor.AddEditor(new StepSpawnerEditor());
DataEditor.AddEditor(new GridPathCircleEditor());
DataEditor.AddEditor(new GridPathBranchEditor());
DataEditor.AddEditor(new AddConnectedRoomsStepEditor());
DataEditor.AddEditor(new AddDisconnectedRoomsStepEditor());
DataEditor.AddEditor(new ConnectRoomStepEditor());
DataEditor.AddEditor(new FloorPathBranchEditor());
DataEditor.AddEditor(new RoomGenCrossEditor());
DataEditor.AddEditor(new SizedRoomGenEditor());
DataEditor.AddEditor(new BasePowerStateEditor());
DataEditor.AddEditor(new AdditionalEffectStateEditor());
DataEditor.AddEditor(new PromoteBranchEditor());
DataEditor.AddEditor(new MonsterIDEditor());
DataEditor.AddEditor(new TeamMemberSpawnEditor());
DataEditor.AddEditor(new MobSpawnEditor());
DataEditor.AddEditor(new MapTilesEditor());
DataEditor.AddEditor(new BaseEmitterEditor());
DataEditor.AddEditor(new ZoneDataEditor());
DataEditor.AddEditor(new BattleDataEditor());
DataEditor.AddEditor(new BattleFXEditor());
DataEditor.AddEditor(new CircleSquareEmitterEditor());
DataEditor.AddEditor(new CombatActionEditor());
DataEditor.AddEditor(new ExplosionDataEditor());
//DataEditor.AddConverter(new ItemDataConverter());
//DataEditor.AddConverter(new TileLayerConverter());
DataEditor.AddEditor(new ShootingEmitterEditor());
DataEditor.AddEditor(new SkillDataEditor());
DataEditor.AddEditor(new ColumnAnimEditor());
DataEditor.AddEditor(new StaticAnimEditor());
DataEditor.AddEditor(new TypeDictEditor());
DataEditor.AddEditor(new RangeDictEditor(false, true));
DataEditor.AddEditor(new SpawnListEditor());
DataEditor.AddEditor(new SpawnRangeListEditor(false, true));
DataEditor.AddEditor(new PriorityListEditor());
DataEditor.AddEditor(new PriorityEditor());
DataEditor.AddEditor(new SegLocEditor());
DataEditor.AddEditor(new LocEditor());
DataEditor.AddEditor(new RandRangeEditor(false, true));
DataEditor.AddEditor(new RandPickerEditor());
DataEditor.AddEditor(new MultiRandPickerEditor());
DataEditor.AddEditor(new IntRangeEditor(false, true));
DataEditor.AddEditor(new FlagTypeEditor());
DataEditor.AddEditor(new ColorEditor());
DataEditor.AddEditor(new TypeEditor());
//TODO: there is no parameterless interface for hashset
//so instead we have to do the painful process of manually adding every hashset of every type we actually use. ugh
DataEditor.AddEditor(new HashSetEditor<int>());
DataEditor.AddEditor(new ArrayEditor());
DataEditor.AddEditor(new DictionaryEditor());
DataEditor.AddEditor(new NoDupeListEditor());
DataEditor.AddEditor(new ListEditor());
DataEditor.AddEditor(new EnumEditor());
DataEditor.AddEditor(new StringEditor());
DataEditor.AddEditor(new DoubleEditor());
DataEditor.AddEditor(new SingleEditor());
DataEditor.AddEditor(new BooleanEditor());
DataEditor.AddEditor(new IntEditor());
DataEditor.AddEditor(new ByteEditor());
DataEditor.AddEditor(new ObjectEditor());
}
}
} | 44.266033 | 208 | 0.5022 | [
"MIT"
] | PMDCollab/PMDC | PMDC/Program.cs | 18,638 | C# |
using LambdaSharp.App.EventBus;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Test.LambdaSharp.App.EventBus.EventPatternMatcherTests {
public class IsValid {
//--- Methods ---
[Fact]
public void Empty_pattern_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_literal_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": ""Bar""
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_empty_list_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_text_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_numeric_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ 42 ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_null_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ null ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_nested_list_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ [ 42 ] ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_prefix_text_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": ""Bar"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_prefix_numeric_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": 42 } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_prefix_null_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": null } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_prefix_list_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": [ ""Bar"" ] } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_anything_but_text_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": ""Bar"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_anything_but_numeric_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": 42 } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_anything_but_list_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": [ ""Bar"" ] } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_anything_but_content_filter_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": { ""prefix"": ""Bar"" } } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_numeric_one_operation_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""numeric"": [ ""="", 42 ] } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_numeric_two_operations_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""numeric"": [ "">"", 42, ""<"", 404 ] } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_cidr_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""1.1.1.1/24"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_cidr_bad_ip_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""1.404.1.1/24"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_cidr_bad_prefix_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""1.1.1.1/42"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_exists_is_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": true } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
[Fact]
public void Pattern_with_exists_text_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": ""Bar"" } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_exists_numeric_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": 42 } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_exists_null_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": null } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_invalid_filter_is_not_valid() {
// arrange
var pattern = JObject.Parse(@"{
""Foo"": [ { ""Bar"": 42 } ]
}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeFalse();
}
[Fact]
public void Pattern_with_null_serialized_is_valid() {
// arrange
var pattern = JObject.Parse("{\"source\":[\"Sample.BlazorEventsSample:1.0-DEV@stevebv7-lambdasharp-cor-deploymentbucketresource-9h53iqcat7uj::MyBlazorApp\"],\"detail-type\":[\"Sample.BlazorEventsSample.MyBlazorApp.Shared.TodoItem\"],\"resources\":[\"lambdasharp:tier:SteveBv7\"],\"detail\":null}");
// act
var isValid = EventPatternMatcher.IsValid(pattern);
// assert
isValid.Should().BeTrue();
}
}
}
| 24.972431 | 310 | 0.458049 | [
"Apache-2.0"
] | LambdaSharp/LambdaSharpTool | Modules/LambdaSharp.App.EventBus/Tests.LambdaSharp.App.EventBus/EventPatternMatcherTests/IsValid.cs | 9,964 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Shouldly;
using SugarChat.Core.Domain;
using SugarChat.Core.Exceptions;
using SugarChat.Core.Services.Users;
using Xunit;
namespace SugarChat.Database.MongoDb.IntegrationTest.DataProviders
{
public class UserDataProviderTests : ServiceFixture
{
private readonly IUserDataProvider _userDataProvider;
public UserDataProviderTests(DatabaseFixture dbFixture) : base(dbFixture)
{
_userDataProvider = Container.Resolve<IUserDataProvider>();
}
[Fact]
public async Task Should_Get_Exist_User_By_Id()
{
User user = await _userDataProvider.GetByIdAsync(Tom.Id);
user.Id.ShouldBe(Tom.Id);
user.DisplayName.ShouldBe(Tom.DisplayName);
}
[Fact]
public async Task Should_Not_Get_None_Exist_User_By_Id()
{
User user = await _userDataProvider.GetByIdAsync("0");
user.ShouldBeNull();
}
[Fact]
public async Task Should_Get_Exist_Users_By_Ids()
{
var users = (await _userDataProvider.GetRangeByIdAsync(new[] {Tom.Id, Jerry.Id})).ToArray();
users.Length.ShouldBe(2);
var tom = users.SingleOrDefault(o => o.Id == Tom.Id);
tom.ShouldNotBeNull();
tom.DisplayName.ShouldBe(Tom.DisplayName);
var jerry = users.SingleOrDefault(o => o.Id == Jerry.Id);
jerry.ShouldNotBeNull();
jerry.DisplayName.ShouldBe(Jerry.DisplayName);
}
[Fact]
public async Task Should_Not_Get_None_Exist_Users_By_Ids()
{
var users = (await _userDataProvider.GetRangeByIdAsync(new[] {Tom.Id, Jerry.Id, "0"})).ToArray();
users.Length.ShouldBe(2);
var tom = users.SingleOrDefault(o => o.Id == Tom.Id);
tom.ShouldNotBeNull();
tom.DisplayName.ShouldBe(Tom.DisplayName);
var jerry = users.SingleOrDefault(o => o.Id == Jerry.Id);
jerry.ShouldNotBeNull();
jerry.DisplayName.ShouldBe(Jerry.DisplayName);
}
[Fact]
public async Task Should_Add_None_Exist_User()
{
User tweety = new() {Id = "0", DisplayName = "Tweety"};
await _userDataProvider.AddAsync(tweety);
User user = await _userDataProvider.GetByIdAsync(tweety.Id);
user.ShouldNotBeNull();
user.Id.ShouldBe(tweety.Id);
user.DisplayName.ShouldBe(tweety.DisplayName);
}
[Fact]
public async Task Should_Not_Add_Exist_User()
{
await Assert.ThrowsAnyAsync<Exception>(async () =>
await _userDataProvider.AddAsync(new() {Id = Tom.Id, DisplayName = "Tweety"}));
}
[Fact]
public async Task Should_Update_Exist_User()
{
await _userDataProvider.UpdateAsync(new() {Id = Tom.Id, DisplayName = "Tweety"});
User user = await _userDataProvider.GetByIdAsync(Tom.Id);
user.DisplayName.ShouldBe("Tweety");
}
[Fact]
public async Task Should_Throw_Exception_On_Update_None_Exist_User()
{
User tweety = new() {Id = "0", DisplayName = "Tweety"};
await Assert.ThrowsAnyAsync<BusinessException>(async () =>
await _userDataProvider.UpdateAsync(tweety));
}
[Fact]
public async Task Should_Remove_Exist_User()
{
await _userDataProvider.RemoveAsync(Tom);
User user = await _userDataProvider.GetByIdAsync(Tom.Id);
user.ShouldBeNull();
}
[Fact]
public async Task Should_Throw_Exception_On_Removing_None_Exist_User()
{
await Assert.ThrowsAnyAsync<BusinessException>(async () =>
await _userDataProvider.RemoveAsync(new() {Id = "0"}));
}
}
} | 35.321739 | 109 | 0.593058 | [
"Apache-2.0"
] | SugarChat/SugarChat | test/SugarChat.Database.MongoDb.IntegrationTest/DataProviders/UserDataProviderTests.cs | 4,064 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TickTrader.BotTerminal
{
internal interface IDropHandler
{
void Drop(object o);
bool CanDrop(object o);
}
}
| 17.6 | 35 | 0.708333 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SoftFx/TTAlgo | TickTrader.BotTerminal/Behaviors/DragDrop/IDropHandler.cs | 266 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OutlookLightHouse")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OutlookLightHouse")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4a63d885-4d40-4fa1-b39e-7ff1605ea583")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 36.692308 | 84 | 0.747729 | [
"MIT"
] | hoovercj/vsto-outlook-busylight | OutlookLightHouse/Properties/AssemblyInfo.cs | 1,434 | C# |
namespace Rules.Framework.Core.ConditionNodes
{
using System;
using System.Diagnostics;
/// <summary>
/// A condition node with a integer data type.
/// </summary>
/// <typeparam name="TConditionType">
/// The condition type that allows to filter rules based on a set of conditions.
/// </typeparam>
[DebuggerDisplay("Integer condition: <{ConditionType.ToString(),nq}> {Operator} {Operand}")]
[Obsolete("IntegerConditionNode is obsolete, please use ValueConditionNode instead. This type will be removed in a future major release.")]
public class IntegerConditionNode<TConditionType> : ValueConditionNodeTemplate<int, TConditionType>
{
/// <summary>
/// Creates a new <see cref="IntegerConditionNode{TConditionType}"/>.
/// </summary>
/// <param name="conditionType">the condition type.</param>
/// <param name="operator">the operator.</param>
/// <param name="operand">the operand.</param>
public IntegerConditionNode(TConditionType conditionType, Operators @operator, int operand)
: base(conditionType, @operator, operand)
{
}
/// <summary>
/// Gets the condition node data type.
/// </summary>
public override DataTypes DataType => DataTypes.Integer;
/// <summary>
/// Clones the condition node into a different instance.
/// </summary>
/// <returns></returns>
public override IConditionNode<TConditionType> Clone()
=> new IntegerConditionNode<TConditionType>(this.ConditionType, this.Operator, this.Operand);
}
} | 42 | 143 | 0.647741 | [
"MIT"
] | Farfetch/rules-framework | src/Rules.Framework/Core/ConditionNodes/IntegerConditionNode.cs | 1,638 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WrapPanel
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 16.944444 | 39 | 0.744262 | [
"MIT"
] | yacper/DevexpressLearning | Wpf/Controls/Layout/WrapPanel/WrapPanel/App.xaml.cs | 307 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace IdentityServerApi
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 23.388889 | 76 | 0.631829 | [
"Apache-2.0"
] | daniel-buchanan/identity-server4-docker | src/api/Program.cs | 423 | C# |
using RESTRunner.Domain.Interfaces;
using RESTRunner.Domain.Models;
namespace RESTRunner.Services.StoreResults.Memory;
/// <summary>
/// Store Results Service
/// </summary>
public class MemoryStoreResultsService : IStoreResults
{
private readonly List<CompareResult> results = new();
/// <summary>
/// Add Result to Store Result Service
/// </summary>
/// <param name="compareResults"></param>
public void Add(CompareResult compareResults)
{
results.Add(compareResults);
}
/// <summary>
/// List of stored results
/// </summary>
/// <returns></returns>
public IEnumerable<CompareResult> Results()
{
return results;
}
}
| 24.103448 | 57 | 0.656652 | [
"MIT"
] | markhazleton/RESTRunner | RESTRunner.Services.StoreResults.Memory/MemoryStoreResultsService.cs | 701 | C# |
public class UIOrderBoardMenu : UIScrollBoxBase // TypeDefIndex: 8746
{
// Fields
private bool isOpening; // 0x68
private List<UIOrderBoardMenu.OrderList> orderLists; // 0x70
[SerializeField] // RVA: 0x1731F0 Offset: 0x1732F1 VA: 0x1731F0
private Sprite[] IconSprite; // 0x78
private bool isOpeningPopup; // 0x80
private OrderCursorEvent cursorEvent; // 0x88
[SerializeField] // RVA: 0x173200 Offset: 0x173301 VA: 0x173200
private Text HeadText; // 0x90
// Methods
// RVA: 0x1DCDE20 Offset: 0x1DCDF21 VA: 0x1DCDE20
private void SetupOrderDataList() { }
// RVA: 0x1DCDFE0 Offset: 0x1DCE0E1 VA: 0x1DCDFE0
private void CheckRemoveAcceptedOrderList() { }
// RVA: 0x1DCE110 Offset: 0x1DCE211 VA: 0x1DCE110 Slot: 8
protected override void Start() { }
// RVA: 0x1DCE2E0 Offset: 0x1DCE3E1 VA: 0x1DCE2E0
public bool OpenCategory() { }
// RVA: 0x1DCED80 Offset: 0x1DCEE81 VA: 0x1DCED80 Slot: 9
protected override void Update() { }
// RVA: 0x1DCF200 Offset: 0x1DCF301 VA: 0x1DCF200
public void NGSelected(bool choice) { }
// RVA: 0x1DCF210 Offset: 0x1DCF311 VA: 0x1DCF210
public void OnSelected(bool choice) { }
// RVA: 0x1DCF440 Offset: 0x1DCF541 VA: 0x1DCF440
private static int GetAcceptableOrderNum(PublicationPlace _place) { }
// RVA: 0x1DCF590 Offset: 0x1DCF691 VA: 0x1DCF590
public static void OpenBoard() { }
// RVA: 0x1DCF800 Offset: 0x1DCF901 VA: 0x1DCF800
public static bool CheckNewOrder(PublicationPlace _place) { }
// RVA: 0x1DCF820 Offset: 0x1DCF921 VA: 0x1DCF820 Slot: 5
protected override int GetListCount() { }
// RVA: 0x1DCF870 Offset: 0x1DCF971 VA: 0x1DCF870 Slot: 6
protected override void SetButtonDisp(UIButtonLinkerInScrollBox button) { }
// RVA: 0x1DCF9B0 Offset: 0x1DCFAB1 VA: 0x1DCF9B0 Slot: 7
public override void SetFocusDetail() { }
// RVA: 0x1DCFA50 Offset: 0x1DCFB51 VA: 0x1DCFA50
public void .ctor() { }
}
| 32.448276 | 76 | 0.742827 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/UIOrderBoardMenu.cs | 1,882 | C# |
using System;
using System.Data.SqlClient;
namespace FlexibleSqlConnectionResolver.ConnectionResolution
{
public interface ISqlConnectionWrapper : IDisposable
{
SqlConnection Connection { get; }
}
public class EmptySqlConnectionWrapper : ISqlConnectionWrapper
{
public EmptySqlConnectionWrapper(SqlConnection connection)
{
Connection = connection;
}
public SqlConnection Connection { get; }
public void Dispose()
{
}
}
public class DisposingSqlConnectionWrapper : ISqlConnectionWrapper
{
public DisposingSqlConnectionWrapper(SqlConnection connection)
{
Connection = connection;
}
public SqlConnection Connection { get; }
public void Dispose()
{
Connection.Dispose();
}
}
}
| 22.8 | 71 | 0.604167 | [
"MIT"
] | manisero/FlexibleSqlConnectionResolver | FlexibleSqlConnectionResolver/ConnectionResolution/SqlConnectionWrapper.cs | 914 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http2Cat;
using Microsoft.AspNetCore.Server.IntegrationTesting.Common;
using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests
{
/// <summary>
/// These are HTTP/2 tests that work on both IIS and Express. See Http2TrailerResetTests for IIS specific tests
/// with newer functionality.
/// </summary>
[Collection(IISHttpsTestSiteCollection.Name)]
public class Http2Tests
{
public Http2Tests(IISTestSiteFixture fixture)
{
var port = TestPortHelper.GetNextSSLPort();
fixture.DeploymentParameters.ApplicationBaseUriHint = $"https://localhost:{port}/";
fixture.DeploymentParameters.AddHttpsToServerConfig();
fixture.DeploymentParameters.SetWindowsAuth(false);
Fixture = fixture;
}
public IISTestSiteFixture Fixture { get; }
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/28265")]
[ConditionalTheory]
[InlineData("GET")]
[InlineData("HEAD")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task Http2_MethodsRequestWithoutData_Success(string method)
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/Http2_MethodsRequestWithoutData_Success"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:443"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("POST")]
[InlineData("PUT")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task Http2_PostRequestWithoutData_LengthRequired(string method)
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:443"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("411", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 344);
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("GET")]
// [InlineData("HEAD")] Reset with code HTTP_1_1_REQUIRED
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "Http2 requires Win10, and older versions of Win10 send some odd empty data frames.")]
public async Task Http2_RequestWithDataAndContentLength_Success(string method)
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/Http2_RequestWithDataAndContentLength_Success"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:443"),
new KeyValuePair<string, string>(HeaderNames.ContentLength, "11"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: false);
await h2Connection.SendDataAsync(1, Encoding.UTF8.GetBytes("Hello World"), endStream: true);
// Http.Sys no longer sends a window update here on later versions.
if (Environment.OSVersion.Version < new Version(10, 0, 19041, 0))
{
var windowUpdate = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.WINDOW_UPDATE, windowUpdate.Type);
}
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
// Some versions send an empty data frame first.
if (dataFrame.PayloadLength == 0)
{
Assert.False(dataFrame.DataEndStream);
dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
}
Assert.Equal(11, dataFrame.PayloadLength);
Assert.Equal("Hello World", Encoding.UTF8.GetString(dataFrame.Payload.Span));
if (!dataFrame.DataEndStream)
{
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
}
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("GET")]
// [InlineData("HEAD")] Reset with code HTTP_1_1_REQUIRED
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "Http2 requires Win10, and older versions of Win10 send some odd empty data frames.")]
public async Task Http2_RequestWithDataAndNoContentLength_Success(string method)
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/Http2_RequestWithDataAndNoContentLength_Success"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:443"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: false);
await h2Connection.SendDataAsync(1, Encoding.UTF8.GetBytes("Hello World"), endStream: true);
// Http.Sys no longer sends a window update here on later versions.
if (Environment.OSVersion.Version < new Version(10, 0, 19041, 0))
{
var windowUpdate = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.WINDOW_UPDATE, windowUpdate.Type);
}
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
// Some versions send an empty data frame first.
if (dataFrame.PayloadLength == 0)
{
Assert.False(dataFrame.DataEndStream);
dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
}
Assert.Equal(11, dataFrame.PayloadLength);
Assert.Equal("Hello World", Encoding.UTF8.GetString(dataFrame.Payload.Span));
if (!dataFrame.DataEndStream)
{
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
}
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "Http2 requires Win10, and older versions of Win10 send some odd empty data frames.")]
public async Task Http2_ResponseWithData_Success()
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, GetHeaders("/Http2_ResponseWithData_Success"), endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
// Some versions send an empty data frame first.
if (dataFrame.PayloadLength == 0)
{
Assert.False(dataFrame.DataEndStream);
dataFrame = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.DATA, dataFrame.Type);
Assert.Equal(1, dataFrame.StreamId);
}
Assert.Equal(11, dataFrame.PayloadLength);
Assert.Equal("Hello World", Encoding.UTF8.GetString(dataFrame.Payload.Span));
if (!dataFrame.DataEndStream)
{
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
}
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
public async Task ResponseTrailers_HTTP1_TrailersNotAvailable()
{
var response = await SendRequestAsync(Fixture.Client.BaseAddress.ToString() + "ResponseTrailers_HTTP1_TrailersNotAvailable", http2: false);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpVersion.Version11, response.Version);
Assert.Empty(response.TrailingHeaders);
}
[ConditionalFact]
[RequiresNewHandler]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task AppException_BeforeResponseHeaders_500()
{
await new HostBuilder()
.UseHttp2Cat(Fixture.Client.BaseAddress.AbsoluteUri, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, GetHeaders("/AppException_BeforeResponseHeaders_500"), endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("500", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[RequiresNewHandler]
public async Task Reset_Http1_NotSupported()
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version11;
var response = await client.GetStringAsync(Fixture.Client.BaseAddress + "Reset_Http1_NotSupported");
Assert.Equal("Hello World", response);
}
[ConditionalFact]
[RequiresNewHandler]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
[MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H2, SkipReason = "This is last version without Reset support")]
public async Task Reset_PriorOSVersions_NotSupported()
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
var response = await client.GetStringAsync(Fixture.Client.BaseAddress + "Reset_PriorOSVersions_NotSupported");
Assert.Equal("Hello World", response);
}
private static List<KeyValuePair<string, string>> GetHeaders(string path)
{
var headers = Headers.ToList();
var kvp = new KeyValuePair<string, string>(HeaderNames.Path, path);
headers.Add(kvp);
return headers;
}
private async Task<HttpResponseMessage> SendRequestAsync(string uri, bool http2 = true)
{
var handler = new HttpClientHandler();
handler.MaxResponseHeadersLength = 128;
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
using var client = new HttpClient(handler);
client.DefaultRequestVersion = http2 ? HttpVersion.Version20 : HttpVersion.Version11;
return await client.GetAsync(uri);
}
private static readonly IEnumerable<KeyValuePair<string, string>> Headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, "GET"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:443"),
new KeyValuePair<string, string>("user-agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"),
new KeyValuePair<string, string>("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"),
new KeyValuePair<string, string>("accept-language", "en-US,en;q=0.5"),
new KeyValuePair<string, string>("accept-encoding", "gzip, deflate, br"),
new KeyValuePair<string, string>("upgrade-insecure-requests", "1"),
};
}
}
| 47.721805 | 179 | 0.595242 | [
"Apache-2.0"
] | Aprite/aspnetcore | src/Servers/IIS/IIS/test/Common.FunctionalTests/Http2Tests.cs | 19,041 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WindowsFormsApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApplication1")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5676e875-fbe7-4963-b44e-07b33c637d0a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.405405 | 84 | 0.749472 | [
"Apache-2.0"
] | satang/CoD2Rotator | CoDRotator/Properties/AssemblyInfo.cs | 1,424 | C# |
/*
* 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.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.CloudAPI.Model.V20160714;
namespace Aliyun.Acs.CloudAPI.Transform.V20160714
{
public class RemoveIpControlPolicyItemResponseUnmarshaller
{
public static RemoveIpControlPolicyItemResponse Unmarshall(UnmarshallerContext context)
{
RemoveIpControlPolicyItemResponse removeIpControlPolicyItemResponse = new RemoveIpControlPolicyItemResponse();
removeIpControlPolicyItemResponse.HttpResponse = context.HttpResponse;
removeIpControlPolicyItemResponse.RequestId = context.StringValue("RemoveIpControlPolicyItem.RequestId");
return removeIpControlPolicyItemResponse;
}
}
}
| 39.3 | 114 | 0.756997 | [
"Apache-2.0"
] | xueandfeng/aliyun-openapi-net-sdk | aliyun-net-sdk-cloudapi/CloudAPI/Transform/V20160714/RemoveIpControlPolicyItemResponseUnmarshaller.cs | 1,572 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace RealTime.SignalR.Server
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
} | 28.347826 | 95 | 0.70092 | [
"MIT"
] | TGrannen/dotnet-samples | RealTime/RealTime.SignalR.Server/Program.cs | 652 | C# |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.Text;
using NUnit.Framework;
namespace NodaTime.Test
{
public class IntervalTest
{
private static readonly Instant SampleStart = NodaConstants.UnixEpoch.PlusNanoseconds(-30001);
private static readonly Instant SampleEnd = NodaConstants.UnixEpoch.PlusNanoseconds(40001);
[Test]
public void Construction_Success()
{
var interval = new Interval(SampleStart, SampleEnd);
Assert.AreEqual(SampleStart, interval.Start);
Assert.AreEqual(SampleEnd, interval.End);
}
[Test]
public void Construction_EqualStartAndEnd()
{
var interval = new Interval(SampleStart, SampleStart);
Assert.AreEqual(SampleStart, interval.Start);
Assert.AreEqual(SampleStart, interval.End);
Assert.AreEqual(NodaTime.Duration.Zero, interval.Duration);
}
[Test]
public void Construction_EndBeforeStart()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Interval(SampleEnd, SampleStart));
Assert.Throws<ArgumentOutOfRangeException>(() => new Interval((Instant?) SampleEnd, (Instant?) SampleStart));
}
[Test]
public void Equals()
{
TestHelper.TestEqualsStruct(
new Interval(SampleStart, SampleEnd),
new Interval(SampleStart, SampleEnd),
new Interval(NodaConstants.UnixEpoch, SampleEnd));
TestHelper.TestEqualsStruct(
new Interval(null, SampleEnd),
new Interval(null, SampleEnd),
new Interval(NodaConstants.UnixEpoch, SampleEnd));
TestHelper.TestEqualsStruct(
new Interval(SampleStart, SampleEnd),
new Interval(SampleStart, SampleEnd),
new Interval(NodaConstants.UnixEpoch, SampleEnd));
TestHelper.TestEqualsStruct(
new Interval(null, null),
new Interval(null, null),
new Interval(NodaConstants.UnixEpoch, SampleEnd));
}
[Test]
public void Operators()
{
TestHelper.TestOperatorEquality(
new Interval(SampleStart, SampleEnd),
new Interval(SampleStart, SampleEnd),
new Interval(NodaConstants.UnixEpoch, SampleEnd));
}
[Test]
public void Duration()
{
var interval = new Interval(SampleStart, SampleEnd);
Assert.AreEqual(NodaTime.Duration.FromNanoseconds(70002), interval.Duration);
}
/// <summary>
/// Using the default constructor is equivalent to a zero duration.
/// </summary>
[Test]
public void DefaultConstructor()
{
var actual = new Interval();
Assert.AreEqual(NodaTime.Duration.Zero, actual.Duration);
}
[Test]
public void ToStringUsesExtendedIsoFormat()
{
var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant();
var end = new LocalDateTime(2013, 10, 12, 17, 1, 2, 120).InUtc().ToInstant();
var value = new Interval(start, end);
Assert.AreEqual("2013-04-12T17:53:23.123456789Z/2013-10-12T17:01:02.12Z", value.ToString());
}
[Test]
public void ToString_Infinite()
{
var value = new Interval(null, null);
Assert.AreEqual("StartOfTime/EndOfTime", value.ToString());
}
[Test]
public void XmlSerialization()
{
var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant();
var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant();
var value = new Interval(start, end);
TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-04-12T17:53:23.123456789Z\" end=\"2013-10-12T17:01:02Z\" />");
}
[Test]
public void XmlSerialization_Extremes()
{
var value = new Interval(Instant.MinValue, Instant.MaxValue);
TestHelper.AssertXmlRoundtrip(value, "<value start=\"-9998-01-01T00:00:00Z\" end=\"9999-12-31T23:59:59.999999999Z\" />");
}
[Test]
public void XmlSerialization_ExtraContent()
{
var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant();
var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant();
var value = new Interval(start, end);
TestHelper.AssertParsableXml(value,
"<value start=\"2013-04-12T17:53:23.123456789Z\" end=\"2013-10-12T17:01:02Z\">Text<child attr=\"value\"/>Text 2</value>");
}
[Test]
public void XmlSerialization_SwapAttributeOrder()
{
var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant();
var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant();
var value = new Interval(start, end);
TestHelper.AssertParsableXml(value, "<value end=\"2013-10-12T17:01:02Z\" start=\"2013-04-12T17:53:23.123456789Z\" />");
}
[Test]
public void XmlSerialization_FromBeginningOfTime()
{
var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant();
var value = new Interval(null, end);
TestHelper.AssertXmlRoundtrip(value, "<value end=\"2013-10-12T17:01:02Z\" />");
}
[Test]
public void XmlSerialization_ToEndOfTime()
{
var start = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant();
var value = new Interval(start, null);
TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-10-12T17:01:02Z\" />");
}
[Test]
public void XmlSerialization_AllOfTime()
{
var value = new Interval(null, null);
TestHelper.AssertXmlRoundtrip(value, "<value />");
}
[Test]
[TestCase("<value start=\"2013-15-12T17:53:23Z\" end=\"2013-11-12T17:53:23Z\"/>",
typeof(UnparsableValueException), Description = "Invalid month in start")]
[TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-15-12T17:53:23Z\"/>",
typeof(UnparsableValueException), Description = "Invalid month in end")]
[TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-11-12T16:53:23Z\"/>",
typeof(ArgumentOutOfRangeException), Description = "End before start")]
public void XmlSerialization_Invalid(string xml, Type expectedExceptionType)
{
TestHelper.AssertXmlInvalid<Interval>(xml, expectedExceptionType);
}
[Test]
[TestCase("1990-01-01T00:00:00Z", false, Description = "Before interval")]
[TestCase("2000-01-01T00:00:00Z", true, Description = "Start of interval")]
[TestCase("2010-01-01T00:00:00Z", true, Description = "Within interval")]
[TestCase("2020-01-01T00:00:00Z", false, Description = "End instant of interval")]
[TestCase("2030-01-01T00:00:00Z", false, Description = "After interval")]
public void Contains(string candidateText, bool expectedResult)
{
var start = Instant.FromUtc(2000, 1, 1, 0, 0);
var end = Instant.FromUtc(2020, 1, 1, 0, 0);
var interval = new Interval(start, end);
var candidate = InstantPattern.ExtendedIso.Parse(candidateText).Value;
Assert.AreEqual(expectedResult, interval.Contains(candidate));
}
[Test]
public void Contains_Infinite()
{
var interval = new Interval(null, null);
Assert.IsTrue(interval.Contains(Instant.MaxValue));
Assert.IsTrue(interval.Contains(Instant.MinValue));
}
[Test]
public void HasStart()
{
Assert.IsTrue(new Interval(Instant.MinValue, null).HasStart);
Assert.IsFalse(new Interval(null, Instant.MinValue).HasStart);
}
[Test]
public void HasEnd()
{
Assert.IsTrue(new Interval(null, Instant.MaxValue).HasEnd);
Assert.IsFalse(new Interval(Instant.MaxValue, null).HasEnd);
}
[Test]
public void Start()
{
Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(NodaConstants.UnixEpoch, null).Start);
Interval noStart = new Interval(null, NodaConstants.UnixEpoch);
Assert.Throws<InvalidOperationException>(() => noStart.Start.ToString());
}
[Test]
public void End()
{
Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(null, NodaConstants.UnixEpoch).End);
Interval noEnd = new Interval(NodaConstants.UnixEpoch, null);
Assert.Throws<InvalidOperationException>(() => noEnd.End.ToString());
}
[Test]
public void Contains_EmptyInterval()
{
var instant = NodaConstants.UnixEpoch;
var interval = new Interval(instant, instant);
Assert.IsFalse(interval.Contains(instant));
}
[Test]
public void Contains_EmptyInterval_MaxValue()
{
var instant = Instant.MaxValue;
var interval = new Interval(instant, instant);
// This would have been true under Noda Time 1.x
Assert.IsFalse(interval.Contains(instant));
}
[Test]
public void Deconstruction()
{
var start = new Instant();
var end = start.PlusTicks(1_000_000);
var value = new Interval(start, end);
(Instant? actualStart, Instant? actualEnd) = value;
Assert.Multiple(() =>
{
Assert.AreEqual(start, actualStart);
Assert.AreEqual(end, actualEnd);
});
}
[Test]
public void Deconstruction_IntervalWithoutStart()
{
Instant? start = null;
var end = new Instant(1500, 1_000_000);
var value = new Interval(start, end);
(Instant? actualStart, Instant? actualEnd) = value;
Assert.Multiple(() =>
{
Assert.AreEqual(start, actualStart);
Assert.AreEqual(end, actualEnd);
});
}
[Test]
public void Deconstruction_IntervalWithoutEnd()
{
var start = new Instant(1500, 1_000_000);
Instant? end = null;
var value = new Interval(start, end);
(Instant? actualStart, Instant? actualEnd) = value;
Assert.Multiple(() =>
{
Assert.AreEqual(start, actualStart);
Assert.AreEqual(end, actualEnd);
});
}
}
}
| 38.386986 | 138 | 0.582478 | [
"Apache-2.0"
] | 0xced/nodatime | src/NodaTime.Test/IntervalTest.cs | 11,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WikiLibs.Shared.Service
{
public interface IUser
{
bool HasPermission(string name);
bool IsExternal { get; }
Data.Models.User User { get; }
string UserId { get; }
int Points { get; set; }
Task Save();
}
}
| 16.478261 | 40 | 0.614776 | [
"BSD-3-Clause"
] | WikiLibs/API | WikiLibs.Shared/Service/IUser.cs | 381 | C# |
namespace CarDealer.Migrations
{
using System;
using CarDealer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
[DbContext(typeof(CarDealerContext))]
partial class CarDealerContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("CarDealer.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Make")
.HasColumnType("nvarchar(max)");
b.Property<string>("Model")
.HasColumnType("nvarchar(max)");
b.Property<long>("TravelledDistance")
.HasColumnType("bigint");
b.HasKey("Id");
b.ToTable("Cars");
});
modelBuilder.Entity("CarDealer.Models.Customer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("BirthDate")
.HasColumnType("datetime2");
b.Property<bool>("IsYoungDriver")
.HasColumnType("bit");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Customers");
});
modelBuilder.Entity("CarDealer.Models.Part", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)");
b.Property<int>("Quantity")
.HasColumnType("int");
b.Property<int>("SupplierId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("SupplierId");
b.ToTable("Parts");
});
modelBuilder.Entity("CarDealer.Models.PartCar", b =>
{
b.Property<int>("CarId")
.HasColumnType("int");
b.Property<int>("PartId")
.HasColumnType("int");
b.HasKey("CarId", "PartId");
b.HasIndex("PartId");
b.ToTable("PartCars");
});
modelBuilder.Entity("CarDealer.Models.Sale", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CarId")
.HasColumnType("int");
b.Property<int>("CustomerId")
.HasColumnType("int");
b.Property<decimal>("Discount")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("CustomerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CarDealer.Models.Supplier", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<bool>("IsImporter")
.HasColumnType("bit");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Suppliers");
});
modelBuilder.Entity("CarDealer.Models.Part", b =>
{
b.HasOne("CarDealer.Models.Supplier", "Supplier")
.WithMany("Parts")
.HasForeignKey("SupplierId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("CarDealer.Models.PartCar", b =>
{
b.HasOne("CarDealer.Models.Car", "Car")
.WithMany("PartCars")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarDealer.Models.Part", "Part")
.WithMany("PartCars")
.HasForeignKey("PartId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("CarDealer.Models.Sale", b =>
{
b.HasOne("CarDealer.Models.Car", "Car")
.WithMany("Sales")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarDealer.Models.Customer", "Customer")
.WithMany("Sales")
.HasForeignKey("CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.547872 | 125 | 0.455933 | [
"MIT"
] | pirocorp/Databases-Advanced---Entity-Framework | Exercises/05. JavaScript Object Notation - JSON/CarDealer/Data/Migrations/CarDealerContextModelSnapshot.cs | 6,685 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using ILLink.Shared;
using Mono.Cecil;
namespace Mono.Linker.Steps
{
[Flags]
public enum AllowedAssemblies
{
ContainingAssembly = 0x1,
AnyAssembly = 0x2 | ContainingAssembly,
AllAssemblies = 0x4 | AnyAssembly
}
public abstract class ProcessLinkerXmlBase
{
const string FullNameAttributeName = "fullname";
const string LinkerElementName = "linker";
const string TypeElementName = "type";
const string SignatureAttributeName = "signature";
const string NameAttributeName = "name";
const string FieldElementName = "field";
const string MethodElementName = "method";
const string EventElementName = "event";
const string PropertyElementName = "property";
const string AllAssembliesFullName = "*";
protected const string XmlNamespace = "";
protected readonly string _xmlDocumentLocation;
readonly XPathNavigator _document;
protected readonly (EmbeddedResource Resource, AssemblyDefinition Assembly)? _resource;
protected readonly LinkContext _context;
protected ProcessLinkerXmlBase(LinkContext context, Stream documentStream, string xmlDocumentLocation)
{
_context = context;
using (documentStream)
{
_document = XDocument.Load(documentStream, LoadOptions.SetLineInfo).CreateNavigator();
}
_xmlDocumentLocation = xmlDocumentLocation;
}
protected ProcessLinkerXmlBase(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation)
: this(context, documentStream, xmlDocumentLocation)
{
_resource = (
resource ?? throw new ArgumentNullException(nameof(resource)),
resourceAssembly ?? throw new ArgumentNullException(nameof(resourceAssembly))
);
}
protected virtual bool ShouldProcessElement(XPathNavigator nav) => FeatureSettings.ShouldProcessElement(nav, _context, _xmlDocumentLocation);
protected virtual void ProcessXml(bool stripResource, bool ignoreResource)
{
if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly) && _resource == null)
throw new InvalidOperationException("The containing assembly must be specified for XML which is restricted to modifying that assembly only.");
try
{
XPathNavigator nav = _document.CreateNavigator();
// Initial structure check - ignore XML document which don't look like linker XML format
if (!nav.MoveToChild(LinkerElementName, XmlNamespace))
return;
if (_resource != null)
{
if (stripResource)
_context.Annotations.AddResourceToRemove(_resource.Value.Assembly, _resource.Value.Resource);
if (ignoreResource)
return;
}
if (!ShouldProcessElement(nav))
return;
ProcessAssemblies(nav);
// For embedded XML, allow not specifying the assembly explicitly in XML.
if (_resource != null)
ProcessAssembly(_resource.Value.Assembly, nav, warnOnUnresolvedTypes: true);
}
catch (Exception ex) when (!(ex is LinkerFatalErrorException))
{
throw new LinkerFatalErrorException(MessageContainer.CreateErrorMessage(null, DiagnosticId.ErrorProcessingXmlLocation, _xmlDocumentLocation), ex);
}
}
protected virtual AllowedAssemblies AllowedAssemblySelector { get => _resource != null ? AllowedAssemblies.ContainingAssembly : AllowedAssemblies.AnyAssembly; }
bool ShouldProcessAllAssemblies(XPathNavigator nav, [NotNullWhen(false)] out AssemblyNameReference? assemblyName)
{
assemblyName = null;
if (GetFullName(nav) == AllAssembliesFullName)
return true;
assemblyName = GetAssemblyName(nav);
return false;
}
protected virtual void ProcessAssemblies(XPathNavigator nav)
{
foreach (XPathNavigator assemblyNav in nav.SelectChildren("assembly", ""))
{
// Errors for invalid assembly names should show up even if this element will be
// skipped due to feature conditions.
bool processAllAssemblies = ShouldProcessAllAssemblies(assemblyNav, out AssemblyNameReference? name);
if (processAllAssemblies && AllowedAssemblySelector != AllowedAssemblies.AllAssemblies)
{
LogWarning(assemblyNav, DiagnosticId.XmlUnsuportedWildcard);
continue;
}
AssemblyDefinition? assemblyToProcess = null;
if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly))
{
Debug.Assert(!processAllAssemblies);
Debug.Assert(_resource != null);
if (_resource.Value.Assembly.Name.Name != name!.Name)
{
LogWarning(assemblyNav, DiagnosticId.AssemblyWithEmbeddedXmlApplyToAnotherAssembly, _resource.Value.Assembly.Name.Name, name.ToString());
continue;
}
assemblyToProcess = _resource.Value.Assembly;
}
if (!ShouldProcessElement(assemblyNav))
continue;
if (processAllAssemblies)
{
// We could avoid loading all references in this case: https://github.com/dotnet/linker/issues/1708
foreach (AssemblyDefinition assembly in _context.GetReferencedAssemblies())
ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: false);
}
else
{
Debug.Assert(!processAllAssemblies);
AssemblyDefinition? assembly = assemblyToProcess ?? _context.TryResolve(name!);
if (assembly == null)
{
LogWarning(assemblyNav, DiagnosticId.XmlCouldNotResolveAssembly, name!.Name);
continue;
}
ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: true);
}
}
}
protected abstract void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes);
protected virtual void ProcessTypes(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes)
{
foreach (XPathNavigator typeNav in nav.SelectChildren(TypeElementName, XmlNamespace))
{
if (!ShouldProcessElement(typeNav))
continue;
string fullname = GetFullName(typeNav);
if (fullname.IndexOf("*") != -1)
{
if (ProcessTypePattern(fullname, assembly, typeNav))
continue;
}
TypeDefinition type = assembly.MainModule.GetType(fullname);
if (type == null && assembly.MainModule.HasExportedTypes)
{
foreach (var exported in assembly.MainModule.ExportedTypes)
{
if (fullname == exported.FullName)
{
var resolvedExternal = ProcessExportedType(exported, assembly, typeNav);
if (resolvedExternal != null)
{
type = resolvedExternal;
break;
}
}
}
}
if (type == null)
{
if (warnOnUnresolvedTypes)
LogWarning(typeNav, DiagnosticId.XmlCouldNotResolveType, fullname);
continue;
}
ProcessType(type, typeNav);
}
}
protected virtual TypeDefinition? ProcessExportedType(ExportedType exported, AssemblyDefinition assembly, XPathNavigator nav) => exported.Resolve();
void MatchType(TypeDefinition type, Regex regex, XPathNavigator nav)
{
if (regex.IsMatch(type.FullName))
ProcessType(type, nav);
if (!type.HasNestedTypes)
return;
foreach (var nt in type.NestedTypes)
MatchType(nt, regex, nav);
}
protected virtual bool ProcessTypePattern(string fullname, AssemblyDefinition assembly, XPathNavigator nav)
{
Regex regex = new Regex(fullname.Replace(".", @"\.").Replace("*", "(.*)"));
foreach (TypeDefinition type in assembly.MainModule.Types)
{
MatchType(type, regex, nav);
}
if (assembly.MainModule.HasExportedTypes)
{
foreach (var exported in assembly.MainModule.ExportedTypes)
{
if (regex.IsMatch(exported.FullName))
{
var type = ProcessExportedType(exported, assembly, nav);
if (type != null)
{
ProcessType(type, nav);
}
}
}
}
return true;
}
protected abstract void ProcessType(TypeDefinition type, XPathNavigator nav);
protected void ProcessTypeChildren(TypeDefinition type, XPathNavigator nav, object? customData = null)
{
if (nav.HasChildren)
{
ProcessSelectedFields(nav, type);
ProcessSelectedMethods(nav, type, customData);
ProcessSelectedEvents(nav, type, customData);
ProcessSelectedProperties(nav, type, customData);
}
}
void ProcessSelectedFields(XPathNavigator nav, TypeDefinition type)
{
foreach (XPathNavigator fieldNav in nav.SelectChildren(FieldElementName, XmlNamespace))
{
if (!ShouldProcessElement(fieldNav))
continue;
ProcessField(type, fieldNav);
}
}
protected virtual void ProcessField(TypeDefinition type, XPathNavigator nav)
{
string signature = GetSignature(nav);
if (!String.IsNullOrEmpty(signature))
{
FieldDefinition? field = GetField(type, signature);
if (field == null)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, signature, type.GetDisplayName());
return;
}
ProcessField(type, field, nav);
}
string name = GetName(nav);
if (!String.IsNullOrEmpty(name))
{
bool foundMatch = false;
if (type.HasFields)
{
foreach (FieldDefinition field in type.Fields)
{
if (field.Name == name)
{
foundMatch = true;
ProcessField(type, field, nav);
}
}
}
if (!foundMatch)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, name, type.GetDisplayName());
}
}
}
protected static FieldDefinition? GetField(TypeDefinition type, string signature)
{
if (!type.HasFields)
return null;
foreach (FieldDefinition field in type.Fields)
if (signature == field.FieldType.FullName + " " + field.Name)
return field;
return null;
}
protected virtual void ProcessField(TypeDefinition type, FieldDefinition field, XPathNavigator nav) { }
void ProcessSelectedMethods(XPathNavigator nav, TypeDefinition type, object? customData)
{
foreach (XPathNavigator methodNav in nav.SelectChildren(MethodElementName, XmlNamespace))
{
if (!ShouldProcessElement(methodNav))
continue;
ProcessMethod(type, methodNav, customData);
}
}
protected virtual void ProcessMethod(TypeDefinition type, XPathNavigator nav, object? customData)
{
string signature = GetSignature(nav);
if (!String.IsNullOrEmpty(signature))
{
MethodDefinition? method = GetMethod(type, signature);
if (method == null)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, signature, type.GetDisplayName());
return;
}
ProcessMethod(type, method, nav, customData);
}
string name = GetAttribute(nav, NameAttributeName);
if (!String.IsNullOrEmpty(name))
{
bool foundMatch = false;
if (type.HasMethods)
{
foreach (MethodDefinition method in type.Methods)
{
if (name == method.Name)
{
foundMatch = true;
ProcessMethod(type, method, nav, customData);
}
}
}
if (!foundMatch)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, name, type.GetDisplayName());
}
}
}
protected virtual MethodDefinition? GetMethod(TypeDefinition type, string signature) => null;
protected virtual void ProcessMethod(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData) { }
void ProcessSelectedEvents(XPathNavigator nav, TypeDefinition type, object? customData)
{
foreach (XPathNavigator eventNav in nav.SelectChildren(EventElementName, XmlNamespace))
{
if (!ShouldProcessElement(eventNav))
continue;
ProcessEvent(type, eventNav, customData);
}
}
protected virtual void ProcessEvent(TypeDefinition type, XPathNavigator nav, object? customData)
{
string signature = GetSignature(nav);
if (!String.IsNullOrEmpty(signature))
{
EventDefinition? @event = GetEvent(type, signature);
if (@event == null)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, signature, type.GetDisplayName());
return;
}
ProcessEvent(type, @event, nav, customData);
}
string name = GetAttribute(nav, NameAttributeName);
if (!String.IsNullOrEmpty(name))
{
bool foundMatch = false;
foreach (EventDefinition @event in type.Events)
{
if (@event.Name == name)
{
foundMatch = true;
ProcessEvent(type, @event, nav, customData);
}
}
if (!foundMatch)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, name, type.GetDisplayName());
}
}
}
protected static EventDefinition? GetEvent(TypeDefinition type, string signature)
{
if (!type.HasEvents)
return null;
foreach (EventDefinition @event in type.Events)
if (signature == @event.EventType.FullName + " " + @event.Name)
return @event;
return null;
}
protected virtual void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData) { }
void ProcessSelectedProperties(XPathNavigator nav, TypeDefinition type, object? customData)
{
foreach (XPathNavigator propertyNav in nav.SelectChildren(PropertyElementName, XmlNamespace))
{
if (!ShouldProcessElement(propertyNav))
continue;
ProcessProperty(type, propertyNav, customData);
}
}
protected virtual void ProcessProperty(TypeDefinition type, XPathNavigator nav, object? customData)
{
string signature = GetSignature(nav);
if (!String.IsNullOrEmpty(signature))
{
PropertyDefinition? property = GetProperty(type, signature);
if (property == null)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, signature, type.GetDisplayName());
return;
}
ProcessProperty(type, property, nav, customData, true);
}
string name = GetAttribute(nav, NameAttributeName);
if (!String.IsNullOrEmpty(name))
{
bool foundMatch = false;
foreach (PropertyDefinition property in type.Properties)
{
if (property.Name == name)
{
foundMatch = true;
ProcessProperty(type, property, nav, customData, false);
}
}
if (!foundMatch)
{
LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, name, type.GetDisplayName());
}
}
}
protected static PropertyDefinition? GetProperty(TypeDefinition type, string signature)
{
if (!type.HasProperties)
return null;
foreach (PropertyDefinition property in type.Properties)
if (signature == property.PropertyType.FullName + " " + property.Name)
return property;
return null;
}
protected virtual void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature) { }
protected virtual AssemblyNameReference GetAssemblyName(XPathNavigator nav)
{
return AssemblyNameReference.Parse(GetFullName(nav));
}
protected static string GetFullName(XPathNavigator nav)
{
return GetAttribute(nav, FullNameAttributeName);
}
protected static string GetName(XPathNavigator nav)
{
return GetAttribute(nav, NameAttributeName);
}
protected static string GetSignature(XPathNavigator nav)
{
return GetAttribute(nav, SignatureAttributeName);
}
protected static string GetAttribute(XPathNavigator nav, string attribute)
{
return nav.GetAttribute(attribute, XmlNamespace);
}
protected MessageOrigin GetMessageOriginForPosition(XPathNavigator position)
{
return (position is IXmlLineInfo lineInfo)
? new MessageOrigin(_xmlDocumentLocation, lineInfo.LineNumber, lineInfo.LinePosition, _resource?.Assembly)
: new MessageOrigin(_xmlDocumentLocation, 0, 0, _resource?.Assembly);
}
protected void LogWarning(string message, int warningCode, XPathNavigator position)
{
_context.LogWarning(message, warningCode, GetMessageOriginForPosition(position));
}
protected void LogWarning(XPathNavigator position, DiagnosticId id, params string[] args)
{
_context.LogWarning(GetMessageOriginForPosition(position), id, args);
}
public override string ToString() => GetType().Name + ": " + _xmlDocumentLocation;
public bool TryConvertValue(string value, TypeReference target, out object? result)
{
switch (target.MetadataType)
{
case MetadataType.Boolean:
if (bool.TryParse(value, out bool bvalue))
{
result = bvalue ? 1 : 0;
return true;
}
goto case MetadataType.Int32;
case MetadataType.Byte:
if (!byte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out byte byteresult))
break;
result = (int)byteresult;
return true;
case MetadataType.SByte:
if (!sbyte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out sbyte sbyteresult))
break;
result = (int)sbyteresult;
return true;
case MetadataType.Int16:
if (!short.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out short shortresult))
break;
result = (int)shortresult;
return true;
case MetadataType.UInt16:
if (!ushort.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ushort ushortresult))
break;
result = (int)ushortresult;
return true;
case MetadataType.Int32:
if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int iresult))
break;
result = iresult;
return true;
case MetadataType.UInt32:
if (!uint.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint uresult))
break;
result = (int)uresult;
return true;
case MetadataType.Double:
if (!double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double dresult))
break;
result = dresult;
return true;
case MetadataType.Single:
if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float fresult))
break;
result = fresult;
return true;
case MetadataType.Int64:
if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long lresult))
break;
result = lresult;
return true;
case MetadataType.UInt64:
if (!ulong.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong ulresult))
break;
result = (long)ulresult;
return true;
case MetadataType.Char:
if (!char.TryParse(value, out char chresult))
break;
result = (int)chresult;
return true;
case MetadataType.String:
if (value is string || value == null)
{
result = value;
return true;
}
break;
case MetadataType.ValueType:
if (value is string &&
_context.TryResolve(target) is TypeDefinition typeDefinition &&
typeDefinition.IsEnum)
{
var enumField = typeDefinition.Fields.Where(f => f.IsStatic && f.Name == value).FirstOrDefault();
if (enumField != null)
{
result = Convert.ToInt32(enumField.Constant);
return true;
}
}
break;
}
result = null;
return false;
}
}
}
| 38.063348 | 174 | 0.540498 | [
"MIT"
] | ChaseKnowlden/runtime | src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/ProcessLinkerXmlBase.cs | 25,236 | C# |
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Dotnet.Portal.App.Areas.Identity.Pages
{
[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 27.454545 | 88 | 0.695364 | [
"MIT"
] | AJEETX/Employee.Management | src/Dotnet.Portal.App/Areas/Identity/Pages/Error.cshtml.cs | 606 | C# |
using System;
using HotChocolate.Language;
namespace HotChocolate.Stitching.SchemaBuilding;
internal static class SchemaInfoExtensions
{
public static ObjectTypeDefinitionNode? GetRootType(
this ISchemaInfo schema,
OperationType operation)
{
switch (operation)
{
case OperationType.Query:
return schema.QueryType;
case OperationType.Mutation:
return schema.MutationType;
case OperationType.Subscription:
return schema.SubscriptionType;
default:
throw new NotSupportedException();
}
}
}
| 26.08 | 56 | 0.627301 | [
"MIT"
] | ChilliCream/prometheus | src/HotChocolate/Stitching/src/Stitching/SchemaBuilding/Extensions/SchemaInfoExtensions.cs | 652 | C# |
#if UNITY_2019_3_OR_NEWER
using UnityEditor.Experimental.GraphView;
#else
using UnityEditor.Experimental.UIElements.GraphView;
#endif
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
using VRC.Udon.Graph.Interfaces;
namespace VRC.Udon.Editor.ProgramSources.UdonGraphProgram.UI.GraphView
{
public class UdonSearchManager
{
private UdonGraph _view;
private UdonGraphWindow _window;
// Search Windows
private UdonFocusedSearchWindow _focusedSearchWindow;
private UdonRegistrySearchWindow _registrySearchWindow;
private UdonFullSearchWindow _fullSearchWindow;
public UdonVariableTypeWindow _variableSearchWindow;
public UdonPortSearchWindow _portSearchWindow;
public UdonSearchManager(UdonGraph view, UdonGraphWindow window)
{
_view = view;
_window = window;
SetupSearchTypes();
view.nodeCreationRequest += OnRequestNodeCreation;
}
private void SetupSearchTypes()
{
if (_registrySearchWindow == null)
_registrySearchWindow = ScriptableObject.CreateInstance<UdonRegistrySearchWindow>();
_registrySearchWindow.Initialize(_window, _view, this);
if (_fullSearchWindow == null)
_fullSearchWindow = ScriptableObject.CreateInstance<UdonFullSearchWindow>();
_fullSearchWindow.Initialize(_window, _view);
if (_focusedSearchWindow == null)
_focusedSearchWindow = ScriptableObject.CreateInstance<UdonFocusedSearchWindow>();
_focusedSearchWindow.Initialize(_window, _view);
if (_variableSearchWindow == null)
_variableSearchWindow = ScriptableObject.CreateInstance<UdonVariableTypeWindow>();
_variableSearchWindow.Initialize(_window, _view);
if (_portSearchWindow == null)
_portSearchWindow = ScriptableObject.CreateInstance<UdonPortSearchWindow>();
_portSearchWindow.Initialize(_window, _view);
}
private void OnRequestNodeCreation(NodeCreationContext context)
{
// started on empty space
if (context.target == null)
{
// If we have a node selected (but not set as context.target because that's a container for new nodes to go into), search within that node's registry
if (Settings.SearchOnSelectedNodeRegistry && _view.selection.Count > 0 && _view.selection.First() is UdonNode)
{
_focusedSearchWindow.targetRegistry = (_view.selection.First() as UdonNode).Registry;
SearchWindow.Open(new SearchWindowContext(context.screenMousePosition, 360, 360), _focusedSearchWindow);
}
else
{
// Create Search Window that only searches Top-Level Registries
SearchWindow.Open(new SearchWindowContext(context.screenMousePosition, 360, 360), _registrySearchWindow);
}
}
else if (context.target is UdonGraph)
{
// Slightly hacky method to figure out that we want a full-search window
SearchWindow.Open(new SearchWindowContext(context.screenMousePosition, 360, 360), _fullSearchWindow);
}
}
public void OpenVariableSearch(Vector2 screenMousePosition)
{
// offset search window to appear next to mouse
screenMousePosition.x += 140;
screenMousePosition.y += 0;
SearchWindow.Open(new SearchWindowContext(screenMousePosition, 360, 360), _variableSearchWindow);
}
public void OpenPortSearch(Type type, Vector2 screenMousePosition, UdonPort port, Direction direction)
{
// offset search window to appear next to mouse
screenMousePosition = _portSearchWindow._editorWindow.position.position + screenMousePosition;
screenMousePosition.x += 140;
screenMousePosition.y += 0;
_portSearchWindow.typeToSearch = type;
_portSearchWindow.startingPort = port;
_portSearchWindow.direction = direction;
SearchWindow.Open(new SearchWindowContext(screenMousePosition, 360, 360), _portSearchWindow);
}
private Vector2 _searchWindowPosition;
public void QueueOpenFocusedSearch(INodeRegistry registry, Vector2 position)
{
_searchWindowPosition = position;
_focusedSearchWindow.targetRegistry = registry;
EditorApplication.update += TryOpenFocusedSearch;
}
private void TryOpenFocusedSearch()
{
if (SearchWindow.Open(new SearchWindowContext(_searchWindowPosition, 360, 360), _focusedSearchWindow))
{
EditorApplication.update -= TryOpenFocusedSearch;
}
}
}
}
| 41.5 | 165 | 0.654819 | [
"Apache-2.0"
] | AverageTurtle/Town-Cuddle-Puddle | Assets/Udon/Editor/ProgramSources/UdonGraphProgram/UI/GraphView/Search/UdonSearchManager.cs | 4,982 | C# |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// 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.ComponentModel.Composition;
using DotNetNuke.ExtensionPoints;
namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.UserControls
{
[Export(typeof(IUserControlExtensionPoint))]
[ExportMetadata("Module", "DigitalAssets")]
[ExportMetadata("Name", "FileFieldsControlExtensionPoint")]
[ExportMetadata("Group", "ViewProperties")]
[ExportMetadata("Priority", 2)]
public class FileFieldsControlExtensionPoint : IUserControlExtensionPoint
{
public string UserControlSrc
{
get { return "~/DesktopModules/DigitalAssets/FileFieldsControl.ascx"; }
}
public string Text
{
get { return ""; }
}
public string Icon
{
get { return ""; }
}
public int Order
{
get { return 1; }
}
public bool Visible
{
get { return true; }
}
}
} | 35.704918 | 116 | 0.69146 | [
"MIT"
] | Mhtshum/Dnn.Platform | DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/UserControls/FileFieldsControlExtensionPoint.cs | 2,181 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BillsPaymentSystem.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BillsPaymentSystem.Models")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9bcc0de4-1f15-456d-9be5-c891cd8640ff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.459459 | 84 | 0.748419 | [
"MIT"
] | ivajlotokiew/Databases_Entity_Framework | Entity_Framework_Relations/BillsPaymentSystem/BillsPaymentSystem.Models/Properties/AssemblyInfo.cs | 1,426 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ServiceBus.V20150801
{
public static class GetNamespaceAuthorizationRule
{
public static Task<GetNamespaceAuthorizationRuleResult> InvokeAsync(GetNamespaceAuthorizationRuleArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetNamespaceAuthorizationRuleResult>("azure-nextgen:servicebus/v20150801:getNamespaceAuthorizationRule", args ?? new GetNamespaceAuthorizationRuleArgs(), options.WithVersion());
}
public sealed class GetNamespaceAuthorizationRuleArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The authorization rule name.
/// </summary>
[Input("authorizationRuleName", required: true)]
public string AuthorizationRuleName { get; set; } = null!;
/// <summary>
/// The namespace name
/// </summary>
[Input("namespaceName", required: true)]
public string NamespaceName { get; set; } = null!;
/// <summary>
/// Name of the Resource group within the Azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetNamespaceAuthorizationRuleArgs()
{
}
}
[OutputType]
public sealed class GetNamespaceAuthorizationRuleResult
{
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name
/// </summary>
public readonly string Name;
/// <summary>
/// The rights associated with the rule.
/// </summary>
public readonly ImmutableArray<string> Rights;
/// <summary>
/// Resource type
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetNamespaceAuthorizationRuleResult(
string? location,
string name,
ImmutableArray<string> rights,
string type)
{
Location = location;
Name = name;
Rights = rights;
Type = type;
}
}
}
| 30.536585 | 231 | 0.61861 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ServiceBus/V20150801/GetNamespaceAuthorizationRule.cs | 2,504 | C# |
using System;
using System.Text.RegularExpressions;
using essentialMix.Extensions;
using JetBrains.Annotations;
namespace essentialMix.Helpers;
public static class EnvironmentHelper
{
private static readonly Regex __rgxIsEnvVar = new Regex("^%\\w+%$", RegexHelper.OPTIONS_I);
private static readonly Regex __rgxHasEnvVar = new Regex("%\\w+%", RegexHelper.OPTIONS_I);
public static bool IsVar(string value) { return !string.IsNullOrEmpty(value) && __rgxIsEnvVar.IsMatch(value); }
public static bool HasVar(string value) { return !string.IsNullOrEmpty(value) && __rgxHasEnvVar.IsMatch(value); }
[NotNull]
public static string GetEnvironmentName()
{
return Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT").ToNullIfEmpty() ??
Environment.GetEnvironmentVariable("APPNETCORE_ENVIRONMENT").ToNullIfEmpty() ??
Environment.GetEnvironmentVariable("ENVIRONMENT").ToNullIfEmpty() ??
"Development";
}
} | 38.666667 | 114 | 0.780172 | [
"MIT"
] | asm2025/essentialMix | Standard/essentialMix/Helpers/EnvironmentHelper.cs | 930 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using LetPortal.Core.Persistences;
using LetPortal.Portal.Entities.Databases;
using LetPortal.Portal.Entities.Shared;
using LetPortal.Portal.Models;
using LetPortal.Portal.Models.Databases;
using Newtonsoft.Json.Linq;
namespace LetPortal.Portal.Executions
{
public interface IExecutionDatabase
{
ConnectionType ConnectionType { get; }
Task<ExecuteDynamicResultModel> Execute(
DatabaseConnection databaseConnection,
string formattedString,
IEnumerable<ExecuteParamModel> parameters);
Task<StepExecutionResult> ExecuteStep(
DatabaseConnection databaseConnection,
string formattedString,
IEnumerable<ExecuteParamModel> parameters,
ExecutionDynamicContext context);
}
public class ExecutionDynamicContext
{
public JObject Data { get; set; }
}
}
| 28.939394 | 55 | 0.71623 | [
"MIT"
] | chuxuantinh/let.portal | src/web-apis/LetPortal.Portal/Executions/IExecutionDatabase.cs | 957 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Newtonsoft.Json;
using PC.PowerApps.Common.Entities.Dataverse;
using PC.PowerApps.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
namespace PC.PowerApps.Common
{
public abstract class Context : IDisposable
{
private const int EnglishCultureId = 1033;
private bool disposedValue;
private readonly Lazy<UserSettings> lazyInitiatingUserSettings;
private readonly Lazy<Dictionary<string, string>> lazyResource;
private readonly Lazy<Organization> lazyOrganization;
private readonly Lazy<ServiceContext> lazyServiceContext;
private readonly Lazy<pc_Settings> lazySettings;
private readonly Lazy<TimeZoneInfo> lazyTimeZoneInfo = new(() => TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time"));
private readonly Lazy<int> lazyUILanguageId;
private readonly Lazy<SystemUser> lazyUser;
protected abstract Guid InitiatingUserId { get; }
private UserSettings InitiatingUserSettings => lazyInitiatingUserSettings.Value;
public abstract ILogger Logger { get; }
protected Organization Organization => lazyOrganization.Value;
private CultureInfo OrganizationCultureInfo { get; }
public abstract IOrganizationService OrganizationService { get; }
private Dictionary<string, string> Resource => lazyResource.Value;
public ServiceContext ServiceContext => lazyServiceContext.Value;
public pc_Settings Settings => lazySettings.Value;
private TimeZoneInfo TimeZoneInfo => lazyTimeZoneInfo.Value;
private int UILanguageId => lazyUILanguageId.Value;
protected abstract Guid UserId { get; }
protected SystemUser User => lazyUser.Value;
protected Context()
{
lazyUILanguageId = new(() => InitiatingUserSettings?.UILanguageId ?? EnglishCultureId);
lazyInitiatingUserSettings = new(() => ServiceContext.Retrieve<UserSettings>(InitiatingUserId, isOptional: true));
lazyResource = new(() =>
{
string resxWebResourceName = $"pc_/Resource.{UILanguageId}.resx";
WebResource resxWebResource = ServiceContext.WebResourceSet
.Where(wr => wr.Name == resxWebResourceName)
.Select(wr => new WebResource
{
ContentJson = wr.ContentJson,
})
.TakeSingle();
Dictionary<string, string> resource = JsonConvert.DeserializeObject<Dictionary<string, string>>(resxWebResource.ContentJson);
return resource;
});
lazyOrganization = new(() => ServiceContext.OrganizationSet.TakeSingle());
lazyServiceContext = new(() => new(OrganizationService));
lazySettings = new(() => ServiceContext.pc_SettingsSet
.Where(s => s.StateCode == pc_SettingsState.Active)
.TakeFirst("Active Settings do not exist."));
lazyUser = new(() => ServiceContext.Retrieve<SystemUser>(UserId));
OrganizationCultureInfo = CultureInfo.GetCultureInfo("lv-LV");
}
public DateTime GetCurrentOrganizationTime()
{
DateTime organizationTime = UtcToOrganizationTime(DateTime.UtcNow);
return organizationTime;
}
public DateTime OrganizationToUtcTime(DateTime organizationTime)
{
DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(organizationTime, TimeZoneInfo);
return utcTime;
}
public DateTime UtcToOrganizationTime(DateTime utcTime)
{
DateTime organizationTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo);
return organizationTime;
}
public void EnsureAttributesNotEmpty<TEntity>(TEntity entity, Expression<Func<TEntity, object>> attributeSelector) where TEntity : Entity
{
HashSet<string> attributeLogicalNamesToCheck = Utils.GetAttributeLogicalNames(attributeSelector);
List<string> emptyAttributeLogicalNames = attributeLogicalNamesToCheck
.Where(aln => Utils.IsEmptyValue(aln))
.ToList();
EnsureNoAttributes(entity.LogicalName, emptyAttributeLogicalNames, nameof(Common.Resource.AttributeCannotBeEmpty), nameof(Common.Resource.AttributesCannotBeEmpty));
}
public string Format(Money money)
{
string moneyString = money?.Value.ToString("c", OrganizationCultureInfo);
return moneyString;
}
public string FormatDate(DateTime? dateTime)
{
string dateString = dateTime?.ToString("d", OrganizationCultureInfo);
return dateString;
}
public InvalidPluginExecutionException CreateException(string key, params string[] args)
{
if (!Resource.TryGetValue(key, out string format))
{
format = key;
}
string message = string.Format(format, args);
InvalidPluginExecutionException exception = new InvalidPluginExecutionException(message);
return exception;
}
public void EnsureNoAttributes(string entityLogicalName, List<string> attributeLogicalNames, string resourceSingle, string resourceMultiple)
{
if (attributeLogicalNames.Count == 0)
{
return;
}
List<string> attributeDisplayNames = attributeLogicalNames
.Select(aln => $"\"{GetAttributeDisplayName(entityLogicalName, aln)}\"")
.ToList();
string entityDisplayName = GetEntityDisplayName(entityLogicalName);
string attributeDisplayNameString = string.Join(", ", attributeDisplayNames);
if (attributeDisplayNames.Count == 1)
{
throw CreateException(resourceSingle, entityDisplayName, attributeDisplayNameString);
}
throw CreateException(resourceMultiple, entityDisplayName, attributeDisplayNameString);
}
protected string GetAttributeDisplayName(string entityLogicalName, string attributeLogicalName)
{
AttributeMetadata attributeMetadata = GetAttributeMetadata(entityLogicalName, attributeLogicalName);
string attributeDisplayName = GetLabelValue(attributeMetadata.DisplayName);
return attributeDisplayName;
}
private string GetEntityDisplayName(string entityLogicalName)
{
EntityMetadata entityMetadata = GetEntityMetadata(entityLogicalName);
string entityDisplayName = GetLabelValue(entityMetadata.DisplayName);
return entityDisplayName;
}
private AttributeMetadata GetAttributeMetadata(string entityLogicalName, string attributeLogicalName)
{
RetrieveAttributeRequest retrieveAttributeRequest = new()
{
EntityLogicalName = entityLogicalName,
LogicalName = attributeLogicalName,
};
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)OrganizationService.Execute(retrieveAttributeRequest);
return retrieveAttributeResponse.AttributeMetadata;
}
protected EntityMetadata GetEntityMetadata(string entityLogicalName)
{
RetrieveEntityRequest retrieveEntityRequest = new()
{
LogicalName = entityLogicalName,
};
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)OrganizationService.Execute(retrieveEntityRequest);
return retrieveEntityResponse.EntityMetadata;
}
protected string GetLabelValue(Label label)
{
LocalizedLabel localizedLabel = GetLocalizedLabel(label, UILanguageId) ?? GetLocalizedLabel(label, EnglishCultureId);
return localizedLabel.Label;
}
private LocalizedLabel GetLocalizedLabel(Label label, int languageId)
{
return label.LocalizedLabels
.Where(ll => ll.LanguageCode == languageId)
.FirstOrDefault();
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (lazyServiceContext.IsValueCreated)
{
ServiceContext.Dispose();
}
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
| 42.178404 | 176 | 0.648041 | [
"MIT"
] | Pilseta-cilvekiem/Participant-Management | PC.PowerApps/PC.PowerApps.Common/Context.cs | 8,986 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.WebPubSub.Models;
namespace Azure.ResourceManager.WebPubSub
{
/// <summary> A Class representing a PrivateEndpointConnection along with the instance operations that can be performed on it. </summary>
public partial class PrivateEndpointConnection : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="PrivateEndpointConnection"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/webPubSub/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _clientDiagnostics;
private readonly WebPubSubPrivateEndpointConnectionsRestOperations _webPubSubPrivateEndpointConnectionsRestClient;
private readonly PrivateEndpointConnectionData _data;
/// <summary> Initializes a new instance of the <see cref="PrivateEndpointConnection"/> class for mocking. </summary>
protected PrivateEndpointConnection()
{
}
/// <summary> Initializes a new instance of the <see cref = "PrivateEndpointConnection"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal PrivateEndpointConnection(ArmResource options, PrivateEndpointConnectionData data) : base(options, data.Id)
{
HasData = true;
_data = data;
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_webPubSubPrivateEndpointConnectionsRestClient = new WebPubSubPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="PrivateEndpointConnection"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal PrivateEndpointConnection(ArmResource options, ResourceIdentifier id) : base(options, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_webPubSubPrivateEndpointConnectionsRestClient = new WebPubSubPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="PrivateEndpointConnection"/> class. </summary>
/// <param name="clientOptions"> The client options to build client context. </param>
/// <param name="credential"> The credential to build client context. </param>
/// <param name="uri"> The uri to build client context. </param>
/// <param name="pipeline"> The pipeline to build client context. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal PrivateEndpointConnection(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_webPubSubPrivateEndpointConnectionsRestClient = new WebPubSubPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.SignalRService/webPubSub/privateEndpointConnections";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual PrivateEndpointConnectionData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Get the specified private endpoint connection. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<PrivateEndpointConnection>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.Get");
scope.Start();
try
{
var response = await _webPubSubPrivateEndpointConnectionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new PrivateEndpointConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Get the specified private endpoint connection. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<PrivateEndpointConnection> Get(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.Get");
scope.Start();
try
{
var response = _webPubSubPrivateEndpointConnectionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new PrivateEndpointConnection(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.GetAvailableLocations");
scope.Start();
try
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.GetAvailableLocations");
scope.Start();
try
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Delete the specified private endpoint connection. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<PrivateEndpointConnectionDeleteOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.Delete");
scope.Start();
try
{
var response = await _webPubSubPrivateEndpointConnectionsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new PrivateEndpointConnectionDeleteOperation(_clientDiagnostics, Pipeline, _webPubSubPrivateEndpointConnectionsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Delete the specified private endpoint connection. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual PrivateEndpointConnectionDeleteOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("PrivateEndpointConnection.Delete");
scope.Start();
try
{
var response = _webPubSubPrivateEndpointConnectionsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new PrivateEndpointConnectionDeleteOperation(_clientDiagnostics, Pipeline, _webPubSubPrivateEndpointConnectionsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 54.0131 | 259 | 0.675802 | [
"MIT"
] | BaherAbdullah/azure-sdk-for-net | sdk/webpubsub/Azure.ResourceManager.WebPubSub/src/Generated/PrivateEndpointConnection.cs | 12,369 | C# |
namespace API.Web.DTOs.Users
{
public class UpdateRequest
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Username { get; set; }
public string? Password { get; set; }
}
}
| 23.818182 | 46 | 0.583969 | [
"MIT"
] | tihomirvasilev/vehicle-marketplace-platform | src/API/Web/API.Web.DTOs/Users/UpdateRequest.cs | 264 | C# |
// Copyright (c) 2017-2020 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sharpmake.Generators;
using Sharpmake.Generators.FastBuild;
using Sharpmake.Generators.VisualStudio;
namespace Sharpmake
{
public static partial class Windows
{
[PlatformImplementation(Platform.win64,
typeof(IPlatformDescriptor),
typeof(Project.Configuration.IConfigurationTasks),
typeof(IFastBuildCompilerSettings),
typeof(IWindowsFastBuildCompilerSettings),
typeof(IPlatformBff),
typeof(IMicrosoftPlatformBff),
typeof(IPlatformVcxproj))]
public sealed class Win64Platform : BaseWindowsPlatform
{
#region IPlatformDescriptor implementation
public override string SimplePlatformString => "x64";
public override EnvironmentVariableResolver GetPlatformEnvironmentResolver(params VariableAssignment[] assignments)
{
return new Win64EnvironmentVariableResolver(assignments);
}
#endregion
#region IMicrosoftPlatformBff implementation
public override string BffPlatformDefine => "WIN64";
public override bool SupportsResourceFiles => true;
public override string CConfigName(Configuration conf)
{
var platformToolset = Options.GetObject<Options.Vc.General.PlatformToolset>(conf);
string platformToolsetString = string.Empty;
if (platformToolset != Options.Vc.General.PlatformToolset.Default && !platformToolset.IsDefaultToolsetForDevEnv(conf.Target.GetFragment<DevEnv>()))
platformToolsetString = $"_{platformToolset}";
string lldString = string.Empty;
var useLldLink = Options.GetObject<Options.Vc.LLVM.UseLldLink>(conf);
if (useLldLink == Options.Vc.LLVM.UseLldLink.Enable ||
(useLldLink == Options.Vc.LLVM.UseLldLink.Default && platformToolset.IsLLVMToolchain()))
{
lldString = "_LLD";
}
if (platformToolset.IsLLVMToolchain())
{
Options.Vc.General.PlatformToolset overridenPlatformToolset = Options.Vc.General.PlatformToolset.Default;
if (Options.WithArgOption<Options.Vc.General.PlatformToolset>.Get<Options.Clang.Compiler.LLVMVcPlatformToolset>(conf, ref overridenPlatformToolset))
platformToolsetString += $"_{overridenPlatformToolset}";
}
return $".win64{platformToolsetString}{lldString}Config";
}
public override string CppConfigName(Configuration conf)
{
return CConfigName(conf);
}
public override void AddCompilerSettings(
IDictionary<string, CompilerSettings> masterCompilerSettings,
Project.Configuration conf
)
{
var projectRootPath = conf.Project.RootPath;
var devEnv = conf.Target.GetFragment<DevEnv>();
var platform = Platform.win64; // could also been retrieved from conf.Target.GetPlatform(), if we want
string compilerName = "Compiler-" + Util.GetSimplePlatformString(platform);
var platformToolset = Options.GetObject<Options.Vc.General.PlatformToolset>(conf);
if (platformToolset.IsLLVMToolchain())
{
var useClangCl = Options.GetObject<Options.Vc.LLVM.UseClangCl>(conf);
// Use default platformToolset to get MS compiler instead of Clang, when ClangCl is disabled
if (useClangCl == Options.Vc.LLVM.UseClangCl.Disable)
{
Options.Vc.General.PlatformToolset overridenPlatformToolset = Options.Vc.General.PlatformToolset.Default;
if (Options.WithArgOption<Options.Vc.General.PlatformToolset>.Get<Options.Clang.Compiler.LLVMVcPlatformToolset>(conf, ref overridenPlatformToolset))
platformToolset = overridenPlatformToolset;
else
platformToolset = Options.Vc.General.PlatformToolset.Default;
}
}
if (platformToolset != Options.Vc.General.PlatformToolset.Default && !platformToolset.IsDefaultToolsetForDevEnv(devEnv))
compilerName += "-" + platformToolset;
else
compilerName += "-" + devEnv;
CompilerSettings compilerSettings = GetMasterCompilerSettings(masterCompilerSettings, compilerName, devEnv, projectRootPath, platformToolset, false);
compilerSettings.PlatformFlags |= Platform.win64;
SetConfiguration(conf, compilerSettings.Configurations, CppConfigName(conf), projectRootPath, devEnv, false);
}
public CompilerSettings GetMasterCompilerSettings(
IDictionary<string, CompilerSettings> masterCompilerSettings,
string compilerName,
DevEnv devEnv,
string projectRootPath,
Options.Vc.General.PlatformToolset platformToolset,
bool useCCompiler
)
{
CompilerSettings compilerSettings;
if (masterCompilerSettings.ContainsKey(compilerName))
{
compilerSettings = masterCompilerSettings[compilerName];
}
else
{
DevEnv? compilerDevEnv = null;
string platformToolSetPath = null;
string pathToCompiler = null;
string compilerExeName = null;
var compilerFamily = Sharpmake.CompilerFamily.Auto;
var fastBuildSettings = PlatformRegistry.Get<IFastBuildCompilerSettings>(Platform.win64);
switch (platformToolset)
{
case Options.Vc.General.PlatformToolset.Default:
compilerDevEnv = devEnv;
break;
case Options.Vc.General.PlatformToolset.v100:
compilerDevEnv = DevEnv.vs2010;
break;
case Options.Vc.General.PlatformToolset.v110:
case Options.Vc.General.PlatformToolset.v110_xp:
compilerDevEnv = DevEnv.vs2012;
break;
case Options.Vc.General.PlatformToolset.v120:
case Options.Vc.General.PlatformToolset.v120_xp:
compilerDevEnv = DevEnv.vs2013;
break;
case Options.Vc.General.PlatformToolset.v140:
case Options.Vc.General.PlatformToolset.v140_xp:
compilerDevEnv = DevEnv.vs2015;
break;
case Options.Vc.General.PlatformToolset.v141:
case Options.Vc.General.PlatformToolset.v141_xp:
compilerDevEnv = DevEnv.vs2017;
break;
case Options.Vc.General.PlatformToolset.v142:
compilerDevEnv = DevEnv.vs2019;
break;
case Options.Vc.General.PlatformToolset.LLVM_vs2012:
case Options.Vc.General.PlatformToolset.LLVM_vs2014:
case Options.Vc.General.PlatformToolset.LLVM:
case Options.Vc.General.PlatformToolset.ClangCL:
platformToolSetPath = ClangForWindows.Settings.LLVMInstallDir;
pathToCompiler = Path.Combine(platformToolSetPath, "bin");
compilerExeName = "clang-cl.exe";
var compilerFamilyKey = new FastBuildWindowsCompilerFamilyKey(devEnv, platformToolset);
if (!fastBuildSettings.CompilerFamily.TryGetValue(compilerFamilyKey, out compilerFamily))
compilerFamily = Sharpmake.CompilerFamily.ClangCl;
break;
default:
throw new ArgumentOutOfRangeException();
}
if (compilerDevEnv.HasValue)
{
platformToolSetPath = Path.Combine(compilerDevEnv.Value.GetVisualStudioDir(), "VC");
pathToCompiler = compilerDevEnv.Value.GetVisualStudioBinPath(Platform.win64);
compilerExeName = "cl.exe";
var compilerFamilyKey = new FastBuildWindowsCompilerFamilyKey(devEnv, platformToolset);
if (!fastBuildSettings.CompilerFamily.TryGetValue(compilerFamilyKey, out compilerFamily))
compilerFamily = Sharpmake.CompilerFamily.MSVC;
}
Strings extraFiles = new Strings();
{
Strings userExtraFiles;
if (fastBuildSettings.ExtraFiles.TryGetValue(devEnv, out userExtraFiles))
extraFiles.AddRange(userExtraFiles);
}
if (compilerDevEnv.HasValue)
{
extraFiles.Add(
@"$ExecutableRootPath$\c1.dll",
@"$ExecutableRootPath$\c1xx.dll",
@"$ExecutableRootPath$\c2.dll",
@"$ExecutableRootPath$\mspdbcore.dll",
@"$ExecutableRootPath$\mspdbsrv.exe",
@"$ExecutableRootPath$\1033\clui.dll"
);
switch (compilerDevEnv)
{
case DevEnv.vs2012:
{
extraFiles.Add(
@"$ExecutableRootPath$\c1ast.dll",
@"$ExecutableRootPath$\c1xxast.dll",
@"$ExecutableRootPath$\mspft110.dll",
@"$ExecutableRootPath$\msobj110.dll",
@"$ExecutableRootPath$\mspdb110.dll",
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC110.CRT\msvcp110.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC110.CRT\msvcr110.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC110.CRT\vccorlib110.dll")
);
}
break;
case DevEnv.vs2013:
{
extraFiles.Add(
@"$ExecutableRootPath$\c1ast.dll",
@"$ExecutableRootPath$\c1xxast.dll",
@"$ExecutableRootPath$\mspft120.dll",
@"$ExecutableRootPath$\msobj120.dll",
@"$ExecutableRootPath$\mspdb120.dll",
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC120.CRT\msvcp120.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC120.CRT\msvcr120.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC120.CRT\vccorlib120.dll")
);
}
break;
case DevEnv.vs2015:
case DevEnv.vs2017:
case DevEnv.vs2019:
{
string systemDllPath = FastBuildSettings.SystemDllRoot;
if (systemDllPath == null)
{
var windowsTargetPlatformVersion = KitsRootPaths.GetWindowsTargetPlatformVersionForDevEnv(compilerDevEnv.Value);
string redistDirectory;
if (windowsTargetPlatformVersion <= Options.Vc.General.WindowsTargetPlatformVersion.v10_0_17134_0)
redistDirectory = @"Redist\ucrt\DLLs\x64\";
else
redistDirectory = $@"Redist\{windowsTargetPlatformVersion.ToVersionString()}\ucrt\DLLs\x64\";
systemDllPath = Path.Combine(KitsRootPaths.GetRoot(KitsRootEnum.KitsRoot10), redistDirectory);
}
if (!Path.IsPathRooted(systemDllPath))
systemDllPath = Util.SimplifyPath(Path.Combine(projectRootPath, systemDllPath));
extraFiles.Add(
@"$ExecutableRootPath$\msobj140.dll",
@"$ExecutableRootPath$\mspft140.dll",
@"$ExecutableRootPath$\mspdb140.dll"
);
if (compilerDevEnv.Value == DevEnv.vs2015)
{
extraFiles.Add(
@"$ExecutableRootPath$\vcvars64.bat",
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC140.CRT\concrt140.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC140.CRT\msvcp140.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC140.CRT\vccorlib140.dll"),
Path.Combine(platformToolSetPath, @"redist\x64\Microsoft.VC140.CRT\vcruntime140.dll"),
Path.Combine(systemDllPath, "ucrtbase.dll")
);
}
else
{
extraFiles.Add(
@"$ExecutableRootPath$\mspdbcore.dll",
@"$ExecutableRootPath$\msvcdis140.dll",
@"$ExecutableRootPath$\msvcp140.dll",
@"$ExecutableRootPath$\pgodb140.dll",
@"$ExecutableRootPath$\vcruntime140.dll",
Path.Combine(platformToolSetPath, @"Auxiliary\Build\vcvars64.bat")
);
}
if (compilerDevEnv.Value == DevEnv.vs2019)
{
Version toolsVersion = compilerDevEnv.Value.GetVisualStudioVCToolsVersion();
if (toolsVersion >= new Version("14.22.27905")) // 16.3.2
extraFiles.Add(@"$ExecutableRootPath$\tbbmalloc.dll");
if (toolsVersion >= new Version("14.25.28610")) // 16.5
extraFiles.Add(@"$ExecutableRootPath$\vcruntime140_1.dll");
if (toolsVersion >= new Version("14.28.29333")) // 16.8
extraFiles.Add(@"$ExecutableRootPath$\msvcp140_atomic_wait.dll");
}
try
{
foreach (string p in Util.DirectoryGetFiles(systemDllPath, "api-ms-win-*.dll"))
extraFiles.Add(p);
}
catch { }
}
break;
default:
throw new NotImplementedException("This devEnv (" + compilerDevEnv.Value + ") is not supported!");
}
}
string executable = Path.Combine("$ExecutableRootPath$", compilerExeName);
compilerSettings = new CompilerSettings(compilerName, compilerFamily, Platform.win64, extraFiles, executable, pathToCompiler, devEnv, new Dictionary<string, CompilerSettings.Configuration>());
masterCompilerSettings.Add(compilerName, compilerSettings);
}
return compilerSettings;
}
private void SetConfiguration(
Project.Configuration conf,
IDictionary<string, CompilerSettings.Configuration> configurations,
string configName,
string projectRootPath,
DevEnv devEnv,
bool useCCompiler)
{
if (configurations.ContainsKey(configName))
return;
string linkerPathOverride = null;
string linkerExeOverride = null;
string librarianExeOverride = null;
GetLinkerExecutableInfo(conf, out linkerPathOverride, out linkerExeOverride, out librarianExeOverride);
var fastBuildCompilerSettings = PlatformRegistry.Get<IWindowsFastBuildCompilerSettings>(Platform.win64);
string binPath;
if (!fastBuildCompilerSettings.BinPath.TryGetValue(devEnv, out binPath))
binPath = devEnv.GetVisualStudioBinPath(Platform.win64);
string linkerPath;
if (!string.IsNullOrEmpty(linkerPathOverride))
linkerPath = linkerPathOverride;
else if (!fastBuildCompilerSettings.LinkerPath.TryGetValue(devEnv, out linkerPath))
linkerPath = binPath;
string linkerExe;
if (!string.IsNullOrEmpty(linkerExeOverride))
linkerExe = linkerExeOverride;
else if (!fastBuildCompilerSettings.LinkerExe.TryGetValue(devEnv, out linkerExe))
linkerExe = "link.exe";
string librarianExe;
if (!string.IsNullOrEmpty(librarianExeOverride))
librarianExe = librarianExeOverride;
else if (!fastBuildCompilerSettings.LibrarianExe.TryGetValue(devEnv, out librarianExe))
librarianExe = "lib.exe";
string resCompiler;
if (!fastBuildCompilerSettings.ResCompiler.TryGetValue(devEnv, out resCompiler))
resCompiler = devEnv.GetWindowsResourceCompiler(Platform.win64);
configurations.Add(
configName,
new CompilerSettings.Configuration(
Platform.win64,
binPath: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, binPath)),
linkerPath: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, linkerPath)),
resourceCompiler: Util.GetCapitalizedPath(Util.PathGetAbsolute(projectRootPath, resCompiler)),
librarian: Path.Combine(@"$LinkerPath$", librarianExe),
linker: Path.Combine(@"$LinkerPath$", linkerExe)
)
);
configurations.Add(
configName + "Masm",
new CompilerSettings.Configuration(
Platform.win64,
compiler: @"$BinPath$\ml64.exe",
usingOtherConfiguration: configName
)
);
}
#endregion
#region IPlatformVcxproj implementation
public override bool HasEditAndContinueDebuggingSupport => true;
public override IEnumerable<string> GetImplicitlyDefinedSymbols(IGenerationContext context)
{
var defines = new List<string>();
defines.AddRange(base.GetImplicitlyDefinedSymbols(context));
defines.Add("WIN64");
return defines;
}
public override void SetupPlatformTargetOptions(IGenerationContext context)
{
context.Options["TargetMachine"] = "MachineX64";
context.CommandLineOptions["TargetMachine"] = "/MACHINE:X64";
}
public override void SelectPlatformAdditionalDependenciesOptions(IGenerationContext context)
{
base.SelectPlatformAdditionalDependenciesOptions(context);
context.Options["AdditionalDependencies"] += ";%(AdditionalDependencies)";
}
protected override IEnumerable<IncludeWithPrefix> GetPlatformIncludePathsWithPrefixImpl(IGenerationContext context)
{
var includes = new List<IncludeWithPrefix>();
string includePrefix = "/I";
var platformToolset = Options.GetObject<Options.Vc.General.PlatformToolset>(context.Configuration);
if (platformToolset.IsLLVMToolchain() && Options.GetObject<Options.Vc.LLVM.UseClangCl>(context.Configuration) == Options.Vc.LLVM.UseClangCl.Enable)
{
includePrefix = "/clang:-isystem";
string clangIncludePath = ClangForWindows.GetWindowsClangIncludePath();
includes.Add(new IncludeWithPrefix(includePrefix, clangIncludePath));
Options.Vc.General.PlatformToolset overridenPlatformToolset = Options.Vc.General.PlatformToolset.Default;
if (Options.WithArgOption<Options.Vc.General.PlatformToolset>.Get<Options.Clang.Compiler.LLVMVcPlatformToolset>(context.Configuration, ref overridenPlatformToolset))
platformToolset = overridenPlatformToolset;
}
DevEnv devEnv = platformToolset.GetDefaultDevEnvForToolset() ?? context.DevelopmentEnvironment;
// when using clang-cl, mark MSVC includes, so they are properly recognized
IEnumerable<string> msvcIncludePaths = EnumerateSemiColonSeparatedString(devEnv.GetWindowsIncludePath());
includes.AddRange(msvcIncludePaths.Select(path => new IncludeWithPrefix(includePrefix, path)));
// Additional system includes
OrderableStrings SystemIncludes = new OrderableStrings(context.Configuration.DependenciesIncludeSystemPaths);
SystemIncludes.AddRange(context.Configuration.IncludeSystemPaths);
if (SystemIncludes.Count > 0)
{
SystemIncludes.Sort();
includes.AddRange(SystemIncludes.Select(path => new IncludeWithPrefix(includePrefix, path)));
}
return includes;
}
public override void GeneratePlatformSpecificProjectDescription(IVcxprojGenerationContext context, IFileGenerator generator)
{
string propertyGroups = string.Empty;
// MSBuild override when mixing devenvs in the same vcxproj is not supported,
// but before throwing an exception check if we have some override
for (DevEnv devEnv = context.DevelopmentEnvironmentsRange.MinDevEnv; devEnv <= context.DevelopmentEnvironmentsRange.MaxDevEnv; devEnv = (DevEnv)((int)devEnv << 1))
{
switch (devEnv)
{
case DevEnv.vs2015:
case DevEnv.vs2017:
{
string platformFolder = MSBuildGlobalSettings.GetCppPlatformFolder(devEnv, Platform.win64);
if (!string.IsNullOrEmpty(platformFolder))
{
using (generator.Declare("platformFolder", Util.EnsureTrailingSeparator(platformFolder))) // _PlatformFolder require the path to end with a "\"
propertyGroups += generator.Resolver.Resolve(Vcxproj.Template.Project.PlatformFolderOverride);
}
}
break;
case DevEnv.vs2019:
{
// Note1: _PlatformFolder override is deprecated starting with vs2019, so we write AdditionalVCTargetsPath instead
// Note2: MSBuildGlobalSettings.SetCppPlatformFolder for vs2019 is no more the valid way to handle it. Older buildtools packages can anyway contain it, and need upgrade.
if (!string.IsNullOrEmpty(MSBuildGlobalSettings.GetCppPlatformFolder(devEnv, Platform.win64)))
throw new Error("SetCppPlatformFolder is not supported by VS2019 correctly: use of MSBuildGlobalSettings.SetCppPlatformFolder should be replaced by use of MSBuildGlobalSettings.SetAdditionalVCTargetsPath.");
// vs2019 use AdditionalVCTargetsPath
string additionalVCTargetsPath = MSBuildGlobalSettings.GetAdditionalVCTargetsPath(devEnv, Platform.win64);
if (!string.IsNullOrEmpty(additionalVCTargetsPath))
{
using (generator.Declare("additionalVCTargetsPath", Util.EnsureTrailingSeparator(additionalVCTargetsPath))) // the path shall end with a "\"
propertyGroups += generator.Resolver.Resolve(Vcxproj.Template.Project.AdditionalVCTargetsPath);
}
}
break;
}
}
string llvmOverrideSection = ClangForWindows.GetLLVMOverridesSection(context, generator.Resolver);
if (!string.IsNullOrEmpty(llvmOverrideSection))
propertyGroups += llvmOverrideSection;
if (!string.IsNullOrEmpty(propertyGroups))
{
if (context.DevelopmentEnvironmentsRange.MinDevEnv != context.DevelopmentEnvironmentsRange.MaxDevEnv)
throw new Error("Different vs versions not supported in the same vcxproj");
using (generator.Declare("platformName", SimplePlatformString))
{
generator.Write(Vcxproj.Template.Project.ProjectDescriptionStartPlatformConditional);
generator.WriteVerbatim(propertyGroups);
generator.Write(Vcxproj.Template.Project.PropertyGroupEnd);
}
}
}
#endregion
}
}
}
| 55.40856 | 243 | 0.529951 | [
"Apache-2.0"
] | Friendly0Fire/Sharpmake | Sharpmake.Platforms/Sharpmake.CommonPlatforms/Windows/Win64Platform.cs | 28,482 | C# |
namespace WDE.SqlQueryGenerator
{
public interface IVariable
{
}
} | 12.428571 | 31 | 0.609195 | [
"Unlicense"
] | BAndysc/WoWDatabaseEditor | WDE.SqlQueryGenerator/IVariable.cs | 87 | C# |
/*
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 Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Umb.CastleWindsor;
using Glass.Mapper.Umb.Configuration;
using Glass.Mapper.Umb.DataMappers;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Services;
namespace Glass.Mapper.Umb.Integration.DataMappers
{
[TestFixture]
public class UmbracoInfoMapperFixture
{
private PetaPocoUnitOfWorkProvider _unitOfWork;
private RepositoryFactory _repoFactory;
#region Method - MapToProperty
[Test]
[Sequential]
public void MapToProperty_UmbracoInfoType_GetsExpectedValueFromUmbraco(
[Values(
//UmbracoInfoType.Url,
UmbracoInfoType.ContentTypeAlias,
UmbracoInfoType.ContentTypeName,
UmbracoInfoType.Name,
UmbracoInfoType.Creator
)] UmbracoInfoType type,
[Values(
//"target", //Url
"TestType", //ContentTypeAlias
"Test Type", //ContentTypeName
"Target", //Name
"admin" //Creator
)] object expected
)
{
//Assign
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
Console.WriteLine(type);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
[ExpectedException(typeof(MapperException))]
public void MapToProperty_UmbracoInfoTypeNotSet_ThrowsException()
{
//Assign
UmbracoInfoType type = UmbracoInfoType.NotSet;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
//No asserts expect exception
}
[Test]
public void MapToProperty_UmbracoInfoTypeVersion_ReturnsVersionIdAsGuid()
{
//Assign
var type = UmbracoInfoType.Version;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.Version;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypePath_ReturnsPathAsString()
{
//Assign
var type = UmbracoInfoType.Path;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.Path;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypeCreateDate_ReturnsCreateDateAsDateTime()
{
//Assign
var type = UmbracoInfoType.CreateDate;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.CreateDate;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypeUpdateDate_ReturnsUpdateDateAsDateTime()
{
//Assign
var type = UmbracoInfoType.UpdateDate;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.UpdateDate;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
#endregion
#region Method - MapToCms
[Test]
public void MapToCms_SavingName_UpdatesTheItemName()
{
//Assign
var type = UmbracoInfoType.Name;
var expected = "new name";
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var oldName = content.Name;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var context = Context.Create(DependencyResolver.CreateStandardResolver());
var dataContext = new UmbracoDataMappingContext(null, content, new UmbracoService(contentService, context), false);
dataContext.PropertyValue = expected;
string actual = string.Empty;
//Act
mapper.MapToCms(dataContext);
content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
actual = content.Name;
//Assert
Assert.AreEqual(expected, actual);
content.Name = oldName;
contentService.Save(content);
}
#endregion
#region Stubs
[TestFixtureSetUp]
public void CreateStub()
{
string name = "Target";
string contentTypeAlias = "TestType";
string contentTypeName = "Test Type";
_unitOfWork = Global.CreateUnitOfWork();
_repoFactory = new RepositoryFactory();
var contentService = new ContentService(_unitOfWork, _repoFactory);
var contentTypeService = new ContentTypeService(_unitOfWork, _repoFactory,
new ContentService(_unitOfWork),
new MediaService(_unitOfWork, _repoFactory));
var contentType = new ContentType(-1);
contentType.Name = contentTypeName;
contentType.Alias = contentTypeAlias;
contentType.Thumbnail = string.Empty;
contentTypeService.Save(contentType);
Assert.Greater(contentType.Id, 0);
var content = new Content(name, -1, contentType);
content.Key = new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}");
contentService.Save(content);
contentService.Publish(content);
}
public class Stub
{
public Guid TemplateId { get; set; }
}
#endregion
}
}
| 36.663194 | 128 | 0.596079 | [
"Apache-2.0"
] | seankearney/Glass.Mapper | Tests/Integration Tests/Umbraco/Glass.Mapper.Umb.Integration/DataMappers/UmbracoInfoMapperFixture.cs | 10,559 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Driver.UI.Interfaces;
using Driver.UI.Selenium;
using Reporters;
using Utilities;
using Utilities.Enums;
namespace Philips.EDI.Foundation.HDSHelp.AutomationTest
{
[TestClass]
public class UITest
{
[TestInitialize]
public void BeforeTest()
{
ProcessUtilities.KillChromeDriver();
}
[TestMethod]
public void LaunchingAndClickingonGetStarted()
{
ValidateOverviewPage();
}
public void ValidateOverviewPage()
{
IWebDriverUi _webdriver = new SeleniumDriver(Driver.Enums.BrowserType.Chrome, "https://hds-help.netlify.app/", null);
object getStartedButton = _webdriver.FindElementByClassName("btn-default");
_webdriver.Click(getStartedButton);
object overViewText = _webdriver.FindElementByClassName("page-header");
string text = _webdriver.GetText(overViewText);
AssertTest.IsTrue(text.ToUpper().Equals("OVERVIEW"),"After clicking Get Started page displayed is not overview: "+text,"Get Started button was clicked and page was navigated to Overview Section");
}
}
}
| 33.861111 | 208 | 0.675964 | [
"Apache-2.0"
] | balajinarayanaa/docs | AutomationTest/Philips.EDI.Foundation.HDSHelp.AutomationTest/UITest.cs | 1,219 | C# |
using System.Data;
namespace SkycorHRM.DesignPattern.Domain
{
public class DataAccessContext
{
private readonly IDataAccessStrategy _dataAccessStrategy;
public DataAccessContext(IDataAccessStrategy dataAccessStrategy)
{
_dataAccessStrategy = dataAccessStrategy;
}
public IDbDataAdapter EstablishDataAccess(IDbDataAdapter adapter)
{
return _dataAccessStrategy.Prepare(adapter);
}
}
}
| 26.5 | 73 | 0.689727 | [
"MIT"
] | pavelski01/SkycoreHRM | SkycorHRM.DesignPattern/Domain/DataAccessContext.cs | 479 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Tiw.V20190919.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class SetOnlineRecordCallbackKeyRequest : AbstractModel
{
/// <summary>
/// 应用的SdkAppId
/// </summary>
[JsonProperty("SdkAppId")]
public long? SdkAppId{ get; set; }
/// <summary>
/// 设置实时录制回调鉴权密钥,最长64字符,如果传入空字符串,那么删除现有的鉴权回调密钥。回调鉴权方式请参考文档:https://cloud.tencent.com/document/product/1137/40257
/// </summary>
[JsonProperty("CallbackKey")]
public string CallbackKey{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "SdkAppId", this.SdkAppId);
this.SetParamSimple(map, prefix + "CallbackKey", this.CallbackKey);
}
}
}
| 32.137255 | 120 | 0.657108 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Tiw/V20190919/Models/SetOnlineRecordCallbackKeyRequest.cs | 1,751 | C# |
namespace HackF5.UnitySpy.Gui.Wpf.View
{
public partial class TypeDefinitionView
{
public TypeDefinitionView()
{
this.InitializeComponent();
this.Loaded += (sender, args) => this.PathTextBox.Focus();
}
}
} | 24.181818 | 70 | 0.586466 | [
"MIT"
] | frcaton/unityspy | src/HackF5.UnitySpy.Gui.Wpf/View/TypeDefinitionView.xaml.cs | 268 | C# |
namespace CNTK6.Models
{
public sealed class CntkResult
{
public string Label
{
get;
set;
}
public double Probability
{
get;
set;
}
public string ProbabilityText
{
get;
set;
}
}
}
| 12.25 | 37 | 0.38484 | [
"MIT"
] | takuya-takeuchi/Demo | CNTK6/source/CNTK6/Models/CntkResult.cs | 345 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.