context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// SmtpClientTest.cs - NUnit Test Cases for System.Net.Mail.SmtpClient
//
// Authors:
// John Luke (john.luke@gmail.com)
//
// (C) 2006 John Luke
//
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Mail.Tests
{
public class SmtpClientTest : IDisposable
{
private SmtpClient _smtp;
private string _tempFolder;
private SmtpClient Smtp
{
get
{
return _smtp ?? (_smtp = new SmtpClient());
}
}
private string TempFolder
{
get
{
if (_tempFolder == null)
{
_tempFolder = Path.Combine(Path.GetTempPath(), GetType().FullName, Guid.NewGuid().ToString());
if (Directory.Exists(_tempFolder))
Directory.Delete(_tempFolder, true);
Directory.CreateDirectory(_tempFolder);
}
return _tempFolder;
}
}
public void Dispose()
{
if (_smtp != null)
{
_smtp.Dispose();
}
if (Directory.Exists(_tempFolder))
Directory.Delete(_tempFolder, true);
}
[Theory]
[InlineData(SmtpDeliveryMethod.SpecifiedPickupDirectory)]
[InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)]
[InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)]
public void DeliveryMethodTest(SmtpDeliveryMethod method)
{
Smtp.DeliveryMethod = method;
Assert.Equal(method, Smtp.DeliveryMethod);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void EnableSslTest(bool value)
{
Smtp.EnableSsl = value;
Assert.Equal(value, Smtp.EnableSsl);
}
[Theory]
[InlineData("127.0.0.1")]
[InlineData("smtp.ximian.com")]
public void HostTest(string host)
{
Smtp.Host = host;
Assert.Equal(host, Smtp.Host);
}
[Fact]
public void InvalidHostTest()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Host = null);
Assert.Throws<ArgumentException>(() => Smtp.Host = "");
}
[Fact]
public void ServicePoint_GetsCachedInstanceSpecificToHostPort()
{
using (var smtp1 = new SmtpClient("localhost1", 25))
using (var smtp2 = new SmtpClient("localhost1", 25))
using (var smtp3 = new SmtpClient("localhost2", 25))
using (var smtp4 = new SmtpClient("localhost2", 26))
{
ServicePoint s1 = smtp1.ServicePoint;
ServicePoint s2 = smtp2.ServicePoint;
ServicePoint s3 = smtp3.ServicePoint;
ServicePoint s4 = smtp4.ServicePoint;
Assert.NotNull(s1);
Assert.NotNull(s2);
Assert.NotNull(s3);
Assert.NotNull(s4);
Assert.Same(s1, s2);
Assert.NotSame(s2, s3);
Assert.NotSame(s2, s4);
Assert.NotSame(s3, s4);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[Fact]
public void ServicePoint_NetCoreApp_AddressIsAccessible()
{
using (var smtp = new SmtpClient("localhost", 25))
{
Assert.Equal("mailto", smtp.ServicePoint.Address.Scheme);
Assert.Equal("localhost", smtp.ServicePoint.Address.Host);
Assert.Equal(25, smtp.ServicePoint.Address.Port);
}
}
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
[Fact]
public void ServicePoint_NetFramework_AddressIsInaccessible()
{
using (var smtp = new SmtpClient("localhost", 25))
{
ServicePoint sp = smtp.ServicePoint;
Assert.Throws<NotSupportedException>(() => sp.Address);
}
}
[Fact]
public void ServicePoint_ReflectsHostAndPortChange()
{
using (var smtp = new SmtpClient("localhost1", 25))
{
ServicePoint s1 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s2 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s3 = smtp.ServicePoint;
Assert.NotSame(s1, s2);
Assert.Same(s2, s3);
smtp.Port = 26;
ServicePoint s4 = smtp.ServicePoint;
smtp.Port = 26;
ServicePoint s5 = smtp.ServicePoint;
Assert.NotSame(s3, s4);
Assert.Same(s4, s5);
}
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData("shouldnotexist")]
[InlineData("\0")]
[InlineData("C:\\some\\path\\like\\string")]
public void PickupDirectoryLocationTest(string folder)
{
Smtp.PickupDirectoryLocation = folder;
Assert.Equal(folder, Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(25)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void PortTest(int value)
{
Smtp.Port = value;
Assert.Equal(value, Smtp.Port);
}
[Fact]
public void TestDefaultsOnProperties()
{
Assert.Equal(25, Smtp.Port);
Assert.Equal(100000, Smtp.Timeout);
Assert.Null(Smtp.Host);
Assert.Null(Smtp.Credentials);
Assert.False(Smtp.EnableSsl);
Assert.False(Smtp.UseDefaultCredentials);
Assert.Equal(SmtpDeliveryMethod.Network, Smtp.DeliveryMethod);
Assert.Null(Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public void Port_Value_Invalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Port = value);
}
[Fact]
public void Send_Message_Null()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Send(null));
}
[Fact]
public void Send_Network_Host_Null()
{
Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Fact]
public void Send_Network_Host_Whitespace()
{
Smtp.Host = " \r\n ";
Assert.Throws<InvalidOperationException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Fact]
public void Send_SpecifiedPickupDirectory()
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = TempFolder;
Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello");
string[] files = Directory.GetFiles(TempFolder, "*");
Assert.Equal(1, files.Length);
Assert.Equal(".eml", Path.GetExtension(files[0]));
}
[Theory]
[InlineData("some_path_not_exist")]
[InlineData("")]
[InlineData(null)]
[InlineData("\0abc")]
public void Send_SpecifiedPickupDirectoryInvalid(string location)
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = location;
Assert.Throws<SmtpException>(() => Smtp.Send("mono@novell.com", "everyone@novell.com", "introduction", "hello"));
}
[Theory]
[InlineData(0)]
[InlineData(50)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(-1)]
public void TestTimeout(int value)
{
if (value < 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Timeout = value);
return;
}
Smtp.Timeout = value;
Assert.Equal(value, Smtp.Timeout);
}
[Fact]
public void TestMailDelivery()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
client.Credentials = new NetworkCredential("user", "password");
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
try
{
Thread t = new Thread(server.Run);
t.Start();
client.Send(msg);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
}
finally
{
server.Stop();
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Crashes or hangs: https://github.com/dotnet/corefx/issues/19604")]
public async Task TestMailDeliveryAsync()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
}
finally
{
server.Stop();
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Crashes or hangs: https://github.com/dotnet/corefx/issues/19604")]
public async Task TestCredentialsCopyInAsyncContext()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
CredentialCache cache = new CredentialCache();
cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials);
client.Credentials = cache;
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg);
t.Join();
Assert.Equal("<foo@example.com>", server.MailFrom);
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
}
finally
{
server.Stop();
}
}
}
}
| |
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord (Big Room)
* C# Port: Ben Baker (HeadSoft)
* Copyright (c) Big Room Ventures Ltd. 2008
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Collections.Generic;
using FlintSharp.Behaviours;
using FlintSharp.Activities;
using FlintSharp.Counters;
using FlintSharp.Easing;
using FlintSharp.Emitters;
using FlintSharp.EnergyEasing;
using FlintSharp.Initializers;
using FlintSharp.Particles;
using FlintSharp.Zones;
namespace FlintSharp.Behaviours
{
/// <summary>
/// The MatchRotateVelocity action applies an angular acceleration to the particle to match
/// its angular velocity to that of its nearest neighbours.
/// </summary>
public class MatchRotateVelocity : Behaviour
{
private double m_min;
private double m_acc;
public MatchRotateVelocity()
: this(1.0, 1.0)
{
}
/// <summary>
/// The constructor creates a MatchRotateVelocity action for use by
/// an emitter. To add a MatchRotateVelocity to all particles created by an emitter, use the
/// emitter's addAction method.
///
/// @see org.flintparticles.emitters.Emitter#addAction()
/// </summary>
/// <param name="maxDistance">The maximum distance, in pixels, over which this action operates.
/// The particle will match its angular velocity other particles that are this close or
/// closer to it.</param>
/// <param name="acceleration">The angular acceleration applied to adjust velocity to match that
/// of the other particles.</param>
public MatchRotateVelocity(double maxDistance, double acceleration)
{
m_min = maxDistance;
m_acc = acceleration;
}
/// <summary>
/// The maximum distance, in pixels, over which this action operates.
/// The particle will match its angular velocity other particles that are this
/// close or closer to it.
/// </summary>
public double MaxDistance
{
get { return m_min; }
set { m_min = value; }
}
/// <summary>
/// The angular acceleration applied to adjust velocity to match that
/// of the other particles.
/// </summary>
public double Acceleration
{
get { return m_acc; }
set { m_acc = value; }
}
/// <summary>
/// The getDefaultPriority method is used to order the execution of actions.
/// It is called within the emitter's addAction method when the user doesn't
/// manually set a priority. It need not be called directly by the user.
///
/// @see org.flintparticles.common.actions.Action#getDefaultPriority()
/// </summary>
/// <returns><p>Returns a value of 10, so that the MutualGravity action executes before other actions.</p></returns>
public override int GetDefaultPriority()
{
return 10;
}
/// <summary>
/// The addedToEmitter method is called by the emitter when the Action is added to it
/// It is called within the emitter's addAction method and need not
/// be called by the user.
/// </summary>
/// <param name="emitter">The Emitter that the Action was added to.</param>
public override void AddedToEmitter(Emitter emitter)
{
if (emitter == null)
{
return;
}
emitter.SpaceSort = true;
}
/// <summary>
/// The update method is used by the emitter to apply the action
/// to every particle. It is called within the emitter's update
/// loop and need not be called by the user.
/// </summary>
/// <param name="emitter">The Emitter that created the particle.</param>
/// <param name="particle">The particle to be updated.</param>
/// <param name="elapsedTime">The duration of the frame - used for time based updates.</param>
public override void Update(Emitter emitter, Particle particle, double elapsedTime)
{
if (emitter == null)
{
return;
}
if (particle == null)
{
return;
}
List<Particle> particles = emitter.Particles;
Particle other;
int i;
int len = particles.Count;
double dy;
double vel = 0;
int count = 0;
double factor;
for (i = particles.IndexOf(particle) - 1; i >= 0; i--)
{
other = particles[i];
if (particle.X - other.X > m_min)
break;
dy = other.Y - particle.Y;
if (dy > m_min || dy < -m_min)
continue;
vel += other.AngularVelocity;
count++;
}
for (i = particles.IndexOf(particle) + 1; i < len; i++)
{
other = particles[i];
if (other.X - particle.X > m_min)
break;
dy = other.Y - particle.Y;
if (dy > m_min || dy < -m_min)
continue;
vel += other.AngularVelocity;
count++;
}
if (count != 0)
{
vel = vel / count - particle.AngularVelocity;
if (vel != 0)
{
double velSign = 1;
if (vel < 0)
{
velSign = -1;
vel = -vel;
}
factor = elapsedTime * m_acc;
if (factor > vel)
factor = vel;
particle.AngularVelocity += factor * velSign;
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Numerics;
using Disunity.Data;
using Disunity.Data.Shaders;
namespace Disunity.Rendering
{
class FaceDrawer
{
private readonly int _borderColor = Color.White.ToArgb();
private float[,] _zBuffer;
private int _width;
private int _height;
private bool _useFill;
private bool _useBorders;
public FaceDrawer(int width, int height)
{
_width = width;
_height = height;
_zBuffer = new float[width, height];
}
public void Init(RenderMode renderMode)
{
_useFill = renderMode.UseFill();
_useBorders = renderMode.UseBorders();
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
_zBuffer[x, y] = float.NegativeInfinity;
}
}
}
public void Draw(int faceIndex, WritableTexture screen, Shader shader, ShaderState shaderState, int startY, int endY)
{
var faceState = shaderState.Face;
var vertexState = shaderState.Vertex;
var fragmentState = shaderState.Fragment;
faceState.Clear();
vertexState.Clear();
shader.Face(faceState, faceIndex);
var v04 = shader.Vertex(vertexState, faceIndex, 0);
var v14 = shader.Vertex(vertexState, faceIndex, 1);
var v24 = shader.Vertex(vertexState, faceIndex, 2);
var v0 = new Vector3(v04.X / v04.W, v04.Y / v04.W, v04.Z / v04.W);
var v1 = new Vector3(v14.X / v14.W, v14.Y / v14.W, v14.Z / v14.W);
var v2 = new Vector3(v24.X / v24.W, v24.Y / v24.W, v24.Z / v24.W);
var diff1 = Vector3.Subtract(v1, v0);
var diff2 = Vector3.Subtract(v2, v1);
var normal = Vector3.Cross(diff1, diff2);
normal = Vector3.Normalize(normal);
var directionCulling = Vector3.Dot(normal, new Vector3(0, 0, 1));
if (directionCulling <= 0)
return;
if (_useFill)
DrawFilling(screen, startY, endY, v0, v1, v2, fragmentState, faceState, vertexState, shader);
if (_useBorders)
DrawBorders(faceIndex, screen, shader, shaderState, startY, endY);
}
private void DrawBorders(int faceIndex, WritableTexture screen, Shader shader, ShaderState shaderState, int startY, int endY)
{
shaderState.Vertex.Clear();
var v0 = shader.Vertex(shaderState.Vertex, faceIndex, 0);
var v1 = shader.Vertex(shaderState.Vertex, faceIndex, 1);
var v2 = shader.Vertex(shaderState.Vertex, faceIndex, 2);
var screenCoords = new[]
{
new Vector3(v0.X/v0.W, v0.Y/v0.W, v0.Z/v0.W),
new Vector3(v1.X/v1.W, v1.Y/v1.W, v1.Z/v1.W),
new Vector3(v2.X/v2.W, v2.Y/v2.W, v2.Z/v2.W)
};
DrawSolidLine((int) screenCoords[0].X, (int) screenCoords[0].Y, (int) screenCoords[1].X, (int) screenCoords[1].Y,
screen, _borderColor, startY, endY);
DrawSolidLine((int) screenCoords[1].X, (int) screenCoords[1].Y, (int) screenCoords[2].X, (int) screenCoords[2].Y,
screen, _borderColor, startY, endY);
DrawSolidLine((int) screenCoords[2].X, (int) screenCoords[2].Y, (int) screenCoords[0].X, (int) screenCoords[0].Y,
screen, _borderColor, startY, endY);
}
private void DrawFilling(WritableTexture screen, int startY, int endY, Vector3 v0, Vector3 v1, Vector3 v2,
FragmentShaderState fragmentState, FaceShaderState faceState, VertexShaderState vertexState, Shader shader)
{
var x0 = (int) Math.Round(v0.X);
var y0 = (int) Math.Round(v0.Y);
var x1 = (int) Math.Round(v1.X);
var y1 = (int) Math.Round(v1.Y);
var x2 = (int) Math.Round(v2.X);
var y2 = (int) Math.Round(v2.Y);
int minX = ClipX(Math3(x0, x1, x2, Math.Min));
int minY = ClipY(Math3(y0, y1, y2, Math.Min), startY, endY);
int maxX = ClipX(Math3(x0, x1, x2, Math.Max));
int maxY = ClipY(Math3(y0, y1, y2, Math.Max), startY, endY);
float midX = (v0.X + v1.X + v2.X)/3;
float midY = (v0.Y + v1.Y + v2.Y)/3;
var dirV0 = new Vector3(v0.X - midX, v0.Y - midY, 0);
var dirV1 = new Vector3(v1.X - midX, v1.Y - midY, 0);
var direction = Vector3.Cross(dirV0, dirV1).Z;
if (direction < 0)
{
Vector3 tbuf;
tbuf = v1;
v1 = v2;
v2 = tbuf;
}
var line1 = new Line(v0.X, v0.Y, v1.X, v1.Y, minX, minY);
var line2 = new Line(v1.X, v1.Y, v2.X, v2.Y, minX, minY);
var line3 = new Line(v2.X, v2.Y, v0.X, v0.Y, minX, minY);
var converter = new BarycentricCoordinatesConverter(v0.X, v0.Y, v1.X, v1.Y, v2.X, v2.Y);
var writer = screen.GetWriter(minY);
for (int y = minY; y <= maxY; y++)
{
for (int x = minX; x <= maxX; x++)
{
var curr1 = line1.Value;
var curr2 = line2.Value;
var curr3 = line3.Value;
if (curr1 >= 0 && curr2 >= 0 && curr3 >= 0)
{
var p = converter.Convert(x, y);
if (p.A < 0 || p.B < 0 || p.C < 0)
continue;
var z = v0.Z*p.A + v1.Z*p.B + v2.Z*p.C;
if (z < _zBuffer[x, y])
continue;
fragmentState.Clear();
fragmentState.Intensity = faceState.Intensity;
for (var i = 0; i < vertexState.Varying[0].Count; i++)
{
var fragmentValue = vertexState.Varying[0][i]*p.A + vertexState.Varying[1][i]*p.B +
vertexState.Varying[2][i]*p.C;
fragmentState.Varying.Add(fragmentValue);
}
var resColor = shader.Fragment(fragmentState);
if (resColor != null)
{
_zBuffer[x, y] = z;
writer.Write(x, resColor.Value);
}
}
line1.StepX();
line2.StepX();
line3.StepX();
}
line1.StepY();
line2.StepY();
line3.StepY();
writer.NextLine();
}
}
private static T Math3<T>(T a, T b, T c, Func<T, T, T> func)
{
var result = func(a, b);
return func(result, c);
}
private int ClipX(int x)
{
return Clip(x, 0, _width - 1);
}
private int ClipY(int y, int minY, int maxY)
{
return Clip(y, minY, maxY);
}
private static int Clip(int a, int minA, int maxA)
{
if (a < minA)
return minA;
if (a > maxA)
return maxA;
return a;
}
private void DrawSolidLine(int x0, int y0, int x1, int y1, WritableTexture screen, int color, int startY, int endY)
{
var vertOrientation = Math.Abs(x1 - x0) < Math.Abs(y1 - y0);
if (vertOrientation)
{
int buf;
buf = x0;
x0 = y0;
y0 = buf;
buf = x1;
x1 = y1;
y1 = buf;
}
if (x0 > x1)
{
int buf;
buf = x0;
x0 = x1;
x1 = buf;
buf = y0;
y0 = y1;
y1 = buf;
}
int errorMul = 0;
int sign = Math.Sign(y1 - y0);
int kMul = 2 * (y1 - y0);
int halfMul = x1 - x0;
int oneMul = 2 * halfMul;
int y = y0;
for (var x = x0; x <= x1; x++)
{
errorMul += kMul;
if (Math.Abs(errorMul) > halfMul)
{
y += sign;
errorMul -= sign * oneMul;
}
if (vertOrientation)
{
if (y >= 0 && y < _width && x >= startY && x <= endY)
{
screen.Write(y, x, color);
}
}
else
{
if (x >= 0 && x < _width && y >= startY && y <= endY)
{
screen.Write(x, y, color);
}
}
}
}
}
}
| |
using System;
using System.Globalization;
using Newtonsoft.Json;
namespace iSukces.UnitedValues
{
}
// -----===== autogenerated code =====-----
// ReSharper disable All
// generator: DerivedUnitGenerator, DerivedUnitGenerator, DerivedUnitGenerator, DerivedUnitGenerator, DerivedUnitGenerator, FractionValuesGenerator, UnitJsonConverterGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator
namespace iSukces.UnitedValues
{
[Serializable]
[JsonConverter(typeof(EnergyMassDensityJsonConverter))]
public partial struct EnergyMassDensity : IUnitedValue<EnergyMassDensityUnit>, IEquatable<EnergyMassDensity>, IFormattable
{
/// <summary>
/// creates instance of EnergyMassDensity
/// </summary>
/// <param name="value">value</param>
/// <param name="unit">unit</param>
public EnergyMassDensity(decimal value, EnergyMassDensityUnit unit)
{
Value = value;
Unit = unit;
}
public EnergyMassDensity(decimal value, EnergyUnit counterUnit, MassUnit denominatorUnit)
{
Value = value;
Unit = new EnergyMassDensityUnit(counterUnit, denominatorUnit);
}
public EnergyMassDensity ConvertTo(EnergyMassDensityUnit newUnit)
{
// generator : FractionValuesGenerator.Add_ConvertTo
if (Unit.Equals(newUnit))
return this;
var a = new Energy(Value, Unit.CounterUnit);
var b = new Mass(1, Unit.DenominatorUnit);
a = a.ConvertTo(newUnit.CounterUnit);
b = b.ConvertTo(newUnit.DenominatorUnit);
return new EnergyMassDensity(a.Value / b.Value, newUnit);
}
public bool Equals(EnergyMassDensity other)
{
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public bool Equals(IUnitedValue<EnergyMassDensityUnit> other)
{
if (other is null)
return false;
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public override bool Equals(object other)
{
return other is IUnitedValue<EnergyMassDensityUnit> unitedValue ? Equals(unitedValue) : false;
}
public EnergyMassDensity FromGigaJoulePerTone(decimal value)
{
return new EnergyMassDensity(value, EnergyMassDensityUnits.GigaJoulePerTone.Unit);
}
public EnergyMassDensity FromKiloJoulePerKg(decimal value)
{
return new EnergyMassDensity(value, EnergyMassDensityUnits.KiloJoulePerKg.Unit);
}
public EnergyMassDensity FromKiloWattHourPerTone(decimal value)
{
return new EnergyMassDensity(value, EnergyMassDensityUnits.KiloWattHourPerTone.Unit);
}
public EnergyMassDensity FromMegaJoulePerKg(decimal value)
{
return new EnergyMassDensity(value, EnergyMassDensityUnits.MegaJoulePerKg.Unit);
}
public EnergyMassDensity FromMegaJoulePerTone(decimal value)
{
return new EnergyMassDensity(value, EnergyMassDensityUnits.MegaJoulePerTone.Unit);
}
public decimal GetBaseUnitValue()
{
// generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue
var factor1 = GlobalUnitRegistry.Factors.Get(Unit.CounterUnit);
var factor2 = GlobalUnitRegistry.Factors.Get(Unit.DenominatorUnit);
if ((factor1.HasValue && factor2.HasValue))
return Value * factor1.Value / factor2.Value;
throw new Exception("Unable to find multiplication for unit " + Unit);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0;
}
}
public EnergyMassDensity Round(int decimalPlaces)
{
return new EnergyMassDensity(Math.Round(Value, decimalPlaces), Unit);
}
/// <summary>
/// Returns unit name
/// </summary>
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName;
}
/// <summary>
/// Returns unit name
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
public string ToString(string format, IFormatProvider provider = null)
{
return this.ToStringFormat(format, provider);
}
public EnergyMassDensity WithCounterUnit(EnergyUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithCounterUnit
var oldUnit = Unit.CounterUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithCounterUnit(newUnit);
return new EnergyMassDensity(oldFactor / newFactor * Value, resultUnit);
}
public EnergyMassDensity WithDenominatorUnit(MassUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithDenominatorUnit
var oldUnit = Unit.DenominatorUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithDenominatorUnit(newUnit);
return new EnergyMassDensity(newFactor / oldFactor * Value, resultUnit);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator !=(EnergyMassDensity left, EnergyMassDensity right)
{
return !left.Equals(right);
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="deltaKelvinTemperature">a divisor (denominator) - a value which dividend is divided by</param>
public static SpecificHeatCapacity operator /(EnergyMassDensity energyMassDensity, DeltaKelvinTemperature deltaKelvinTemperature)
{
// generator : MultiplyAlgebraGenerator.CreateCodeForLeftFractionValue
// SpecificHeatCapacity operator /(EnergyMassDensity energyMassDensity, DeltaKelvinTemperature deltaKelvinTemperature)
// scenario with hint
// .Is<EnergyMassDensity, DeltaKelvinTemperature, SpecificHeatCapacity>("/")
// hint location Add_EnergyMassDensity_DeltaKelvinTemperature_SpecificHeatCapacity, line 16
var energyMassDensityUnit = energyMassDensity.Unit;
var resultUnit = new SpecificHeatCapacityUnit(energyMassDensityUnit.CounterUnit, energyMassDensityUnit.DenominatorUnit, deltaKelvinTemperature.Unit);
var value = energyMassDensity.Value / deltaKelvinTemperature.Value;
return new SpecificHeatCapacity(value, resultUnit);
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="specificHeatCapacity">a divisor (denominator) - a value which dividend is divided by</param>
public static DeltaKelvinTemperature operator /(EnergyMassDensity energyMassDensity, SpecificHeatCapacity specificHeatCapacity)
{
// generator : MultiplyAlgebraGenerator.CreateOperator
// scenario with hint
// .Is<EnergyMassDensity, SpecificHeatCapacity, DeltaKelvinTemperature>("/")
// hint location Add_EnergyMassDensity_DeltaKelvinTemperature_SpecificHeatCapacity, line 16
var energyMassDensityUnit = energyMassDensity.Unit;
var specificHeatCapacityUnit = specificHeatCapacity.Unit;
var tmp1 = specificHeatCapacityUnit.DenominatorUnit;
var targetRightUnit = new SpecificHeatCapacityUnit(energyMassDensityUnit.CounterUnit, energyMassDensityUnit.DenominatorUnit, tmp1);
var specificHeatCapacityConverted = specificHeatCapacity.ConvertTo(targetRightUnit);
var value = energyMassDensity.Value / specificHeatCapacityConverted.Value;
return new DeltaKelvinTemperature(value, tmp1);
// scenario F1
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="deltaKelvinTemperature">a divisor (denominator) - a value which dividend is divided by</param>
public static SpecificHeatCapacity? operator /(EnergyMassDensity? energyMassDensity, DeltaKelvinTemperature deltaKelvinTemperature)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (energyMassDensity is null)
return null;
return energyMassDensity.Value / deltaKelvinTemperature;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="specificHeatCapacity">a divisor (denominator) - a value which dividend is divided by</param>
public static DeltaKelvinTemperature? operator /(EnergyMassDensity? energyMassDensity, SpecificHeatCapacity specificHeatCapacity)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (energyMassDensity is null)
return null;
return energyMassDensity.Value / specificHeatCapacity;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="deltaKelvinTemperature">a divisor (denominator) - a value which dividend is divided by</param>
public static SpecificHeatCapacity? operator /(EnergyMassDensity energyMassDensity, DeltaKelvinTemperature? deltaKelvinTemperature)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (deltaKelvinTemperature is null)
return null;
return energyMassDensity / deltaKelvinTemperature.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="specificHeatCapacity">a divisor (denominator) - a value which dividend is divided by</param>
public static DeltaKelvinTemperature? operator /(EnergyMassDensity energyMassDensity, SpecificHeatCapacity? specificHeatCapacity)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (specificHeatCapacity is null)
return null;
return energyMassDensity / specificHeatCapacity.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="deltaKelvinTemperature">a divisor (denominator) - a value which dividend is divided by</param>
public static SpecificHeatCapacity? operator /(EnergyMassDensity? energyMassDensity, DeltaKelvinTemperature? deltaKelvinTemperature)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (energyMassDensity is null || deltaKelvinTemperature is null)
return null;
return energyMassDensity.Value / deltaKelvinTemperature.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="energyMassDensity">a dividend (counter) - a value that is being divided</param>
/// <param name="specificHeatCapacity">a divisor (denominator) - a value which dividend is divided by</param>
public static DeltaKelvinTemperature? operator /(EnergyMassDensity? energyMassDensity, SpecificHeatCapacity? specificHeatCapacity)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (energyMassDensity is null || specificHeatCapacity is null)
return null;
return energyMassDensity.Value / specificHeatCapacity.Value;
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator ==(EnergyMassDensity left, EnergyMassDensity right)
{
return left.Equals(right);
}
public static EnergyMassDensity Parse(string value)
{
// generator : FractionValuesGenerator.Add_Parse
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
var r = CommonParse.Parse(value, typeof(EnergyMassDensity));
var units = Common.SplitUnitNameBySlash(r.UnitName);
if (units.Length != 2)
throw new Exception($"{r.UnitName} is not valid EnergyMassDensity unit");
var counterUnit = new EnergyUnit(units[0]);
var denominatorUnit = new MassUnit(units[1]);
return new EnergyMassDensity(r.Value, counterUnit, denominatorUnit);
}
/// <summary>
/// value
/// </summary>
public decimal Value { get; }
/// <summary>
/// unit
/// </summary>
public EnergyMassDensityUnit Unit { get; }
}
public partial class EnergyMassDensityJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(EnergyMassDensityUnit);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The JsonReader to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string))
{
if (objectType == typeof(EnergyMassDensity))
return EnergyMassDensity.Parse((string)reader.Value);
}
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null)
writer.WriteNull();
else
writer.WriteValue(value.ToString());
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <mgorse@novell.com>
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using NDesk.DBus;
using org.freedesktop.DBus;
namespace Atspi
{
public class Registry : Application
{
public static Registry Instance {
get {
return instance;
}
}
private volatile static Registry instance;
private Bus bus;
private IBus busProxy;
private IRegistry proxy;
private Dictionary<string, Application> applications;
private Desktop desktop;
private bool suspendDBusCalls;
private static object sync = new object ();
private static Thread loopThread;
internal static Queue<System.Action> pendingCalls = new Queue<System.Action> ();
private Dictionary<string, int> eventListeners;
public static void Initialize ()
{
Initialize (false);
}
public static void Initialize (bool startLoop)
{
lock (sync) {
if (instance != null)
return;
new Registry (startLoop);
}
}
public static void Terminate ()
{
instance.TerminateInternal ();
Desktop.Terminate ();
instance = null;
}
internal static Bus Bus { get { return Instance.bus; } }
internal static IBus BusProxy {
get {
return instance.busProxy;
}
}
internal Registry (bool startLoop)
: base ("org.a11y.atspi.Registry")
{
lock (sync) {
if (instance != null)
throw new Exception ("Attempt to create a second registry");
instance = this;
}
bus = GetAtspiBus ();
if (bus == null)
bus = Bus.Session;
ObjectPath op = new ObjectPath ("/org/a11y/atspi/registry");
proxy = Registry.Bus.GetObject<IRegistry> ("org.a11y.atspi.Registry", op);
eventListeners = new Dictionary<string, int> ();
RegisterEventListener ("Object:ChildrenChanged");
RegisterEventListener ("Object:StateChanged");
RegisterEventListener ("Object:PropertyChange");
applications = new Dictionary<string, Application> ();
applications [name] = this;
desktop = new Desktop (this);
applications [desktop.GetAlternateBusName ()] = this;
accessibles [SPI_PATH_ROOT] = desktop;
busProxy = Bus.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus"));
PostInit ();
desktop.PostInit ();
if (DeviceEventController.Instance == null)
new DeviceEventController ();
if (startLoop && loopThread == null) {
loopThread = new Thread (new ThreadStart (Iterate));
loopThread.IsBackground = true;
loopThread.Start ();
}
}
[DllImport("libX11.so.6")]
static extern IntPtr XOpenDisplay (string name);
[DllImport("libX11.so.6")]
static extern IntPtr XDefaultRootWindow (IntPtr display);
[DllImport("libX11.so.6")]
static extern IntPtr XInternAtom (IntPtr display, string atom_name, int only_if_eists);
[DllImport("libX11.so.6")]
static extern int XGetWindowProperty (IntPtr display, IntPtr w, IntPtr property, IntPtr long_offset, IntPtr long_length, int delete, IntPtr req_type, out IntPtr actual_type_return, out int actual_format_return, out IntPtr nitems_return, out IntPtr bytes_after_return, out string prop_return);
internal static Bus GetAtspiBus ()
{
string displayName = Environment.GetEnvironmentVariable ("AT_SPI_DISPLAY");
if (displayName == null || displayName == String.Empty)
displayName = Environment.GetEnvironmentVariable ("DISPLAY");
if (displayName == null || displayName == String.Empty)
displayName = ":0";
for (int i = displayName.Length - 1; i >= 0; i--) {
if (displayName [i] == '.') {
displayName = displayName.Substring (0, i);
break;
} else if (displayName [i] == ':')
break;
}
IntPtr display = XOpenDisplay (displayName);
if (display == IntPtr.Zero)
return null;
IntPtr atSpiBus = XInternAtom (display, "AT_SPI_BUS", 0);
IntPtr actualType, nItems, leftOver;
int actualFormat;
string data;
XGetWindowProperty (display,
XDefaultRootWindow (display),
atSpiBus, (IntPtr) 0,
(IntPtr) 2048, 0,
(IntPtr) 31, out actualType, out actualFormat,
out nItems, out leftOver, out data);
if (data == null)
return null;
return Bus.Open (data);
}
internal Application GetApplication (string name)
{
return GetApplication (name, true);
}
internal Application GetApplication (string name, bool create)
{
if (string.IsNullOrEmpty (name))
return null;
if (!applications.ContainsKey (name) && create) {
// TODO: Perhaps allow reentering GLib main
// loop to support inspecting our own window
if (BusProxy.GetConnectionUnixProcessID (name) == Process.GetCurrentProcess ().Id)
return null;
applications [name] = new Application (name);
desktop.Add (applications [name]);
applications [name].PostInit ();
}
if (applications.ContainsKey (name))
return applications [name];
return null;
}
public static Desktop Desktop {
get { return Instance.desktop; }
}
internal static Accessible GetElement (AccessiblePath ap, bool create)
{
Application application;
application = Instance.GetApplication (ap.bus_name, create);
if (application == null)
return null;
return application.GetElement (ap.path, create);
}
internal void TerminateInternal ()
{
List<string> dispose = new List<string> ();
foreach (string bus_name in applications.Keys)
dispose.Add (bus_name);
// TODO: Thread safety
foreach (string bus_name in dispose)
if (applications.ContainsKey (bus_name))
applications [bus_name].Dispose ();
applications = null;
}
internal void RemoveApplication (string name)
{
if (applications.ContainsKey (name)) {
Application application = applications [name];
Desktop.Remove (application);
applications.Remove (name);
application.Dispose ();
}
}
internal static bool SuspendDBusCalls {
get {
return instance.suspendDBusCalls;
}
set {
if (instance.suspendDBusCalls && !value) {
instance.suspendDBusCalls = value;
instance.ProcessPendingCalls ();
} else
instance.suspendDBusCalls = value;
}
}
private void ProcessPendingCalls ()
{
while (pendingCalls.Count > 0)
pendingCalls.Dequeue ()();
}
private void Iterate ()
{
// TODO: Make try optional; could affect performance
for (;;)
{
try {
bus.Iterate ();
} catch (System.Threading.ThreadAbortException) {
return;
} catch (Exception e) {
Console.WriteLine ("at-spi-sharp: Exception in Iterate: " + e);
}
}
}
internal static void RegisterEventListener (string name)
{
if (!instance.eventListeners.ContainsKey (name))
instance.eventListeners [name] = 1;
else
instance.eventListeners [name]++;
if (instance.eventListeners [name] == 1)
instance.proxy.RegisterEvent (name);
}
internal static void DeregisterEventListener (string name)
{
if (!instance.eventListeners.ContainsKey (name) ||
instance.eventListeners [name] == 0)
return;
instance.eventListeners [name]--;
if (instance.eventListeners [name] == 0)
instance.proxy.DeregisterEvent (name);
}
}
[Interface ("org.a11y.atspi.Registry")]
interface IRegistry
{
void RegisterEvent (string name);
void DeregisterEvent (string name);
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A shapefile class that handles the special case where the data type is point
/// </summary>
public class PointShapefile : Shapefile
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PointShapefile"/> class for in-ram handling only.
/// </summary>
public PointShapefile()
: base(FeatureType.Point, ShapeType.Point)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PointShapefile"/> class that is loaded from the supplied fileName.
/// </summary>
/// <param name="fileName">The string fileName of the polygon shapefile to load</param>
public PointShapefile(string fileName)
: this()
{
Open(fileName, null);
}
#endregion
#region Methods
/// <inheritdoc />
public override IFeature GetFeature(int index)
{
IFeature f;
if (!IndexMode)
{
f = Features[index];
}
else
{
f = GetPoint(index);
f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0];
}
return f;
}
/// <summary>
/// Opens a shapefile.
/// </summary>
/// <param name="fileName">The string fileName of the point shapefile to load</param>
/// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
public void Open(string fileName, IProgressHandler progressHandler)
{
if (!File.Exists(fileName)) return;
Filename = fileName;
IndexMode = true;
Header = new ShapefileHeader(Filename);
switch (Header.ShapeType)
{
case ShapeType.PointM:
CoordinateType = CoordinateType.M;
break;
case ShapeType.PointZ:
CoordinateType = CoordinateType.Z;
break;
default:
CoordinateType = CoordinateType.Regular;
break;
}
Extent = Header.ToExtent();
Name = Path.GetFileNameWithoutExtension(fileName);
Attributes.Open(Filename);
FillPoints(Filename, progressHandler);
ReadProjection();
}
/// <inheritdoc />
protected override StreamLengthPair PopulateShpAndShxStreams(Stream shpStream, Stream shxStream, bool indexed)
{
if (indexed) return PopulateShpAndShxStreamsIndexed(shpStream, shxStream);
return PopulateShpAndShxStreamsNotIndexed(shpStream, shxStream);
}
/// <inheritdoc />
protected override void SetHeaderShapeType()
{
if (CoordinateType == CoordinateType.Regular) Header.ShapeType = ShapeType.Point;
else if (CoordinateType == CoordinateType.M) Header.ShapeType = ShapeType.PointM;
else if (CoordinateType == CoordinateType.Z) Header.ShapeType = ShapeType.PointZ;
}
/// <summary>
/// Calculates the ContentLength that is needed to save a shape with the given number of parts and points.
/// </summary>
/// <param name="shapeType">The shape type.</param>
/// <returns>ContentLength that is needed to save a shape with the given number of parts and points.</returns>
private static int GetContentLength(ShapeType shapeType)
{
int contentLength = 2; // Shape Type
switch (shapeType)
{
case ShapeType.Point:
contentLength += 8; // x, y
break;
case ShapeType.PointM:
contentLength += 12; // x, y, m
break;
case ShapeType.PointZ:
contentLength += 16; // x, y, m, z
break;
}
return contentLength;
}
// X Y Points: Total Length = 28 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 1 Integer 1 Little
// Byte 12 X Double 1 Little
// Byte 20 Y Double 1 Little
// X Y M Points: Total Length = 36 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 21 Integer 1 Little
// Byte 12 X Double 1 Little
// Byte 20 Y Double 1 Little
// Byte 28 M Double 1 Little
// X Y Z M Points: Total Length = 44 Bytes
// ---------------------------------------------------------
// Position Value Type Number Byte Order
// ---------------------------------------------------------
// Byte 0 Record Number Integer 1 Big
// Byte 4 Content Length Integer 1 Big
// Byte 8 Shape Type 11 Integer 1 Little
// Byte 12 X Double 1 Little
// Byte 20 Y Double 1 Little
// Byte 28 Z Double 1 Little
// Byte 36 M Double 1 Little
/// <summary>
/// Obtains a typed list of ShapefilePoint structures with double values associated with the various coordinates.
/// </summary>
/// <param name="fileName">A string fileName</param>
/// <param name="progressHandler">Progress handler</param>
private void FillPoints(string fileName, IProgressHandler progressHandler)
{
if (!CanBeRead(fileName, this, ShapeType.Point, ShapeType.PointM, ShapeType.PointZ)) return;
// Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
List<ShapeHeader> shapeHeaders = ReadIndexFile(fileName);
var numShapes = shapeHeaders.Count;
var shapeIndices = new List<ShapeRange>(numShapes);
int totalPointsCount = 0;
var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName))
{
StepPercent = 5
};
using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
for (var shp = 0; shp < numShapes; shp++)
{
progressMeter.CurrentPercent = (int)(shp * 50.0 / numShapes);
reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
var shape = new ShapeRange(FeatureType.Point, CoordinateType)
{
RecordNumber = reader.ReadInt32(Endian.BigEndian),
ContentLength = reader.ReadInt32(Endian.BigEndian),
StartIndex = totalPointsCount,
ShapeType = (ShapeType)reader.ReadInt32()
};
Debug.Assert(shape.RecordNumber == shp + 1, "The record number should equal " + shp + 1);
Debug.Assert(shape.ContentLength == shapeHeaders[shp].ContentLength, "The shapes content length should equals the shapeHeaders content length.");
if (shape.ShapeType == ShapeType.NullShape)
{
shape.NumPoints = 0;
shape.NumParts = 0;
}
else
{
totalPointsCount += 1;
shape.NumPoints = 1;
shape.NumParts = 1;
}
shapeIndices.Add(shape);
}
double[] m = null;
double[] z = null;
var vert = new double[2 * totalPointsCount]; // X,Y
if (Header.ShapeType == ShapeType.PointM || Header.ShapeType == ShapeType.PointZ)
{
m = new double[totalPointsCount];
}
if (Header.ShapeType == ShapeType.PointZ)
{
z = new double[totalPointsCount];
}
int i = 0;
for (var shp = 0; shp < numShapes; shp++)
{
progressMeter.CurrentPercent = (int)(50 + (shp * 50.0 / numShapes));
var shape = shapeIndices[shp];
if (shape.ShapeType == ShapeType.NullShape) continue;
reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
reader.Seek(3 * 4, SeekOrigin.Current); // Skip first bytes (Record Number, Content Length, Shapetype)
// Read X
var ind = 4;
vert[i * 2] = reader.ReadDouble();
ind += 8;
// Read Y
vert[(i * 2) + 1] = reader.ReadDouble();
ind += 8;
// Read Z
if (z != null)
{
z[i] = reader.ReadDouble();
ind += 8;
}
// Read M
if (m != null)
{
if (shapeHeaders[shp].ByteLength <= ind)
{
m[i] = double.MinValue;
}
else
{
m[i] = reader.ReadDouble();
}
}
var part = new PartRange(vert, shape.StartIndex, 0, FeatureType.Point)
{
NumVertices = 1
};
shape.Parts.Add(part);
shape.Extent = new Extent(new[] { vert[i * 2], vert[(i * 2) + 1], vert[i * 2], vert[(i * 2) + 1] });
i++;
}
Vertex = vert;
M = m;
Z = z;
ShapeIndices = shapeIndices;
}
progressMeter.Reset();
}
/// <summary>
/// Populates the given streams for the shp and shx file when in IndexMode.
/// </summary>
/// <param name="shpStream">Stream that is used to write the shp file.</param>
/// <param name="shxStream">Stream that is used to write the shx file.</param>
/// <returns>The lengths of the streams in bytes.</returns>
private StreamLengthPair PopulateShpAndShxStreamsIndexed(Stream shpStream, Stream shxStream)
{
int fid = 0;
int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words
foreach (ShapeRange shape in ShapeIndices)
{
int contentLength = shape.ShapeType == ShapeType.NullShape ? 2 : GetContentLength(Header.ShapeType);
shxStream.WriteBe(offset);
shxStream.WriteBe(contentLength);
shpStream.WriteBe(fid + 1);
shpStream.WriteBe(contentLength);
if (shape.ShapeType == ShapeType.NullShape)
{
shpStream.WriteLe((int)ShapeType.NullShape); // Byte 8 Shape Type 3 Integer 1 Little
}
else
{
shpStream.WriteLe((int)Header.ShapeType);
shpStream.WriteLe(Vertex[shape.StartIndex * 2]);
shpStream.WriteLe(Vertex[(shape.StartIndex * 2) + 1]);
if (Z != null) shpStream.WriteLe(Z[shape.StartIndex]);
if (M != null) shpStream.WriteLe(M[shape.StartIndex]);
}
fid++;
offset += 4; // header bytes
offset += contentLength; // adding the content length from each loop calculates the word offset
}
return new StreamLengthPair
{
ShpLength = offset,
ShxLength = 50 + (fid * 4)
};
}
/// <summary>
/// Populates the given streams for the shp and shx file when not in IndexMode.
/// </summary>
/// <param name="shpStream">Stream that is used to write the shp file.</param>
/// <param name="shxStream">Stream that is used to write the shx file.</param>
/// <returns>The lengths of the streams in bytes.</returns>
private StreamLengthPair PopulateShpAndShxStreamsNotIndexed(Stream shpStream, Stream shxStream)
{
var progressMeter = new ProgressMeter(ProgressHandler, "Saving (Not Indexed)...", Features.Count);
int fid = 0;
int offset = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words
foreach (IFeature f in Features)
{
bool isNullShape = false;
int contentLength;
if (f.Geometry.IsEmpty)
{
contentLength = 2;
isNullShape = true;
}
else
{
contentLength = GetContentLength(Header.ShapeType);
}
shxStream.WriteBe(offset);
shxStream.WriteBe(contentLength);
shpStream.WriteBe(fid + 1);
shpStream.WriteBe(contentLength);
if (isNullShape)
{
shpStream.WriteLe((int)ShapeType.NullShape); // Byte 8 Shape Type 0 Integer 1 Little
}
else
{
shpStream.WriteLe((int)Header.ShapeType); // Byte 8 Shape Type Integer 1 Little
Coordinate c = f.Geometry.Coordinates[0];
shpStream.WriteLe(c.X);
shpStream.WriteLe(c.Y);
if (Header.ShapeType == ShapeType.PointZ)
{
shpStream.WriteLe(c.Z);
}
if (Header.ShapeType == ShapeType.PointM || Header.ShapeType == ShapeType.PointZ)
{
shpStream.WriteLe(c.M);
}
}
progressMeter.CurrentValue = fid;
fid++;
offset += 4; // header bytes
offset += contentLength; // adding the content length from each loop calculates the word offset
}
progressMeter.Reset();
return new StreamLengthPair
{
ShpLength = offset,
ShxLength = 50 + (fid * 4)
};
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Snake.Api.Areas.HelpPage.ModelDescriptions;
using Snake.Api.Areas.HelpPage.Models;
namespace Snake.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media;
using Avalonia.Media.Fonts;
using Avalonia.Media.TextFormatting;
using Avalonia.Platform;
using Avalonia.Utilities;
namespace Avalonia.Headless
{
class HeadlessClipboardStub : IClipboard
{
private string _text;
private IDataObject _data;
public Task<string> GetTextAsync()
{
return Task.Run(() => _text);
}
public Task SetTextAsync(string text)
{
return Task.Run(() => _text = text);
}
public Task ClearAsync()
{
return Task.Run(() => _text = null);
}
public Task SetDataObjectAsync(IDataObject data)
{
return Task.Run(() => _data = data);
}
public Task<string[]> GetFormatsAsync()
{
throw new NotImplementedException();
}
public async Task<object> GetDataAsync(string format)
{
return await Task.Run(() => _data);
}
}
class HeadlessCursorFactoryStub : ICursorFactory
{
public ICursorImpl GetCursor(StandardCursorType cursorType) => new CursorStub();
public ICursorImpl CreateCursor(IBitmapImpl cursor, PixelPoint hotSpot) => new CursorStub();
private class CursorStub : ICursorImpl
{
public void Dispose() { }
}
}
class HeadlessPlatformSettingsStub : IPlatformSettings
{
public Size DoubleClickSize { get; } = new Size(2, 2);
public TimeSpan DoubleClickTime { get; } = TimeSpan.FromMilliseconds(500);
}
class HeadlessSystemDialogsStub : ISystemDialogImpl
{
public Task<string[]> ShowFileDialogAsync(FileDialog dialog, Window parent)
{
return Task.Run(() => (string[])null);
}
public Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent)
{
return Task.Run(() => (string)null);
}
}
class HeadlessGlyphTypefaceImpl : IGlyphTypefaceImpl
{
public short DesignEmHeight => 10;
public int Ascent => 5;
public int Descent => 5;
public int LineGap => 2;
public int UnderlinePosition => 5;
public int UnderlineThickness => 5;
public int StrikethroughPosition => 5;
public int StrikethroughThickness => 2;
public bool IsFixedPitch => true;
public void Dispose()
{
}
public ushort GetGlyph(uint codepoint)
{
return 1;
}
public int GetGlyphAdvance(ushort glyph)
{
return 1;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
return glyphs.ToArray().Select(x => (int)x).ToArray();
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return codepoints.ToArray().Select(x => (ushort)x).ToArray();
}
}
class HeadlessTextShaperStub : ITextShaperImpl
{
public GlyphRun ShapeText(ReadOnlySlice<char> text, Typeface typeface, double fontRenderingEmSize, CultureInfo culture)
{
return new GlyphRun(new GlyphTypeface(typeface), 10,
new ReadOnlySlice<ushort>(new ushort[] { 1, 2, 3 }),
new ReadOnlySlice<double>(new double[] { 1, 2, 3 }),
new ReadOnlySlice<Vector>(new Vector[] { new Vector(1, 1), new Vector(2, 2), new Vector(3, 3) }),
text,
new ReadOnlySlice<ushort>(new ushort[] { 1, 2, 3 }));
}
}
class HeadlessFontManagerStub : IFontManagerImpl
{
public IGlyphTypefaceImpl CreateGlyphTypeface(Typeface typeface)
{
return new HeadlessGlyphTypefaceImpl();
}
public string GetDefaultFontFamilyName()
{
return "Arial";
}
public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false)
{
return new List<string> { "Arial" };
}
public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight, FontFamily fontFamily, CultureInfo culture, out Typeface typeface)
{
typeface = new Typeface("Arial", fontStyle, fontWeight);
return true;
}
}
class HeadlessIconLoaderStub : IPlatformIconLoader
{
class IconStub : IWindowIconImpl
{
public void Save(Stream outputStream)
{
}
}
public IWindowIconImpl LoadIcon(string fileName)
{
return new IconStub();
}
public IWindowIconImpl LoadIcon(Stream stream)
{
return new IconStub();
}
public IWindowIconImpl LoadIcon(IBitmapImpl bitmap)
{
return new IconStub();
}
}
class HeadlessScreensStub : IScreenImpl
{
public int ScreenCount { get; } = 1;
public IReadOnlyList<Screen> AllScreens { get; } = new[]
{
new Screen(1, new PixelRect(0, 0, 1920, 1280),
new PixelRect(0, 0, 1920, 1280), true),
};
}
}
| |
using System;
using System.Reactive.Disposables;
using Avalonia.Platform;
namespace Avalonia.Threading
{
/// <summary>
/// A timer that uses a <see cref="Dispatcher"/> to fire at a specified interval.
/// </summary>
public class DispatcherTimer
{
private IDisposable? _timer;
private readonly DispatcherPriority _priority;
private TimeSpan _interval;
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
public DispatcherTimer() : this(DispatcherPriority.Background)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
/// <param name="priority">The priority to use.</param>
public DispatcherTimer(DispatcherPriority priority)
{
_priority = priority;
}
/// <summary>
/// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
/// <param name="interval">The interval at which to tick.</param>
/// <param name="priority">The priority to use.</param>
/// <param name="callback">The event to call when the timer ticks.</param>
public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler callback) : this(priority)
{
_priority = priority;
Interval = interval;
Tick += callback;
}
/// <summary>
/// Finalizes an instance of the <see cref="DispatcherTimer"/> class.
/// </summary>
~DispatcherTimer()
{
if (_timer != null)
{
Stop();
}
}
/// <summary>
/// Raised when the timer ticks.
/// </summary>
public event EventHandler? Tick;
/// <summary>
/// Gets or sets the interval at which the timer ticks.
/// </summary>
public TimeSpan Interval
{
get
{
return _interval;
}
set
{
bool enabled = IsEnabled;
Stop();
_interval = value;
IsEnabled = enabled;
}
}
/// <summary>
/// Gets or sets a value indicating whether the timer is running.
/// </summary>
public bool IsEnabled
{
get
{
return _timer != null;
}
set
{
if (IsEnabled != value)
{
if (value)
{
Start();
}
else
{
Stop();
}
}
}
}
/// <summary>
/// Gets or sets user-defined data associated with the timer.
/// </summary>
public object? Tag
{
get;
set;
}
/// <summary>
/// Starts a new timer.
/// </summary>
/// <param name="action">
/// The method to call on timer tick. If the method returns false, the timer will stop.
/// </param>
/// <param name="interval">The interval at which to tick.</param>
/// <param name="priority">The priority to use.</param>
/// <returns>An <see cref="IDisposable"/> used to cancel the timer.</returns>
public static IDisposable Run(Func<bool> action, TimeSpan interval, DispatcherPriority priority = DispatcherPriority.Normal)
{
var timer = new DispatcherTimer(priority) { Interval = interval };
timer.Tick += (s, e) =>
{
if (!action())
{
timer.Stop();
}
};
timer.Start();
return Disposable.Create(() => timer.Stop());
}
/// <summary>
/// Runs a method once, after the specified interval.
/// </summary>
/// <param name="action">
/// The method to call after the interval has elapsed.
/// </param>
/// <param name="interval">The interval after which to call the method.</param>
/// <param name="priority">The priority to use.</param>
/// <returns>An <see cref="IDisposable"/> used to cancel the timer.</returns>
public static IDisposable RunOnce(
Action action,
TimeSpan interval,
DispatcherPriority priority = DispatcherPriority.Normal)
{
interval = (interval != TimeSpan.Zero) ? interval : TimeSpan.FromTicks(1);
var timer = new DispatcherTimer(priority) { Interval = interval };
timer.Tick += (s, e) =>
{
action();
timer.Stop();
};
timer.Start();
return Disposable.Create(() => timer.Stop());
}
/// <summary>
/// Starts the timer.
/// </summary>
public void Start()
{
if (!IsEnabled)
{
var threading = AvaloniaLocator.Current.GetService<IPlatformThreadingInterface>();
if (threading == null)
{
throw new Exception("Could not start timer: IPlatformThreadingInterface is not registered.");
}
_timer = threading.StartTimer(_priority, Interval, InternalTick);
}
}
/// <summary>
/// Stops the timer.
/// </summary>
public void Stop()
{
if (IsEnabled)
{
_timer!.Dispose();
_timer = null;
}
}
/// <summary>
/// Raises the <see cref="Tick"/> event on the dispatcher thread.
/// </summary>
private void InternalTick()
{
Dispatcher.UIThread.EnsurePriority(_priority);
Tick?.Invoke(this, EventArgs.Empty);
}
}
}
| |
/*
* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified for use with the Chartboost Unity plugin
*/
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace ChartboostSDK {
[CustomEditor(typeof(CBSettings))]
public class CBSettingEditor : Editor {
GUIContent iOSAppIdLabel = new GUIContent("App Id [?]:", "Chartboost App Ids can be found at https://dashboard.chartboost.com/app");
GUIContent iOSAppSecretLabel = new GUIContent("App Signature [?]:", "Chartboost App Signature can be found at https://dashboard.chartboost.com/app");
GUIContent androidAppIdLabel = new GUIContent("App Id [?]:", "Chartboost App Ids can be found at https://dashboard.chartboost.com/app");
GUIContent androidAppSecretLabel = new GUIContent("App Signature [?]:", "Chartboost App Signature can be found at https://dashboard.chartboost.com/app");
GUIContent amazonAppIdLabel = new GUIContent("App Id [?]:", "Chartboost App Ids can be found at https://dashboard.chartboost.com/app");
GUIContent amazonAppSecretLabel = new GUIContent("App Signature [?]:", "Chartboost App Signature can be found at https://dashboard.chartboost.com/app");
GUIContent selectorLabel = new GUIContent("Android Platform [?]:", "Select if building for Google Play or Amazon Store");
GUIContent iOSLabel = new GUIContent("iOS");
GUIContent androidLabel = new GUIContent("Google Play");
GUIContent amazonLabel = new GUIContent("Amazon");
GUIContent enableLoggingLabel = new GUIContent("Enable Logging for Debug Builds");
GUIContent enableLoggingToggle = new GUIContent("isLoggingEnabled");
// minimum version of the Google Play Services library project
private long MinGmsCoreVersionCode = 4030530;
private string googlePlayServicesVersion = "9.0.0";
private string sError = "Error";
private string sOk = "OK";
private string sCancel = "Cancel";
private string sSuccess = "Success";
private string sWarning = "Warning";
private string sSdkNotFound = "Android SDK Not found";
private string sSdkNotFoundBlurb = "The Android SDK path was not found. " +
"Please configure it in the Unity preferences window (under External Tools).";
private string sLibProjNotFound = "Google Play Services Library Project Not Found";
private string sLibProjNotFoundBlurb = "Google Play Services library project " +
"could not be found your SDK installation. Make sure it is installed (open " +
"the SDK manager and go to Extras, and select Google Play Services).";
private string sLibProjVerNotFound = "The version of your copy of the Google Play " +
"Services Library Project could not be determined. Please make sure it is " +
"at least version {0}. Continue?";
private string sLibProjVerTooOld = "Your copy of the Google Play " +
"Services Library Project is out of date. Please launch the Android SDK manager " +
"and upgrade your Google Play Services bundle to the latest version (your version: " +
"{0}; required version: {1}). Proceeding may cause problems. Proceed anyway?";
private string sSetupComplete = "Chartboost configured successfully.";
private CBSettings instance;
public override void OnInspectorGUI() {
instance = (CBSettings)target;
SetupUI();
}
private void SetupUI() {
EditorGUILayout.HelpBox("Add the Chartboost App Id and App Secret associated with this game", MessageType.None);
// iOS
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(iOSLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(iOSAppIdLabel);
EditorGUILayout.LabelField(iOSAppSecretLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
instance.SetIOSAppId(EditorGUILayout.TextField(instance.iOSAppId));
instance.SetIOSAppSecret(EditorGUILayout.TextField(instance.iOSAppSecret));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Android
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(androidLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(androidAppIdLabel);
EditorGUILayout.LabelField(androidAppSecretLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
instance.SetAndroidAppId(EditorGUILayout.TextField(instance.androidAppId));
instance.SetAndroidAppSecret(EditorGUILayout.TextField(instance.androidAppSecret));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Amazon
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(amazonLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(amazonAppIdLabel);
EditorGUILayout.LabelField(amazonAppSecretLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
instance.SetAmazonAppId(EditorGUILayout.TextField(instance.amazonAppId));
instance.SetAmazonAppSecret(EditorGUILayout.TextField(instance.amazonAppSecret));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Android Selector
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(selectorLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
instance.SetAndroidPlatformIndex(EditorGUILayout.Popup("Android Platform", instance.SelectedAndroidPlatformIndex, instance.AndroidPlatformLabels));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Loggin toggle.
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(enableLoggingLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
CBSettings.enableLogging(EditorGUILayout.Toggle(enableLoggingToggle, instance.isLoggingEnabled));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Setup Android SDK"))
{
DoSetup();
}
EditorGUILayout.EndHorizontal();
}
private void DoSetup() {
string sdkPath = GetAndroidSdkPath();
string libProjPath = sdkPath +
FixSlashes("/extras/google/google_play_services/libproject/google-play-services_lib");
string libProjPathv30 = sdkPath +
FixSlashes("/extras/google/m2repository/com/google/android/gms/play-services-basement/"
+ googlePlayServicesVersion
+ "/play-services-basement-" + googlePlayServicesVersion + ".aar");
string libProjAM = libProjPath + FixSlashes("/AndroidManifest.xml");
string libProjDestDir = FixSlashes("Assets/Plugins/Android/google-play-services_lib");
string libProjDestDirv30 = FixSlashes ("Assets/Plugins/Android"
+ "/play-services-basement-" + googlePlayServicesVersion + ".aar");;
// check that Android SDK is there
if (!HasAndroidSdk()) {
Debug.LogError("Android SDK not found.");
EditorUtility.DisplayDialog(sSdkNotFound,
sSdkNotFoundBlurb, sOk);
return;
}
// create needed directories
EnsureDirExists("Assets/Plugins");
EnsureDirExists("Assets/Plugins/Android");
// Delete old libraries, to avoid duplicate symbols
DeleteDirIfExists(libProjDestDir);
DeleteFileIfExists(libProjDestDirv30);
// check that the Google Play Services lib project is there
if (System.IO.Directory.Exists (libProjPath) || System.IO.File.Exists (libProjAM)) {
// Old Google Play Services directory structure
// Copy the full jar into the project
// Check lib project version
if (!CheckAndWarnAboutGmsCoreVersion(libProjAM)) {
return;
}
// Clear out the destination library project
DeleteDirIfExists(libProjDestDir);
// Copy Google Play Services library
FileUtil.CopyFileOrDirectory(libProjPath, libProjDestDir);
} else {
if (System.IO.File.Exists (libProjPathv30)) {
// New Google Play Services directory structure
// Copy the .aar file that contains the needed classes
FileInfo libProjFile = new FileInfo(libProjPathv30);
libProjFile.CopyTo(libProjDestDirv30,true);
} else {
Debug.LogError ("Google Play Services lib project not found at: " + libProjPath);
EditorUtility.DisplayDialog (sLibProjNotFound,
sLibProjNotFoundBlurb, sOk);
return;
}
}
// refresh assets, and we're done
AssetDatabase.Refresh();
EditorUtility.DisplayDialog(sSuccess,
sSetupComplete, sOk);
}
private bool CheckAndWarnAboutGmsCoreVersion(string libProjAMFile) {
string manifestContents = ReadFile(libProjAMFile);
string[] fields = manifestContents.Split('\"');
int i;
long vercode = 0;
for (i = 0; i < fields.Length; i++) {
if (fields[i].Contains("android:versionCode") && i + 1 < fields.Length) {
vercode = System.Convert.ToInt64(fields[i + 1]);
}
}
if (vercode == 0) {
return EditorUtility.DisplayDialog(sWarning, string.Format(
sLibProjVerNotFound,
MinGmsCoreVersionCode),
sOk, sCancel);
} else if (vercode < MinGmsCoreVersionCode) {
return EditorUtility.DisplayDialog(sWarning, string.Format(
sLibProjVerTooOld, vercode,
MinGmsCoreVersionCode),
sOk, sCancel);
}
return true;
}
private void EnsureDirExists(string dir) {
dir = dir.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
if (!System.IO.Directory.Exists(dir)) {
System.IO.Directory.CreateDirectory(dir);
}
}
private void DeleteDirIfExists(string dir) {
if (System.IO.Directory.Exists(dir)) {
System.IO.Directory.Delete(dir, true);
}
}
private void DeleteFileIfExists(string file) {
if (System.IO.File.Exists (file)) {
System.IO.File.Delete (file);
}
}
private string FixSlashes(string path) {
return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
}
private string ReadFile(string filePath) {
filePath = FixSlashes(filePath);
if (!File.Exists(filePath)) {
EditorUtility.DisplayDialog(sError, "Plugin error: file not found: " + filePath, sOk);
return null;
}
StreamReader sr = new StreamReader(filePath);
string body = sr.ReadToEnd();
sr.Close();
return body;
}
private string GetAndroidSdkPath() {
string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\"))) {
sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
}
return sdkPath;
}
private bool HasAndroidSdk() {
string sdkPath = GetAndroidSdkPath();
return sdkPath != null && sdkPath.Trim() != "" && System.IO.Directory.Exists(sdkPath);
}
}
}
| |
using FeralLib.uTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
namespace FeralNerd.uTest.Tests
{
[TestClass]
// [Ignore] // Un-comment this attribute if you want to run these tests.
public class AutomatedTest_LoggerTests : AutomatedTest
{
[TestMethod]
[Description("Demo of how to use the Logger object.")]
[TestCategory("LocalOnly")]
public void ShouldFail_LoggerDemo()
{
Logger.WriteLine("This test demonstrates how to use the Logger object.");
Logger.WriteLine();
int x = 0;
try
{
for (x = 1; x < 10; x++)
{
// Test some random thing.
foo(x);
Logger.LogResult(Result.Pass, "Iteraiton {0}. Everything's good so far.", x);
}
Logger.LogResult(Result.Pass, "Testing completed without an error.");
}
catch (Exception ex)
{
Logger.LogException(ex, "Caught an exception on try number {0}", x);
}
}
[TestMethod]
[Description("Test that doesn't use Logger")]
public void ValidateNotUsingLogger()
{
Console.WriteLine("This test demonstrates what happens if you don't use the Logger object.");
Console.WriteLine();
Console.WriteLine("It should just pass.");
Console.WriteLine("You SHOULD NOT see any banners from the Logger object.");
}
[TestMethod]
[Description("Test that doesn't log a result")]
[TestCategory("LocalOnly")]
public void ShouldSkip_ValidateNoResultLogged()
{
Logger.WriteLine("This test demonstrates what happens if you initialize the Logger object, but don't log a result.");
Logger.WriteLine("Expected final outcome: Skipped.");
Logger.WriteLine();
}
[TestMethod]
[Description("Test that logs a information.")]
[TestCategory("LocalOnly")]
public void ShouldSkip_ValidateInformation()
{
Logger.WriteLine("This test demonstrates what happens when you log an information result.");
Logger.WriteLine("Expected final outcome: Skipped.");
Logger.WriteLine();
Logger.LogResult(Result.Information, "This demonstrates an informational result.");
}
[TestMethod]
[Description("Test that logs a pass.")]
public void ValidatePass()
{
Logger.WriteLine("This test demonstrates what happens when you log a passing result.");
Logger.WriteLine("This test should have an outcome of a pass.");
Logger.WriteLine();
Logger.LogResult(Result.Pass, "This demonstrates a passing result.");
}
[TestMethod]
[Description("Test that logs a warning.")]
public void ValidateWarning()
{
Logger.WriteLine("This test demonstrates what happens when you log a warning result.");
Logger.WriteLine("This test should have an outcome of a pass.");
Logger.WriteLine();
Logger.LogResult(Result.Warning, "This demonstrates a warning result.");
}
[TestMethod]
[Description("Test that logs a fail.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateFail()
{
Logger.WriteLine("This test demonstrates what happens when you log a failing result.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Logger.LogResult(Result.Fail, "This demonstrates a failing result.");
}
[TestMethod]
[Description("Test that logs a skipped.")]
[TestCategory("LocalOnly")]
public void ShouldSkip_ValidateSkipped()
{
Logger.WriteLine("This test demonstrates what happens when you log a skipped result. You can");
Logger.WriteLine("get a skipped result by logging infomational or ignore results, but those");
Logger.WriteLine("can be overridden if you log a pass/warning/fail. Logging a skipped will force");
Logger.WriteLine("the final result to be skipped.");
Logger.WriteLine("Expected final outcome: Skipped.");
Logger.WriteLine();
Logger.LogResult(Result.Skipped, "This demonstrates a skipped result.");
}
[TestMethod]
[Description("Test the priority of a pass.")]
public void ValidatePriorityPass()
{
Logger.WriteLine("This test demonstrates that a passing result overrides an ignore / infomration result.");
Logger.WriteLine("This test should have an outcome of pass.");
Logger.WriteLine();
Logger.LogResult(Result.Pass, "This demonstrates a passing result.");
Logger.LogResult(Result.Information, "This demonstrates an info result.");
Logger.LogResult(Result.Ignore, "This demonstrates an ignore result.");
}
[TestMethod]
[Description("Test the priority of a warning.")]
public void ValidatePriorityWarning()
{
Logger.WriteLine("This test demonstrates that a warning result overrides a passing result.");
Logger.WriteLine("This test should have an outcome of pass.");
Logger.WriteLine();
Logger.LogResult(Result.Warning, "This demonstrates a passing result.");
Logger.LogResult(Result.Pass, "This demonstrates a passing result.");
Logger.LogResult(Result.Information, "This demonstrates an info result.");
Logger.LogResult(Result.Ignore, "This demonstrates an ignore result.");
}
[TestMethod]
[Description("Test the priority of a fail.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidatePriorityFail()
{
Logger.WriteLine("This test demonstrates that a fail result overrides a passing/warning result.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Logger.LogResult(Result.Fail, "This demonstrates a failing result.");
Logger.LogResult(Result.Warning, "This demonstrates a passing result.");
Logger.LogResult(Result.Pass, "This demonstrates a passing result.");
Logger.LogResult(Result.Information, "This demonstrates an info result.");
Logger.LogResult(Result.Ignore, "This demonstrates an ignore result.");
}
[TestMethod]
[Description("Test the priority of a skip.")]
[TestCategory("LocalOnly")]
public void ShouldSkip_ValidatePrioritySkip()
{
Logger.WriteLine("This test demonstrates that a skip result overrides all other results.");
Logger.WriteLine("Expected final outcome: Skipped.");
Logger.WriteLine();
Logger.LogResult(Result.Skipped, "This demonstrates a failing result.");
Logger.LogResult(Result.Fail, "This demonstrates a failing result.");
Logger.LogResult(Result.Warning, "This demonstrates a passing result.");
Logger.LogResult(Result.Pass, "This demonstrates a passing result.");
Logger.LogResult(Result.Information, "This demonstrates an info result.");
Logger.LogResult(Result.Ignore, "This demonstrates an ignore result.");
}
[TestMethod]
[Description("Test Abort")]
[TestCategory("LocalOnly")]
public void ShouldFail_AbortBailsOutOfATest()
{
Logger.WriteLine("This test demonstrates that calling Abort will immediately fail a test and bail out.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
Logger.Abort("Oh, the HUMANITY!!!");
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE!!!");
}
[TestMethod]
[Description("Test Abort with exception")]
[TestCategory("LocalOnly")]
public void ShouldFail_AbortWithException()
{
Logger.WriteLine("This test demonstrates that calling Abort will immediately fail a test and bail out.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
try
{
for (int x = 0; x < 10; x++)
{
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
if (x >= 2)
throw new Exception("Oh, my gosh! Why??? This is how it ends!!");
}
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE!!!");
}
catch (Exception ex)
{
Logger.Abort(ex, "The best-laid plans of mice and men so often go astray.");
}
}
[TestMethod]
[Description("Test Assert with a passing result.")]
public void ValidateAssertPassing()
{
Logger.WriteLine("This test validates calling assert with a passing result.");
Logger.WriteLine();
Logger.AssertIsTrue(1 + 1 == 2, "Make sure 1 + 1 is 2.");
Logger.AssertIsTrue(true, "Make sure true is the source of truth.");
}
[TestMethod]
[Description("Test Assert with a failing result.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateAssertFailing()
{
Logger.WriteLine("This test validates calling assert with a failing result.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Logger.AssertIsTrue(1 == 0, "Check that a false result fails.");
}
[TestMethod]
[Description("Test AssertIsEqual with a passing result.")]
public void ValidateAssertIsEqualPassing()
{
Logger.WriteLine("This test validates calling AssertIsEqual with a passing result.");
Logger.WriteLine();
Logger.AssertIsEqual(1, 101 - 100, "Make sure we get a 1.");
}
[TestMethod]
[Description("Test AssertIsEqual with a failing result.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateAssertIsEqualFailing()
{
Logger.WriteLine("This test validates calling AssertIsEqual with a failing result.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Logger.AssertIsEqual(1, 100 - 100, "Check that the value is 1.");
}
[TestMethod]
[Description("Test AssertIsOneOf with a passing result.")]
public void ValidateAssertIsOneOfPassing()
{
Logger.WriteLine("This test validates calling AssertIsOneOf with a passing result.");
Logger.WriteLine();
int[] testValues = new int[] { 1, 2, 3, 5, 8, 13, 21 };
Logger.AssertIsOneOf(testValues, 8, "Make sure we got a Fibonacci value.");
}
[TestMethod]
[Description("Test AssertIsOneOf with a failing result.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateAssertIsOneOfFailing()
{
Logger.WriteLine("This test validates calling AssertIsOneOf with a failing result.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
int[] testValues = new int[] { 1, 2, 3, 5, 8, 13, 21 };
Logger.AssertIsOneOf(testValues, 9, "Make sure we got a Fibonacci value.");
}
[TestMethod]
[Description("Test CompareLists")]
public void ValidateCompareLists()
{
Logger.WriteLine("This test validates comparing two lists. Red, green, and blue should show up as matching.");
Logger.WriteLine("Black and white should show up as missing, and get logged as a warning. Apple, banana, and peach");
Logger.WriteLine("should show up as extras, and get logged as Info.");
string[] expectedValues = new string[] { "white", "red", "green", "blue", "black" };
string[] actualValues = new string[] { "Red", "GREEN", "BlUe", "apple", "banana", "peach" };
Logger.CompareLists(expectedValues, actualValues, Result.Warning, Result.Information, true);
}
[TestMethod]
[Description("Test exception without a message.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateExceptionWithoutMessage()
{
Logger.WriteLine("This test will show what happens when you just throw an exception and catch it.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
try
{
for (int x = 0; x < 10; x++)
{
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
if (x >= 2)
throw new Exception("Oh, my gosh! Why??? This is how it ends!!");
}
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE!!!");
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
[TestMethod]
[Description("Test exception with a message.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateExceptionWithMessage()
{
Logger.WriteLine("This test will show what happens when you just throw an exception and catch it.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
int x = 0;
try
{
for (x = 1; x < 10; x++)
{
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
if (x == 3)
throw new Exception("Oh, my gosh! Why??? This is how it ends!!");
}
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE!!!");
}
catch (Exception ex)
{
Logger.LogException(ex, "Caught an exception on try number {0}", x);
}
}
private void bar(int x)
{
try
{
if (x == 3)
throw new Exception("Oh, my gosh! Why??? This is how it ends!!");
}
catch (Exception ex)
{
throw new System.NotSupportedException("WTH are you doing??", ex);
}
}
private void foo(int x)
{
try
{
bar(x);
}
catch (Exception ex)
{
throw new AutomationFrameworkException(ex, "A terrible, no-good, very bad thing happened!");
}
}
[TestMethod]
[Description("Test exception with multiple inner exceptions.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateExceptionWithInnerException()
{
Logger.WriteLine("This test will show what happens when you just throw an exception and catch it.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
int x = 0;
try
{
for (x = 1; x < 10; x++)
{
foo(x);
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
}
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE!!!");
}
catch (Exception ex)
{
Logger.LogException(ex, "Caught an exception on try number {0}", x);
}
}
[TestMethod]
[Description("Test when a test throws an unhandled exception.")]
[TestCategory("LocalOnly")]
public void ShouldFail_ValidateFailOnUnhandledException()
{
Logger.WriteLine("This test will show what happens when a test throws an unhandled exception. The log should NOT say");
Logger.WriteLine("that the test was skipped. It should say FAIL.");
Logger.WriteLine("Expected final outcome: Failed.");
Logger.WriteLine();
Dictionary<string, string> someDictionary = new Dictionary<string, string>();
Logger.LogResult(Result.Pass, "Laa-de-daa. Testing stuff...everything's good so far.");
Logger.AssertIsEqual("Hoo boy!", someDictionary["bad key"], "Check the random thing.");
Logger.LogResult(Result.Information, "YOU SHOULD NOT SEE THIS MESSAGE.");
}
}
}
| |
using MS.Utility;
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using MS.Internal.Ink.InkSerializedFormat;
using System.Windows.Media;
using System.Reflection;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Ink
{
/// <summary>
/// A collection of name/value pairs, called ExtendedProperties, can be stored
/// in a collection to enable aggregate operations and assignment to Ink object
/// model objects, such StrokeCollection and Stroke.
/// </summary>
internal sealed class ExtendedPropertyCollection //does not implement ICollection, we don't need it
{
/// <summary>
/// Create a new empty ExtendedPropertyCollection
/// </summary>
internal ExtendedPropertyCollection()
{
}
/// <summary>Overload of the Equals method which determines if two ExtendedPropertyCollection
/// objects contain equivalent key/value pairs</summary>
public override bool Equals(object o)
{
if (o == null || o.GetType() != GetType())
{
return false;
}
//
// compare counts
//
ExtendedPropertyCollection that = (ExtendedPropertyCollection)o;
if (that.Count != this.Count)
{
return false;
}
//
// counts are equal, compare individual items
//
//
for (int x = 0; x < that.Count; x++)
{
bool cont = false;
for (int i = 0; i < _extendedProperties.Count; i++)
{
if (_extendedProperties[i].Equals(that[x]))
{
cont = true;
break;
}
}
if (!cont)
{
return false;
}
}
return true;
}
/// <summary>Overload of the equality operator which determines
/// if two ExtendedPropertyCollections are equal</summary>
public static bool operator ==(ExtendedPropertyCollection first, ExtendedPropertyCollection second)
{
// compare the GC ptrs for the obvious reference equality
if (((object)first == null && (object)second == null) ||
((object)first == (object)second))
{
return true;
}
// otherwise, if one of the ptrs are null, but not the other then return false
else if ((object)first == null || (object)second == null)
{
return false;
}
// finally use the full `blown value-style comparison against the collection contents
else
{
return first.Equals(second);
}
}
/// <summary>Overload of the not equals operator to determine if two
/// ExtendedPropertyCollections have different key/value pairs</summary>
public static bool operator!=(ExtendedPropertyCollection first, ExtendedPropertyCollection second)
{
return !(first == second);
}
/// <summary>
/// GetHashCode
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Check to see if the attribute is defined in the collection.
/// </summary>
/// <param name="attributeId">Attribute identifier</param>
/// <returns>True if attribute is set in the mask, false otherwise</returns>
internal bool Contains(Guid attributeId)
{
for (int x = 0; x < _extendedProperties.Count; x++)
{
if (_extendedProperties[x].Id == attributeId)
{
//
// a typical pattern is to first check if
// ep.Contains(guid)
// before accessing:
// object o = ep[guid];
//
// I'm caching the index that contains returns so that we
// can look there first for the guid in the indexer
//
_optimisticIndex = x;
return true;
}
}
return false;
}
/// <summary>
/// Copies the ExtendedPropertyCollection
/// </summary>
/// <returns>Copy of the ExtendedPropertyCollection</returns>
/// <remarks>Any reference types held in the collection will only be deep copied (e.g. Arrays).
/// </remarks>
internal ExtendedPropertyCollection Clone()
{
ExtendedPropertyCollection copied = new ExtendedPropertyCollection();
for (int x = 0; x < _extendedProperties.Count; x++)
{
copied.Add(_extendedProperties[x].Clone());
}
return copied;
}
/// <summary>
/// Add
/// </summary>
/// <param name="id">Id</param>
/// <param name="value">value</param>
internal void Add(Guid id, object value)
{
if (this.Contains(id))
{
throw new ArgumentException(SR.Get(SRID.EPExists), "id");
}
ExtendedProperty extendedProperty = new ExtendedProperty(id, value);
//this will raise change events
this.Add(extendedProperty);
}
/// <summary>
/// Remove
/// </summary>
/// <param name="id">id</param>
internal void Remove(Guid id)
{
if (!Contains(id))
{
throw new ArgumentException(SR.Get(SRID.EPGuidNotFound), "id");
}
ExtendedProperty propertyToRemove = GetExtendedPropertyById(id);
System.Diagnostics.Debug.Assert(propertyToRemove != null);
_extendedProperties.Remove(propertyToRemove);
//
// this value is bogus now
//
_optimisticIndex = -1;
// fire notification event
if (this.Changed != null)
{
ExtendedPropertiesChangedEventArgs eventArgs
= new ExtendedPropertiesChangedEventArgs(propertyToRemove, null);
this.Changed(this, eventArgs);
}
}
/// <value>
/// Retrieve the Guid array of ExtendedProperty Ids in the collection.
/// <paramref>Guid[]</paramref> is of type <see cref="System.Int32"/>.
/// <seealso cref="System.Collections.ICollection.Count"/>
/// </value>
internal Guid[] GetGuidArray()
{
if (_extendedProperties.Count > 0)
{
Guid[] guids = new Guid[_extendedProperties.Count];
for (int i = 0; i < _extendedProperties.Count; i++)
{
guids[i] = this[i].Id;
}
return guids;
}
else
{
return new Guid[0];
}
}
/// <summary>
/// Generic accessor for the ExtendedPropertyCollection.
/// </summary>
/// <param name="attributeId">Attribue Id to find</param>
/// <returns>Value for attribute specified by Id</returns>
/// <exception cref="System.ArgumentException">Specified identifier was not found</exception>
/// <remarks>
/// Note that you can access extended properties via this indexer.
/// </remarks>
internal object this[Guid attributeId]
{
get
{
ExtendedProperty ep = GetExtendedPropertyById(attributeId);
if (ep == null)
{
throw new ArgumentException(SR.Get(SRID.EPNotFound), "attributeId");
}
return ep.Value;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
for (int i = 0; i < _extendedProperties.Count; i++)
{
ExtendedProperty currentProperty = _extendedProperties[i];
if (currentProperty.Id == attributeId)
{
object oldValue = currentProperty.Value;
//this will raise events
currentProperty.Value = value;
//raise change if anyone is listening
if (this.Changed != null)
{
ExtendedPropertiesChangedEventArgs eventArgs
= new ExtendedPropertiesChangedEventArgs(
new ExtendedProperty(currentProperty.Id, oldValue), //old prop
currentProperty); //new prop
this.Changed(this, eventArgs);
}
return;
}
}
//
// we didn't find the Id in the collection, we need to add it.
// this will raise change notifications
//
ExtendedProperty attributeToAdd = new ExtendedProperty(attributeId, value);
this.Add(attributeToAdd);
}
}
/// <summary>
/// Generic accessor for the ExtendedPropertyCollection.
/// </summary>
/// <param name="index">index into masking collection to retrieve</param>
/// <returns>ExtendedProperty specified at index</returns>
/// <exception cref="System.ArgumentOutOfRangeException">Index was not found</exception>
/// <remarks>
/// Note that you can access extended properties via this indexer.
/// </remarks>
internal ExtendedProperty this[int index]
{
get
{
return _extendedProperties[index];
}
}
/// <value>
/// Retrieve the number of ExtendedProperty objects in the collection.
/// <paramref>Count</paramref> is of type <see cref="System.Int32"/>.
/// <seealso cref="System.Collections.ICollection.Count"/>
/// </value>
internal int Count
{
get
{
return _extendedProperties.Count;
}
}
/// <summary>
/// Event fired whenever a ExtendedProperty is modified in the collection
/// </summary>
internal event ExtendedPropertiesChangedEventHandler Changed;
/// <summary>
/// private Add, we need to consider making this public in order to implement the generic ICollection
/// </summary>
private void Add(ExtendedProperty extendedProperty)
{
System.Diagnostics.Debug.Assert(!this.Contains(extendedProperty.Id), "ExtendedProperty already belongs to the collection");
_extendedProperties.Add(extendedProperty);
// fire notification event
if (this.Changed != null)
{
ExtendedPropertiesChangedEventArgs eventArgs
= new ExtendedPropertiesChangedEventArgs(null, extendedProperty);
this.Changed(this, eventArgs);
}
}
/// <summary>
/// Private helper for getting an EP out of our internal collection
/// </summary>
/// <param name="id">id</param>
private ExtendedProperty GetExtendedPropertyById(Guid id)
{
//
// a typical pattern is to first check if
// ep.Contains(guid)
// before accessing:
// object o = ep[guid];
//
// The last call to .Contains sets this index
//
if (_optimisticIndex != -1 &&
_optimisticIndex < _extendedProperties.Count &&
_extendedProperties[_optimisticIndex].Id == id)
{
return _extendedProperties[_optimisticIndex];
}
//we didn't find the ep optimistically, perform linear lookup
for (int i = 0; i < _extendedProperties.Count; i++)
{
if (_extendedProperties[i].Id == id)
{
return _extendedProperties[i];
}
}
return null;
}
// the set of ExtendedProperties stored in this collection
private List<ExtendedProperty> _extendedProperties = new List<ExtendedProperty>();
//used to optimize across Contains / Index calls
private int _optimisticIndex = -1;
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.NetworkAnalystUI;
namespace NABarrierLocationEditor
{
/// <summary>
/// Summary description for BarrierLocationEditor.
///
/// This sample teaches how to load polygon and polyline barrier values programmatically,
/// while also providing a way to visualize and edit the underlying network element values that make up a polygon or polyline barrier.
/// As a side benefit, the programmer also learns how to flash the geometry of a network element
/// (with a corresponding digitized direction arrow), as well as how to set up a context menu command for the NAWindow.
///
/// </summary>
[Guid("7a93ba10-9dee-11da-a746-0800200c9a66")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("NABarrierLocationEditor.NABarrierLocationEditor")]
public sealed class NABarrierLocationEditor : BaseCommand, INAWindowCommand2
{
public INetworkAnalystExtension m_naExt; // Hook into the Desktop NA Extension
public IApplication m_application; // Hook into ArcMap
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ESRI.ArcGIS.ADF.CATIDs.MxCommands.Register(regKey);
ESRI.ArcGIS.ADF.CATIDs.ControlsCommands.Register(regKey);
// Register with NetworkAnalystWindowItemsCommand to get the
// command to show up when you right click on the class in the NAWindow
ESRI.ArcGIS.ADF.CATIDs.NetworkAnalystWindowItemsCommand.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ESRI.ArcGIS.ADF.CATIDs.MxCommands.Unregister(regKey);
ESRI.ArcGIS.ADF.CATIDs.ControlsCommands.Unregister(regKey);
ESRI.ArcGIS.ADF.CATIDs.NetworkAnalystWindowItemsCommand.Unregister(regKey);
}
#endregion
#endregion
public NABarrierLocationEditor()
{
base.m_category = "Developer Samples";
base.m_caption = "Edit Network Analyst Barrier Location Ranges";
base.m_message = "Edit Network Analyst Barrier Location Ranges";
base.m_toolTip = "Edit Network Analyst Barrier Location Ranges";
base.m_name = "EditNABarrierLocationRanges";
try
{
string bitmapResourceName = GetType().Name + ".bmp";
base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
}
}
~NABarrierLocationEditor()
{
m_application = null;
m_naExt = null;
GC.Collect();
}
#region Overriden Class Methods
/// <summary>
/// Occurs when this command is created
/// </summary>
/// <param name="hook">Instance of the application</param>
///
public override void OnCreate(object hook)
{
if (hook == null)
return;
m_application = hook as IApplication;
base.m_enabled = true;
if (m_application != null)
m_naExt = m_application.FindExtensionByName("Network Analyst") as INetworkAnalystExtension;
}
/// <summary>
/// Occurs when this command is clicked
/// </summary>
public override void OnClick()
{
try
{
OpenBarrierEditorForm();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error");
}
}
#endregion
#region Overridden INAWindowCommand Methods
public bool Applies(INALayer naLayer, INAWindowCategory category)
{
// The category is associated with an NAClass.
// In our case, we want the PolygonBarriers and PolylineBarriers classes
if (category != null)
{
string categoryName = category.NAClass.ClassDefinition.Name;
if (categoryName == "PolygonBarriers" || categoryName == "PolylineBarriers")
return true;
}
return false;
}
#region INAWindowCommand2 Members
/// <summary>
/// Occurs in determining whether or not to include the command as a context menu item
/// <param name="naLayer">The active analysis layer</param>
/// <param name="categoryGroup">The selected group in the NAWindow</param>
/// </summary>
bool INAWindowCommand2.AppliesToGroup(INALayer naLayer, INAWindowCategoryGroup categoryGroup)
{
if (categoryGroup != null)
{
return Applies(naLayer, categoryGroup.Category);
}
return false;
}
int INAWindowCommand2.Priority
{
get { return 1; }
}
#endregion
#endregion
/// <summary>
/// This command will be enabled for Polygon and Polyline Barriers
/// </summary>
public override bool Enabled
{
get
{
return Applies(null, GetActiveCategory());
}
}
/// <summary>
/// To open the editor form, we need to first determine which barrier is
/// being edited, then pass that value to the form
/// </summary>
private void OpenBarrierEditorForm()
{
// get the barrier layer by using the category name to as the NAClassName
INAWindowCategory activeCategory = GetActiveCategory();
string categoryName = activeCategory.NAClass.ClassDefinition.Name;
INALayer naLayer = GetActiveAnalysisLayer();
ILayer layer = naLayer.get_LayerByNAClassName(categoryName);
// get a selection count and popup a message if more or less than one item is selected
IFeatureSelection fSel = layer as IFeatureSelection;
ISelectionSet selSet = fSel.SelectionSet;
if (selSet.Count != 1)
System.Windows.Forms.MessageBox.Show("Only one barrier in a category can be selected at a time for this command to execute", "Barrier Location Editor Warning");
else
{
// get the object IDs of the selected item
int id = selSet.IDs.Next();
// Get the barrier feature by using the selected ID
IFeatureClass fClass = naLayer.Context.NAClasses.get_ItemByName(categoryName) as IFeatureClass;
IFeature barrierFeature = fClass.GetFeature(id);
// display the form for editing the barrier
EditorForm form = new EditorForm(m_application, naLayer.Context, barrierFeature);
form.ShowDialog();
form = null;
}
}
#region "NAWindow Interaction"
private INALayer GetActiveAnalysisLayer()
{
if (m_naExt != null)
return m_naExt.NAWindow.ActiveAnalysis;
else
return null;
}
private INAWindowCategory2 GetActiveCategory()
{
if (m_naExt != null)
return m_naExt.NAWindow.ActiveCategory as INAWindowCategory2;
else
return null;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Log = Microsoft.AspNetCore.SignalR.HubConnectionHandlerLog;
namespace Microsoft.AspNetCore.SignalR
{
/// <summary>
/// Handles incoming connections and implements the SignalR Hub Protocol.
/// </summary>
public class HubConnectionHandler<THub> : ConnectionHandler where THub : Hub
{
private readonly HubLifetimeManager<THub> _lifetimeManager;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<HubConnectionHandler<THub>> _logger;
private readonly IHubProtocolResolver _protocolResolver;
private readonly HubOptions<THub> _hubOptions;
private readonly HubOptions _globalHubOptions;
private readonly IUserIdProvider _userIdProvider;
private readonly HubDispatcher<THub> _dispatcher;
private readonly bool _enableDetailedErrors;
private readonly long? _maximumMessageSize;
private readonly int _maxParallelInvokes;
// Internal for testing
internal ISystemClock SystemClock { get; set; } = new SystemClock();
/// <summary>
/// Initializes a new instance of the <see cref="HubConnectionHandler{THub}"/> class.
/// </summary>
/// <param name="lifetimeManager">The hub lifetime manager.</param>
/// <param name="protocolResolver">The protocol resolver used to resolve the protocols between client and server.</param>
/// <param name="globalHubOptions">The global options used to initialize hubs.</param>
/// <param name="hubOptions">Hub specific options used to initialize hubs. These options override the global options.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="userIdProvider">The user ID provider used to get the user ID from a hub connection.</param>
/// <param name="serviceScopeFactory">The service scope factory.</param>
/// <remarks>This class is typically created via dependency injection.</remarks>
public HubConnectionHandler(HubLifetimeManager<THub> lifetimeManager,
IHubProtocolResolver protocolResolver,
IOptions<HubOptions> globalHubOptions,
IOptions<HubOptions<THub>> hubOptions,
ILoggerFactory loggerFactory,
IUserIdProvider userIdProvider,
IServiceScopeFactory serviceScopeFactory
)
{
_protocolResolver = protocolResolver;
_lifetimeManager = lifetimeManager;
_loggerFactory = loggerFactory;
_hubOptions = hubOptions.Value;
_globalHubOptions = globalHubOptions.Value;
_logger = loggerFactory.CreateLogger<HubConnectionHandler<THub>>();
_userIdProvider = userIdProvider;
_enableDetailedErrors = false;
List<IHubFilter>? hubFilters = null;
if (_hubOptions.UserHasSetValues)
{
_maximumMessageSize = _hubOptions.MaximumReceiveMessageSize;
_enableDetailedErrors = _hubOptions.EnableDetailedErrors ?? _enableDetailedErrors;
_maxParallelInvokes = _hubOptions.MaximumParallelInvocationsPerClient;
if (_hubOptions.HubFilters != null)
{
hubFilters = new List<IHubFilter>(_hubOptions.HubFilters);
}
}
else
{
_maximumMessageSize = _globalHubOptions.MaximumReceiveMessageSize;
_enableDetailedErrors = _globalHubOptions.EnableDetailedErrors ?? _enableDetailedErrors;
_maxParallelInvokes = _globalHubOptions.MaximumParallelInvocationsPerClient;
if (_globalHubOptions.HubFilters != null)
{
hubFilters = new List<IHubFilter>(_globalHubOptions.HubFilters);
}
}
_dispatcher = new DefaultHubDispatcher<THub>(
serviceScopeFactory,
new HubContext<THub>(lifetimeManager),
_enableDetailedErrors,
new Logger<DefaultHubDispatcher<THub>>(loggerFactory),
hubFilters);
}
/// <inheritdoc />
public override async Task OnConnectedAsync(ConnectionContext connection)
{
// We check to see if HubOptions<THub> are set because those take precedence over global hub options.
// Then set the keepAlive and handshakeTimeout values to the defaults in HubOptionsSetup when they were explicitly set to null.
var supportedProtocols = _hubOptions.SupportedProtocols ?? _globalHubOptions.SupportedProtocols;
if (supportedProtocols == null || supportedProtocols.Count == 0)
{
throw new InvalidOperationException("There are no supported protocols");
}
var handshakeTimeout = _hubOptions.HandshakeTimeout ?? _globalHubOptions.HandshakeTimeout ?? HubOptionsSetup.DefaultHandshakeTimeout;
var contextOptions = new HubConnectionContextOptions()
{
KeepAliveInterval = _hubOptions.KeepAliveInterval ?? _globalHubOptions.KeepAliveInterval ?? HubOptionsSetup.DefaultKeepAliveInterval,
ClientTimeoutInterval = _hubOptions.ClientTimeoutInterval ?? _globalHubOptions.ClientTimeoutInterval ?? HubOptionsSetup.DefaultClientTimeoutInterval,
StreamBufferCapacity = _hubOptions.StreamBufferCapacity ?? _globalHubOptions.StreamBufferCapacity ?? HubOptionsSetup.DefaultStreamBufferCapacity,
MaximumReceiveMessageSize = _maximumMessageSize,
SystemClock = SystemClock,
MaximumParallelInvocations = _maxParallelInvokes,
};
Log.ConnectedStarting(_logger);
var connectionContext = new HubConnectionContext(connection, contextOptions, _loggerFactory);
var resolvedSupportedProtocols = (supportedProtocols as IReadOnlyList<string>) ?? supportedProtocols.ToList();
if (!await connectionContext.HandshakeAsync(handshakeTimeout, resolvedSupportedProtocols, _protocolResolver, _userIdProvider, _enableDetailedErrors))
{
return;
}
// -- the connectionContext has been set up --
try
{
await _lifetimeManager.OnConnectedAsync(connectionContext);
await RunHubAsync(connectionContext);
}
finally
{
connectionContext.Cleanup();
Log.ConnectedEnding(_logger);
await _lifetimeManager.OnDisconnectedAsync(connectionContext);
}
}
private async Task RunHubAsync(HubConnectionContext connection)
{
try
{
await _dispatcher.OnConnectedAsync(connection);
}
catch (Exception ex)
{
Log.ErrorDispatchingHubEvent(_logger, "OnConnectedAsync", ex);
// The client shouldn't try to reconnect given an error in OnConnected.
await SendCloseAsync(connection, ex, allowReconnect: false);
// return instead of throw to let close message send successfully
return;
}
try
{
await DispatchMessagesAsync(connection);
}
catch (OperationCanceledException)
{
// Don't treat OperationCanceledException as an error, it's basically a "control flow"
// exception to stop things from running
}
catch (Exception ex)
{
Log.ErrorProcessingRequest(_logger, ex);
await HubOnDisconnectedAsync(connection, ex);
// return instead of throw to let close message send successfully
return;
}
await HubOnDisconnectedAsync(connection, connection.CloseException);
}
private async Task HubOnDisconnectedAsync(HubConnectionContext connection, Exception? exception)
{
// send close message before aborting the connection
await SendCloseAsync(connection, exception, connection.AllowReconnect);
// We wait on abort to complete, this is so that we can guarantee that all callbacks have fired
// before OnDisconnectedAsync
// Ensure the connection is aborted before firing disconnect
await connection.AbortAsync();
try
{
await _dispatcher.OnDisconnectedAsync(connection, exception);
}
catch (Exception ex)
{
Log.ErrorDispatchingHubEvent(_logger, "OnDisconnectedAsync", ex);
throw;
}
}
private async Task SendCloseAsync(HubConnectionContext connection, Exception? exception, bool allowReconnect)
{
var closeMessage = CloseMessage.Empty;
if (exception != null)
{
var errorMessage = ErrorMessageHelper.BuildErrorMessage("Connection closed with an error.", exception, _enableDetailedErrors);
closeMessage = new CloseMessage(errorMessage, allowReconnect);
}
else if (allowReconnect)
{
closeMessage = new CloseMessage(error: null, allowReconnect);
}
try
{
await connection.WriteAsync(closeMessage, ignoreAbort: true);
}
catch (Exception ex)
{
Log.ErrorSendingClose(_logger, ex);
}
}
private async Task DispatchMessagesAsync(HubConnectionContext connection)
{
var input = connection.Input;
var protocol = connection.Protocol;
connection.BeginClientTimeout();
var binder = new HubConnectionBinder<THub>(_dispatcher, connection);
while (true)
{
var result = await input.ReadAsync();
var buffer = result.Buffer;
try
{
if (result.IsCanceled)
{
break;
}
if (!buffer.IsEmpty)
{
bool messageReceived = false;
// No message limit, just parse and dispatch
if (_maximumMessageSize == null)
{
while (protocol.TryParseMessage(ref buffer, binder, out var message))
{
connection.StopClientTimeout();
// This lets us know the timeout has stopped and we need to re-enable it after dispatching the message
messageReceived = true;
await _dispatcher.DispatchMessageAsync(connection, message);
}
if (messageReceived)
{
connection.BeginClientTimeout();
}
}
else
{
// We give the parser a sliding window of the default message size
var maxMessageSize = _maximumMessageSize.Value;
while (!buffer.IsEmpty)
{
var segment = buffer;
var overLength = false;
if (segment.Length > maxMessageSize)
{
segment = segment.Slice(segment.Start, maxMessageSize);
overLength = true;
}
if (protocol.TryParseMessage(ref segment, binder, out var message))
{
connection.StopClientTimeout();
// This lets us know the timeout has stopped and we need to re-enable it after dispatching the message
messageReceived = true;
await _dispatcher.DispatchMessageAsync(connection, message);
}
else if (overLength)
{
throw new InvalidDataException($"The maximum message size of {maxMessageSize}B was exceeded. The message size can be configured in AddHubOptions.");
}
else
{
// No need to update the buffer since we didn't parse anything
break;
}
// Update the buffer to the remaining segment
buffer = buffer.Slice(segment.Start);
}
if (messageReceived)
{
connection.BeginClientTimeout();
}
}
}
if (result.IsCompleted)
{
if (!buffer.IsEmpty)
{
throw new InvalidDataException("Connection terminated while reading a message.");
}
break;
}
}
finally
{
// The buffer was sliced up to where it was consumed, so we can just advance to the start.
// We mark examined as buffer.End so that if we didn't receive a full frame, we'll wait for more data
// before yielding the read again.
input.AdvanceTo(buffer.Start, buffer.End);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Common.Logging;
using Spring.Context;
using Spring.Messaging.Support;
using Spring.Objects.Factory;
namespace Spring.Messaging.Core
{
/// <summary>
/// Hold cached data for queue's metadata.
/// </summary>
public class MessageQueueMetadataCache : IApplicationContextAware, IInitializingObject
{
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof(MessageQueueMetadataCache));
#endregion
private readonly IDictionary itemStore = new Hashtable();
private IConfigurableApplicationContext configurableApplicationContext;
private IApplicationContext applicationContext;
private bool isInitialized;
/// <summary>
/// Constructs a new instance of <see cref="MessageQueueMetadataCache"/>.
/// </summary>
public MessageQueueMetadataCache()
{
}
/// <summary>
/// Constructs a new instance of <see cref="MessageQueueMetadataCache"/>.
/// </summary>
public MessageQueueMetadataCache(IConfigurableApplicationContext configurableApplicationContext)
{
this.configurableApplicationContext = configurableApplicationContext;
}
/// <summary>
/// Sets the <see cref="Spring.Context.IApplicationContext"/> that this
/// object runs in.
/// </summary>
public IApplicationContext ApplicationContext
{
set { applicationContext = value; }
}
/// <summary>
/// Initializes the cache.
/// </summary>
public void Initialize()
{
var messageQueueDictionary = configurableApplicationContext.GetObjects<MessageQueueFactoryObject>();
lock (itemStore.SyncRoot)
{
foreach (KeyValuePair<string, MessageQueueFactoryObject> entry in messageQueueDictionary)
{
MessageQueueFactoryObject mqfo = entry.Value;
if (mqfo != null)
{
if (mqfo.Path != null)
{
Insert(mqfo.Path,
new MessageQueueMetadata(mqfo.RemoteQueue, mqfo.RemoteQueueIsTransactional));
} else
{
#region Logging
if (LOG.IsWarnEnabled)
{
LOG.Warn(
"Path for MessageQueueFactoryObject named [" +
mqfo.ObjectName + "] is null, so can't cache its metadata.");
}
#endregion
}
} else
{
// This would indicate some bug in GetObjectsOfType
LOG.Error("Unexpected type of " + entry.Value.GetType() + " was given as candidate for caching MessageQueueMetadata.");
}
}
isInitialized = true;
}
}
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
public void AfterPropertiesSet()
{
IConfigurableApplicationContext ctx = applicationContext as IConfigurableApplicationContext;
if (ctx == null)
{
throw new InvalidOperationException(
"Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
}
configurableApplicationContext = ctx;
}
/// <summary>
/// Gets the number of items in the cache.
/// </summary>
public int Count
{
get
{
lock (itemStore.SyncRoot)
{
return itemStore.Count;
}
}
}
/// <summary>
/// Returns whether this cache has been initialized yet.
/// </summary>
public bool Initalized
{
get
{
lock (itemStore.SyncRoot)
{
return isInitialized;
}
}
}
/// <summary>
/// Gets a collection of all cache queue paths.
/// </summary>
public string[] Paths
{
get
{
lock (itemStore.SyncRoot)
{
string[] paths = new string[itemStore.Count];
int count = 0;
foreach (object path in itemStore.Keys)
{
paths[count] = (string) path;
count++;
}
return paths;
}
}
}
/// <summary>
/// Retrieves MessageQueueMetadata from the cache.
/// </summary>
/// <param name="queuePath">The queue path.</param>
/// <returns>
/// Item for the specified <paramref name="queuePath"/>, or <c>null</c>.
/// </returns>
public MessageQueueMetadata Get(string queuePath)
{
lock (itemStore.SyncRoot)
{
return (MessageQueueMetadata) itemStore[queuePath];
}
}
/// <summary>
/// Removes the specified queue path from the cache
/// </summary>
/// <param name="queuePath">The queue path.</param>
public void Remove(string queuePath)
{
lock (itemStore.SyncRoot)
{
itemStore.Remove(queuePath);
}
}
/// <summary>
/// Removes collection of MessageQueueMetaCache from the cache.
/// </summary>
/// <param name="queuePaths">
/// Array of MessageQueue paths to remove.
/// </param>
public void RemoveAll(string[] queuePaths)
{
lock (itemStore.SyncRoot)
{
foreach (string queuePath in queuePaths)
{
itemStore.Remove(queuePath);
}
}
}
/// <summary>
/// Removes all MessageQueueMetadata from the cache.
/// </summary>
public void Clear()
{
lock (itemStore.SyncRoot)
{
itemStore.Clear();
}
}
/// <summary>
/// Inserts metadata to the cache.
/// </summary>
public void Insert(string path, MessageQueueMetadata messageQueueMetadata)
{
lock (itemStore.SyncRoot)
{
itemStore[path] = messageQueueMetadata;
}
}
}
}
| |
#region Imported Types
using DeviceSQL.Device.ROC.Data;
using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.IO;
#endregion
namespace DeviceSQL.SQLTypes.ROCMaster
{
[Serializable()]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 27)]
public struct ROCMaster_ArchiveInformation : INullable, IBinarySerialize
{
#region Fields
private byte[] data;
#endregion
#region Properties
public bool IsNull
{
get;
internal set;
}
public static ROCMaster_ArchiveInformation Null
{
get
{
return new ROCMaster_ArchiveInformation() { IsNull = true };
}
}
public byte[] Data
{
get
{
if (data == null)
{
data = new byte[26];
}
return data;
}
internal set
{
data = value;
}
}
public int AlarmLogPointer
{
get
{
return new ArchiveInfo(Data).AlarmLogPointer;
}
}
public int EventLogPointer
{
get
{
return new ArchiveInfo(Data).EventLogPointer;
}
}
public int BaseRamCurrentHistoricalHour
{
get
{
return new ArchiveInfo(Data).BaseRamCurrentHistoricalHour;
}
}
public int BaseRam1CurrentHistoricalHour
{
get
{
return new ArchiveInfo(Data).BaseRam1CurrentHistoricalHour;
}
}
public int BaseRam2CurrentHistoricalHour
{
get
{
return new ArchiveInfo(Data).BaseRam2CurrentHistoricalHour;
}
}
public byte BaseRamCurrentHistoricalDay
{
get
{
return new ArchiveInfo(Data).BaseRamCurrentHistoricalDay;
}
}
public byte Base1RamCurrentHistoricalDay
{
get
{
return new ArchiveInfo(Data).Base1RamCurrentHistoricalDay;
}
}
public byte BaseRam2CurrentHistoricalDay
{
get
{
return new ArchiveInfo(Data).BaseRam2CurrentHistoricalDay;
}
}
public int MaximumNumberOfAlarms
{
get
{
return new ArchiveInfo(Data).MaximumNumberOfAlarms;
}
}
public int MaximumNumberOfEvents
{
get
{
return new ArchiveInfo(Data).MaximumNumberOfEvents;
}
}
public byte BaseRamNumberOfDays
{
get
{
return new ArchiveInfo(Data).BaseRamNumberOfDays;
}
}
public byte BaseRam1NumberOfDays
{
get
{
return new ArchiveInfo(Data).BaseRam1NumberOfDays;
}
}
public byte BaseRam2NumberOfDays
{
get
{
return new ArchiveInfo(Data).BaseRam2NumberOfDays;
}
}
public int CurrentAuditLogPointer
{
get
{
return new ArchiveInfo(Data).CurrentAuditLogPointer;
}
}
public byte MinutesPerHistoricalPeriod
{
get
{
return new ArchiveInfo(Data).MinutesPerHistoricalPeriod;
}
}
#endregion
#region Helper Methods
public static ROCMaster_ArchiveInformation Parse(SqlString stringToParse)
{
var base64Bytes = Convert.FromBase64String(stringToParse.Value);
if (base64Bytes.Length == 24)
{
return new ROCMaster_ArchiveInformation() { Data = base64Bytes };
}
else
{
throw new ArgumentException("Input must be exactly 24 bytes");
}
}
public override string ToString()
{
return Convert.ToBase64String(Data);
}
#endregion
#region Serialization Methods
public void Read(BinaryReader binaryReader)
{
IsNull = binaryReader.ReadBoolean();
if (!IsNull)
{
Data = binaryReader.ReadBytes(26);
}
}
public void Write(BinaryWriter binaryWriter)
{
binaryWriter.Write(IsNull);
if (!IsNull)
{
binaryWriter.Write(Data, 0, 26);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml.Serialization
{
using System;
using System.Text;
using System.IO;
using Microsoft.Xml.Schema;
using System.Collections;
using System.Collections.Specialized;
internal class XmlAttributeComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlAttribute a1 = (XmlAttribute)o1;
XmlAttribute a2 = (XmlAttribute)o2;
int ns = String.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal);
if (ns == 0)
{
return String.Compare(a1.Name, a2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal class XmlFacetComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlSchemaFacet f1 = (XmlSchemaFacet)o1;
XmlSchemaFacet f2 = (XmlSchemaFacet)o2;
return String.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal);
}
}
internal class QNameComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlQualifiedName qn1 = (XmlQualifiedName)o1;
XmlQualifiedName qn2 = (XmlQualifiedName)o2;
int ns = String.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal);
if (ns == 0)
{
return String.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal class XmlSchemaObjectComparer : IComparer
{
private QNameComparer _comparer = new QNameComparer();
public int Compare(object o1, object o2)
{
return _comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2));
}
internal static XmlQualifiedName NameOf(XmlSchemaObject o)
{
if (o is XmlSchemaAttribute)
{
return ((XmlSchemaAttribute)o).QualifiedName;
}
else if (o is XmlSchemaAttributeGroup)
{
return ((XmlSchemaAttributeGroup)o).QualifiedName;
}
else if (o is XmlSchemaComplexType)
{
return ((XmlSchemaComplexType)o).QualifiedName;
}
else if (o is XmlSchemaSimpleType)
{
return ((XmlSchemaSimpleType)o).QualifiedName;
}
else if (o is XmlSchemaElement)
{
return ((XmlSchemaElement)o).QualifiedName;
}
else if (o is XmlSchemaGroup)
{
return ((XmlSchemaGroup)o).QualifiedName;
}
else if (o is XmlSchemaGroupRef)
{
return ((XmlSchemaGroupRef)o).RefName;
}
else if (o is XmlSchemaNotation)
{
return ((XmlSchemaNotation)o).QualifiedName;
}
else if (o is XmlSchemaSequence)
{
XmlSchemaSequence s = (XmlSchemaSequence)o;
if (s.Items.Count == 0)
return new XmlQualifiedName(".sequence", Namespace(o));
return NameOf(s.Items[0]);
}
else if (o is XmlSchemaAll)
{
XmlSchemaAll a = (XmlSchemaAll)o;
if (a.Items.Count == 0)
return new XmlQualifiedName(".all", Namespace(o));
return NameOf(a.Items);
}
else if (o is XmlSchemaChoice)
{
XmlSchemaChoice c = (XmlSchemaChoice)o;
if (c.Items.Count == 0)
return new XmlQualifiedName(".choice", Namespace(o));
return NameOf(c.Items);
}
else if (o is XmlSchemaAny)
{
return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList));
}
else if (o is XmlSchemaIdentityConstraint)
{
return ((XmlSchemaIdentityConstraint)o).QualifiedName;
}
return new XmlQualifiedName("?", Namespace(o));
}
internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items)
{
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(NameOf(items[i]));
}
list.Sort(new QNameComparer());
return (XmlQualifiedName)list[0];
}
internal static string Namespace(XmlSchemaObject o)
{
while (o != null && !(o is XmlSchema))
{
o = o.Parent;
}
return o == null ? "" : ((XmlSchema)o).TargetNamespace;
}
}
internal class SchemaObjectWriter
{
private StringBuilder _w = new StringBuilder();
private int _indentLevel = -1;
private void WriteIndent()
{
for (int i = 0; i < _indentLevel; i++)
{
_w.Append(" ");
}
}
protected void WriteAttribute(string localName, string ns, string value)
{
if (value == null || value.Length == 0)
return;
_w.Append(",");
_w.Append(ns);
if (ns != null && ns.Length != 0)
_w.Append(":");
_w.Append(localName);
_w.Append("=");
_w.Append(value);
}
protected void WriteAttribute(string localName, string ns, XmlQualifiedName value)
{
if (value.IsEmpty)
return;
WriteAttribute(localName, ns, value.ToString());
}
protected void WriteStartElement(string name)
{
NewLine();
_indentLevel++;
_w.Append("[");
_w.Append(name);
}
protected void WriteEndElement()
{
_w.Append("]");
_indentLevel--;
}
protected void NewLine()
{
_w.Append(Environment.NewLine);
WriteIndent();
}
protected string GetString()
{
return _w.ToString();
}
private void WriteAttribute(XmlAttribute a)
{
if (a.Value != null)
{
WriteAttribute(a.Name, a.NamespaceURI, a.Value);
}
}
private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o)
{
if (a == null) return;
ArrayList attrs = new ArrayList();
for (int i = 0; i < a.Length; i++)
{
attrs.Add(a[i]);
}
attrs.Sort(new XmlAttributeComparer());
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attribute = (XmlAttribute)attrs[i];
WriteAttribute(attribute);
}
}
internal static string ToString(NamespaceList list)
{
if (list == null)
return null;
switch (list.Type)
{
case NamespaceList.ListType.Any:
return "##any";
case NamespaceList.ListType.Other:
return "##other";
case NamespaceList.ListType.Set:
ArrayList ns = new ArrayList();
foreach (string s in list.Enumerate)
{
ns.Add(s);
}
ns.Sort();
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string s in ns)
{
if (first)
{
first = false;
}
else
{
sb.Append(" ");
}
if (s.Length == 0)
{
sb.Append("##local");
}
else
{
sb.Append(s);
}
}
return sb.ToString();
default:
return list.ToString();
}
}
internal string WriteXmlSchemaObject(XmlSchemaObject o)
{
if (o == null) return String.Empty;
Write3_XmlSchemaObject((XmlSchemaObject)o);
return GetString();
}
private void WriteSortedItems(XmlSchemaObjectCollection items)
{
if (items == null) return;
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(items[i]);
}
list.Sort(new XmlSchemaObjectComparer());
for (int i = 0; i < list.Count; i++)
{
Write3_XmlSchemaObject((XmlSchemaObject)list[i]);
}
}
private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o)
{
if ((object)o == null) return;
WriteStartElement("attribute");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
WriteAttribute(@"default", @"", ((System.String)o.@DefaultValue));
WriteAttribute(@"fixed", @"", ((System.String)o.@FixedValue));
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
WriteAttribute(@"name", @"", ((System.String)o.@Name));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use;
WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType);
WriteEndElement();
}
private void Write3_XmlSchemaObject(XmlSchemaObject o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaComplexType))
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o);
return;
}
else if (t == typeof(XmlSchemaSimpleType))
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o);
return;
}
else if (t == typeof(XmlSchemaElement))
{
Write46_XmlSchemaElement((XmlSchemaElement)o);
return;
}
else if (t == typeof(XmlSchemaAppInfo))
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o);
return;
}
else if (t == typeof(XmlSchemaDocumentation))
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o);
return;
}
else if (t == typeof(XmlSchemaAnnotation))
{
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o);
return;
}
else if (t == typeof(XmlSchemaGroup))
{
Write57_XmlSchemaGroup((XmlSchemaGroup)o);
return;
}
else if (t == typeof(XmlSchemaXPath))
{
Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o);
return;
}
else if (t == typeof(XmlSchemaIdentityConstraint))
{
Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o);
return;
}
else if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
else if (t == typeof(XmlSchemaGroupRef))
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAny))
{
Write53_XmlSchemaAny((XmlSchemaAny)o);
return;
}
else if (t == typeof(XmlSchemaSequence))
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o);
return;
}
else if (t == typeof(XmlSchemaChoice))
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o);
return;
}
else if (t == typeof(XmlSchemaAll))
{
Write43_XmlSchemaAll((XmlSchemaAll)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentRestriction))
{
Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentExtension))
{
Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentRestriction))
{
Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentExtension))
{
Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaComplexContent))
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContent))
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o);
return;
}
else if (t == typeof(XmlSchemaAnyAttribute))
{
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroupRef))
{
Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroup))
{
Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeRestriction))
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeList))
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeUnion))
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o);
return;
}
else if (t == typeof(XmlSchemaAttribute))
{
Write1_XmlSchemaAttribute((XmlSchemaAttribute)o);
return;
}
}
private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o)
{
if ((object)o == null) return;
WriteStartElement("annotation");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Microsoft.Xml.Schema.XmlSchemaObjectCollection a = (Microsoft.Xml.Schema.XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAppInfo)
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai);
}
else if (ai is XmlSchemaDocumentation)
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai);
}
}
}
WriteEndElement();
}
private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o)
{
if ((object)o == null) return;
WriteStartElement("documentation");
WriteAttribute(@"source", @"", ((System.String)o.@Source));
WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((System.String)o.@Language));
XmlNode[] a = (XmlNode[])o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia];
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o)
{
if ((object)o == null) return;
WriteStartElement("appinfo");
WriteAttribute("source", "", o.Source);
XmlNode[] a = (XmlNode[])o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia];
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o)
{
if ((object)o == null) return;
WriteStartElement("simpleType");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaSimpleTypeUnion)
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeRestriction)
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeList)
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content);
}
WriteEndElement();
}
private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v)
{
return v.ToString();
}
private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o)
{
if ((object)o == null) return;
WriteStartElement("union");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (o.MemberTypes != null)
{
ArrayList list = new ArrayList();
for (int i = 0; i < o.MemberTypes.Length; i++)
{
list.Add(o.MemberTypes[i]);
}
list.Sort(new QNameComparer());
_w.Append(",");
_w.Append("memberTypes=");
for (int i = 0; i < list.Count; i++)
{
XmlQualifiedName q = (XmlQualifiedName)list[i];
_w.Append(q.ToString());
_w.Append(",");
}
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@BaseTypes);
WriteEndElement();
}
private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o)
{
if ((object)o == null) return;
WriteStartElement("list");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@ItemTypeName.IsEmpty)
{
WriteAttribute(@"itemType", @"", o.@ItemTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType);
WriteEndElement();
}
private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType);
WriteFacets(o.Facets);
WriteEndElement();
}
private void WriteFacets(XmlSchemaObjectCollection facets)
{
if (facets == null) return;
ArrayList a = new ArrayList();
for (int i = 0; i < facets.Count; i++)
{
a.Add(facets[i]);
}
a.Sort(new XmlFacetComparer());
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaMinExclusiveFacet)
{
Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxInclusiveFacet)
{
Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxExclusiveFacet)
{
Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinInclusiveFacet)
{
Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaLengthFacet)
{
Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaEnumerationFacet)
{
Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinLengthFacet)
{
Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaPatternFacet)
{
Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaTotalDigitsFacet)
{
Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxLengthFacet)
{
Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaWhiteSpaceFacet)
{
Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaFractionDigitsFacet)
{
Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai);
}
}
}
private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o)
{
if ((object)o == null) return;
WriteStartElement(name);
WriteAttribute("id", "", o.Id);
WriteAttribute("value", "", o.Value);
if (o.IsFixed)
{
WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed));
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private string Write30_XmlSchemaUse(XmlSchemaUse v)
{
string s = null;
switch (v)
{
case XmlSchemaUse.@Optional: s = @"optional"; break;
case XmlSchemaUse.@Prohibited: s = @"prohibited"; break;
case XmlSchemaUse.@Required: s = @"required"; break;
default: break;
}
return s;
}
private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o)
{
if ((object)o == null) return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o)
{
if ((object)o == null) return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o)
{
if ((object)o == null) return;
WriteStartElement("anyAttribute");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute("namespace", "", ToString(o.NamespaceList));
XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v)
{
string s = null;
switch (v)
{
case XmlSchemaContentProcessing.@Skip: s = @"skip"; break;
case XmlSchemaContentProcessing.@Lax: s = @"lax"; break;
case XmlSchemaContentProcessing.@Strict: s = @"strict"; break;
default: break;
}
return s;
}
private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o)
{
if ((object)o == null) return;
WriteStartElement("complexType");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
if (((System.Boolean)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
if (((System.Boolean)o.@IsMixed) != false)
{
WriteAttribute(@"mixed", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsMixed)));
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@ContentModel is XmlSchemaComplexContent)
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel);
}
else if (o.@ContentModel is XmlSchemaSimpleContent)
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel);
}
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o)
{
if ((object)o == null) return;
WriteStartElement("simpleContent");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaSimpleContentRestriction)
{
Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleContentExtension)
{
Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content);
}
WriteEndElement();
}
private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o)
{
if ((object)o == null) return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType);
WriteFacets(o.Facets);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o)
{
if ((object)o == null) return;
WriteStartElement("complexContent");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"mixed", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsMixed)));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaComplexContentRestriction)
{
Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaComplexContentExtension)
{
Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content);
}
WriteEndElement();
}
private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o)
{
if ((object)o == null) return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write43_XmlSchemaAll(XmlSchemaAll o)
{
if ((object)o == null) return;
WriteStartElement("all");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write46_XmlSchemaElement(XmlSchemaElement o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("element");
WriteAttribute(@"id", @"", o.Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
if (((System.Boolean)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((System.Boolean)((System.Boolean)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
WriteAttribute(@"default", @"", o.DefaultValue);
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
WriteAttribute(@"fixed", @"", o.FixedValue);
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
if (o.Name != null && o.Name.Length != 0)
{
WriteAttribute(@"name", @"", o.Name);
}
if (o.IsNillable)
{
WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable));
}
if (!o.SubstitutionGroup.IsEmpty)
{
WriteAttribute("substitutionGroup", "", o.SubstitutionGroup);
}
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation(o.Annotation);
if (o.SchemaType is XmlSchemaComplexType)
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType);
}
else if (o.SchemaType is XmlSchemaSimpleType)
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType);
}
WriteSortedItems(o.Constraints);
WriteEndElement();
}
private void Write47_XmlSchemaKey(XmlSchemaKey o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("key");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
}
private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o)
{
if ((object)o == null) return;
WriteStartElement(name);
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute(@"xpath", @"", o.@XPath);
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("keyref");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
// UNDONE compare reference here
WriteAttribute(@"refer", @"", o.@Refer);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write51_XmlSchemaUnique(XmlSchemaUnique o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("unique");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]);
}
}
WriteEndElement();
}
private void Write52_XmlSchemaChoice(XmlSchemaChoice o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("choice");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write53_XmlSchemaAny(XmlSchemaAny o)
{
if ((object)o == null) return;
WriteStartElement("any");
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttribute(@"namespace", @"", ToString(o.NamespaceList));
XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write54_XmlSchemaSequence(XmlSchemaSequence o)
{
if ((object)o == null) return;
WriteStartElement("sequence");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAny)
{
Write53_XmlSchemaAny((XmlSchemaAny)ai);
}
else if (ai is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)ai);
}
else if (ai is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)ai);
}
else if (ai is XmlSchemaElement)
{
Write46_XmlSchemaElement((XmlSchemaElement)ai);
}
else if (ai is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai);
}
}
}
WriteEndElement();
}
private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o)
{
if ((object)o == null) return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write57_XmlSchemaGroup(XmlSchemaGroup o)
{
if ((object)o == null) return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((System.String)o.@Id));
WriteAttribute(@"name", @"", ((System.String)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteEndElement();
}
}
}
| |
//
// BpmEntry.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Gui;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.Collection.Database;
using Banshee.Gui;
using Banshee.Gui.TrackEditor;
namespace Banshee.Bpm
{
public class BpmEntry : HBox, ICanUndo, IEditorField
{
private SpinButton bpm_entry;
private Button detect_button;
private BpmTapAdapter tap_adapter;
private EditorTrackInfo track;
private IBpmDetector detector;
private EditorEditableUndoAdapter<Entry> undo_adapter = new EditorEditableUndoAdapter<Entry> ();
public event EventHandler Changed;
public BpmEntry ()
{
detector = BpmDetectJob.GetDetector ();
if (detector != null) {
detector.FileFinished += OnFileFinished;
}
BuildWidgets ();
Destroyed += delegate {
if (detector != null) {
detector.Dispose ();
detector = null;
}
};
}
public void SetAsReadOnly ()
{
Sensitive = false;
}
private void BuildWidgets ()
{
Spacing = 6;
bpm_entry = new SpinButton (0, 9999, 1);
bpm_entry.MaxLength = bpm_entry.WidthChars = 4;
bpm_entry.Digits = 0;
bpm_entry.Numeric = true;
bpm_entry.ValueChanged += OnChanged;
bpm_entry.Output += OnOutput;
Add (bpm_entry);
if (detector != null) {
detect_button = new Button (Catalog.GetString ("D_etect"));
detect_button.Clicked += OnDetectClicked;
Add (detect_button);
}
Image play = new Image ();
play.IconName = "media-playback-start";;
play.IconSize = (int)IconSize.Menu;
Button play_button = new Button (play);
play_button.Clicked += OnPlayClicked;
Add (play_button);
Button tap_button = new Button (Catalog.GetString ("T_ap"));
tap_adapter = new BpmTapAdapter (tap_button);
tap_adapter.BpmChanged += OnTapBpmChanged;
Add (tap_button);
detect_button.TooltipText = Catalog.GetString ("Have Banshee attempt to auto-detect the BPM of this song");
play_button.TooltipText = Catalog.GetString ("Play this song");
tap_button.TooltipText = Catalog.GetString ("Tap this button to the beat to set the BPM for this song manually");
ShowAll ();
}
public void DisconnectUndo ()
{
undo_adapter.DisconnectUndo ();
}
public void ConnectUndo (EditorTrackInfo track)
{
this.track = track;
tap_adapter.Reset ();
undo_adapter.ConnectUndo (bpm_entry, track);
}
public int Bpm {
get { return bpm_entry.ValueAsInt; }
set { bpm_entry.Value = value; }
}
protected override bool OnMnemonicActivated (bool group_cycling)
{
return bpm_entry.MnemonicActivate (group_cycling);
}
private void OnChanged (object o, EventArgs args)
{
EventHandler handler = Changed;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private void OnTapBpmChanged (int bpm)
{
Console.WriteLine ("Got Tap Bpm changed: {0}", bpm);
Bpm = bpm;
OnChanged (null, null);
}
private void OnDetectClicked (object o, EventArgs args)
{
if (track != null) {
detect_button.Sensitive = false;
detector.ProcessFile (track.Uri);
}
}
private void OnFileFinished (object o, BpmEventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
detect_button.Sensitive = true;
if (track.Uri != args.Uri || args.Bpm == 0) {
return;
}
Log.DebugFormat ("Detected BPM of {0} for {1}", args.Bpm, args.Uri);
Bpm = args.Bpm;
OnChanged (null, null);
});
}
private void OnPlayClicked (object o, EventArgs args)
{
if (track != null) {
// Pause playback only if the selected track is playing.
if (ServiceManager.PlayerEngine.CurrentTrack == track
&& ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing) {
ServiceManager.PlayerEngine.Pause ();
Image play = new Image ();
play.IconName = "media-playback-start";
play.IconSize = (int)IconSize.Menu;
((Button)o).Image = play;
} else {
ServiceManager.PlayerEngine.Open (track);
Gtk.ActionGroup actions = ServiceManager.Get<InterfaceActionService> ().PlaybackActions;
(actions["StopWhenFinishedAction"] as Gtk.ToggleAction).Active = true;
ServiceManager.PlayerEngine.Play ();
Image stop = new Image ();
stop.IconName = "media-playback-stop";
stop.IconSize = (int)IconSize.Menu;
((Button)o).Image = stop;
}
}
}
private void OnOutput (object o, OutputArgs args)
{
SpinButton entry = (SpinButton) o;
if (0 == entry.ValueAsInt) {
entry.Text = "";
} else {
entry.Text = entry.ValueAsInt.ToString ();
}
args.RetVal = 1;
}
}
}
| |
/*
Copyright 2016 Utrecht University http://www.uu.nl/
This software has been created in the context of the EU-funded RAGE project.
Realising and Applied Gaming Eco-System (RAGE), Grant agreement No 644187,
http://rageproject.eu/
The Behavior Markup Language (BML) is a language whose specifications were developed
in the SAIBA framework. More information here : http://www.mindmakers.org/projects/bml-1-0/wiki
Created by: Christyowidiasmoro, Utrecht University <c.christyowidiasmoro@uu.nl>
For more information, contact Dr. Zerrin YUMAK, Email: z.yumak@uu.nl Web: http://www.zerrinyumak.com/
https://www.staff.science.uu.nl/~yumak001/UUVHC/index.html
*/
// <copyright file="RageBMLRealizer.cs" company="RAGE">
// Copyright (c) 2016 RAGE All rights reserved.
// </copyright>
// <author>Chris021</author>
// <date>12/5/2016 11:53:54 AM</date>
// <summary>Implements the RageBMLRealizer class</summary>
namespace AssetPackage
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using AssetManagerPackage;
using BMLRealizer;
/// <summary>
/// An BMLRealizer Rage asset
/// </summary>
public class RageBMLRealizer : BaseAsset
{
#region Fields
/// <summary>
/// callback function. it will be called when the specific sync point is completed
/// </summary>
/// <param name="id"></param> the ID of block
/// <param name="eventName"></param>the event name of sync point (start, ready, strokeStart, attackPeak, stroke, strokeEnd, relax, end)
public delegate void SyncPointCompleted(string id, string eventName);
public SyncPointCompleted OnSyncPointCompleted;
/// <summary>
/// Options for controlling the operation.
/// </summary>
private RageBMLRealizerSettings settings = null;
/// <summary>
/// dictionary that will hold the value of all block / behavior
/// </summary>
private Dictionary<string, Type> blocks = new Dictionary<string, Type>();
/// <summary>
/// the dictionary that save all the blocks / behavior that need to be run
/// </summary>
private Dictionary<string, BMLBlock> scheduledBlocks = new Dictionary<string, BMLBlock>();
/// <summary>
/// global timer
/// </summary>
private float timer;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the RageBMLRealizer.Asset class.
/// </summary>
public RageBMLRealizer()
: base()
{
//! Create Settings and let it's BaseSettings class assign Defaultvalues where it can.
//
settings = new RageBMLRealizerSettings();
blocks.Add("bml", typeof(BMLBml));
blocks.Add("wait", typeof(BMLWait));
// TODO <synchronize>, <before>
blocks.Add("face", typeof(BMLFace));
blocks.Add("faceFacs", typeof(BMLFaceFacs));
blocks.Add("faceLexeme", typeof(BMLFaceLexeme));
blocks.Add("faceShift", typeof(BMLFaceShift));
blocks.Add("gaze", typeof(BMLGaze));
blocks.Add("gazeShift", typeof(BMLGazeShift));
blocks.Add("gesture", typeof(BMLGesture));
blocks.Add("pointing", typeof(BMLPointing));
blocks.Add("head", typeof(BMLHead));
blocks.Add("headDirectionShift", typeof(BMLHeadDirectionShift));
blocks.Add("locomotion", typeof(BMLLocomotion));
blocks.Add("posture", typeof(BMLPosture));
blocks.Add("postureShift", typeof(BMLPostureShift));
blocks.Add("stance", typeof(BMLStance));
blocks.Add("pose", typeof(BMLPose));
blocks.Add("speech", typeof(BMLSpeech));
// TODO <feedback> <blockProgress>
timer = 0.0f;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets options for controlling the operation.
/// </summary>
///
/// <remarks> Besides the toXml() and fromXml() methods, we never use this property but use
/// it's correctly typed backing field 'settings' instead. </remarks>
/// <remarks> This property should go into each asset having Settings of its own. </remarks>
/// <remarks> The actual class used should be derived from BaseAsset (and not directly from
/// ISetting). </remarks>
///
/// <value>
/// The settings.
/// </value>
public override ISettings Settings
{
get
{
return settings;
}
set
{
settings = (value as RageBMLRealizerSettings);
}
}
/// <summary>
/// the dictionary that hold the blocks / behavior that need to be run
/// </summary>
public Dictionary<string, BMLBlock> ScheduledBlocks
{
get
{
return scheduledBlocks;
}
}
/// <summary>
/// global timer
/// </summary>
public float Timer
{
get
{
return timer;
}
}
#endregion Properties
#region Methods
public void ParseFromFile(string filename)
{
AssetManager.Instance.Log(Severity.Warning, "not supported yet in portable version");
//XmlTextReader reader = new XmlTextReader(filename);
//if (reader != null)
// Parse(reader);
//else
// AssetManager.Instance.Log(Severity.Warning, "file error");
}
public void ParseFromString(string xml)
{
XmlReader reader = XmlReader.Create(new StringReader(xml));
Parse(reader);
}
/// <summary>
/// update function will be called everytime when the program is run. it can be called inside Unity Update function
/// </summary>
/// <param name="deltaTime"></param> the time from last called
public void Update(float deltaTime)
{
timer += deltaTime;
foreach (KeyValuePair<string, BMLBlock> block in scheduledBlocks)
{
foreach (KeyValuePair<string, BMLSyncPoint> syncPoint in block.Value.syncPoints)
{
syncPoint.Value.Update(this);
}
}
}
/// <summary>
/// this function can be called from outside library to trigger sync point.
/// </summary>
/// <param name="id"></param> the ID of the block where the sync point is resided
/// <param name="eventName"></param> the event name of sync point (start, ready, strokeStart, attackPeak, stroke, strokeEnd, relax, end)
public void TriggerSyncPoint(string id, string eventName)
{
if (scheduledBlocks.ContainsKey(id))
{
if (scheduledBlocks[id].syncPoints.ContainsKey(eventName) == false)
{
// create a new sync point
scheduledBlocks[id].syncPoints.Add(eventName, new BMLSyncPoint(scheduledBlocks[id], eventName, ""));
}
// trigger sync point
scheduledBlocks[id].syncPoints[eventName].TriggerSyncPoint();
}
}
/// <summary>
/// function to get behavior from ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public BMLBlock GetBehaviorFromId(string id)
{
if (scheduledBlocks.ContainsKey(id))
{
return scheduledBlocks[id];
}
else
{
return null;
}
}
/// <summary>
/// parsing the XML
/// TODO: need to check whether we have bml tag or not
/// </summary>
/// <param name="reader"></param> the XMLReader
private void Parse(XmlReader reader)
{
BMLBml currentBml = null;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (blocks.ContainsKey(reader.Name))
{
Type t = blocks[reader.Name];
BMLBlock instance = (BMLBlock)Activator.CreateInstance(t);
instance.Parse(reader);
// TODO: need to accomodate different tag such as constraint, ...
if (instance is BMLBml)
{
BMLBml bml = (BMLBml)instance;
if (bml.composition == BMLBml.Composition.REPLACE)
{
// The new block will completely replace all prior <bml> blocks.
// All behavior specified in earlier blocks will be ended and
ClearBlocks();
// TODO: the ECA will revert to a neutral state before the new block starts.
}
else if (bml.composition == BMLBml.Composition.APPEND)
{
// The start time of the new block will be as soon as possible after the end time of all prior blocks.
if (currentBml != null)
bml.SetGlobalStartTrigger(currentBml.id + ":globalEnd");
}
else if (bml.composition == BMLBml.Composition.MERGE)
{
// The behaviors specified in the new <bml> block will be realized together with the behaviors specified in prior <bml> blocks.
// TODO: In case of conflict, behaviors in the newly merged <bml> block cannot modify behaviors defined by prior <bml> blocks.
}
// save this bml for upcomming tag
currentBml = bml;
// add to scheduled block
scheduledBlocks.Add((bml).id, bml);
}
else
{
// create a new bml if this xml is started without <bml> tag
if (currentBml == null)
{
currentBml = new BMLBml();
}
// track this tag belong to a bml tag
instance.parentBml = currentBml;
// keep tracking the number of tag inside <bml> tag. in order to check whether all bml inside this <bml> tag are already finish or not
instance.parentBml.IncreaseChild();
if (instance is BMLBehavior)
{
// add to scheduled block
scheduledBlocks.Add(((BMLBehavior)instance).id, (BMLBehavior)instance);
}
}
}
break;
}
}
}
private void ClearBlocks()
{
IEnumerator enumerator = scheduledBlocks.GetEnumerator();
while (enumerator.MoveNext())
{
//get the pair of Dictionary
KeyValuePair<string, BMLBlock> pair = ((KeyValuePair<string, BMLBlock>)(enumerator.Current));
//dispose it
pair.Value.Dispose();
}
// clear the dictionary
scheduledBlocks.Clear();
}
#endregion Methods
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 591573 $
* $Date: 2007-11-03 04:17:59 -0600 (Sat, 03 Nov 2007) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2005 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using IBatisNet.Common;
using IBatisNet.Common.Logging;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
#endregion
namespace IBatisNet.DataMapper.Commands
{
/// <summary>
/// Summary description for DefaultPreparedCommand.
/// </summary>
internal class DefaultPreparedCommand : IPreparedCommand
{
private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType );
#region IPreparedCommand Members
/// <summary>
/// Create an IDbCommand for the SqlMapSession and the current SQL Statement
/// and fill IDbCommand IDataParameter's with the parameterObject.
/// </summary>
/// <param name="request"></param>
/// <param name="session">The SqlMapSession</param>
/// <param name="statement">The IStatement</param>
/// <param name="parameterObject">
/// The parameter object that will fill the sql parameter
/// </param>
/// <returns>An IDbCommand with all the IDataParameter filled.</returns>
public void Create(RequestScope request, ISqlMapSession session, IStatement statement, object parameterObject )
{
// the IDbConnection & the IDbTransaction are assign in the CreateCommand
request.IDbCommand = new DbCommandDecorator(session.CreateCommand(statement.CommandType), request);
request.IDbCommand.CommandText = request.PreparedStatement.PreparedSql;
if (_logger.IsDebugEnabled)
{
_logger.Debug("Statement Id: [" + statement.Id + "] PreparedStatement : [" + request.IDbCommand.CommandText + "]");
}
ApplyParameterMap( session, request.IDbCommand, request, statement, parameterObject );
}
/// <summary>
/// Applies the parameter map.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="command">The command.</param>
/// <param name="request">The request.</param>
/// <param name="statement">The statement.</param>
/// <param name="parameterObject">The parameter object.</param>
protected virtual void ApplyParameterMap
( ISqlMapSession session, IDbCommand command,
RequestScope request, IStatement statement, object parameterObject )
{
StringCollection properties = request.PreparedStatement.DbParametersName;
IDbDataParameter[] parameters = request.PreparedStatement.DbParameters;
StringBuilder paramLogList = new StringBuilder(); // Log info
StringBuilder typeLogList = new StringBuilder(); // Log info
int count = properties.Count;
for ( int i = 0; i < count; ++i )
{
IDbDataParameter sqlParameter = parameters[i];
IDbDataParameter parameterCopy = command.CreateParameter();
ParameterProperty property = request.ParameterMap.GetProperty(i);
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append(sqlParameter.ParameterName);
paramLogList.Append("=[");
typeLogList.Append(sqlParameter.ParameterName);
typeLogList.Append("=[");
}
#endregion
if (command.CommandType == CommandType.StoredProcedure)
{
#region store procedure command
// A store procedure must always use a ParameterMap
// to indicate the mapping order of the properties to the columns
if (request.ParameterMap == null) // Inline Parameters
{
throw new DataMapperException("A procedure statement tag must alway have a parameterMap attribute, which is not the case for the procedure '"+statement.Id+"'.");
}
else // Parameters via ParameterMap
{
if (property.DirectionAttribute.Length == 0)
{
property.Direction = sqlParameter.Direction;
}
sqlParameter.Direction = property.Direction;
}
#endregion
}
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append(property.PropertyName);
paramLogList.Append(",");
}
#endregion
request.ParameterMap.SetParameter(property, parameterCopy, parameterObject );
parameterCopy.Direction = sqlParameter.Direction;
// With a ParameterMap, we could specify the ParameterDbTypeProperty
if (request.ParameterMap != null)
{
if (property.DbType != null && property.DbType.Length > 0)
{
string dbTypePropertyName = session.DataSource.DbProvider.ParameterDbTypeProperty;
object propertyValue = ObjectProbe.GetMemberValue(sqlParameter, dbTypePropertyName, request.DataExchangeFactory.AccessorFactory);
ObjectProbe.SetMemberValue(parameterCopy, dbTypePropertyName, propertyValue,
request.DataExchangeFactory.ObjectFactory, request.DataExchangeFactory.AccessorFactory);
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
#region Logging
if (_logger.IsDebugEnabled)
{
if (parameterCopy.Value == DBNull.Value)
{
paramLogList.Append("null");
paramLogList.Append("], ");
typeLogList.Append("System.DBNull, null");
typeLogList.Append("], ");
}
else
{
paramLogList.Append(parameterCopy.Value.ToString());
paramLogList.Append("], ");
// sqlParameter.DbType could be null (as with Npgsql)
// if PreparedStatementFactory did not find a dbType for the parameter in:
// line 225: "if (property.DbType.Length >0)"
// Use parameterCopy.DbType
//typeLogList.Append( sqlParameter.DbType.ToString() );
typeLogList.Append(parameterCopy.DbType.ToString());
typeLogList.Append(", ");
typeLogList.Append(parameterCopy.Value.GetType().ToString());
typeLogList.Append("], ");
}
}
#endregion
// JIRA-49 Fixes (size, precision, and scale)
if (session.DataSource.DbProvider.SetDbParameterSize)
{
if (sqlParameter.Size > 0)
{
parameterCopy.Size = sqlParameter.Size;
}
}
if (session.DataSource.DbProvider.SetDbParameterPrecision)
{
parameterCopy.Precision = sqlParameter.Precision;
}
if (session.DataSource.DbProvider.SetDbParameterScale)
{
parameterCopy.Scale = sqlParameter.Scale;
}
parameterCopy.ParameterName = sqlParameter.ParameterName;
command.Parameters.Add( parameterCopy );
}
#region Logging
if (_logger.IsDebugEnabled && properties.Count>0)
{
_logger.Debug("Statement Id: [" + statement.Id + "] Parameters: [" + paramLogList.ToString(0, paramLogList.Length - 2) + "]");
_logger.Debug("Statement Id: [" + statement.Id + "] Types: [" + typeLogList.ToString(0, typeLogList.Length - 2) + "]");
}
#endregion
}
#endregion
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// ReceivingProcess
/// </summary>
[DataContract]
public partial class ReceivingProcess : IEquatable<ReceivingProcess>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingProcess" /> class.
/// </summary>
[JsonConstructorAttribute]
protected ReceivingProcess() { }
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingProcess" /> class.
/// </summary>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="Status">Status (required).</param>
/// <param name="WorkBatchId">WorkBatchId.</param>
/// <param name="ReceivingWorksheetId">ReceivingWorksheetId.</param>
public ReceivingProcess(int? WarehouseId = null, string Status = null, int? WorkBatchId = null, int? ReceivingWorksheetId = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for ReceivingProcess and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "Status" is required (not null)
if (Status == null)
{
throw new InvalidDataException("Status is a required property for ReceivingProcess and cannot be null");
}
else
{
this.Status = Status;
}
this.WorkBatchId = WorkBatchId;
this.ReceivingWorksheetId = ReceivingWorksheetId;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets WorkBatchId
/// </summary>
[DataMember(Name="workBatchId", EmitDefaultValue=false)]
public int? WorkBatchId { get; set; }
/// <summary>
/// Gets or Sets ReceivingWorksheetId
/// </summary>
[DataMember(Name="receivingWorksheetId", EmitDefaultValue=false)]
public int? ReceivingWorksheetId { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ReceivingProcess {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" WorkBatchId: ").Append(WorkBatchId).Append("\n");
sb.Append(" ReceivingWorksheetId: ").Append(ReceivingWorksheetId).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ReceivingProcess);
}
/// <summary>
/// Returns true if ReceivingProcess instances are equal
/// </summary>
/// <param name="other">Instance of ReceivingProcess to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReceivingProcess other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.WorkBatchId == other.WorkBatchId ||
this.WorkBatchId != null &&
this.WorkBatchId.Equals(other.WorkBatchId)
) &&
(
this.ReceivingWorksheetId == other.ReceivingWorksheetId ||
this.ReceivingWorksheetId != null &&
this.ReceivingWorksheetId.Equals(other.ReceivingWorksheetId)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.WorkBatchId != null)
hash = hash * 59 + this.WorkBatchId.GetHashCode();
if (this.ReceivingWorksheetId != null)
hash = hash * 59 + this.ReceivingWorksheetId.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Raging.Toolbox.Extensions;
namespace Raging.Data.Schema.SqlServer
{
public class SqlServerSchemaReader : ISchemaReader
{
private readonly string connectionString;
#region . Tables Schema Sql .
private const string TablesSchemaSql = @"
SELECT
[Extent1].[SchemaName],
[Extent1].[Name] AS [TableName],
--[Extent1].[TABLE_TYPE] AS TableType,
CASE
WHEN ( [Extent1].[TABLE_TYPE] = 'VIEW' ) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT)
END AS [IsView],
[UnionAll1].[Ordinal],
[UnionAll1].[Name] AS [ColumnName],
[UnionAll1].[IsNullable],
[UnionAll1].[TypeName],
ISNULL([UnionAll1].[MaxLength], 0) AS [MaxLength],
ISNULL([UnionAll1].[Precision], 0) AS [Precision],
ISNULL([UnionAll1].[Default], '') AS [DefaultValue],
ISNULL([UnionAll1].[DateTimePrecision], '') AS [DateTimePrecision],
ISNULL([UnionAll1].[Scale], 0) AS [Scale],
[UnionAll1].[IsIdentity],
[UnionAll1].[IsStoreGenerated],
CASE
WHEN ( [Project5].[C2] IS NULL ) THEN CAST(0 AS BIT)
ELSE [Project5].[C2]
END AS [IsPrimaryKey]
FROM (SELECT
QUOTENAME(TABLE_SCHEMA)
+ QUOTENAME(TABLE_NAME) [Id],
TABLE_SCHEMA [SchemaName],
TABLE_NAME [Name],
TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE IN ( 'BASE TABLE', 'VIEW' )) AS [Extent1]
INNER JOIN (SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Name] AS [Name],
[Extent2].[Ordinal] AS [Ordinal],
[Extent2].[IsNullable] AS [IsNullable],
[Extent2].[TypeName] AS [TypeName],
[Extent2].[MaxLength] AS [MaxLength],
[Extent2].[Precision] AS [Precision],
[Extent2].[Default],
[Extent2].[DateTimePrecision] AS [DateTimePrecision],
[Extent2].[Scale] AS [Scale],
[Extent2].[IsIdentity] AS [IsIdentity],
[Extent2].[IsStoreGenerated] AS [IsStoreGenerated],
0 AS [C1],
[Extent2].[ParentId] AS [ParentId]
FROM (SELECT
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME)
+ QUOTENAME(c.COLUMN_NAME) [Id],
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME) [ParentId],
c.COLUMN_NAME [Name],
c.ORDINAL_POSITION [Ordinal],
CAST(CASE c.IS_NULLABLE
WHEN 'YES' THEN 1
WHEN 'NO' THEN 0
ELSE 0
END AS BIT) [IsNullable],
CASE
WHEN c.DATA_TYPE IN ( 'varchar', 'nvarchar', 'varbinary' )
AND c.CHARACTER_MAXIMUM_LENGTH = -1 THEN c.DATA_TYPE + '(max)'
ELSE c.DATA_TYPE
END AS [TypeName],
c.CHARACTER_MAXIMUM_LENGTH [MaxLength],
CAST(c.NUMERIC_PRECISION AS INTEGER) [Precision],
CAST(c.DATETIME_PRECISION AS INTEGER) [DateTimePrecision],
CAST(c.NUMERIC_SCALE AS INTEGER) [Scale],
c.COLLATION_CATALOG [CollationCatalog],
c.COLLATION_SCHEMA [CollationSchema],
c.COLLATION_NAME [CollationName],
c.CHARACTER_SET_CATALOG [CharacterSetCatalog],
c.CHARACTER_SET_SCHEMA [CharacterSetSchema],
c.CHARACTER_SET_NAME [CharacterSetName],
CAST(0 AS BIT) AS [IsMultiSet],
CAST(COLUMNPROPERTY (OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') AS BIT) AS [IsIdentity],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') | CASE
WHEN c.DATA_TYPE = 'timestamp' THEN 1
ELSE 0
END AS BIT) AS [IsStoreGenerated],
c.COLUMN_DEFAULT AS [Default]
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.TABLES t
ON c.TABLE_CATALOG = t.TABLE_CATALOG
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE IN ( 'BASE TABLE', 'VIEW' )) AS [Extent2]
UNION ALL
SELECT
[Extent3].[Id] AS [Id],
[Extent3].[Name] AS [Name],
[Extent3].[Ordinal] AS [Ordinal],
[Extent3].[IsNullable] AS [IsNullable],
[Extent3].[TypeName] AS [TypeName],
[Extent3].[MaxLength] AS [MaxLength],
[Extent3].[Precision] AS [Precision],
[Extent3].[Default],
[Extent3].[DateTimePrecision] AS [DateTimePrecision],
[Extent3].[Scale] AS [Scale],
[Extent3].[IsIdentity] AS [IsIdentity],
[Extent3].[IsStoreGenerated] AS [IsStoreGenerated],
6 AS [C1],
[Extent3].[ParentId] AS [ParentId]
FROM (SELECT
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME)
+ QUOTENAME(c.COLUMN_NAME) [Id],
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME) [ParentId],
c.COLUMN_NAME [Name],
c.ORDINAL_POSITION [Ordinal],
CAST(CASE c.IS_NULLABLE
WHEN 'YES' THEN 1
WHEN 'NO' THEN 0
ELSE 0
END AS BIT) [IsNullable],
CASE
WHEN c.DATA_TYPE IN ( 'varchar', 'nvarchar', 'varbinary' )
AND c.CHARACTER_MAXIMUM_LENGTH = -1 THEN c.DATA_TYPE + '(max)'
ELSE c.DATA_TYPE
END AS [TypeName],
c.CHARACTER_MAXIMUM_LENGTH [MaxLength],
CAST(c.NUMERIC_PRECISION AS INTEGER) [Precision],
CAST(c.DATETIME_PRECISION AS INTEGER) AS [DateTimePrecision],
CAST(c.NUMERIC_SCALE AS INTEGER) [Scale],
c.COLLATION_CATALOG [CollationCatalog],
c.COLLATION_SCHEMA [CollationSchema],
c.COLLATION_NAME [CollationName],
c.CHARACTER_SET_CATALOG [CharacterSetCatalog],
c.CHARACTER_SET_SCHEMA [CharacterSetSchema],
c.CHARACTER_SET_NAME [CharacterSetName],
CAST(0 AS BIT) AS [IsMultiSet],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') AS BIT) AS [IsIdentity],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') | CASE
WHEN c.DATA_TYPE = 'timestamp' THEN 1
ELSE 0
END AS BIT) AS [IsStoreGenerated],
c.COLUMN_DEFAULT [Default]
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.VIEWS v
ON c.TABLE_CATALOG = v.TABLE_CATALOG
AND c.TABLE_SCHEMA = v.TABLE_SCHEMA
AND c.TABLE_NAME = v.TABLE_NAME
WHERE NOT
(
v.TABLE_SCHEMA = 'dbo'
AND v.TABLE_NAME IN ( 'syssegments', 'sysconstraints' )
AND SUBSTRING (CAST(SERVERPROPERTY('productversion') AS VARCHAR(20)), 1, 1) = 8
)
) AS [Extent3]) AS [UnionAll1]
ON
(
0 = [UnionAll1].[C1]
)
AND
(
[Extent1].[Id] = [UnionAll1].[ParentId]
)
LEFT OUTER JOIN (SELECT
[UnionAll2].[Id] AS [C1],
CAST(1 AS BIT) AS [C2]
FROM (SELECT
QUOTENAME(tc.CONSTRAINT_SCHEMA)
+ QUOTENAME(tc.CONSTRAINT_NAME) [Id],
QUOTENAME(tc.TABLE_SCHEMA)
+ QUOTENAME(tc.TABLE_NAME) [ParentId],
tc.CONSTRAINT_NAME [Name],
tc.CONSTRAINT_TYPE [ConstraintType],
CAST(CASE tc.IS_DEFERRABLE
WHEN 'NO' THEN 0
ELSE 1
END AS BIT) [IsDeferrable],
CAST(CASE tc.INITIALLY_DEFERRED
WHEN 'NO' THEN 0
ELSE 1
END AS BIT) [IsInitiallyDeferred]
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
WHERE tc.TABLE_NAME IS NOT NULL) AS [Extent4]
INNER JOIN (SELECT
7 AS [C1],
[Extent5].[ConstraintId] AS [ConstraintId],
[Extent6].[Id] AS [Id]
FROM (SELECT
QUOTENAME(CONSTRAINT_SCHEMA)
+ QUOTENAME(CONSTRAINT_NAME) [ConstraintId],
QUOTENAME(TABLE_SCHEMA)
+ QUOTENAME(TABLE_NAME)
+ QUOTENAME(COLUMN_NAME) [ColumnId]
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE) AS [Extent5]
INNER JOIN (SELECT
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME)
+ QUOTENAME(c.COLUMN_NAME) [Id],
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME) [ParentId],
c.COLUMN_NAME [Name],
c.ORDINAL_POSITION [Ordinal],
CAST(CASE c.IS_NULLABLE
WHEN 'YES' THEN 1
WHEN 'NO' THEN 0
ELSE 0
END AS BIT) [IsNullable],
CASE
WHEN c.DATA_TYPE IN ( 'varchar', 'nvarchar', 'varbinary' )
AND c.CHARACTER_MAXIMUM_LENGTH = -1 THEN c.DATA_TYPE + '(max)'
ELSE c.DATA_TYPE
END AS [TypeName],
c.CHARACTER_MAXIMUM_LENGTH [MaxLength],
CAST(c.NUMERIC_PRECISION AS INTEGER) [Precision],
CAST(c.DATETIME_PRECISION AS INTEGER) [DateTimePrecision],
CAST(c.NUMERIC_SCALE AS INTEGER) [Scale],
c.COLLATION_CATALOG [CollationCatalog],
c.COLLATION_SCHEMA [CollationSchema],
c.COLLATION_NAME [CollationName],
c.CHARACTER_SET_CATALOG [CharacterSetCatalog],
c.CHARACTER_SET_SCHEMA [CharacterSetSchema],
c.CHARACTER_SET_NAME [CharacterSetName],
CAST(0 AS BIT) AS [IsMultiSet],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') AS BIT) AS [IsIdentity],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') | CASE
WHEN c.DATA_TYPE = 'timestamp' THEN 1
ELSE 0
END AS BIT) AS [IsStoreGenerated],
c.COLUMN_DEFAULT AS [Default]
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.TABLES t
ON c.TABLE_CATALOG = t.TABLE_CATALOG
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE IN ( 'BASE TABLE', 'VIEW' )) AS [Extent6]
ON [Extent6].[Id] = [Extent5].[ColumnId]
UNION ALL
SELECT
11 AS [C1],
[Extent7].[ConstraintId] AS [ConstraintId],
[Extent8].[Id] AS [Id]
FROM (SELECT
CAST(NULL AS NVARCHAR (1)) [ConstraintId],
CAST(NULL AS NVARCHAR (MAX)) [ColumnId]
WHERE 1 = 2) AS [Extent7]
INNER JOIN (SELECT
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME)
+ QUOTENAME(c.COLUMN_NAME) [Id],
QUOTENAME(c.TABLE_SCHEMA)
+ QUOTENAME(c.TABLE_NAME) [ParentId],
c.COLUMN_NAME [Name],
c.ORDINAL_POSITION [Ordinal],
CAST(CASE c.IS_NULLABLE
WHEN 'YES' THEN 1
WHEN 'NO' THEN 0
ELSE 0
END AS BIT) [IsNullable],
CASE
WHEN c.DATA_TYPE IN ( 'varchar', 'nvarchar', 'varbinary' )
AND c.CHARACTER_MAXIMUM_LENGTH = -1 THEN c.DATA_TYPE + '(max)'
ELSE c.DATA_TYPE
END AS [TypeName],
c.CHARACTER_MAXIMUM_LENGTH [MaxLength],
CAST(c.NUMERIC_PRECISION AS INTEGER) [Precision],
CAST(c.DATETIME_PRECISION AS INTEGER) AS [DateTimePrecision],
CAST(c.NUMERIC_SCALE AS INTEGER) [Scale],
c.COLLATION_CATALOG [CollationCatalog],
c.COLLATION_SCHEMA [CollationSchema],
c.COLLATION_NAME [CollationName],
c.CHARACTER_SET_CATALOG [CharacterSetCatalog],
c.CHARACTER_SET_SCHEMA [CharacterSetSchema],
c.CHARACTER_SET_NAME [CharacterSetName],
CAST(0 AS BIT) AS [IsMultiSet],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') AS BIT) AS [IsIdentity],
CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.'
+ QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') | CASE
WHEN c.DATA_TYPE = 'timestamp' THEN 1
ELSE 0
END AS BIT) AS [IsStoreGenerated],
c.COLUMN_DEFAULT [Default]
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN INFORMATION_SCHEMA.VIEWS v
ON c.TABLE_CATALOG = v.TABLE_CATALOG
AND c.TABLE_SCHEMA = v.TABLE_SCHEMA
AND c.TABLE_NAME = v.TABLE_NAME
WHERE NOT
(
v.TABLE_SCHEMA = 'dbo'
AND v.TABLE_NAME IN ( 'syssegments', 'sysconstraints' )
AND SUBSTRING(CAST(SERVERPROPERTY('productversion') AS VARCHAR(20)), 1, 1) = 8
)
) AS [Extent8]
ON [Extent8].[Id] = [Extent7].[ColumnId]) AS [UnionAll2]
ON
(
7 = [UnionAll2].[C1]
)
AND
(
[Extent4].[Id] = [UnionAll2].[ConstraintId]
)
WHERE [Extent4].[ConstraintType] = N'PRIMARY KEY') AS [Project5]
ON [UnionAll1].[Id] = [Project5].[C1]
WHERE NOT
(
[Extent1].[Name] IN ( 'EdmMetadata', '__MigrationHistory' )
)
";
#endregion
#region . Foreign Keys Schema Sql .
private const string ForeignKeysSchemaSql = @"
SELECT
Object_schema_name(f.parent_object_id) AS TableSchema,
Object_name(f.parent_object_id) AS TableName,
Col_name(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
Object_schema_name(f.referenced_object_id) AS ReferenceTableSchema,
Object_name (f.referenced_object_id) AS ReferenceTableName,
Col_name(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName,
f.name AS ForeignKey
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
--WHERE Object_name(f.parent_object_id) = 'Media'
-- OR Object_name (f.referenced_object_id) = 'Media'
ORDER BY
TableName,
ColumnName
";
#endregion
public SqlServerSchemaReader(string connectionString)
{
this.connectionString = connectionString;
}
public IReadOnlyList<ISchemaTable> Read()
{
using (var connection = new SqlConnection(this.connectionString))
{
connection.Open();
return this.InternalRead(connection);
}
}
private IReadOnlyList<ISchemaTable> InternalRead(SqlConnection connection)
{
var foreignKeys = this.LoadForeignKeySchemas(connection).ToList();
var tables = new List<SqlSchemaTable>();
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = TablesSchemaSql;
SqlSchemaTable table = null;
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
var tableName = reader["TableName"].ToString().Trim();
var schemaName = reader["SchemaName"].ToString().Trim();
//create table if one was not created before, and add the foreign keys plus the related keys
if(table == null || !table.Schema.Equals(schemaName) || !table.Name.Equals(tableName))
{
table = new SqlSchemaTable(
tableName,
schemaName,
bool.Parse(reader["IsView"].ToString()));
table.ForeignKeys.AddRange(
foreignKeys.Where(
key =>
key.ForeignKeySchema.Equals(table.Schema) && key.ForeignKeyTableName.Equals(table.Name) ||
key.PrimaryKeySchema.Equals(table.Schema) && key.PrimaryKeyTableName.Equals(table.Name)));
tables.Add(table);
}
var columnSchema = new SqlSchemaColumn(
reader["ColumnName"].ToString().Trim(),
reader["TypeName"].ToString().Trim(),
this.GetPropertyTypeFromSqlType(reader["TypeName"].ToString().Trim()),
(int) reader["DateTimePrecision"],
reader["DefaultValue"].ToString().Trim(),
(int) reader["MaxLength"],
(int) reader["Precision"],
(int) reader["Scale"],
(int) reader["Ordinal"],
reader["IsIdentity"].ToString().Trim().ToLower() == "true",
reader["IsNullable"].ToString().Trim().ToLower() == "true",
reader["IsPrimaryKey"].ToString().Trim().ToLower() == "true",
reader["IsStoreGenerated"].ToString().Trim().ToLower() == "true");
table.Columns.Add(columnSchema);
}
}
}
return tables.AsReadOnly();
}
#region . Helpers .
private IEnumerable<ISchemaForeignKey> LoadForeignKeySchemas(SqlConnection connection)
{
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = ForeignKeysSchemaSql;
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
yield return new SqlSchemaForeignKey(
reader["TableSchema"].ToString(),
reader["TableName"].ToString(),
reader["ColumnName"].ToString(),
reader["ReferenceTableSchema"].ToString(),
reader["ReferenceTableName"].ToString(),
reader["ReferenceColumnName"].ToString(),
reader["ForeignKey"].ToString());
}
}
}
}
private string GetPropertyTypeFromSqlType(string sqlType)
{
var sysTypes = new Dictionary<string, string>
{
{"bigint", "long"},
{"smallint", "short"},
{"int", "int"},
{"uniqueidentifier", "Guid"},
{"smalldatetime", "DateTime"},
{"datetime", "DateTime"},
{"datetime2", "DateTime"},
{"date", "DateTime"},
{"datetimeoffset", "DateTimeOffset"},
{"time", "TimeSpan"},
{"float", "double"},
{"real", "float"},
{"numeric", "decimal"},
{"smallmoney", "decimal"},
{"decimal", "decimal"},
{"money", "decimal"},
{"tinyint", "byte"},
{"bit", "bool"},
{"binary", "byte[]"},
{"varbinary", "byte[]"},
{"varbinary(max)", "byte[]"},
{"geography", "DbGeography"},
{"geometry", "DbGeometry"},
};
var sysType = "";
sysTypes.TryGetValue(sqlType, out sysType);
if (sysType.IsBlank())
{
sysType = "string";
}
return sysType;
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.UserModel
{
using System;
using NUnit.Framework;
using NPOI.SS;
using System.Collections;
using TestCases.SS;
using NPOI.SS.UserModel;
/**
* A base class for Testing implementations of
* {@link NPOI.SS.UserModel.Row}
*/
public class BaseTestRow
{
private ITestDataProvider _testDataProvider;
public BaseTestRow()
: this(TestCases.HSSF.HSSFITestDataProvider.Instance)
{ }
protected BaseTestRow(ITestDataProvider TestDataProvider)
{
_testDataProvider = TestDataProvider;
}
[Test]
public void TestLastAndFirstColumns()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
Assert.AreEqual(-1, row.FirstCellNum);
Assert.AreEqual(-1, row.LastCellNum);
//getting cells from an empty row should returns null
for (int i = 0; i < 10; i++) Assert.IsNull(row.GetCell(i));
row.CreateCell(2);
Assert.AreEqual(2, row.FirstCellNum);
Assert.AreEqual(3, row.LastCellNum);
row.CreateCell(1);
Assert.AreEqual(1, row.FirstCellNum);
Assert.AreEqual(3, row.LastCellNum);
// check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based
row.CreateCell(3);
Assert.AreEqual(1, row.FirstCellNum);
Assert.AreEqual(4, row.LastCellNum);
}
/**
* Make sure that there is no cross-talk between rows especially with GetFirstCellNum and GetLastCellNum
* This Test was Added in response to bug report 44987.
*/
[Test]
public void TestBoundsInMultipleRows()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow rowA = sheet.CreateRow(0);
rowA.CreateCell(10);
rowA.CreateCell(5);
Assert.AreEqual(5, rowA.FirstCellNum);
Assert.AreEqual(11, rowA.LastCellNum);
IRow rowB = sheet.CreateRow(1);
rowB.CreateCell(15);
rowB.CreateCell(30);
Assert.AreEqual(15, rowB.FirstCellNum);
Assert.AreEqual(31, rowB.LastCellNum);
Assert.AreEqual(5, rowA.FirstCellNum);
Assert.AreEqual(11, rowA.LastCellNum);
rowA.CreateCell(50);
Assert.AreEqual(51, rowA.LastCellNum);
Assert.AreEqual(31, rowB.LastCellNum);
}
[Test]
public void TestRemoveCell()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
Assert.AreEqual(0, row.PhysicalNumberOfCells);
Assert.AreEqual(-1, row.LastCellNum);
Assert.AreEqual(-1, row.FirstCellNum);
row.CreateCell(1);
Assert.AreEqual(2, row.LastCellNum);
Assert.AreEqual(1, row.FirstCellNum);
Assert.AreEqual(1, row.PhysicalNumberOfCells);
row.CreateCell(3);
Assert.AreEqual(4, row.LastCellNum);
Assert.AreEqual(1, row.FirstCellNum);
Assert.AreEqual(2, row.PhysicalNumberOfCells);
row.RemoveCell(row.GetCell(3));
Assert.AreEqual(2, row.LastCellNum);
Assert.AreEqual(1, row.FirstCellNum);
Assert.AreEqual(1, row.PhysicalNumberOfCells);
row.RemoveCell(row.GetCell(1));
Assert.AreEqual(-1, row.LastCellNum);
Assert.AreEqual(-1, row.FirstCellNum);
Assert.AreEqual(0, row.PhysicalNumberOfCells);
workbook = _testDataProvider.WriteOutAndReadBack(workbook);
sheet = workbook.GetSheetAt(0);
row = sheet.GetRow(0);
Assert.AreEqual(-1, row.LastCellNum);
Assert.AreEqual(-1, row.FirstCellNum);
Assert.AreEqual(0, row.PhysicalNumberOfCells);
}
public void BaseTestRowBounds(int maxRowNum)
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
//Test low row bound
sheet.CreateRow(0);
//Test low row bound exception
try
{
sheet.CreateRow(-1);
Assert.Fail("expected exception");
}
catch (ArgumentException e)
{
// expected during successful Test
Assert.IsTrue(e.Message.StartsWith("Invalid row number (-1)"));
}
//Test high row bound
sheet.CreateRow(maxRowNum);
//Test high row bound exception
try
{
sheet.CreateRow(maxRowNum + 1);
Assert.Fail("expected exception");
}
catch (ArgumentException e)
{
// expected during successful Test
Assert.AreEqual("Invalid row number (" + (maxRowNum + 1) + ") outside allowable range (0.." + maxRowNum + ")", e.Message);
}
}
public void BaseTestCellBounds(int maxCellNum)
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
//Test low cell bound
try
{
row.CreateCell(-1);
Assert.Fail("expected exception");
}
catch (ArgumentException e)
{
// expected during successful Test
Assert.IsTrue(e.Message.StartsWith("Invalid column index (-1)"));
}
//Test high cell bound
try
{
row.CreateCell(maxCellNum + 1);
Assert.Fail("expected exception");
}
catch (ArgumentException e)
{
// expected during successful Test
Assert.IsTrue(e.Message.StartsWith("Invalid column index (" + (maxCellNum + 1) + ")"));
}
for (int i = 0; i < maxCellNum; i++)
{
row.CreateCell(i);
}
Assert.AreEqual(maxCellNum, row.PhysicalNumberOfCells);
workbook = _testDataProvider.WriteOutAndReadBack(workbook);
sheet = workbook.GetSheetAt(0);
row = sheet.GetRow(0);
Assert.AreEqual(maxCellNum, row.PhysicalNumberOfCells);
for (int i = 0; i < maxCellNum; i++)
{
ICell cell = row.GetCell(i);
Assert.AreEqual(i, cell.ColumnIndex);
}
}
/**
* Prior to patch 43901, POI was producing files with the wrong last-column
* number on the row
*/
[Test]
public void TestLastCellNumIsCorrectAfterAddCell_bug43901()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet("test");
IRow row = sheet.CreateRow(0);
// New row has last col -1
Assert.AreEqual(-1, row.LastCellNum);
if (row.LastCellNum == 0)
{
Assert.Fail("Identified bug 43901");
}
// Create two cells, will return one higher
// than that for the last number
row.CreateCell(0);
Assert.AreEqual(1, row.LastCellNum);
row.CreateCell(255);
Assert.AreEqual(256, row.LastCellNum);
}
/**
* Tests for the missing/blank cell policy stuff
*/
[Test]
public void TestGetCellPolicy()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet("test");
IRow row = sheet.CreateRow(0);
// 0 -> string
// 1 -> num
// 2 missing
// 3 missing
// 4 -> blank
// 5 -> num
row.CreateCell(0).SetCellValue("test");
row.CreateCell(1).SetCellValue(3.2);
row.CreateCell(4, CellType.Blank);
row.CreateCell(5).SetCellValue(4);
// First up, no policy given, uses default
Assert.AreEqual(CellType.String, row.GetCell(0).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(1).CellType);
Assert.AreEqual(null, row.GetCell(2));
Assert.AreEqual(null, row.GetCell(3));
Assert.AreEqual(CellType.Blank, row.GetCell(4).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(5).CellType);
// RETURN_NULL_AND_BLANK - same as default
Assert.AreEqual(CellType.String, row.GetCell(0, MissingCellPolicy.RETURN_NULL_AND_BLANK).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(1, MissingCellPolicy.RETURN_NULL_AND_BLANK).CellType);
Assert.AreEqual(null, row.GetCell(2, MissingCellPolicy.RETURN_NULL_AND_BLANK));
Assert.AreEqual(null, row.GetCell(3, MissingCellPolicy.RETURN_NULL_AND_BLANK));
Assert.AreEqual(CellType.Blank, row.GetCell(4, MissingCellPolicy.RETURN_NULL_AND_BLANK).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(5, MissingCellPolicy.RETURN_NULL_AND_BLANK).CellType);
// RETURN_BLANK_AS_NULL - nearly the same
Assert.AreEqual(CellType.String, row.GetCell(0, MissingCellPolicy.RETURN_BLANK_AS_NULL).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(1, MissingCellPolicy.RETURN_BLANK_AS_NULL).CellType);
Assert.AreEqual(null, row.GetCell(2, MissingCellPolicy.RETURN_BLANK_AS_NULL));
Assert.AreEqual(null, row.GetCell(3, MissingCellPolicy.RETURN_BLANK_AS_NULL));
Assert.AreEqual(null, row.GetCell(4, MissingCellPolicy.RETURN_BLANK_AS_NULL));
Assert.AreEqual(CellType.Numeric, row.GetCell(5, MissingCellPolicy.RETURN_BLANK_AS_NULL).CellType);
// CREATE_NULL_AS_BLANK - Creates as needed
Assert.AreEqual(CellType.String, row.GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
Assert.AreEqual(CellType.Blank, row.GetCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
Assert.AreEqual(CellType.Blank, row.GetCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
Assert.AreEqual(CellType.Blank, row.GetCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellType);
// Check Created ones Get the right column
Assert.AreEqual(0, row.GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
Assert.AreEqual(1, row.GetCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
Assert.AreEqual(2, row.GetCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
Assert.AreEqual(3, row.GetCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
Assert.AreEqual(4, row.GetCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
Assert.AreEqual(5, row.GetCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).ColumnIndex);
// Now change the cell policy on the workbook, check
// that that is now used if no policy given
workbook.MissingCellPolicy = (MissingCellPolicy.RETURN_BLANK_AS_NULL);
Assert.AreEqual(CellType.String, row.GetCell(0).CellType);
Assert.AreEqual(CellType.Numeric, row.GetCell(1).CellType);
Assert.AreEqual(null, row.GetCell(2));
Assert.AreEqual(null, row.GetCell(3));
Assert.AreEqual(null, row.GetCell(4));
Assert.AreEqual(CellType.Numeric, row.GetCell(5).CellType);
}
[Test]
public void TestRowHeight()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row1 = sheet.CreateRow(0);
Assert.AreEqual(sheet.DefaultRowHeight, row1.Height);
sheet.DefaultRowHeightInPoints = (/*setter*/20);
row1.Height = (short)-1; //reset the row height
Assert.AreEqual(20.0f, row1.HeightInPoints, 0F);
Assert.AreEqual(20 * 20, row1.Height);
IRow row2 = sheet.CreateRow(1);
Assert.AreEqual(sheet.DefaultRowHeight, row2.Height);
row2.Height = (short)310;
Assert.AreEqual(310, row2.Height);
Assert.AreEqual(310F / 20, row2.HeightInPoints, 0F);
IRow row3 = sheet.CreateRow(2);
row3.HeightInPoints = (/*setter*/25.5f);
Assert.AreEqual((short)(25.5f * 20), row3.Height);
Assert.AreEqual(25.5f, row3.HeightInPoints, 0F);
IRow row4 = sheet.CreateRow(3);
Assert.IsFalse(row4.ZeroHeight);
row4.ZeroHeight = (/*setter*/true);
Assert.IsTrue(row4.ZeroHeight);
workbook = _testDataProvider.WriteOutAndReadBack(workbook);
sheet = workbook.GetSheetAt(0);
row1 = sheet.GetRow(0);
row2 = sheet.GetRow(1);
row3 = sheet.GetRow(2);
row4 = sheet.GetRow(3);
Assert.AreEqual(20.0f, row1.HeightInPoints, 0F);
Assert.AreEqual(20 * 20, row1.Height);
Assert.AreEqual(310, row2.Height);
Assert.AreEqual(310F / 20, row2.HeightInPoints, 0F);
Assert.AreEqual((short)(25.5f * 20), row3.Height);
Assert.AreEqual(25.5f, row3.HeightInPoints, 0F);
Assert.IsFalse(row1.ZeroHeight);
Assert.IsFalse(row2.ZeroHeight);
Assert.IsFalse(row3.ZeroHeight);
Assert.IsTrue(row4.ZeroHeight);
}
/**
* Test Adding cells to a row in various places and see if we can find them again.
*/
[Test]
public void TestCellIterator()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
// One cell at the beginning
ICell cell1 = row.CreateCell(1);
IEnumerator it = row.GetEnumerator();
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell1 == it.Current);
Assert.IsFalse(it.MoveNext());
// Add another cell at the end
ICell cell2 = row.CreateCell(99);
it = row.GetEnumerator();
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell1 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell2 == it.Current);
// Add another cell at the beginning
ICell cell3 = row.CreateCell(0);
it = row.GetEnumerator();
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell3 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell1 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell2 == it.Current);
// Replace cell1
ICell cell4 = row.CreateCell(1);
it = row.GetEnumerator();
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell3 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell4 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell2 == it.Current);
Assert.IsFalse(it.MoveNext());
// Add another cell, specifying the cellType
ICell cell5 = row.CreateCell(2, CellType.String);
it = row.GetEnumerator();
Assert.IsNotNull(cell5);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell3 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell4 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell5 == it.Current);
Assert.IsTrue(it.MoveNext());
Assert.IsTrue(cell2 == it.Current);
Assert.AreEqual(CellType.String, cell5.CellType);
}
[Test]
public void TestRowStyle()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet("test");
IRow row1 = sheet.CreateRow(0);
IRow row2 = sheet.CreateRow(1);
// Won't be styled currently
Assert.AreEqual(false, row1.IsFormatted);
Assert.AreEqual(false, row2.IsFormatted);
Assert.AreEqual(null, row1.RowStyle);
Assert.AreEqual(null, row2.RowStyle);
// Style one
ICellStyle style = workbook.CreateCellStyle();
style.DataFormat = (/*setter*/(short)4);
row2.RowStyle = (/*setter*/style);
// Check
Assert.AreEqual(false, row1.IsFormatted);
Assert.AreEqual(true, row2.IsFormatted);
Assert.AreEqual(null, row1.RowStyle);
Assert.AreEqual(style, row2.RowStyle);
// Save, load and re-check
workbook = _testDataProvider.WriteOutAndReadBack(workbook);
sheet = workbook.GetSheetAt(0);
row1 = sheet.GetRow(0);
row2 = sheet.GetRow(1);
style = workbook.GetCellStyleAt(style.Index);
Assert.AreEqual(false, row1.IsFormatted);
Assert.AreEqual(true, row2.IsFormatted);
Assert.AreEqual(null, row1.RowStyle);
Assert.AreEqual(style, row2.RowStyle);
Assert.AreEqual(4, style.DataFormat);
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
// ReSharper disable CheckNamespace
namespace Mono.Options
// ReSharper restore CheckNamespace
#endif
{
static class StringCoda {
public static IEnumerable<string> WrappedLines (string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines (self, w);
}
public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
{
if (widths == null)
throw new ArgumentNullException ("widths");
return CreateWrappedLinesIterator (self, widths);
}
private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty (self)) {
yield return string.Empty;
yield break;
}
using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
bool? hw = null;
int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
int start = 0, end;
do {
end = GetLineEnd (start, width, self);
char c = self [end-1];
if (char.IsWhiteSpace (c))
--end;
bool needContinuation = end != self.Length && !IsEolChar (c);
string continuation = "";
if (needContinuation) {
--end;
continuation = "-";
}
string line = self.Substring (start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
width = GetNextWidth (ewidths, width, ref hw);
} while (start < self.Length);
}
}
private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
throw new ArgumentOutOfRangeException ("widths",
string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.description = description;
this.count = maxValueCount;
this.names = (this is OptionSet.Category)
// append GetHashCode() so that "duplicate" categories have distinct
// names, e.g. adding multiple "" categories should be valid.
? new[]{prototype + this.GetHashCode ()}
: prototype.Split ('|');
if (this is OptionSet.Category)
return;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
public abstract class ArgumentSource {
protected ArgumentSource ()
{
}
public abstract string[] GetNames ();
public abstract string Description { get; }
public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
public static IEnumerable<string> GetArgumentsFromFile (string file)
{
return GetArguments (File.OpenText (file), true);
}
public static IEnumerable<string> GetArguments (TextReader reader)
{
return GetArguments (reader, false);
}
// Cribbed from mcs/driver.cs:LoadArgs(string)
static IEnumerable<string> GetArguments (TextReader reader, bool close)
{
try {
StringBuilder arg = new StringBuilder ();
string line;
while ((line = reader.ReadLine ()) != null) {
int t = line.Length;
for (int i = 0; i < t; i++) {
char c = line [i];
if (c == '"' || c == '\'') {
char end = c;
for (i++; i < t; i++){
c = line [i];
if (c == end)
break;
arg.Append (c);
}
} else if (c == ' ') {
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
} else
arg.Append (c);
}
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
}
}
finally {
if (close)
reader.Close ();
}
}
}
public class ResponseFileSource : ArgumentSource {
public override string[] GetNames ()
{
return new string[]{"@file"};
}
public override string Description {
get {return "Read response file for more options.";}
}
public override bool GetArguments (string value, out IEnumerable<string> replacement)
{
if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
replacement = null;
return false;
}
replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
return true;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
List<ArgumentSource> sources = new List<ArgumentSource> ();
ReadOnlyCollection<ArgumentSource> roSources;
public ReadOnlyCollection<ArgumentSource> ArgumentSources {
get {return roSources;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
Option p = Items [index];
base.RemoveItem (index);
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public OptionSet Add (string header)
{
if (header == null)
throw new ArgumentNullException ("header");
Add (new Category (header));
return this;
}
internal sealed class Category : Option {
// Prototype starts with '=' because this is an invalid prototype
// (see Option.ParsePrototype(), and thus it'll prevent Category
// instances from being accidentally used as normal options.
public Category (string description)
: base ("=:Category:= " + description, description)
{
}
protected override void OnParseComplete (OptionContext c)
{
throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
public OptionSet Add (ArgumentSource source)
{
if (source == null)
throw new ArgumentNullException ("source");
sources.Add (source);
return this;
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
public List<string> Parse (IEnumerable<string> arguments)
{
if (arguments == null)
throw new ArgumentNullException ("arguments");
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
foreach (string argument in ae) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (AddSource (ae, argument))
continue;
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
class ArgumentEnumerator : IEnumerable<string> {
List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
public ArgumentEnumerator (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public void Add (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public IEnumerator<string> GetEnumerator ()
{
do {
IEnumerator<string> c = sources [sources.Count-1];
if (c.MoveNext ())
yield return c.Current;
else {
c.Dispose ();
sources.RemoveAt (sources.Count-1);
}
} while (sources.Count > 0);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
bool AddSource (ArgumentEnumerator ae, string argument)
{
foreach (ArgumentSource source in sources) {
IEnumerable<string> replacement;
if (!source.GetArguments (argument, out replacement))
continue;
ae.Add (replacement);
return true;
}
return false;
}
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
private const int Description_FirstWidth = 80 - OptionWidth;
private const int Description_RemWidth = 80 - OptionWidth - 2;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
Category c = p as Category;
if (c != null) {
WriteDescription (o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
foreach (ArgumentSource s in sources) {
string[] names = s.GetNames ();
if (names == null || names.Length == 0)
continue;
int written = 0;
Write (o, ref written, " ");
Write (o, ref written, names [0]);
for (int i = 1; i < names.Length; ++i) {
Write (o, ref written, ", ");
Write (o, ref written, names [i]);
}
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
}
void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
bool indent = false;
foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
{
return StringCoda.WrappedLines (description, firstWidth, remWidth);
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Redis/
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2014 Service Stack LLC. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using ServiceStack.Caching;
using ServiceStack.Data;
using ServiceStack.Model;
using ServiceStack.Redis.Generic;
using ServiceStack.Redis.Pipeline;
namespace ServiceStack.Redis
{
public interface IRedisClient
: IEntityStore, ICacheClientExtended
{
//Basic Redis Connection operations
long Db { get; set; }
long DbSize { get; }
Dictionary<string, string> Info { get; }
DateTime GetServerTime();
DateTime LastSave { get; }
string Host { get; }
int Port { get; }
int ConnectTimeout { get; set; }
int RetryTimeout { get; set; }
int RetryCount { get; set; }
int SendTimeout { get; set; }
string Password { get; set; }
bool HadExceptions { get; }
RedisText Custom(params object[] cmdWithArgs);
void Save();
void SaveAsync();
void Shutdown();
void RewriteAppendOnlyFileAsync();
void FlushDb();
RedisText GetServerRoleInfo();
string GetConfig(string item);
void SetConfig(string item, string value);
void SaveConfig();
void ResetInfoStats();
string GetClient();
void SetClient(string name);
void KillClient(string address);
long KillClients(string fromAddress = null, string withId = null, RedisClientType? ofType = null, bool? skipMe = null);
List<Dictionary<string, string>> GetClientsInfo();
void PauseAllClients(TimeSpan duration);
//Basic Redis Connection Info
string this[string key] { get; set; }
List<string> GetAllKeys();
void SetEntry(string key, string value);
void SetEntry(string key, string value, TimeSpan expireIn);
bool SetEntryIfNotExists(string key, string value);
void SetAll(IEnumerable<string> keys, IEnumerable<string> values);
void SetAll(Dictionary<string, string> map);
string GetEntry(string key);
string GetValue(string key);
string GetAndSetEntry(string key, string value);
List<string> GetValues(List<string> keys);
List<T> GetValues<T>(List<string> keys);
Dictionary<string, string> GetValuesMap(List<string> keys);
Dictionary<string, T> GetValuesMap<T>(List<string> keys);
long AppendToValue(string key, string value);
void RenameKey(string fromName, string toName);
//store POCOs as hash
T GetFromHash<T>(object id);
void StoreAsHash<T>(T entity);
object StoreObject(object entity);
bool ContainsKey(string key);
bool RemoveEntry(params string[] args);
long IncrementValue(string key);
long IncrementValueBy(string key, int count);
long IncrementValueBy(string key, long count);
double IncrementValueBy(string key, double count);
long DecrementValue(string key);
long DecrementValueBy(string key, int count);
List<string> SearchKeys(string pattern);
RedisKeyType GetEntryType(string key);
string GetRandomKey();
bool ExpireEntryIn(string key, TimeSpan expireIn);
bool ExpireEntryAt(string key, DateTime expireAt);
List<string> GetSortedEntryValues(string key, int startingFrom, int endingAt);
//Store entities without registering entity ids
void WriteAll<TEntity>(IEnumerable<TEntity> entities);
//Scan APIs
IEnumerable<string> ScanAllKeys(string pattern = null, int pageSize = 1000);
IEnumerable<string> ScanAllSetItems(string setId, string pattern = null, int pageSize = 1000);
IEnumerable<KeyValuePair<string, double>> ScanAllSortedSetItems(string setId, string pattern = null, int pageSize = 1000);
IEnumerable<KeyValuePair<string, string>> ScanAllHashEntries(string hashId, string pattern = null, int pageSize = 1000);
//Hyperlog APIs
bool AddToHyperLog(string key, params string[] elements);
long CountHyperLog(string key);
void MergeHyperLogs(string toKey, params string[] fromKeys);
/// <summary>
/// Returns a high-level typed client API
/// </summary>
/// <typeparam name="T"></typeparam>
IRedisTypedClient<T> As<T>();
IHasNamed<IRedisList> Lists { get; set; }
IHasNamed<IRedisSet> Sets { get; set; }
IHasNamed<IRedisSortedSet> SortedSets { get; set; }
IHasNamed<IRedisHash> Hashes { get; set; }
IRedisTransaction CreateTransaction();
IRedisPipeline CreatePipeline();
IDisposable AcquireLock(string key);
IDisposable AcquireLock(string key, TimeSpan timeOut);
#region Redis pubsub
void Watch(params string[] keys);
void UnWatch();
IRedisSubscription CreateSubscription();
long PublishMessage(string toChannel, string message);
#endregion
#region Set operations
HashSet<string> GetAllItemsFromSet(string setId);
void AddItemToSet(string setId, string item);
void AddRangeToSet(string setId, List<string> items);
void RemoveItemFromSet(string setId, string item);
string PopItemFromSet(string setId);
void MoveBetweenSets(string fromSetId, string toSetId, string item);
long GetSetCount(string setId);
bool SetContainsItem(string setId, string item);
HashSet<string> GetIntersectFromSets(params string[] setIds);
void StoreIntersectFromSets(string intoSetId, params string[] setIds);
HashSet<string> GetUnionFromSets(params string[] setIds);
void StoreUnionFromSets(string intoSetId, params string[] setIds);
HashSet<string> GetDifferencesFromSet(string fromSetId, params string[] withSetIds);
void StoreDifferencesFromSet(string intoSetId, string fromSetId, params string[] withSetIds);
string GetRandomItemFromSet(string setId);
#endregion
#region List operations
List<string> GetAllItemsFromList(string listId);
List<string> GetRangeFromList(string listId, int startingFrom, int endingAt);
List<string> GetRangeFromSortedList(string listId, int startingFrom, int endingAt);
List<string> GetSortedItemsFromList(string listId, SortOptions sortOptions);
void AddItemToList(string listId, string value);
void AddRangeToList(string listId, List<string> values);
void PrependItemToList(string listId, string value);
void PrependRangeToList(string listId, List<string> values);
void RemoveAllFromList(string listId);
string RemoveStartFromList(string listId);
string BlockingRemoveStartFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingRemoveStartFromLists(string[] listIds, TimeSpan? timeOut);
string RemoveEndFromList(string listId);
void TrimList(string listId, int keepStartingFrom, int keepEndingAt);
long RemoveItemFromList(string listId, string value);
long RemoveItemFromList(string listId, string value, int noOfMatches);
long GetListCount(string listId);
string GetItemFromList(string listId, int listIndex);
void SetItemInList(string listId, int listIndex, string value);
//Queue operations
void EnqueueItemOnList(string listId, string value);
string DequeueItemFromList(string listId);
string BlockingDequeueItemFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingDequeueItemFromLists(string[] listIds, TimeSpan? timeOut);
//Stack operations
void PushItemToList(string listId, string value);
string PopItemFromList(string listId);
string BlockingPopItemFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingPopItemFromLists(string[] listIds, TimeSpan? timeOut);
string PopAndPushItemBetweenLists(string fromListId, string toListId);
string BlockingPopAndPushItemBetweenLists(string fromListId, string toListId, TimeSpan? timeOut);
#endregion
#region Sorted Set operations
bool AddItemToSortedSet(string setId, string value);
bool AddItemToSortedSet(string setId, string value, double score);
bool AddRangeToSortedSet(string setId, List<string> values, double score);
bool AddRangeToSortedSet(string setId, List<string> values, long score);
bool RemoveItemFromSortedSet(string setId, string value);
string PopItemWithLowestScoreFromSortedSet(string setId);
string PopItemWithHighestScoreFromSortedSet(string setId);
bool SortedSetContainsItem(string setId, string value);
double IncrementItemInSortedSet(string setId, string value, double incrementBy);
double IncrementItemInSortedSet(string setId, string value, long incrementBy);
long GetItemIndexInSortedSet(string setId, string value);
long GetItemIndexInSortedSetDesc(string setId, string value);
List<string> GetAllItemsFromSortedSet(string setId);
List<string> GetAllItemsFromSortedSetDesc(string setId);
List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank);
List<string> GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank);
IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId);
IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank);
IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank);
List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take);
long RemoveRangeFromSortedSet(string setId, int minRank, int maxRank);
long RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore);
long RemoveRangeFromSortedSetByScore(string setId, long fromScore, long toScore);
long GetSortedSetCount(string setId);
long GetSortedSetCount(string setId, string fromStringScore, string toStringScore);
long GetSortedSetCount(string setId, long fromScore, long toScore);
long GetSortedSetCount(string setId, double fromScore, double toScore);
double GetItemScoreInSortedSet(string setId, string value);
long StoreIntersectFromSortedSets(string intoSetId, params string[] setIds);
long StoreUnionFromSortedSets(string intoSetId, params string[] setIds);
List<string> SearchSortedSet(string setId, string start = null, string end = null, int? skip = null, int? take = null);
long SearchSortedSetCount(string setId, string start = null, string end = null);
long RemoveRangeFromSortedSetBySearch(string setId, string start = null, string end = null);
#endregion
#region Hash operations
bool HashContainsEntry(string hashId, string key);
bool SetEntryInHash(string hashId, string key, string value);
bool SetEntryInHashIfNotExists(string hashId, string key, string value);
void SetRangeInHash(string hashId, IEnumerable<KeyValuePair<string, string>> keyValuePairs);
long IncrementValueInHash(string hashId, string key, int incrementBy);
double IncrementValueInHash(string hashId, string key, double incrementBy);
string GetValueFromHash(string hashId, string key);
List<string> GetValuesFromHash(string hashId, params string[] keys);
bool RemoveEntryFromHash(string hashId, string key);
long GetHashCount(string hashId);
List<string> GetHashKeys(string hashId);
List<string> GetHashValues(string hashId);
Dictionary<string, string> GetAllEntriesFromHash(string hashId);
#endregion
#region Eval/Lua operations
string ExecLuaAsString(string luaBody, params string[] args);
string ExecLuaAsString(string luaBody, string[] keys, string[] args);
string ExecLuaShaAsString(string sha1, params string[] args);
string ExecLuaShaAsString(string sha1, string[] keys, string[] args);
long ExecLuaAsInt(string luaBody, params string[] args);
long ExecLuaAsInt(string luaBody, string[] keys, string[] args);
long ExecLuaShaAsInt(string sha1, params string[] args);
long ExecLuaShaAsInt(string sha1, string[] keys, string[] args);
List<string> ExecLuaAsList(string luaBody, params string[] args);
List<string> ExecLuaAsList(string luaBody, string[] keys, string[] args);
List<string> ExecLuaShaAsList(string sha1, params string[] args);
List<string> ExecLuaShaAsList(string sha1, string[] keys, string[] args);
string CalculateSha1(string luaBody);
bool HasLuaScript(string sha1Ref);
Dictionary<string, bool> WhichLuaScriptsExists(params string[] sha1Refs);
void RemoveAllLuaScripts();
void KillRunningLuaScript();
string LoadLuaScript(string body);
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using Mono.Cecil.Cil;
namespace Mono.Cecil.Tests
{
public class ILFormatter
{
public bool IncludeSequencePoints { get; set; }
public ILFormatter(bool includeSequencePoints)
{
IncludeSequencePoints = includeSequencePoints;
}
public string FormatInstruction(Instruction instruction)
{
var writer = new StringWriter();
WriteInstruction(writer, instruction);
return writer.ToString();
}
public string FormatType(TypeDefinition type)
{
var writer = new StringWriter();
var indentedWriter = new IndentedTextWriter(writer);
WriteType(indentedWriter, type);
return writer.ToString();
}
public string FormatMethodBody(MethodDefinition method)
{
var writer = new StringWriter();
var indentedWriter = new IndentedTextWriter(writer);
WriteMethodBody(indentedWriter, method.Body);
return writer.ToString();
}
public void WriteType(IndentedTextWriter writer, TypeDefinition type)
{
writer.Write(".class ");
if (type.IsPublic)
writer.Write("public ");
writer.WriteLine(type.Name);
writer.WriteLine("{");
writer.Indent++;
foreach (var method in type.Methods)
WriteMethod(writer, method);
foreach (var nestedType in type.NestedTypes)
WriteType(writer, nestedType);
writer.Indent--;
writer.WriteLine("}");
}
public void WriteMethod(IndentedTextWriter writer, MethodDefinition method)
{
writer.Write(".method ");
if (method.IsPublic)
writer.Write("public ");
if (method.IsStatic)
writer.Write("static ");
writer.Write($"{method.ReturnType.FullName} ");
writer.WriteLine(method.Name);
writer.WriteLine("{");
writer.Indent++;
WriteMethodBody(writer, method.Body);
writer.Indent--;
writer.WriteLine("}");
}
public void WriteMethodBody(IndentedTextWriter writer, MethodBody body)
{
WriteVariables(writer, body);
foreach (Instruction instruction in body.Instructions)
{
foreach (var tryStart in body.ExceptionHandlers.Where(a => a.TryStart.Equals(instruction)))
{
writer.WriteLine(".try");
writer.WriteLine("{");
writer.Indent++;
}
foreach (var tryEnd in body.ExceptionHandlers.Where(a => a.TryEnd.Equals(instruction)))
{
writer.Indent--;
writer.WriteLine("}");
}
foreach (var handlerStart in body.ExceptionHandlers.Where(a => a.HandlerStart.Equals(instruction)))
{
writer.WriteLine(FormatHandlerType(handlerStart));
writer.WriteLine("{");
writer.Indent++;
}
foreach (var handlerEnd in body.ExceptionHandlers.Where(a => a.HandlerEnd.Equals(instruction)))
{
writer.Indent--;
writer.WriteLine("}");
}
WriteInstructionLine(writer, body, instruction);
}
}
private void WriteInstructionLine(IndentedTextWriter writer, MethodBody body, Instruction instruction)
{
if (IncludeSequencePoints)
{
var sequence_point = body.Method.DebugInformation.GetSequencePoint(instruction);
if (sequence_point != null)
{
WriteSequencePoint(writer, sequence_point);
writer.WriteLine();
}
}
WriteInstruction(writer, instruction);
writer.WriteLine();
}
void WriteVariables(TextWriter writer, MethodBody body)
{
var variables = body.Variables;
writer.Write(".locals {0}(", body.InitLocals ? "init " : string.Empty);
for (int i = 0; i < variables.Count; i++)
{
if (i > 0)
writer.Write(", ");
var variable = variables[i];
writer.Write("{0} {1}", variable.VariableType, GetVariableName(variable, body));
}
writer.WriteLine(")");
}
string GetVariableName(VariableDefinition variable, MethodBody body)
{
if (body.Method.DebugInformation.TryGetName(variable, out var name))
return name;
return variable.ToString();
}
void WriteInstruction(TextWriter writer, Instruction instruction)
{
writer.Write(FormatLabel(instruction.Offset));
writer.Write(": ");
writer.Write(instruction.OpCode.Name);
if (null != instruction.Operand)
{
writer.Write(' ');
WriteOperand(writer, instruction.Operand);
}
if (instruction.OpCode == OpCodes.Ldarg_0)
{
writer.Write(" // this");
}
}
void WriteSequencePoint(TextWriter writer, SequencePoint sequence_point)
{
if (sequence_point.IsHidden)
{
writer.Write(".line hidden '{0}'", sequence_point.Document.Url);
return;
}
writer.Write($"// [{sequence_point.StartLine} {sequence_point.EndLine} - {sequence_point.StartColumn} {sequence_point.EndColumn}]");
}
string FormatLabel(int offset)
{
string label = "000" + offset.ToString("x");
return "IL_" + label.Substring(label.Length - 4);
}
void WriteOperand(TextWriter writer, object operand)
{
if (null == operand) throw new ArgumentNullException(nameof(operand));
var target = operand as Instruction;
if (null != target)
{
writer.Write(FormatLabel(target.Offset));
return;
}
var targets = operand as Instruction[];
if (null != targets)
{
WriteLabelList(writer, targets);
return;
}
string s = operand as string;
if (null != s)
{
writer.Write("\"" + s + "\"");
return;
}
var parameter = operand as ParameterDefinition;
if (parameter != null)
{
writer.Write(ToInvariantCultureString(parameter.Sequence));
return;
}
s = ToInvariantCultureString(operand);
writer.Write(s);
}
void WriteLabelList(TextWriter writer, Instruction[] instructions)
{
writer.Write("(");
for (int i = 0; i < instructions.Length; i++)
{
if (i != 0) writer.Write(", ");
writer.Write(FormatLabel(instructions[i].Offset));
}
writer.Write(")");
}
string FormatHandlerType(ExceptionHandler handler)
{
var handler_type = handler.HandlerType;
var type = handler_type.ToString().ToLowerInvariant();
switch (handler_type)
{
case ExceptionHandlerType.Catch:
return string.Format("{0} {1}", type, handler.CatchType.FullName);
case ExceptionHandlerType.Filter:
throw new NotImplementedException();
default:
return type;
}
}
public string ToInvariantCultureString(object value)
{
var convertible = value as IConvertible;
return (null != convertible)
? convertible.ToString(System.Globalization.CultureInfo.InvariantCulture)
: value.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.LanguageServerProtocol.Handlers;
using OmniSharp.Models;
using OmniSharp.Models.Diagnostics;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
namespace OmniSharp.LanguageServerProtocol
{
public static class Helpers
{
public static Diagnostic ToDiagnostic(this DiagnosticLocation location)
{
var tags = new List<DiagnosticTag>();
foreach (var tag in location?.Tags ?? Array.Empty<string>())
{
if (tag == "Unnecessary") tags.Add(DiagnosticTag.Unnecessary);
if (tag == "Deprecated") tags.Add(DiagnosticTag.Deprecated);
}
return new Diagnostic()
{
// We don't have a code at the moment
// Code = quickFix.,
Message = !string.IsNullOrWhiteSpace(location.Text) ? location.Text : location.Id,
Range = location.ToRange(),
Severity = ToDiagnosticSeverity(location.LogLevel),
Code = location.Id,
// TODO: We need to forward this type though if we add something like Vb Support
Source = "csharp",
Tags = tags,
};
}
public static Range ToRange(this QuickFix location)
{
return new Range()
{
Start = new Position()
{
Character = location.Column,
Line = location.Line
},
End = new Position()
{
Character = location.EndColumn,
Line = location.EndLine
},
};
}
public static OmniSharp.Models.V2.Range FromRange(Range range)
{
return new OmniSharp.Models.V2.Range
{
Start = new OmniSharp.Models.V2.Point
{
Column = Convert.ToInt32(range.Start.Character),
Line = Convert.ToInt32(range.Start.Line),
},
End = new OmniSharp.Models.V2.Point
{
Column = Convert.ToInt32(range.End.Character),
Line = Convert.ToInt32(range.End.Line),
},
};
}
public static DiagnosticSeverity ToDiagnosticSeverity(string logLevel)
{
// We stringify this value and pass to clients
// should probably use the enum at somepoint
if (Enum.TryParse<Microsoft.CodeAnalysis.DiagnosticSeverity>(logLevel, out var severity))
{
switch (severity)
{
case Microsoft.CodeAnalysis.DiagnosticSeverity.Error:
return DiagnosticSeverity.Error;
case Microsoft.CodeAnalysis.DiagnosticSeverity.Hidden:
return DiagnosticSeverity.Hint;
case Microsoft.CodeAnalysis.DiagnosticSeverity.Info:
return DiagnosticSeverity.Information;
case Microsoft.CodeAnalysis.DiagnosticSeverity.Warning:
return DiagnosticSeverity.Warning;
}
}
return DiagnosticSeverity.Information;
}
public static DocumentUri ToUri(string fileName) => DocumentUri.File(fileName);
public static string FromUri(DocumentUri uri) => uri.GetFileSystemPath().Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
public static Range ToRange((int column, int line) location)
{
return new Range()
{
Start = ToPosition(location),
End = ToPosition(location)
};
}
public static Position ToPosition((int column, int line) location)
{
return new Position(location.line, location.column);
}
public static Position ToPosition(OmniSharp.Models.V2.Point point)
{
return new Position(point.Line, point.Column);
}
public static Range ToRange((int column, int line) start, (int column, int line) end)
{
return new Range()
{
Start = new Position(start.line, start.column),
End = new Position(end.line, end.column)
};
}
public static Range ToRange(OmniSharp.Models.V2.Range range)
{
return new Range()
{
Start = ToPosition(range.Start),
End = ToPosition(range.End)
};
}
private static readonly IDictionary<string, SymbolKind> Kinds = new Dictionary<string, SymbolKind>
{
{ OmniSharp.Models.V2.SymbolKinds.Class, SymbolKind.Class },
{ OmniSharp.Models.V2.SymbolKinds.Delegate, SymbolKind.Class },
{ OmniSharp.Models.V2.SymbolKinds.Enum, SymbolKind.Enum },
{ OmniSharp.Models.V2.SymbolKinds.Interface, SymbolKind.Interface },
{ OmniSharp.Models.V2.SymbolKinds.Struct, SymbolKind.Struct },
{ OmniSharp.Models.V2.SymbolKinds.Constant, SymbolKind.Constant },
{ OmniSharp.Models.V2.SymbolKinds.Constructor, SymbolKind.Constructor },
{ OmniSharp.Models.V2.SymbolKinds.Destructor, SymbolKind.Method },
{ OmniSharp.Models.V2.SymbolKinds.EnumMember, SymbolKind.EnumMember },
{ OmniSharp.Models.V2.SymbolKinds.Event, SymbolKind.Event },
{ OmniSharp.Models.V2.SymbolKinds.Field, SymbolKind.Field },
{ OmniSharp.Models.V2.SymbolKinds.Indexer, SymbolKind.Property },
{ OmniSharp.Models.V2.SymbolKinds.Method, SymbolKind.Method },
{ OmniSharp.Models.V2.SymbolKinds.Operator, SymbolKind.Operator },
{ OmniSharp.Models.V2.SymbolKinds.Property, SymbolKind.Property },
{ OmniSharp.Models.V2.SymbolKinds.Namespace, SymbolKind.Namespace },
{ OmniSharp.Models.V2.SymbolKinds.Unknown, SymbolKind.Class },
};
public static SymbolKind ToSymbolKind(string omnisharpKind)
{
return Kinds.TryGetValue(omnisharpKind.ToLowerInvariant(), out var symbolKind) ? symbolKind : SymbolKind.Class;
}
public static WorkspaceEdit ToWorkspaceEdit(IEnumerable<FileOperationResponse> responses, WorkspaceEditCapability workspaceEditCapability, DocumentVersions documentVersions)
{
workspaceEditCapability ??= new WorkspaceEditCapability();
workspaceEditCapability.ResourceOperations ??= Array.Empty<ResourceOperationKind>();
if (workspaceEditCapability.DocumentChanges)
{
var documentChanges = new List<WorkspaceEditDocumentChange>();
foreach (var response in responses)
{
documentChanges.Add(ToWorkspaceEditDocumentChange(response, workspaceEditCapability,
documentVersions));
}
return new WorkspaceEdit()
{
DocumentChanges = documentChanges
};
}
else
{
var changes = new Dictionary<DocumentUri, IEnumerable<TextEdit>>();
foreach (var response in responses)
{
changes.Add(DocumentUri.FromFileSystemPath(response.FileName), ToTextEdits(response));
}
return new WorkspaceEdit()
{
Changes = changes
};
}
}
public static WorkspaceEditDocumentChange ToWorkspaceEditDocumentChange(FileOperationResponse response, WorkspaceEditCapability workspaceEditCapability, DocumentVersions documentVersions)
{
workspaceEditCapability ??= new WorkspaceEditCapability();
workspaceEditCapability.ResourceOperations ??= Array.Empty<ResourceOperationKind>();
if (response is ModifiedFileResponse modified)
{
return new TextDocumentEdit()
{
Edits = new TextEditContainer(modified.Changes.Select(ToTextEdit)),
TextDocument = new OptionalVersionedTextDocumentIdentifier()
{
Version = documentVersions.GetVersion(DocumentUri.FromFileSystemPath(response.FileName)),
Uri = DocumentUri.FromFileSystemPath(response.FileName)
},
};
}
if (response is RenamedFileResponse rename && workspaceEditCapability.ResourceOperations.Contains(ResourceOperationKind.Rename))
{
return new RenameFile()
{
// Options = new RenameFileOptions()
// {
// Overwrite = true,
// IgnoreIfExists = false
// },
NewUri = DocumentUri.FromFileSystemPath(rename.NewFileName).ToString(),
OldUri = DocumentUri.FromFileSystemPath(rename.FileName).ToString(),
};
}
return default;
}
public static IEnumerable<TextEdit> ToTextEdits(FileOperationResponse response)
{
if (!(response is ModifiedFileResponse modified)) yield break;
foreach (var change in modified.Changes)
{
yield return ToTextEdit(change);
}
}
public static TextEdit ToTextEdit(LinePositionSpanTextChange textChange)
{
return new TextEdit()
{
NewText = textChange.NewText,
Range = ToRange(
(textChange.StartColumn, textChange.StartLine),
(textChange.EndColumn, textChange.EndLine)
)
};
}
public static LinePositionSpanTextChange FromTextEdit(TextEdit textEdit)
=> new LinePositionSpanTextChange
{
NewText = textEdit.NewText,
StartLine = textEdit.Range.Start.Line,
EndLine = textEdit.Range.End.Line,
StartColumn = textEdit.Range.Start.Character,
EndColumn = textEdit.Range.End.Character
};
}
public static class CommandExtensions
{
public static T ExtractArguments<T>(this IExecuteCommandParams @params, ISerializer serializer)
where T : notnull =>
ExtractArguments<T>(@params.Arguments, serializer);
public static T ExtractArguments<T>(this Command @params, ISerializer serializer)
where T : notnull =>
ExtractArguments<T>(@params.Arguments, serializer);
public static (T arg1, T2 arg2) ExtractArguments<T, T2>(this IExecuteCommandParams command, ISerializer serializer)
where T : notnull
where T2 : notnull =>
ExtractArguments<T, T2>(command.Arguments, serializer);
public static (T arg1, T2 arg2) ExtractArguments<T, T2>(this Command command, ISerializer serializer)
where T : notnull
where T2 : notnull =>
ExtractArguments<T, T2>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3) ExtractArguments<T, T2, T3>(this IExecuteCommandParams command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull =>
ExtractArguments<T, T2, T3>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3) ExtractArguments<T, T2, T3>(this Command command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull =>
ExtractArguments<T, T2, T3>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4) ExtractArguments<T, T2, T3, T4>(this IExecuteCommandParams command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull =>
ExtractArguments<T, T2, T3, T4>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4) ExtractArguments<T, T2, T3, T4>(this Command command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull =>
ExtractArguments<T, T2, T3, T4>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) ExtractArguments<T, T2, T3, T4, T5>(this IExecuteCommandParams command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull =>
ExtractArguments<T, T2, T3, T4, T5>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) ExtractArguments<T, T2, T3, T4, T5>(this Command command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull =>
ExtractArguments<T, T2, T3, T4, T5>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) ExtractArguments<T, T2, T3, T4, T5, T6>(this IExecuteCommandParams command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull
where T6 : notnull =>
ExtractArguments<T, T2, T3, T4, T5, T6>(command.Arguments, serializer);
public static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) ExtractArguments<T, T2, T3, T4, T5, T6>(this Command command, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull
where T6 : notnull =>
ExtractArguments<T, T2, T3, T4, T5, T6>(command.Arguments, serializer);
private static T ExtractArguments<T>(JArray args, ISerializer serializer)
where T : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
return arg1!;
}
private static (T arg1, T2 arg2) ExtractArguments<T, T2>(JArray args, ISerializer serializer)
where T : notnull
where T2 : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
T2 arg2 = default;
if (args.Count > 1) arg2 = args[1].ToObject<T2>(serializer.JsonSerializer);
return (arg1!, arg2!);
}
private static (T arg1, T2 arg2, T3 arg3) ExtractArguments<T, T2, T3>(JArray args, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
T2 arg2 = default;
if (args.Count > 1) arg2 = args[1].ToObject<T2>(serializer.JsonSerializer);
T3 arg3 = default;
if (args.Count > 2) arg3 = args[2].ToObject<T3>(serializer.JsonSerializer);
return (arg1!, arg2!, arg3!);
}
private static (T arg1, T2 arg2, T3 arg3, T4 arg4) ExtractArguments<T, T2, T3, T4>(JArray args, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
T2 arg2 = default;
if (args.Count > 1) arg2 = args[1].ToObject<T2>(serializer.JsonSerializer);
T3 arg3 = default;
if (args.Count > 2) arg3 = args[2].ToObject<T3>(serializer.JsonSerializer);
T4 arg4 = default;
if (args.Count > 3) arg4 = args[3].ToObject<T4>(serializer.JsonSerializer);
return (arg1!, arg2!, arg3!, arg4!);
}
private static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) ExtractArguments<T, T2, T3, T4, T5>(JArray args, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
T2 arg2 = default;
if (args.Count > 1) arg2 = args[1].ToObject<T2>(serializer.JsonSerializer);
T3 arg3 = default;
if (args.Count > 2) arg3 = args[2].ToObject<T3>(serializer.JsonSerializer);
T4 arg4 = default;
if (args.Count > 3) arg4 = args[3].ToObject<T4>(serializer.JsonSerializer);
T5 arg5 = default;
if (args.Count > 4) arg5 = args[4].ToObject<T5>(serializer.JsonSerializer);
return (arg1!, arg2!, arg3!, arg4!, arg5!);
}
private static (T arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) ExtractArguments<T, T2, T3, T4, T5, T6>(JArray args, ISerializer serializer)
where T : notnull
where T2 : notnull
where T3 : notnull
where T4 : notnull
where T5 : notnull
where T6 : notnull
{
args ??= new JArray();
T arg1 = default;
if (args.Count > 0) arg1 = args[0].ToObject<T>(serializer.JsonSerializer);
T2 arg2 = default;
if (args.Count > 1) arg2 = args[1].ToObject<T2>(serializer.JsonSerializer);
T3 arg3 = default;
if (args.Count > 2) arg3 = args[2].ToObject<T3>(serializer.JsonSerializer);
T4 arg4 = default;
if (args.Count > 3) arg4 = args[3].ToObject<T4>(serializer.JsonSerializer);
T5 arg5 = default;
if (args.Count > 4) arg5 = args[4].ToObject<T5>(serializer.JsonSerializer);
T6 arg6 = default;
if (args.Count > 5) arg6 = args[5].ToObject<T6>(serializer.JsonSerializer);
return (arg1!, arg2!, arg3!, arg4!, arg5!, arg6!);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Buffers;
namespace System.Data.SqlTypes
{
public sealed partial class SqlFileStream : System.IO.Stream
{
// NOTE: if we ever unseal this class, be sure to specify the Name, SafeFileHandle, and
// TransactionContext accessors as virtual methods. Doing so now on a sealed class
// generates a compiler error (CS0549)
// from System.IO.FileStream implementation
// DefaultBufferSize = 4096;
// SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
// potential exceptions during Close/Finalization. Since System.IO.FileStream will
// not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
// usage, will not be used and the user buffer will automatically flush directly to
// the disk cache. In pathological scenarios where the client is writing a single
// byte at a time, we'll explicitly call flush ourselves.
internal const int DefaultBufferSize = 1;
private const ushort IoControlCodeFunctionCode = 2392;
private const int ERROR_MR_MID_NOT_FOUND = 317;
#region Definitions from devioctl.h
private const ushort FILE_DEVICE_FILE_SYSTEM = 0x0009;
#endregion
private System.IO.FileStream _m_fs;
private string _m_path;
private byte[] _m_txn;
private bool _m_disposed;
private static readonly byte[] s_eaNameString = new byte[]
{
(byte)'F', (byte)'i', (byte)'l', (byte)'e', (byte)'s', (byte)'t', (byte)'r', (byte)'e', (byte)'a', (byte)'m', (byte)'_',
(byte)'T', (byte)'r', (byte)'a', (byte)'n', (byte)'s', (byte)'a', (byte)'c', (byte)'t', (byte)'i', (byte)'o', (byte)'n', (byte)'_',
(byte)'T', (byte)'a', (byte)'g', (byte) '\0'
};
public SqlFileStream(string path, byte[] transactionContext, FileAccess access) :
this(path, transactionContext, access, FileOptions.None, 0)
{ }
public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
{
//-----------------------------------------------------------------
// precondition validation
if (transactionContext == null)
throw ADP.ArgumentNull("transactionContext");
if (path == null)
throw ADP.ArgumentNull("path");
//-----------------------------------------------------------------
_m_disposed = false;
_m_fs = null;
OpenSqlFileStream(path, transactionContext, access, options, allocationSize);
// only set internal state once the file has actually been successfully opened
Name = path;
TransactionContext = transactionContext;
}
#region destructor/dispose code
// NOTE: this destructor will only be called only if the Dispose
// method is not called by a client, giving the class a chance
// to finalize properly (i.e., free unmanaged resources)
~SqlFileStream()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
try
{
if (!_m_disposed)
{
try
{
if (disposing)
{
if (_m_fs != null)
{
_m_fs.Close();
_m_fs = null;
}
}
}
finally
{
_m_disposed = true;
}
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion
public string Name
{
get
{
// assert that path has been properly processed via GetFullPathInternal
// (e.g. m_path hasn't been set directly)
AssertPathFormat(_m_path);
return _m_path;
}
private set
{
// should be validated by callers of this method
Debug.Assert(value != null);
Debug.Assert(!_m_disposed);
_m_path = GetFullPathInternal(value);
}
}
public byte[] TransactionContext
{
get
{
if (_m_txn == null)
return null;
return (byte[])_m_txn.Clone();
}
private set
{
// should be validated by callers of this method
Debug.Assert(value != null);
Debug.Assert(!_m_disposed);
_m_txn = (byte[])value.Clone();
}
}
#region System.IO.Stream methods
public override bool CanRead
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.CanRead;
}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.CanSeek;
}
}
public override bool CanTimeout
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.CanTimeout;
}
}
public override bool CanWrite
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.CanWrite;
}
}
public override long Length
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.Length;
}
}
public override long Position
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.Position;
}
set
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.Position = value;
}
}
public override int ReadTimeout
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.ReadTimeout;
}
set
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.WriteTimeout;
}
set
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.WriteTimeout = value;
}
}
public override void Flush()
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.Flush();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.EndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
IAsyncResult asyncResult = _m_fs.BeginWrite(buffer, offset, count, callback, state);
// SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
// potential exceptions during Close/Finalization. Since System.IO.FileStream will
// not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
// usage, will not be used and the user buffer will automatically flush directly to
// the disk cache. In pathological scenarios where the client is writing a single
// byte at a time, we'll explicitly call flush ourselves.
if (count == 1)
{
// calling flush here will mimic the internal control flow of System.IO.FileStream
_m_fs.Flush();
}
return asyncResult;
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.EndWrite(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.Seek(offset, origin);
}
public override void SetLength(long value)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.SetLength(value);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.Read(buffer, offset, count);
}
public override int ReadByte()
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
return _m_fs.ReadByte();
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.Write(buffer, offset, count);
// SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
// potential exceptions during Close/Finalization. Since System.IO.FileStream will
// not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
// usage, will cause System.IO.FileStream to utilize the user-supplied buffer and
// automatically flush the data directly to the disk cache. In pathological scenarios
// where the user is writing a single byte at a time, we'll explicitly call flush ourselves.
if (count == 1)
{
// calling flush here will mimic the internal control flow of System.IO.FileStream
_m_fs.Flush();
}
}
public override void WriteByte(byte value)
{
if (_m_disposed)
throw ADP.ObjectDisposed(this);
_m_fs.WriteByte(value);
// SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
// potential exceptions during Close/Finalization. Since our internal buffer is
// only a single byte in length, the provided user data will always be cached.
// As a result, we need to be sure to flush the data to disk ourselves.
// calling flush here will mimic the internal control flow of System.IO.FileStream
_m_fs.Flush();
}
#endregion
[Conditional("DEBUG")]
private static void AssertPathFormat(string path)
{
Debug.Assert(path != null);
Debug.Assert(path == path.Trim());
Debug.Assert(path.Length > 0);
Debug.Assert(path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase));
}
private static string GetFullPathInternal(string path)
{
//-----------------------------------------------------------------
// precondition validation should be validated by callers of this method
// NOTE: if this method moves elsewhere, this assert should become an actual runtime check
// as the implicit assumptions here cannot be relied upon in an inter-class context
Debug.Assert(path != null);
// remove leading and trailing whitespace
path = path.Trim();
if (path.Length == 0)
{
throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidPath), "path");
}
// make sure path is not DOS device path
if (!path.StartsWith(@"\\") && !System.IO.PathInternal.IsDevice(path.AsSpan()))
{
throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidPath), "path");
}
// normalize the path
path = System.IO.Path.GetFullPath(path);
// make sure path is a UNC path
if (System.IO.PathInternal.IsDeviceUNC(path.AsSpan()))
{
throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource), "path");
}
return path;
}
private unsafe void OpenSqlFileStream
(
string sPath,
byte[] transactionContext,
System.IO.FileAccess access,
System.IO.FileOptions options,
long allocationSize
)
{
//-----------------------------------------------------------------
// precondition validation
// these should be checked by any caller of this method
// ensure we have validated and normalized the path before
Debug.Assert(sPath != null);
Debug.Assert(transactionContext != null);
if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite)
throw ADP.ArgumentOutOfRange("access");
// FileOptions is a set of flags, so AND the given value against the set of values we do not support
if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0)
throw ADP.ArgumentOutOfRange("options");
//-----------------------------------------------------------------
// normalize the provided path
// * compress path to remove any occurrences of '.' or '..'
// * trim whitespace from the beginning and end of the path
// * ensure that the path starts with '\\'
// * ensure that the path does not start with '\\.\'
sPath = GetFullPathInternal(sPath);
Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;
Interop.NtDll.DesiredAccess nDesiredAccess = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE;
Interop.NtDll.CreateOptions dwCreateOptions = 0;
Interop.NtDll.CreateDisposition dwCreateDisposition = 0;
System.IO.FileShare nShareAccess = System.IO.FileShare.None;
switch (access)
{
case System.IO.FileAccess.Read:
nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA;
nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN;
break;
case System.IO.FileAccess.Write:
nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read;
dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
break;
case System.IO.FileAccess.ReadWrite:
default:
// we validate the value of 'access' parameter in the beginning of this method
Debug.Assert(access == System.IO.FileAccess.ReadWrite);
nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read;
dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
break;
}
if ((options & System.IO.FileOptions.WriteThrough) != 0)
{
dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH;
}
if ((options & System.IO.FileOptions.Asynchronous) == 0)
{
dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
}
if ((options & System.IO.FileOptions.SequentialScan) != 0)
{
dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY;
}
if ((options & System.IO.FileOptions.RandomAccess) != 0)
{
dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS;
}
try
{
// NOTE: the Name property is intended to reveal the publicly available moniker for the
// FILESTREAM attributed column data. We will not surface the internal processing that
// takes place to create the mappedPath.
string mappedPath = InitializeNtPath(sPath);
int retval = 0;
Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode);
try
{
if (transactionContext.Length >= ushort.MaxValue)
throw ADP.ArgumentOutOfRange("transactionContext");
int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION);
int fullSize = headerSize + transactionContext.Length + s_eaNameString.Length;
byte[] buffer = ArrayPool<byte>.Shared.Rent(fullSize);
fixed (byte* b = buffer)
{
Interop.NtDll.FILE_FULL_EA_INFORMATION* ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION*)b;
ea->NextEntryOffset = 0;
ea->Flags = 0;
ea->EaNameLength = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character.
ea->EaValueLength = (ushort)transactionContext.Length;
// We could continue to do pointer math here, chose to use Span for convenience to
// make sure we get the other members in the right place.
Span<byte> data = buffer.AsSpan(headerSize);
s_eaNameString.AsSpan().CopyTo(data);
data = data.Slice(s_eaNameString.Length);
transactionContext.AsSpan().CopyTo(data);
(int status, IntPtr handle) = Interop.NtDll.CreateFile(
path: mappedPath.AsSpan(),
rootDirectory: IntPtr.Zero,
createDisposition: dwCreateDisposition,
desiredAccess: nDesiredAccess,
shareAccess: nShareAccess,
fileAttributes: 0,
createOptions: dwCreateOptions,
eaBuffer: b,
eaLength: (uint)fullSize);
retval = status;
hFile = new SafeFileHandle(handle, true);
}
ArrayPool<byte>.Shared.Return(buffer);
}
finally
{
Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
}
switch (retval)
{
case 0:
break;
case Interop.Errors.ERROR_SHARING_VIOLATION:
throw ADP.InvalidOperation(SR.GetString(SR.SqlFileStream_FileAlreadyInTransaction));
case Interop.Errors.ERROR_INVALID_PARAMETER:
throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidParameter));
case Interop.Errors.ERROR_FILE_NOT_FOUND:
{
System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
ADP.TraceExceptionAsReturnValue(e);
throw e;
}
default:
{
uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
if (error == ERROR_MR_MID_NOT_FOUND)
{
// status code could not be mapped to a Win32 error code
error = (uint)retval;
}
System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked((int)error));
ADP.TraceExceptionAsReturnValue(e);
throw e;
}
}
if (hFile.IsInvalid)
{
System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
ADP.TraceExceptionAsReturnValue(e);
throw e;
}
if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
{
hFile.Dispose();
throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource));
}
// if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
// through current data and then append new data to the end, so we need to tell SQL Server to preserve
// the existing file contents.
if (access == System.IO.FileAccess.ReadWrite)
{
uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
(byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);
if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
{
System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
ADP.TraceExceptionAsReturnValue(e);
throw e;
}
}
// now that we've successfully opened a handle on the path and verified that it is a file,
// use the SafeFileHandle to initialize our internal System.IO.FileStream instance
System.Diagnostics.Debug.Assert(_m_fs == null);
_m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
}
catch
{
if (hFile != null && !hFile.IsInvalid)
hFile.Dispose();
throw;
}
}
// This method exists to ensure that the requested path name is unique so that SMB/DNS is prevented
// from collapsing a file open request to a file handle opened previously. In the SQL FILESTREAM case,
// this would likely be a file open in another transaction, so this mechanism ensures isolation.
private static string InitializeNtPath(string path)
{
// Ensure we have validated and normalized the path before
AssertPathFormat(path);
string uniqueId = Guid.NewGuid().ToString("N");
return System.IO.PathInternal.IsDeviceUNC(path) ? string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", path.Replace(@"\\.", @"\??"), uniqueId)
: string.Format(CultureInfo.InvariantCulture, @"\??\UNC\{0}\{1}", path.Trim('\\'), uniqueId);
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "Event_Condition_instance", IsSet = false)]
public class Event_Condition_instance : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Event_Condition_instance));
private DefinitionChoiceType definition_;
private ObjectName name_;
[ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public ObjectName Name
{
get
{
return name_;
}
set
{
name_ = value;
}
}
[ASN1Element(Name = "definition", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public DefinitionChoiceType Definition
{
get
{
return definition_;
}
set
{
definition_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "definition")]
public class DefinitionChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType));
private DetailsSequenceType details_;
private bool details_selected;
private ObjectIdentifier reference_;
private bool reference_selected;
[ASN1ObjectIdentifier(Name = "")]
[ASN1Element(Name = "reference", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ObjectIdentifier Reference
{
get
{
return reference_;
}
set
{
selectReference(value);
}
}
[ASN1Element(Name = "details", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public DetailsSequenceType Details
{
get
{
return details_;
}
set
{
selectDetails(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isReferenceSelected()
{
return reference_selected;
}
public void selectReference(ObjectIdentifier val)
{
reference_ = val;
reference_selected = true;
details_selected = false;
}
public bool isDetailsSelected()
{
return details_selected;
}
public void selectDetails(DetailsSequenceType val)
{
details_ = val;
details_selected = true;
reference_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "details", IsSet = false)]
public class DetailsSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType));
private Access_Control_List_instance accessControl_;
private bool alarmSummaryReports_;
private bool alarmSummaryReports_present;
private DisplayEnhancementChoiceType displayEnhancement_;
private EC_Class ecClass_;
private EC_State ecState_;
private bool enabled_;
private bool enabled_present;
private long evaluationInterval_;
private bool evaluationInterval_present;
private ICollection<Event_Enrollment_instance> eventEnrollments_;
private Group_Priority_OverrideChoiceType group_Priority_Override_;
private bool group_Priority_Override_present;
private MonitoredVariableChoiceType monitoredVariable_;
private bool monitoredVariable_present;
private Priority priority_;
private ICollection<Event_Condition_List_instance> referencingEventConditionLists_;
private Severity severity_;
[ASN1Element(Name = "accessControl", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public Access_Control_List_instance AccessControl
{
get
{
return accessControl_;
}
set
{
accessControl_ = value;
}
}
[ASN1Element(Name = "ecClass", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public EC_Class EcClass
{
get
{
return ecClass_;
}
set
{
ecClass_ = value;
}
}
[ASN1Element(Name = "ecState", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)]
public EC_State EcState
{
get
{
return ecState_;
}
set
{
ecState_ = value;
}
}
[ASN1Element(Name = "priority", IsOptional = false, HasTag = true, Tag = 6, HasDefaultValue = false)]
public Priority Priority
{
get
{
return priority_;
}
set
{
priority_ = value;
}
}
[ASN1Element(Name = "severity", IsOptional = false, HasTag = true, Tag = 7, HasDefaultValue = false)]
public Severity Severity
{
get
{
return severity_;
}
set
{
severity_ = value;
}
}
[ASN1SequenceOf(Name = "eventEnrollments", IsSetOf = false)]
[ASN1Element(Name = "eventEnrollments", IsOptional = false, HasTag = true, Tag = 8, HasDefaultValue = false)]
public ICollection<Event_Enrollment_instance> EventEnrollments
{
get
{
return eventEnrollments_;
}
set
{
eventEnrollments_ = value;
}
}
[ASN1Boolean(Name = "")]
[ASN1Element(Name = "enabled", IsOptional = true, HasTag = true, Tag = 9, HasDefaultValue = false)]
public bool Enabled
{
get
{
return enabled_;
}
set
{
enabled_ = value;
enabled_present = true;
}
}
[ASN1Boolean(Name = "")]
[ASN1Element(Name = "alarmSummaryReports", IsOptional = true, HasTag = true, Tag = 10, HasDefaultValue = false)]
public bool AlarmSummaryReports
{
get
{
return alarmSummaryReports_;
}
set
{
alarmSummaryReports_ = value;
alarmSummaryReports_present = true;
}
}
[ASN1Element(Name = "monitoredVariable", IsOptional = true, HasTag = false, HasDefaultValue = false)]
public MonitoredVariableChoiceType MonitoredVariable
{
get
{
return monitoredVariable_;
}
set
{
monitoredVariable_ = value;
monitoredVariable_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "evaluationInterval", IsOptional = true, HasTag = true, Tag = 14, HasDefaultValue = false)]
public long EvaluationInterval
{
get
{
return evaluationInterval_;
}
set
{
evaluationInterval_ = value;
evaluationInterval_present = true;
}
}
[ASN1Element(Name = "displayEnhancement", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public DisplayEnhancementChoiceType DisplayEnhancement
{
get
{
return displayEnhancement_;
}
set
{
displayEnhancement_ = value;
}
}
[ASN1Element(Name = "group-Priority-Override", IsOptional = true, HasTag = false, HasDefaultValue = false)]
public Group_Priority_OverrideChoiceType Group_Priority_Override
{
get
{
return group_Priority_Override_;
}
set
{
group_Priority_Override_ = value;
group_Priority_Override_present = true;
}
}
[ASN1SequenceOf(Name = "referencingEventConditionLists", IsSetOf = false)]
[ASN1Element(Name = "referencingEventConditionLists", IsOptional = false, HasTag = true, Tag = 20, HasDefaultValue = false)]
public ICollection<Event_Condition_List_instance> ReferencingEventConditionLists
{
get
{
return referencingEventConditionLists_;
}
set
{
referencingEventConditionLists_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isEnabledPresent()
{
return enabled_present;
}
public bool isAlarmSummaryReportsPresent()
{
return alarmSummaryReports_present;
}
public bool isMonitoredVariablePresent()
{
return monitoredVariable_present;
}
public bool isEvaluationIntervalPresent()
{
return evaluationInterval_present;
}
public bool isGroup_Priority_OverridePresent()
{
return group_Priority_Override_present;
}
[ASN1PreparedElement]
[ASN1Choice(Name = "displayEnhancement")]
public class DisplayEnhancementChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DisplayEnhancementChoiceType));
private NullObject none_;
private bool none_selected;
private long number_;
private bool number_selected;
private MMSString text_;
private bool text_selected;
[ASN1Element(Name = "text", IsOptional = false, HasTag = true, Tag = 15, HasDefaultValue = false)]
public MMSString Text
{
get
{
return text_;
}
set
{
selectText(value);
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "number", IsOptional = false, HasTag = true, Tag = 16, HasDefaultValue = false)]
public long Number
{
get
{
return number_;
}
set
{
selectNumber(value);
}
}
[ASN1Null(Name = "none")]
[ASN1Element(Name = "none", IsOptional = false, HasTag = true, Tag = 17, HasDefaultValue = false)]
public NullObject None
{
get
{
return none_;
}
set
{
selectNone(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isTextSelected()
{
return text_selected;
}
public void selectText(MMSString val)
{
text_ = val;
text_selected = true;
number_selected = false;
none_selected = false;
}
public bool isNumberSelected()
{
return number_selected;
}
public void selectNumber(long val)
{
number_ = val;
number_selected = true;
text_selected = false;
none_selected = false;
}
public bool isNoneSelected()
{
return none_selected;
}
public void selectNone()
{
selectNone(new NullObject());
}
public void selectNone(NullObject val)
{
none_ = val;
none_selected = true;
text_selected = false;
number_selected = false;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "group-Priority-Override")]
public class Group_Priority_OverrideChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Group_Priority_OverrideChoiceType));
private Priority priority_;
private bool priority_selected;
private NullObject undefined_;
private bool undefined_selected;
[ASN1Element(Name = "priority", IsOptional = false, HasTag = true, Tag = 18, HasDefaultValue = false)]
public Priority Priority
{
get
{
return priority_;
}
set
{
selectPriority(value);
}
}
[ASN1Null(Name = "undefined")]
[ASN1Element(Name = "undefined", IsOptional = false, HasTag = true, Tag = 19, HasDefaultValue = false)]
public NullObject Undefined
{
get
{
return undefined_;
}
set
{
selectUndefined(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isPrioritySelected()
{
return priority_selected;
}
public void selectPriority(Priority val)
{
priority_ = val;
priority_selected = true;
undefined_selected = false;
}
public bool isUndefinedSelected()
{
return undefined_selected;
}
public void selectUndefined()
{
selectUndefined(new NullObject());
}
public void selectUndefined(NullObject val)
{
undefined_ = val;
undefined_selected = true;
priority_selected = false;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "monitoredVariable")]
public class MonitoredVariableChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(MonitoredVariableChoiceType));
private Named_Variable_instance named_;
private bool named_selected;
private Unnamed_Variable_instance unnamed_;
private bool unnamed_selected;
private NullObject unspecified_;
private bool unspecified_selected;
[ASN1Element(Name = "named", IsOptional = false, HasTag = true, Tag = 11, HasDefaultValue = false)]
public Named_Variable_instance Named
{
get
{
return named_;
}
set
{
selectNamed(value);
}
}
[ASN1Element(Name = "unnamed", IsOptional = false, HasTag = true, Tag = 12, HasDefaultValue = false)]
public Unnamed_Variable_instance Unnamed
{
get
{
return unnamed_;
}
set
{
selectUnnamed(value);
}
}
[ASN1Null(Name = "unspecified")]
[ASN1Element(Name = "unspecified", IsOptional = false, HasTag = true, Tag = 13, HasDefaultValue = false)]
public NullObject Unspecified
{
get
{
return unspecified_;
}
set
{
selectUnspecified(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isNamedSelected()
{
return named_selected;
}
public void selectNamed(Named_Variable_instance val)
{
named_ = val;
named_selected = true;
unnamed_selected = false;
unspecified_selected = false;
}
public bool isUnnamedSelected()
{
return unnamed_selected;
}
public void selectUnnamed(Unnamed_Variable_instance val)
{
unnamed_ = val;
unnamed_selected = true;
named_selected = false;
unspecified_selected = false;
}
public bool isUnspecifiedSelected()
{
return unspecified_selected;
}
public void selectUnspecified()
{
selectUnspecified(new NullObject());
}
public void selectUnspecified(NullObject val)
{
unspecified_ = val;
unspecified_selected = true;
named_selected = false;
unnamed_selected = false;
}
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Collections;
using System.Drawing.Design;
using SharpGL.SceneGraph.Core;
using SharpGL.SceneGraph.Assets;
namespace SharpGL.SceneGraph
{
// This namespace contains classes for use with the .NET design surface,
// typeconverters, UI editors etc. Most clients can safely ingore this,
// it's not important 3D code, it just makes editing it easier.
namespace NETDesignSurface
{
// Designers are used to aid design of controls, components etc.
namespace Designers
{
/// <summary>
/// This aids the design of the OpenGLCtrl
/// </summary>
public class OpenGLCtrlDesigner : System.Windows.Forms.Design.ControlDesigner
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenGLCtrlDesigner"/> class.
/// </summary>
public OpenGLCtrlDesigner() {}
/// <summary>
/// Remove Control properties that are not supported by the control.
/// </summary>
/// <param name="Properties"></param>
protected override void PostFilterProperties(IDictionary Properties)
{
// Appearance
Properties.Remove("BackColor");
Properties.Remove("BackgroundImage");
Properties.Remove("Font");
Properties.Remove("ForeColor");
Properties.Remove("RightToLeft");
// Behaviour
Properties.Remove("AllowDrop");
Properties.Remove("ContextMenu");
// Layout
Properties.Remove("AutoScroll");
Properties.Remove("AutoScrollMargin");
Properties.Remove("AutoScrollMinSize");
}
}
}
// Converters are used to change objects of one type into another, at design time
// and also programmatically.
namespace Converters
{
/// <summary>
/// The VertexConverter class allows you to edit vertices in the propties window.
/// </summary>
internal class VertexConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type t)
{
// We allow conversion from a string.
if (t == typeof(string))
return true;
return base.CanConvertFrom(context, t);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo info, object value)
{
// If it's a string, we'll parse it for coords.
if (value is string)
{
try
{
string s = (string) value;
// Parse the format (x, y, z).
int openbracket = s.IndexOf('(');
int comma = s.IndexOf(',');
int nextcomma = s.IndexOf(',', comma + 1);
int closebracket = s.IndexOf(')');
float xValue, yValue, zValue;
if(comma != -1 && openbracket != -1)
{
// We have the comma and open bracket, so get x.
string parsed = s.Substring(openbracket + 1, (comma - (openbracket + 1)));
parsed.Trim();
xValue = float.Parse(parsed);
if(comma != -1 && nextcomma != -1)
{
parsed = s.Substring(comma + 1, (nextcomma - (comma + 1)));
parsed.Trim();
yValue = float.Parse(parsed);
if(nextcomma != -1 && closebracket != -1)
{
parsed = s.Substring(nextcomma + 1, (closebracket - (nextcomma + 1)));
parsed.Trim();
zValue = float.Parse(parsed);
return new Vertex(xValue, yValue, zValue);
}
}
}
}
catch {}
// Somehow we couldn't parse it.
throw new ArgumentException("Can not convert '" + (string)value +
"' to type Vertex");
}
return base.ConvertFrom(context, info, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
object value, Type destType)
{
if (destType == typeof(string) && value is Vertex)
{
// We can easily convert a vertex to a string, format (x, y, z).
Vertex v = (Vertex)value;
return "(" + v.X + ", " + v.Y + ", " + v.Z + ")";
}
return base.ConvertTo(context, culture, value, destType);
}
}
/// <summary>
/// This converts the Material Collection into something more functional.
/// </summary>
internal class MaterialCollectionConverter : System.ComponentModel.CollectionConverter
{
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
if (value is System.Collections.ICollection)
return "Materials";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
// Editors are classes that increase the functionality of the properties window
// in editing objects, e.g texture objects have a thumbnail.
namespace Editors
{
/// <summary>
/// The texture editor makes Textures in the properties window much better,
/// giving them a little thumbnail.
/// </summary>
internal class UITextureEditor : UITypeEditor
{
public override System.Boolean GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context )
{
return true;
}
public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e)
{
// Make sure we are dealing with an actual texture.
if(e.Value is Texture)
{
// Get the texture.
Texture tex = e.Value as Texture;
if(tex.TextureName != 0)
e.Graphics.DrawImage(tex.ToBitmap(), e.Bounds);
}
}
}
/// <summary>
/// This converts the Quadric Collection into something more functional, and
/// allows you to add many types of quadrics.
/// </summary>
internal class QuadricCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public QuadricCollectionEditor(Type type) : base(type) {}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] {typeof(Quadrics.Cylinder), typeof(Quadrics.Disk), typeof(Quadrics.Sphere)};
}
}
/// <summary>
/// This converts the Camera collection into something more usable (design time wise)
/// by allowing all the types of camera to be added.
/// </summary>
internal class CameraCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public CameraCollectionEditor(Type type) : base(type) {}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] {typeof(Cameras.FrustumCamera), typeof(Cameras.OrthographicCamera), typeof(Cameras.PerspectiveCamera)};
}
}
/// <summary>
/// This converts the evaluator collection into something more usable (design time wise)
/// by allowing all the types of evaluator to be added.
/// </summary>
internal class EvaluatorCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public EvaluatorCollectionEditor(Type type) : base(type) {}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] {typeof(Evaluators.Evaluator1D), typeof(Evaluators.Evaluator2D), typeof(Evaluators.NurbsCurve), typeof(Evaluators.NurbsSurface)};
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: Stack.cs
//
// Description: Implementation of StackPanel class.
// Spec at http://avalon/layout/Specs/StackPanel.doc
//
// History:
// 06/25/2004 : olego - Created
// 09/03/2004 : greglett - Converted to new layout system, IScrollInfo implementation
//
//---------------------------------------------------------------------------
//#define Profiling
using MS.Internal;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Threading;
namespace System.Windows.Controls
{
/// <summary>
/// Internal interface for elements which needs stack like measure
/// </summary>
internal interface IStackMeasure
{
bool IsScrolling { get; }
UIElementCollection InternalChildren { get; }
Orientation Orientation { get; }
bool CanVerticallyScroll { get; }
bool CanHorizontallyScroll { get; }
void OnScrollChange();
}
/// <summary>
/// Internal interface for scrolling information of elements which
/// need stack like measure.
/// </summary>
internal interface IStackMeasureScrollData
{
Vector Offset { get; set; }
Size Viewport { get; set; }
Size Extent { get; set; }
Vector ComputedOffset { get; set; }
void SetPhysicalViewport(double value);
}
/// <summary>
/// StackPanel is used to arrange children into single line.
/// </summary>
public class StackPanel : Panel, IScrollInfo, IStackMeasure
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public StackPanel() : base()
{
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
//-----------------------------------------------------------
// IScrollInfo Methods
//-----------------------------------------------------------
#region IScrollInfo Methods
/// <summary>
/// Scroll content by one line to the top.
/// </summary>
public void LineUp()
{
SetVerticalOffset(VerticalOffset - ((Orientation == Orientation.Vertical) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one line to the bottom.
/// </summary>
public void LineDown()
{
SetVerticalOffset(VerticalOffset + ((Orientation == Orientation.Vertical) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one line to the left.
/// </summary>
public void LineLeft()
{
SetHorizontalOffset(HorizontalOffset - ((Orientation == Orientation.Horizontal) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one line to the right.
/// </summary>
public void LineRight()
{
SetHorizontalOffset(HorizontalOffset + ((Orientation == Orientation.Horizontal) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one page to the top.
/// </summary>
public void PageUp()
{
SetVerticalOffset(VerticalOffset - ViewportHeight);
}
/// <summary>
/// Scroll content by one page to the bottom.
/// </summary>
public void PageDown()
{
SetVerticalOffset(VerticalOffset + ViewportHeight);
}
/// <summary>
/// Scroll content by one page to the left.
/// </summary>
public void PageLeft()
{
SetHorizontalOffset(HorizontalOffset - ViewportWidth);
}
/// <summary>
/// Scroll content by one page to the right.
/// </summary>
public void PageRight()
{
SetHorizontalOffset(HorizontalOffset + ViewportWidth);
}
/// <summary>
/// Scroll content by one page to the top.
/// </summary>
public void MouseWheelUp()
{
SetVerticalOffset(VerticalOffset - SystemParameters.WheelScrollLines * ((Orientation == Orientation.Vertical) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one page to the bottom.
/// </summary>
public void MouseWheelDown()
{
SetVerticalOffset(VerticalOffset + SystemParameters.WheelScrollLines * ((Orientation == Orientation.Vertical) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one page to the left.
/// </summary>
public void MouseWheelLeft()
{
SetHorizontalOffset(HorizontalOffset - 3.0 * ((Orientation == Orientation.Horizontal) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Scroll content by one page to the right.
/// </summary>
public void MouseWheelRight()
{
SetHorizontalOffset(HorizontalOffset + 3.0 * ((Orientation == Orientation.Horizontal) ? 1.0 : ScrollViewer._scrollLineDelta));
}
/// <summary>
/// Set the HorizontalOffset to the passed value.
/// </summary>
public void SetHorizontalOffset(double offset)
{
EnsureScrollData();
double scrollX = ScrollContentPresenter.ValidateInputOffset(offset, "HorizontalOffset");
if (!DoubleUtil.AreClose(scrollX, _scrollData._offset.X))
{
_scrollData._offset.X = scrollX;
InvalidateMeasure();
}
}
/// <summary>
/// Set the VerticalOffset to the passed value.
/// </summary>
public void SetVerticalOffset(double offset)
{
EnsureScrollData();
double scrollY = ScrollContentPresenter.ValidateInputOffset(offset, "VerticalOffset");
if (!DoubleUtil.AreClose(scrollY, _scrollData._offset.Y))
{
_scrollData._offset.Y = scrollY;
InvalidateMeasure();
}
}
/// <summary>
/// StackPanel implementation of <seealso cref="IScrollInfo.MakeVisible" />.
/// </summary>
// The goal is to change offsets to bring the child into view, and return a rectangle in our space to make visible.
// The rectangle we return is in the physical dimension the input target rect transformed into our pace.
// In the logical dimension, it is our immediate child's rect.
// Note: This code presently assumes we/children are layout clean. See work item 22269 for more detail.
public Rect MakeVisible(Visual visual, Rect rectangle)
{
Vector newOffset = new Vector();
Rect newRect = new Rect();
// We can only work on visuals that are us or children.
// An empty rect has no size or position. We can't meaningfully use it.
if ( rectangle.IsEmpty
|| visual == null
|| visual == (Visual)this
|| !this.IsAncestorOf(visual))
{
return Rect.Empty;
}
#pragma warning disable 1634, 1691
#pragma warning disable 56506
// Compute the child's rect relative to (0,0) in our coordinate space.
// This is a false positive by PreSharp. visual cannot be null because of the 'if' check above
GeneralTransform childTransform = visual.TransformToAncestor(this);
#pragma warning restore 56506
#pragma warning restore 1634, 1691
rectangle = childTransform.TransformBounds(rectangle);
// We can't do any work unless we're scrolling.
if (!IsScrolling)
{
return rectangle;
}
// Bring the target rect into view in the physical dimension.
MakeVisiblePhysicalHelper(rectangle, ref newOffset, ref newRect);
// Bring our child containing the visual into view.
int childIndex = FindChildIndexThatParentsVisual(visual);
MakeVisibleLogicalHelper(childIndex, ref newOffset, ref newRect);
// We have computed the scrolling offsets; validate and scroll to them.
newOffset.X = ScrollContentPresenter.CoerceOffset(newOffset.X, _scrollData._extent.Width, _scrollData._viewport.Width);
newOffset.Y = ScrollContentPresenter.CoerceOffset(newOffset.Y, _scrollData._extent.Height, _scrollData._viewport.Height);
if (!DoubleUtil.AreClose(newOffset, _scrollData._offset))
{
_scrollData._offset = newOffset;
InvalidateMeasure();
OnScrollChange();
}
// Return the rectangle
return newRect;
}
#endregion
#endregion
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Specifies dimension of children stacking.
/// </summary>
public Orientation Orientation
{
get { return (Orientation) GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="Orientation" /> property.
/// </summary>
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(
"Orientation",
typeof(Orientation),
typeof(StackPanel),
new FrameworkPropertyMetadata(
Orientation.Vertical,
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnOrientationChanged)),
new ValidateValueCallback(ScrollBar.IsValidOrientation));
/// <summary>
/// This property is always true because this panel has vertical or horizontal orientation
/// </summary>
protected internal override bool HasLogicalOrientation
{
get { return true; }
}
/// <summary>
/// Orientation of the panel if its layout is in one dimension.
/// Otherwise HasLogicalOrientation is false and LogicalOrientation should be ignored
/// </summary>
protected internal override Orientation LogicalOrientation
{
get { return this.Orientation; }
}
//-----------------------------------------------------------
// IScrollInfo Properties
//-----------------------------------------------------------
#region IScrollInfo Properties
/// <summary>
/// StackPanel reacts to this property by changing it's child measurement algorithm.
/// If scrolling in a dimension, infinite space is allowed the child; otherwise, available size is preserved.
/// </summary>
[DefaultValue(false)]
public bool CanHorizontallyScroll
{
get
{
if (_scrollData == null) { return false; }
return _scrollData._allowHorizontal;
}
set
{
EnsureScrollData();
if (_scrollData._allowHorizontal != value)
{
_scrollData._allowHorizontal = value;
InvalidateMeasure();
}
}
}
/// <summary>
/// StackPanel reacts to this property by changing it's child measurement algorithm.
/// If scrolling in a dimension, infinite space is allowed the child; otherwise, available size is preserved.
/// </summary>
[DefaultValue(false)]
public bool CanVerticallyScroll
{
get
{
if (_scrollData == null) { return false; }
return _scrollData._allowVertical;
}
set
{
EnsureScrollData();
if (_scrollData._allowVertical != value)
{
_scrollData._allowVertical = value;
InvalidateMeasure();
}
}
}
/// <summary>
/// ExtentWidth contains the horizontal size of the scrolled content element in 1/96"
/// </summary>
public double ExtentWidth
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._extent.Width;
}
}
/// <summary>
/// ExtentHeight contains the vertical size of the scrolled content element in 1/96"
/// </summary>
public double ExtentHeight
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._extent.Height;
}
}
/// <summary>
/// ViewportWidth contains the horizontal size of content's visible range in 1/96"
/// </summary>
public double ViewportWidth
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._viewport.Width;
}
}
/// <summary>
/// ViewportHeight contains the vertical size of content's visible range in 1/96"
/// </summary>
public double ViewportHeight
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._viewport.Height;
}
}
/// <summary>
/// HorizontalOffset is the horizontal offset of the scrolled content in 1/96".
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public double HorizontalOffset
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._computedOffset.X;
}
}
/// <summary>
/// VerticalOffset is the vertical offset of the scrolled content in 1/96".
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public double VerticalOffset
{
get
{
if (_scrollData == null) { return 0.0; }
return _scrollData._computedOffset.Y;
}
}
/// <summary>
/// ScrollOwner is the container that controls any scrollbars, headers, etc... that are dependant
/// on this IScrollInfo's properties.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ScrollViewer ScrollOwner
{
get
{
EnsureScrollData();
return _scrollData._scrollOwner;
}
set
{
EnsureScrollData();
if (value != _scrollData._scrollOwner)
{
ResetScrolling(this);
_scrollData._scrollOwner = value;
}
}
}
#endregion IScrollInfo Properties
#endregion Public Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// General StackPanel layout behavior is to grow unbounded in the "stacking" direction (Size To Content).
/// Children in this dimension are encouraged to be as large as they like. In the other dimension,
/// StackPanel will assume the maximum size of its children.
/// </summary>
/// <remarks>
/// When scrolling, StackPanel will not grow in layout size but effectively add the children on a z-plane which
/// will probably be clipped by some parent (typically a ScrollContentPresenter) to Stack's size.
/// </remarks>
/// <param name="constraint">Constraint</param>
/// <returns>Desired size</returns>
protected override Size MeasureOverride(Size constraint)
{
#if Profiling
if (Panel.IsAboutToGenerateContent(this))
return MeasureOverrideProfileStub(constraint);
else
return RealMeasureOverride(constraint);
}
// this is a handy place to start/stop profiling
private Size MeasureOverrideProfileStub(Size constraint)
{
return RealMeasureOverride(constraint);
}
private Size RealMeasureOverride(Size constraint)
{
#endif
Size stackDesiredSize = new Size();
bool etwTracingEnabled = IsScrolling && EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info);
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringBegin, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "STACK:MeasureOverride");
}
try
{
// Call the measure helper.
stackDesiredSize = StackMeasureHelper(this, _scrollData, constraint);
}
finally
{
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringEnd, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "STACK:MeasureOverride");
}
}
return stackDesiredSize;
}
/// <summary>
/// Helper method which implements the stack like measure.
/// </summary>
internal static Size StackMeasureHelper(IStackMeasure measureElement, IStackMeasureScrollData scrollData, Size constraint)
{
Size stackDesiredSize = new Size();
UIElementCollection children = measureElement.InternalChildren;
Size layoutSlotSize = constraint;
bool fHorizontal = (measureElement.Orientation == Orientation.Horizontal);
int firstViewport; // First child index in the viewport.
int lastViewport = -1; // Last child index in the viewport. -1 indicates we have not yet iterated through the last child.
double logicalVisibleSpace, childLogicalSize;
//
// Initialize child sizing and iterator data
// Allow children as much size as they want along the stack.
//
if (fHorizontal)
{
layoutSlotSize.Width = Double.PositiveInfinity;
if (measureElement.IsScrolling && measureElement.CanVerticallyScroll) { layoutSlotSize.Height = Double.PositiveInfinity; }
firstViewport = (measureElement.IsScrolling) ? CoerceOffsetToInteger(scrollData.Offset.X, children.Count) : 0;
logicalVisibleSpace = constraint.Width;
}
else
{
layoutSlotSize.Height = Double.PositiveInfinity;
if (measureElement.IsScrolling && measureElement.CanHorizontallyScroll) { layoutSlotSize.Width = Double.PositiveInfinity; }
firstViewport = (measureElement.IsScrolling) ? CoerceOffsetToInteger(scrollData.Offset.Y, children.Count) : 0;
logicalVisibleSpace = constraint.Height;
}
//
// Iterate through children.
// While we still supported virtualization, this was hidden in a child iterator (see source history).
//
for (int i = 0, count = children.Count; i < count; ++i)
{
// Get next child.
UIElement child = children[i];
if (child == null) { continue; }
// Measure the child.
child.Measure(layoutSlotSize);
Size childDesiredSize = child.DesiredSize;
// Accumulate child size.
if (fHorizontal)
{
stackDesiredSize.Width += childDesiredSize.Width;
stackDesiredSize.Height = Math.Max(stackDesiredSize.Height, childDesiredSize.Height);
childLogicalSize = childDesiredSize.Width;
}
else
{
stackDesiredSize.Width = Math.Max(stackDesiredSize.Width, childDesiredSize.Width);
stackDesiredSize.Height += childDesiredSize.Height;
childLogicalSize = childDesiredSize.Height;
}
// Adjust remaining viewport space if we are scrolling and within the viewport region.
// While scrolling (not virtualizing), we always measure children before and after the viewport.
if (measureElement.IsScrolling && lastViewport == -1 && i >= firstViewport)
{
logicalVisibleSpace -= childLogicalSize;
if (DoubleUtil.LessThanOrClose(logicalVisibleSpace, 0.0))
{
lastViewport = i;
}
}
}
//
// Compute Scrolling stuff.
//
if (measureElement.IsScrolling)
{
// Compute viewport and extent.
Size viewport = constraint;
Size extent = stackDesiredSize;
Vector offset = scrollData.Offset;
// If we have not yet set the last child in the viewport, set it to the last child.
if (lastViewport == -1) { lastViewport = children.Count - 1; }
// If we or children have resized, it's possible that we can now display more content.
// This is true if we started at a nonzero offeset and still have space remaining.
// In this case, we loop back through previous children until we run out of space.
while (firstViewport > 0)
{
double projectedLogicalVisibleSpace = logicalVisibleSpace;
if (fHorizontal) { projectedLogicalVisibleSpace -= children[firstViewport - 1].DesiredSize.Width; }
else { projectedLogicalVisibleSpace -= children[firstViewport - 1].DesiredSize.Height; }
// If we have run out of room, break.
if (DoubleUtil.LessThan(projectedLogicalVisibleSpace, 0.0)) { break; }
// Adjust viewport
firstViewport--;
logicalVisibleSpace = projectedLogicalVisibleSpace;
}
int logicalExtent = children.Count;
int logicalViewport = lastViewport - firstViewport;
// We are conservative when estimating a viewport, not including the last element in case it is only partially visible.
// We want to count it if it is fully visible (>= 0 space remaining) or the only element in the viewport.
if (logicalViewport == 0 || DoubleUtil.GreaterThanOrClose(logicalVisibleSpace, 0.0)) { logicalViewport++; }
if (fHorizontal)
{
scrollData.SetPhysicalViewport(viewport.Width);
viewport.Width = logicalViewport;
extent.Width = logicalExtent;
offset.X = firstViewport;
offset.Y = Math.Max(0, Math.Min(offset.Y, extent.Height - viewport.Height));
}
else
{
scrollData.SetPhysicalViewport(viewport.Height);
viewport.Height = logicalViewport;
extent.Height = logicalExtent;
offset.Y = firstViewport;
offset.X = Math.Max(0, Math.Min(offset.X, extent.Width - viewport.Width));
}
// Since we can offset and clip our content, we never need to be larger than the parent suggestion.
// If we returned the full size of the content, we would always be so big we didn't need to scroll. :)
stackDesiredSize.Width = Math.Min(stackDesiredSize.Width, constraint.Width);
stackDesiredSize.Height = Math.Min(stackDesiredSize.Height, constraint.Height);
// Verify Scroll Info, invalidate ScrollOwner if necessary.
VerifyScrollingData(measureElement, scrollData, viewport, extent, offset);
}
return stackDesiredSize;
}
/// <summary>
/// Content arrangement.
/// </summary>
/// <param name="arrangeSize">Arrange size</param>
protected override Size ArrangeOverride(Size arrangeSize)
{
bool etwTracingEnabled = IsScrolling && EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info);
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringBegin, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "STACK:ArrangeOverride");
}
try
{
// Call the arrange helper.
StackArrangeHelper(this, _scrollData, arrangeSize);
}
finally
{
if (etwTracingEnabled)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringEnd, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "STACK:ArrangeOverride");
}
}
return arrangeSize;
}
/// <summary>
/// Helper method which implements the stack like arrange.
/// </summary>
internal static Size StackArrangeHelper(IStackMeasure arrangeElement, IStackMeasureScrollData scrollData, Size arrangeSize)
{
UIElementCollection children = arrangeElement.InternalChildren;
bool fHorizontal = (arrangeElement.Orientation == Orientation.Horizontal);
Rect rcChild = new Rect(arrangeSize);
double previousChildSize = 0.0;
//
// Compute scroll offset and seed it into rcChild.
//
if (arrangeElement.IsScrolling)
{
if (fHorizontal)
{
rcChild.X = ComputePhysicalFromLogicalOffset(arrangeElement, scrollData.ComputedOffset.X, true);
rcChild.Y = -1.0 * scrollData.ComputedOffset.Y;
}
else
{
rcChild.X = -1.0 * scrollData.ComputedOffset.X;
rcChild.Y = ComputePhysicalFromLogicalOffset(arrangeElement, scrollData.ComputedOffset.Y, false);
}
}
//
// Arrange and Position Children.
//
for (int i = 0, count = children.Count; i < count; ++i)
{
UIElement child = (UIElement)children[i];
if (child == null) { continue; }
if (fHorizontal)
{
rcChild.X += previousChildSize;
previousChildSize = child.DesiredSize.Width;
rcChild.Width = previousChildSize;
rcChild.Height = Math.Max(arrangeSize.Height, child.DesiredSize.Height);
}
else
{
rcChild.Y += previousChildSize;
previousChildSize = child.DesiredSize.Height;
rcChild.Height = previousChildSize;
rcChild.Width = Math.Max(arrangeSize.Width, child.DesiredSize.Width);
}
child.Arrange(rcChild);
}
return arrangeSize;
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
private void EnsureScrollData()
{
if (_scrollData == null) { _scrollData = new ScrollData(); }
}
private static void ResetScrolling(StackPanel element)
{
element.InvalidateMeasure();
// Clear scrolling data. Because of thrash (being disconnected & reconnected, &c...), we may
if (element.IsScrolling)
{
element._scrollData.ClearLayout();
}
}
// OnScrollChange is an override called whenever the IScrollInfo exposed scrolling state changes on this element.
// At the time this method is called, scrolling state is in its new, valid state.
private void OnScrollChange()
{
if (ScrollOwner != null) { ScrollOwner.InvalidateScrollInfo(); }
}
private static void VerifyScrollingData(IStackMeasure measureElement, IStackMeasureScrollData scrollData, Size viewport, Size extent, Vector offset)
{
bool fValid = true;
Debug.Assert(measureElement.IsScrolling);
fValid &= DoubleUtil.AreClose(viewport, scrollData.Viewport);
fValid &= DoubleUtil.AreClose(extent, scrollData.Extent);
fValid &= DoubleUtil.AreClose(offset, scrollData.ComputedOffset);
scrollData.Offset = offset;
if (!fValid)
{
scrollData.Viewport = viewport;
scrollData.Extent = extent;
scrollData.ComputedOffset = offset;
measureElement.OnScrollChange();
}
}
// Translates a logical (child index) offset to a physical (1/96") when scrolling.
// If virtualizing, it makes the assumption that the logicalOffset is always the first in the visual collection
// and thus returns 0.
// If not virtualizing, it assumes that children are Measure clean; should only be called after running Measure.
private static double ComputePhysicalFromLogicalOffset(IStackMeasure arrangeElement, double logicalOffset, bool fHorizontal)
{
double physicalOffset = 0.0;
UIElementCollection children = arrangeElement.InternalChildren;
Debug.Assert(logicalOffset == 0 || (logicalOffset > 0 && logicalOffset < children.Count));
for (int i = 0; i < logicalOffset; i++)
{
physicalOffset -= (fHorizontal)
? ((UIElement)children[i]).DesiredSize.Width
: ((UIElement)children[i]).DesiredSize.Height;
}
return physicalOffset;
}
private int FindChildIndexThatParentsVisual(Visual child)
{
DependencyObject dependencyObjectChild = child;
DependencyObject parent = VisualTreeHelper.GetParent(child);
while (parent != this)
{
dependencyObjectChild = parent;
parent = VisualTreeHelper.GetParent(dependencyObjectChild);
if (parent == null)
{
throw new ArgumentException(SR.Get(SRID.Stack_VisualInDifferentSubTree),"child");
}
}
UIElementCollection children = this.Children;
//The Downcast is ok because StackPanel's
//child has to be a UIElement to be in this.Children collection
return (children.IndexOf((UIElement)dependencyObjectChild));
}
private void MakeVisiblePhysicalHelper(Rect r, ref Vector newOffset, ref Rect newRect)
{
double viewportOffset;
double viewportSize;
double targetRectOffset;
double targetRectSize;
double minPhysicalOffset;
bool fHorizontal = (Orientation == Orientation.Horizontal);
if (fHorizontal)
{
viewportOffset = _scrollData._computedOffset.Y;
viewportSize = ViewportHeight;
targetRectOffset = r.Y;
targetRectSize = r.Height;
}
else
{
viewportOffset = _scrollData._computedOffset.X;
viewportSize = ViewportWidth;
targetRectOffset = r.X;
targetRectSize = r.Width;
}
targetRectOffset += viewportOffset;
minPhysicalOffset = ScrollContentPresenter.ComputeScrollOffsetWithMinimalScroll(
viewportOffset, viewportOffset + viewportSize, targetRectOffset, targetRectOffset + targetRectSize);
// Compute the visible rectangle of the child relative to the viewport.
double left = Math.Max(targetRectOffset, minPhysicalOffset);
targetRectSize = Math.Max(Math.Min(targetRectSize + targetRectOffset, minPhysicalOffset + viewportSize) - left, 0);
targetRectOffset = left;
targetRectOffset -= viewportOffset;
if (fHorizontal)
{
newOffset.Y = minPhysicalOffset;
newRect.Y = targetRectOffset;
newRect.Height = targetRectSize;
}
else
{
newOffset.X = minPhysicalOffset;
newRect.X = targetRectOffset;
newRect.Width = targetRectSize;
}
}
private void MakeVisibleLogicalHelper(int childIndex, ref Vector newOffset, ref Rect newRect)
{
bool fHorizontal = (Orientation == Orientation.Horizontal);
int firstChildInView;
int newFirstChild;
int viewportSize;
double childOffsetWithinViewport = 0;
if (fHorizontal)
{
firstChildInView = (int)_scrollData._computedOffset.X;
viewportSize = (int)_scrollData._viewport.Width;
}
else
{
firstChildInView = (int)_scrollData._computedOffset.Y;
viewportSize = (int)_scrollData._viewport.Height;
}
newFirstChild = firstChildInView;
// If the target child is before the current viewport, move the viewport to put the child at the top.
if (childIndex < firstChildInView)
{
newFirstChild = childIndex;
}
// If the target child is after the current viewport, move the viewport to put the child at the bottom.
else if (childIndex > firstChildInView + viewportSize - 1)
{
Size childDesiredSize = InternalChildren[childIndex].DesiredSize;
double nextChildSize = ((fHorizontal) ? childDesiredSize.Width : childDesiredSize.Height);
double viewportSpace = _scrollData._physicalViewport - nextChildSize;
int i = childIndex;
while (i > 0 && DoubleUtil.GreaterThanOrClose(viewportSpace, 0.0))
{
i--;
childDesiredSize = InternalChildren[i].DesiredSize;
nextChildSize = ((fHorizontal) ? childDesiredSize.Width : childDesiredSize.Height);
childOffsetWithinViewport += nextChildSize;
viewportSpace -= nextChildSize;
}
if (i != childIndex && DoubleUtil.LessThan(viewportSpace, 0.0))
{
childOffsetWithinViewport -= nextChildSize;
i++;
}
newFirstChild = i;
}
if (fHorizontal)
{
newOffset.X = newFirstChild;
newRect.X = childOffsetWithinViewport;
newRect.Width = InternalChildren[childIndex].DesiredSize.Width;
}
else
{
newOffset.Y = newFirstChild;
newRect.Y = childOffsetWithinViewport;
newRect.Height = InternalChildren[childIndex].DesiredSize.Height;
}
}
static private int CoerceOffsetToInteger(double offset, int numberOfItems)
{
int iNewOffset;
if (Double.IsNegativeInfinity(offset))
{
iNewOffset = 0;
}
else if (Double.IsPositiveInfinity(offset))
{
iNewOffset = numberOfItems - 1;
}
else
{
iNewOffset = (int)offset;
iNewOffset = Math.Max(Math.Min(numberOfItems - 1, iNewOffset), 0);
}
return iNewOffset;
}
//-----------------------------------------------------------
// Avalon Property Callbacks/Overrides
//-----------------------------------------------------------
#region Avalon Property Callbacks/Overrides
/// <summary>
/// <see cref="PropertyMetadata.PropertyChangedCallback"/>
/// </summary>
private static void OnOrientationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Since Orientation is so essential to logical scrolling/virtualization, we synchronously check if
// the new value is different and clear all scrolling data if so.
ResetScrolling(d as StackPanel);
}
#endregion
#endregion Private Methods
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
private bool IsScrolling
{
get { return (_scrollData != null) && (_scrollData._scrollOwner != null); }
}
//
// This property
// 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject
// 2. This is a performance optimization
//
internal override int EffectiveValuesInitialSize
{
get { return 9; }
}
bool IStackMeasure.IsScrolling
{
get { return IsScrolling; }
}
UIElementCollection IStackMeasure.InternalChildren
{
get { return InternalChildren; }
}
void IStackMeasure.OnScrollChange()
{
OnScrollChange();
}
#endregion Private Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Logical scrolling and virtualization data.
private ScrollData _scrollData;
#endregion Private Fields
//------------------------------------------------------
//
// Private Structures / Classes
//
//------------------------------------------------------
#region Private Structures Classes
//-----------------------------------------------------------
// ScrollData class
//-----------------------------------------------------------
#region ScrollData
// Helper class to hold scrolling data.
// This class exists to reduce working set when StackPanel is used outside a scrolling situation.
// Standard "extra pointer always for less data sometimes" cache savings model:
// !Scroll [1xReference]
// Scroll [1xReference] + [6xDouble + 1xReference]
private class ScrollData: IStackMeasureScrollData
{
// Clears layout generated data.
// Does not clear scrollOwner, because unless resetting due to a scrollOwner change, we won't get reattached.
internal void ClearLayout()
{
_offset = new Vector();
_viewport = _extent = new Size();
_physicalViewport = 0;
}
// For Stack/Flow, the two dimensions of properties are in different units:
// 1. The "logically scrolling" dimension uses items as units.
// 2. The other dimension physically scrolls. Units are in Avalon pixels (1/96").
internal bool _allowHorizontal;
internal bool _allowVertical;
internal Vector _offset; // Scroll offset of content. Positive corresponds to a visually upward offset.
internal Vector _computedOffset = new Vector(0,0);
internal Size _viewport; // ViewportSize is in {pixels x items} (or vice-versa).
internal Size _extent; // Extent is the total number of children (logical dimension) or physical size
internal double _physicalViewport; // The physical size of the viewport for the items dimension above.
internal ScrollViewer _scrollOwner; // ScrollViewer to which we're attached.
public Vector Offset
{
get
{
return _offset;
}
set
{
_offset = value;
}
}
public Size Viewport
{
get
{
return _viewport;
}
set
{
_viewport = value;
}
}
public Size Extent
{
get
{
return _extent;
}
set
{
_extent = value;
}
}
public Vector ComputedOffset
{
get
{
return _computedOffset;
}
set
{
_computedOffset = value;
}
}
public void SetPhysicalViewport(double value)
{
_physicalViewport = value;
}
}
#endregion ScrollData
#endregion Private Structures Classes
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// TaxRateBatchLocationResponse
/// </summary>
[DataContract]
public partial class TaxRateBatchLocationResponse : IEquatable<TaxRateBatchLocationResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxRateBatchLocationResponse" /> class.
/// </summary>
/// <param name="ObjectId">ObjectId.</param>
/// <param name="Confidence">Confidence.</param>
/// <param name="Jurisdiction">Jurisdiction.</param>
/// <param name="MatchedAddress">MatchedAddress.</param>
/// <param name="SalesTax">SalesTax.</param>
/// <param name="UseTax">UseTax.</param>
/// <param name="Census">Census.</param>
/// <param name="LatLongFields">LatLongFields.</param>
public TaxRateBatchLocationResponse(string ObjectId = null, double? Confidence = null, TaxJurisdiction Jurisdiction = null, MatchedAddress MatchedAddress = null, SalesTaxRate SalesTax = null, UseTaxRate UseTax = null, Census Census = null, LatLongFields LatLongFields = null)
{
this.ObjectId = ObjectId;
this.Confidence = Confidence;
this.Jurisdiction = Jurisdiction;
this.MatchedAddress = MatchedAddress;
this.SalesTax = SalesTax;
this.UseTax = UseTax;
this.Census = Census;
this.LatLongFields = LatLongFields;
}
/// <summary>
/// Gets or Sets ObjectId
/// </summary>
[DataMember(Name="objectId", EmitDefaultValue=false)]
public string ObjectId { get; set; }
/// <summary>
/// Gets or Sets Confidence
/// </summary>
[DataMember(Name="confidence", EmitDefaultValue=false)]
public double? Confidence { get; set; }
/// <summary>
/// Gets or Sets Jurisdiction
/// </summary>
[DataMember(Name="jurisdiction", EmitDefaultValue=false)]
public TaxJurisdiction Jurisdiction { get; set; }
/// <summary>
/// Gets or Sets MatchedAddress
/// </summary>
[DataMember(Name="matchedAddress", EmitDefaultValue=false)]
public MatchedAddress MatchedAddress { get; set; }
/// <summary>
/// Gets or Sets SalesTax
/// </summary>
[DataMember(Name="salesTax", EmitDefaultValue=false)]
public SalesTaxRate SalesTax { get; set; }
/// <summary>
/// Gets or Sets UseTax
/// </summary>
[DataMember(Name="useTax", EmitDefaultValue=false)]
public UseTaxRate UseTax { get; set; }
/// <summary>
/// Gets or Sets Census
/// </summary>
[DataMember(Name="census", EmitDefaultValue=false)]
public Census Census { get; set; }
/// <summary>
/// Gets or Sets LatLongFields
/// </summary>
[DataMember(Name="latLongFields", EmitDefaultValue=false)]
public LatLongFields LatLongFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TaxRateBatchLocationResponse {\n");
sb.Append(" ObjectId: ").Append(ObjectId).Append("\n");
sb.Append(" Confidence: ").Append(Confidence).Append("\n");
sb.Append(" Jurisdiction: ").Append(Jurisdiction).Append("\n");
sb.Append(" MatchedAddress: ").Append(MatchedAddress).Append("\n");
sb.Append(" SalesTax: ").Append(SalesTax).Append("\n");
sb.Append(" UseTax: ").Append(UseTax).Append("\n");
sb.Append(" Census: ").Append(Census).Append("\n");
sb.Append(" LatLongFields: ").Append(LatLongFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as TaxRateBatchLocationResponse);
}
/// <summary>
/// Returns true if TaxRateBatchLocationResponse instances are equal
/// </summary>
/// <param name="other">Instance of TaxRateBatchLocationResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxRateBatchLocationResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ObjectId == other.ObjectId ||
this.ObjectId != null &&
this.ObjectId.Equals(other.ObjectId)
) &&
(
this.Confidence == other.Confidence ||
this.Confidence != null &&
this.Confidence.Equals(other.Confidence)
) &&
(
this.Jurisdiction == other.Jurisdiction ||
this.Jurisdiction != null &&
this.Jurisdiction.Equals(other.Jurisdiction)
) &&
(
this.MatchedAddress == other.MatchedAddress ||
this.MatchedAddress != null &&
this.MatchedAddress.Equals(other.MatchedAddress)
) &&
(
this.SalesTax == other.SalesTax ||
this.SalesTax != null &&
this.SalesTax.Equals(other.SalesTax)
) &&
(
this.UseTax == other.UseTax ||
this.UseTax != null &&
this.UseTax.Equals(other.UseTax)
) &&
(
this.Census == other.Census ||
this.Census != null &&
this.Census.Equals(other.Census)
) &&
(
this.LatLongFields == other.LatLongFields ||
this.LatLongFields != null &&
this.LatLongFields.Equals(other.LatLongFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ObjectId != null)
hash = hash * 59 + this.ObjectId.GetHashCode();
if (this.Confidence != null)
hash = hash * 59 + this.Confidence.GetHashCode();
if (this.Jurisdiction != null)
hash = hash * 59 + this.Jurisdiction.GetHashCode();
if (this.MatchedAddress != null)
hash = hash * 59 + this.MatchedAddress.GetHashCode();
if (this.SalesTax != null)
hash = hash * 59 + this.SalesTax.GetHashCode();
if (this.UseTax != null)
hash = hash * 59 + this.UseTax.GetHashCode();
if (this.Census != null)
hash = hash * 59 + this.Census.GetHashCode();
if (this.LatLongFields != null)
hash = hash * 59 + this.LatLongFields.GetHashCode();
return hash;
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace NLog.Fluent
{
/// <summary>
/// A fluent class to build log events for NLog.
/// </summary>
[Obsolete("Obsoleted since it allocates unnecessary. Instead use ILogger.ForLogEvent and LogEventBuilder. Obsoleted in NLog 5.0")]
public class LogBuilder
{
private readonly LogEventInfo _logEvent;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger)
: this(logger, LogLevel.Debug)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
/// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger, LogLevel logLevel)
{
if (logger is null)
throw new ArgumentNullException(nameof(logger));
if (logLevel is null)
throw new ArgumentNullException(nameof(logLevel));
_logger = logger;
_logEvent = new LogEventInfo() { LoggerName = logger.Name, Level = logLevel };
}
/// <summary>
/// Gets the <see cref="LogEventInfo"/> created by the builder.
/// </summary>
public LogEventInfo LogEventInfo => _logEvent;
/// <summary>
/// Sets the <paramref name="exception"/> information of the logging event.
/// </summary>
/// <param name="exception">The exception information of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Exception(Exception exception)
{
_logEvent.Exception = exception;
return this;
}
/// <summary>
/// Sets the level of the logging event.
/// </summary>
/// <param name="logLevel">The level of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Level(LogLevel logLevel)
{
if (logLevel is null)
throw new ArgumentNullException(nameof(logLevel));
_logEvent.Level = logLevel;
return this;
}
/// <summary>
/// Sets the logger name of the logging event.
/// </summary>
/// <param name="loggerName">The logger name of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder LoggerName(string loggerName)
{
_logEvent.LoggerName = loggerName;
return this;
}
/// <summary>
/// Sets the log message on the logging event.
/// </summary>
/// <param name="message">The log message for the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Message(string message)
{
_logEvent.Message = message;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <param name="arg3">The fourth object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2, object arg3)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2, arg3 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(string format, params object[] args)
{
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[MessageTemplateFormatMethod("format")]
public LogBuilder Message(IFormatProvider provider, string format, params object[] args)
{
_logEvent.FormatProvider = provider;
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets a per-event context property on the logging event.
/// </summary>
/// <param name="name">The name of the context property.</param>
/// <param name="value">The value of the context property.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Property(object name, object value)
{
if (name is null)
throw new ArgumentNullException(nameof(name));
_logEvent.Properties[name] = value;
return this;
}
/// <summary>
/// Sets multiple per-event context properties on the logging event.
/// </summary>
/// <param name="properties">The properties to set.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Properties(IDictionary properties)
{
if (properties is null)
throw new ArgumentNullException(nameof(properties));
foreach (var key in properties.Keys)
{
_logEvent.Properties[key] = properties[key];
}
return this;
}
/// <summary>
/// Sets the timestamp of the logging event.
/// </summary>
/// <param name="timeStamp">The timestamp of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder TimeStamp(DateTime timeStamp)
{
_logEvent.TimeStamp = timeStamp;
return this;
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame)
{
_logEvent.SetStackTrace(stackTrace, userStackFrame);
return this;
}
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
#if !NET35 && !NET40
public void Write(
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!_logger.IsEnabled(_logEvent.Level))
return;
SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
public void Write(
string callerMemberName = null,
string callerFilePath = null,
int callerLineNumber = 0)
{
_logger.Log(_logEvent);
}
#endif
/// <summary>
/// Writes the log event to the underlying logger if the condition delegate is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
#if !NET35 && !NET40
public void WriteIf(
Func<bool> condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (condition is null || !condition() || !_logger.IsEnabled(_logEvent.Level))
return;
SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
public void WriteIf(
Func<bool> condition,
string callerMemberName = null,
string callerFilePath = null,
int callerLineNumber = 0)
{
if (condition is null || !condition() || !_logger.IsEnabled(_logEvent.Level))
return;
_logger.Log(_logEvent);
}
#endif
/// <summary>
/// Writes the log event to the underlying logger if the condition is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
#if !NET35 && !NET40
public void WriteIf(
bool condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!condition || !_logger.IsEnabled(_logEvent.Level))
return;
SetCallerInfo(callerMemberName, callerFilePath, callerLineNumber);
_logger.Log(_logEvent);
}
#else
public void WriteIf(
bool condition,
string callerMemberName = null,
string callerFilePath = null,
int callerLineNumber = 0)
{
if (!condition || !_logger.IsEnabled(_logEvent.Level))
return;
_logger.Log(_logEvent);
}
#endif
private void SetCallerInfo(string callerMethodName, string callerFilePath, int callerLineNumber)
{
if (callerMethodName != null || callerFilePath != null || callerLineNumber != 0)
_logEvent.SetCallerInfo(null, callerMethodName, callerFilePath, callerLineNumber);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the Order class.
/// </summary>
[Serializable]
public partial class OrderCollection : RepositoryList<Order, OrderCollection>
{
public OrderCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>OrderCollection</returns>
public OrderCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Order o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Orders table.
/// </summary>
[Serializable]
public partial class Order : RepositoryRecord<Order>, IRecordBase
{
#region .ctors and Default Settings
public Order()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Order(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Orders", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = true;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = true;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
colvarOrderID.DefaultSetting = @"";
colvarOrderID.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = true;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "Customers";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 0;
colvarEmployeeID.AutoIncrement = false;
colvarEmployeeID.IsNullable = true;
colvarEmployeeID.IsPrimaryKey = false;
colvarEmployeeID.IsForeignKey = true;
colvarEmployeeID.IsReadOnly = false;
colvarEmployeeID.DefaultSetting = @"";
colvarEmployeeID.ForeignKeyTableName = "Employees";
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema);
colvarOrderDate.ColumnName = "OrderDate";
colvarOrderDate.DataType = DbType.DateTime;
colvarOrderDate.MaxLength = 0;
colvarOrderDate.AutoIncrement = false;
colvarOrderDate.IsNullable = true;
colvarOrderDate.IsPrimaryKey = false;
colvarOrderDate.IsForeignKey = false;
colvarOrderDate.IsReadOnly = false;
colvarOrderDate.DefaultSetting = @"";
colvarOrderDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderDate);
TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema);
colvarRequiredDate.ColumnName = "RequiredDate";
colvarRequiredDate.DataType = DbType.DateTime;
colvarRequiredDate.MaxLength = 0;
colvarRequiredDate.AutoIncrement = false;
colvarRequiredDate.IsNullable = true;
colvarRequiredDate.IsPrimaryKey = false;
colvarRequiredDate.IsForeignKey = false;
colvarRequiredDate.IsReadOnly = false;
colvarRequiredDate.DefaultSetting = @"";
colvarRequiredDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarRequiredDate);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
colvarShippedDate.DefaultSetting = @"";
colvarShippedDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarShipVia = new TableSchema.TableColumn(schema);
colvarShipVia.ColumnName = "ShipVia";
colvarShipVia.DataType = DbType.Int32;
colvarShipVia.MaxLength = 0;
colvarShipVia.AutoIncrement = false;
colvarShipVia.IsNullable = true;
colvarShipVia.IsPrimaryKey = false;
colvarShipVia.IsForeignKey = true;
colvarShipVia.IsReadOnly = false;
colvarShipVia.DefaultSetting = @"";
colvarShipVia.ForeignKeyTableName = "Shippers";
schema.Columns.Add(colvarShipVia);
TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema);
colvarFreight.ColumnName = "Freight";
colvarFreight.DataType = DbType.Currency;
colvarFreight.MaxLength = 0;
colvarFreight.AutoIncrement = false;
colvarFreight.IsNullable = true;
colvarFreight.IsPrimaryKey = false;
colvarFreight.IsForeignKey = false;
colvarFreight.IsReadOnly = false;
colvarFreight.DefaultSetting = @"((0))";
colvarFreight.ForeignKeyTableName = "";
schema.Columns.Add(colvarFreight);
TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema);
colvarShipName.ColumnName = "ShipName";
colvarShipName.DataType = DbType.String;
colvarShipName.MaxLength = 40;
colvarShipName.AutoIncrement = false;
colvarShipName.IsNullable = true;
colvarShipName.IsPrimaryKey = false;
colvarShipName.IsForeignKey = false;
colvarShipName.IsReadOnly = false;
colvarShipName.DefaultSetting = @"";
colvarShipName.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipName);
TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema);
colvarShipAddress.ColumnName = "ShipAddress";
colvarShipAddress.DataType = DbType.String;
colvarShipAddress.MaxLength = 60;
colvarShipAddress.AutoIncrement = false;
colvarShipAddress.IsNullable = true;
colvarShipAddress.IsPrimaryKey = false;
colvarShipAddress.IsForeignKey = false;
colvarShipAddress.IsReadOnly = false;
colvarShipAddress.DefaultSetting = @"";
colvarShipAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipAddress);
TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema);
colvarShipCity.ColumnName = "ShipCity";
colvarShipCity.DataType = DbType.String;
colvarShipCity.MaxLength = 15;
colvarShipCity.AutoIncrement = false;
colvarShipCity.IsNullable = true;
colvarShipCity.IsPrimaryKey = false;
colvarShipCity.IsForeignKey = false;
colvarShipCity.IsReadOnly = false;
colvarShipCity.DefaultSetting = @"";
colvarShipCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCity);
TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema);
colvarShipRegion.ColumnName = "ShipRegion";
colvarShipRegion.DataType = DbType.String;
colvarShipRegion.MaxLength = 15;
colvarShipRegion.AutoIncrement = false;
colvarShipRegion.IsNullable = true;
colvarShipRegion.IsPrimaryKey = false;
colvarShipRegion.IsForeignKey = false;
colvarShipRegion.IsReadOnly = false;
colvarShipRegion.DefaultSetting = @"";
colvarShipRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipRegion);
TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema);
colvarShipPostalCode.ColumnName = "ShipPostalCode";
colvarShipPostalCode.DataType = DbType.String;
colvarShipPostalCode.MaxLength = 10;
colvarShipPostalCode.AutoIncrement = false;
colvarShipPostalCode.IsNullable = true;
colvarShipPostalCode.IsPrimaryKey = false;
colvarShipPostalCode.IsForeignKey = false;
colvarShipPostalCode.IsReadOnly = false;
colvarShipPostalCode.DefaultSetting = @"";
colvarShipPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipPostalCode);
TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema);
colvarShipCountry.ColumnName = "ShipCountry";
colvarShipCountry.DataType = DbType.String;
colvarShipCountry.MaxLength = 15;
colvarShipCountry.AutoIncrement = false;
colvarShipCountry.IsNullable = true;
colvarShipCountry.IsPrimaryKey = false;
colvarShipCountry.IsForeignKey = false;
colvarShipCountry.IsReadOnly = false;
colvarShipCountry.DefaultSetting = @"";
colvarShipCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCountry);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Orders",schema);
}
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get { return GetColumnValue<int>(Columns.OrderID); }
set { SetColumnValue(Columns.OrderID, value); }
}
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int? EmployeeID
{
get { return GetColumnValue<int?>(Columns.EmployeeID); }
set { SetColumnValue(Columns.EmployeeID, value); }
}
[XmlAttribute("OrderDate")]
[Bindable(true)]
public DateTime? OrderDate
{
get { return GetColumnValue<DateTime?>(Columns.OrderDate); }
set { SetColumnValue(Columns.OrderDate, value); }
}
[XmlAttribute("RequiredDate")]
[Bindable(true)]
public DateTime? RequiredDate
{
get { return GetColumnValue<DateTime?>(Columns.RequiredDate); }
set { SetColumnValue(Columns.RequiredDate, value); }
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get { return GetColumnValue<DateTime?>(Columns.ShippedDate); }
set { SetColumnValue(Columns.ShippedDate, value); }
}
[XmlAttribute("ShipVia")]
[Bindable(true)]
public int? ShipVia
{
get { return GetColumnValue<int?>(Columns.ShipVia); }
set { SetColumnValue(Columns.ShipVia, value); }
}
[XmlAttribute("Freight")]
[Bindable(true)]
public decimal? Freight
{
get { return GetColumnValue<decimal?>(Columns.Freight); }
set { SetColumnValue(Columns.Freight, value); }
}
[XmlAttribute("ShipName")]
[Bindable(true)]
public string ShipName
{
get { return GetColumnValue<string>(Columns.ShipName); }
set { SetColumnValue(Columns.ShipName, value); }
}
[XmlAttribute("ShipAddress")]
[Bindable(true)]
public string ShipAddress
{
get { return GetColumnValue<string>(Columns.ShipAddress); }
set { SetColumnValue(Columns.ShipAddress, value); }
}
[XmlAttribute("ShipCity")]
[Bindable(true)]
public string ShipCity
{
get { return GetColumnValue<string>(Columns.ShipCity); }
set { SetColumnValue(Columns.ShipCity, value); }
}
[XmlAttribute("ShipRegion")]
[Bindable(true)]
public string ShipRegion
{
get { return GetColumnValue<string>(Columns.ShipRegion); }
set { SetColumnValue(Columns.ShipRegion, value); }
}
[XmlAttribute("ShipPostalCode")]
[Bindable(true)]
public string ShipPostalCode
{
get { return GetColumnValue<string>(Columns.ShipPostalCode); }
set { SetColumnValue(Columns.ShipPostalCode, value); }
}
[XmlAttribute("ShipCountry")]
[Bindable(true)]
public string ShipCountry
{
get { return GetColumnValue<string>(Columns.ShipCountry); }
set { SetColumnValue(Columns.ShipCountry, value); }
}
#endregion
//no foreign key tables defined (3)
//no ManyToMany tables defined (1)
#region Typed Columns
public static TableSchema.TableColumn OrderIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EmployeeIDColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn OrderDateColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn RequiredDateColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ShippedDateColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn ShipViaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FreightColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ShipNameColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ShipAddressColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ShipCityColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn ShipRegionColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn ShipPostalCodeColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ShipCountryColumn
{
get { return Schema.Columns[13]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string CustomerID = @"CustomerID";
public static string EmployeeID = @"EmployeeID";
public static string OrderDate = @"OrderDate";
public static string RequiredDate = @"RequiredDate";
public static string ShippedDate = @"ShippedDate";
public static string ShipVia = @"ShipVia";
public static string Freight = @"Freight";
public static string ShipName = @"ShipName";
public static string ShipAddress = @"ShipAddress";
public static string ShipCity = @"ShipCity";
public static string ShipRegion = @"ShipRegion";
public static string ShipPostalCode = @"ShipPostalCode";
public static string ShipCountry = @"ShipCountry";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JabbR.Commands;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
using JabbR.Models;
using JabbR.Services;
using JabbR.ViewModels;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace JabbR
{
[AuthorizeClaim(JabbRClaimTypes.Identifier)]
public class Chat : Hub, INotificationService
{
private static readonly TimeSpan _disconnectThreshold = TimeSpan.FromSeconds(10);
private readonly IJabbrRepository _repository;
private readonly IChatService _service;
private readonly IRecentMessageCache _recentMessageCache;
private readonly ICache _cache;
private readonly ContentProviderProcessor _resourceProcessor;
private readonly ILogger _logger;
private readonly ApplicationSettings _settings;
public Chat(ContentProviderProcessor resourceProcessor,
IChatService service,
IRecentMessageCache recentMessageCache,
IJabbrRepository repository,
ICache cache,
ILogger logger,
ApplicationSettings settings)
{
_resourceProcessor = resourceProcessor;
_service = service;
_recentMessageCache = recentMessageCache;
_repository = repository;
_cache = cache;
_logger = logger;
_settings = settings;
}
private string UserAgent
{
get
{
if (Context.Headers != null)
{
return Context.Headers["User-Agent"];
}
return null;
}
}
private bool OutOfSync
{
get
{
string version = Context.QueryString["version"];
if (String.IsNullOrEmpty(version))
{
return true;
}
return new Version(version) != Constants.JabbRVersion;
}
}
public override Task OnConnected()
{
_logger.Log("OnConnected({0})", Context.ConnectionId);
CheckStatus();
return base.OnConnected();
}
public void Join()
{
Join(reconnecting: false);
}
public void Join(bool reconnecting)
{
// Get the client state
var userId = Context.User.GetUserId();
// Try to get the user from the client state
ChatUser user = _repository.GetUserById(userId);
if (reconnecting)
{
_logger.Log("{0}:{1} connected after dropping connection.", user.Name, Context.ConnectionId);
// If the user was marked as offline then mark them inactive
if (user.Status == (int)UserStatus.Offline)
{
user.Status = (int)UserStatus.Inactive;
_repository.CommitChanges();
}
// Ensure the client is re-added
_service.AddClient(user, Context.ConnectionId, UserAgent);
}
else
{
_logger.Log("{0}:{1} connected.", user.Name, Context.ConnectionId);
// Update some user values
_service.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
}
ClientState clientState = GetClientState();
OnUserInitialize(clientState, user, reconnecting);
}
private void CheckStatus()
{
if (OutOfSync)
{
Clients.Caller.outOfSync();
}
}
private void OnUserInitialize(ClientState clientState, ChatUser user, bool reconnecting)
{
// Update the active room on the client (only if it's still a valid room)
if (user.Rooms.Any(room => room.Name.Equals(clientState.ActiveRoom, StringComparison.OrdinalIgnoreCase)))
{
// Update the active room on the client (only if it's still a valid room)
Clients.Caller.activeRoom = clientState.ActiveRoom;
}
LogOn(user, Context.ConnectionId, reconnecting);
}
public bool Send(string content, string roomName)
{
var message = new ClientMessage
{
Content = content,
Room = roomName
};
return Send(message);
}
public bool Send(ClientMessage clientMessage)
{
CheckStatus();
// reject it if it's too long
if (_settings.MaxMessageLength > 0 && clientMessage.Content.Length > _settings.MaxMessageLength)
{
throw new HubException(String.Format(LanguageResources.SendMessageTooLong, _settings.MaxMessageLength));
}
// See if this is a valid command (starts with /)
if (TryHandleCommand(clientMessage.Content, clientMessage.Room))
{
return true;
}
var userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
ChatRoom room = _repository.VerifyUserRoom(_cache, user, clientMessage.Room);
if (room == null || (room.Private && !user.AllowedRooms.Contains(room)))
{
return false;
}
// REVIEW: Is it better to use the extension method room.EnsureOpen here?
if (room.Closed)
{
throw new HubException(String.Format(LanguageResources.SendMessageRoomClosed, clientMessage.Room));
}
// Update activity *after* ensuring the user, this forces them to be active
UpdateActivity(user, room);
// Create a true unique id and save the message to the db
string id = Guid.NewGuid().ToString("d");
ChatMessage chatMessage = _service.AddMessage(user, room, id, clientMessage.Content);
_repository.CommitChanges();
var messageViewModel = new MessageViewModel(chatMessage);
if (clientMessage.Id == null)
{
// If the client didn't generate an id for the message then just
// send it to everyone. The assumption is that the client has some ui
// that it wanted to update immediately showing the message and
// then when the actual message is roundtripped it would "solidify it".
Clients.Group(room.Name).addMessage(messageViewModel, room.Name);
}
else
{
// If the client did set an id then we need to give everyone the real id first
Clients.OthersInGroup(room.Name).addMessage(messageViewModel, room.Name);
// Now tell the caller to replace the message
Clients.Caller.replaceMessage(clientMessage.Id, messageViewModel, room.Name);
}
// Add mentions
AddMentions(chatMessage);
var urls = UrlExtractor.ExtractUrls(chatMessage.Content);
if (urls.Count > 0)
{
_resourceProcessor.ProcessUrls(urls, Clients, room.Name, chatMessage.Id);
}
return true;
}
private void AddMentions(ChatMessage message)
{
var mentionedUsers = new List<ChatUser>();
foreach (var userName in MentionExtractor.ExtractMentions(message.Content))
{
ChatUser mentionedUser = _repository.GetUserByName(userName);
// Don't create a mention if
// 1. If the mentioned user doesn't exist.
// 2. If you mention yourself
// 3. If you're mentioned in a private room that you don't have access to
// 4. You've already been mentioned in this message
if (mentionedUser == null ||
mentionedUser == message.User ||
(message.Room.Private && !mentionedUser.AllowedRooms.Contains(message.Room)) ||
mentionedUsers.Contains(mentionedUser))
{
continue;
}
// mark as read if ALL of the following
// 1. user is not offline
// 2. user is not AFK
// 3. user has been active within the last 10 minutes
// 4. user is currently in the room
bool markAsRead = mentionedUser.Status != (int)UserStatus.Offline
&& !mentionedUser.IsAfk
&& (DateTimeOffset.UtcNow - mentionedUser.LastActivity) < TimeSpan.FromMinutes(10)
&& _repository.IsUserInRoom(_cache, mentionedUser, message.Room);
_service.AddNotification(mentionedUser, message, message.Room, markAsRead);
mentionedUsers.Add(mentionedUser);
}
if (mentionedUsers.Count > 0)
{
_repository.CommitChanges();
}
foreach (var user in mentionedUsers)
{
UpdateUnreadMentions(user);
}
}
private void UpdateUnreadMentions(ChatUser mentionedUser)
{
var unread = _repository.GetUnreadNotificationsCount(mentionedUser);
Clients.User(mentionedUser.Id)
.updateUnreadNotifications(unread);
}
public UserViewModel GetUserInfo()
{
var userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
return new UserViewModel(user);
}
public override Task OnReconnected()
{
_logger.Log("OnReconnected({0})", Context.ConnectionId);
var userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
if (user == null)
{
_logger.Log("Reconnect failed user {0}:{1} doesn't exist.", userId, Context.ConnectionId);
return TaskAsyncHelper.Empty;
}
// Make sure this client is being tracked
_service.AddClient(user, Context.ConnectionId, UserAgent);
var currentStatus = (UserStatus)user.Status;
if (currentStatus == UserStatus.Offline)
{
_logger.Log("{0}:{1} reconnected after temporary network problem and marked offline.", user.Name, Context.ConnectionId);
// Mark the user as inactive
user.Status = (int)UserStatus.Inactive;
_repository.CommitChanges();
// If the user was offline that means they are not in the user list so we need to tell
// everyone the user is really in the room
var userViewModel = new UserViewModel(user);
foreach (var room in user.Rooms)
{
var isOwner = user.OwnedRooms.Contains(room);
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner);
}
}
else
{
_logger.Log("{0}:{1} reconnected after temporary network problem.", user.Name, Context.ConnectionId);
}
CheckStatus();
return base.OnReconnected();
}
public override Task OnDisconnected()
{
_logger.Log("OnDisconnected({0})", Context.ConnectionId);
DisconnectClient(Context.ConnectionId, useThreshold: true);
return base.OnDisconnected();
}
public object GetCommands()
{
return CommandManager.GetCommandsMetaData();
}
public object GetShortcuts()
{
return new[] {
new { Name = "Tab or Shift + Tab", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutTabs },
new { Name = "Alt + L", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutLobby },
new { Name = "Alt + Number", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutSpecificTab }
};
}
public Task<List<LobbyRoomViewModel>> GetRooms()
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
return _repository.GetAllowedRooms(user).Select(r => new LobbyRoomViewModel
{
Name = r.Name,
Count = r.Users.Count(u => u.Status != (int)UserStatus.Offline),
Private = r.Private,
Closed = r.Closed,
Topic = r.Topic
}).ToListAsync();
}
public async Task<IEnumerable<MessageViewModel>> GetPreviousMessages(string messageId)
{
var previousMessages = await (from m in _repository.GetPreviousMessages(messageId)
orderby m.When descending
select m).Take(100).ToListAsync();
return previousMessages.AsEnumerable()
.Reverse()
.Select(m => new MessageViewModel(m));
}
public async Task LoadRooms(string[] roomNames)
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
var rooms = await _repository.Rooms.Where(r => roomNames.Contains(r.Name))
.ToListAsync();
// Can't async whenall because we'd be hitting a single
// EF context with multiple concurrent queries.
foreach (var room in rooms)
{
if (room == null || (room.Private && !user.AllowedRooms.Contains(room)))
{
continue;
}
RoomViewModel roomInfo = null;
while (true)
{
try
{
// If invoking roomLoaded fails don't get the roomInfo again
roomInfo = roomInfo ?? await GetRoomInfoCore(room);
Clients.Caller.roomLoaded(roomInfo);
break;
}
catch (Exception ex)
{
_logger.Log(ex);
}
}
}
}
public Task<RoomViewModel> GetRoomInfo(string roomName)
{
if (String.IsNullOrEmpty(roomName))
{
return null;
}
string userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
ChatRoom room = _repository.GetRoomByName(roomName);
if (room == null || (room.Private && !user.AllowedRooms.Contains(room)))
{
return null;
}
return GetRoomInfoCore(room);
}
private async Task<RoomViewModel> GetRoomInfoCore(ChatRoom room)
{
var recentMessages = _recentMessageCache.GetRecentMessages(room.Name);
// If we haven't cached enough messages just populate it now
if (recentMessages.Count == 0)
{
var messages = await (from m in _repository.GetMessagesByRoom(room)
orderby m.When descending
select m).Take(50).ToListAsync();
// Reverse them since we want to get them in chronological order
messages.Reverse();
recentMessages = messages.Select(m => new MessageViewModel(m)).ToList();
_recentMessageCache.Add(room.Name, recentMessages);
}
// Get online users through the repository
List<ChatUser> onlineUsers = await _repository.GetOnlineUsers(room).ToListAsync();
return new RoomViewModel
{
Name = room.Name,
Users = from u in onlineUsers
select new UserViewModel(u),
Owners = from u in room.Owners.Online()
select u.Name,
RecentMessages = recentMessages,
Topic = room.Topic ?? String.Empty,
Welcome = room.Welcome ?? String.Empty,
Closed = room.Closed
};
}
public void PostNotification(ClientNotification notification)
{
PostNotification(notification, executeContentProviders: true);
}
public void PostNotification(ClientNotification notification, bool executeContentProviders)
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.GetUserById(userId);
ChatRoom room = _repository.VerifyUserRoom(_cache, user, notification.Room);
// User must be an owner
if (room == null ||
!room.Owners.Contains(user) ||
(room.Private && !user.AllowedRooms.Contains(room)))
{
throw new HubException(LanguageResources.PostNotification_NotAllowed);
}
var chatMessage = new ChatMessage
{
Id = Guid.NewGuid().ToString("d"),
Content = notification.Content,
User = user,
Room = room,
HtmlEncoded = false,
ImageUrl = notification.ImageUrl,
Source = notification.Source,
When = DateTimeOffset.UtcNow,
MessageType = (int)MessageType.Notification
};
_repository.Add(chatMessage);
_repository.CommitChanges();
Clients.Group(room.Name).addMessage(new MessageViewModel(chatMessage), room.Name);
if (executeContentProviders)
{
var urls = UrlExtractor.ExtractUrls(chatMessage.Content);
if (urls.Count > 0)
{
_resourceProcessor.ProcessUrls(urls, Clients, room.Name, chatMessage.Id);
}
}
}
public void Typing(string roomName)
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.GetUserById(userId);
ChatRoom room = _repository.VerifyUserRoom(_cache, user, roomName);
if (room == null || (room.Private && !user.AllowedRooms.Contains(room)))
{
return;
}
UpdateActivity(user, room);
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).setTyping(userViewModel, room.Name);
}
public void UpdateActivity()
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.GetUserById(userId);
foreach (var room in user.Rooms)
{
UpdateActivity(user, room);
}
CheckStatus();
}
public void TabOrderChanged(string[] tabOrdering)
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.GetUserById(userId);
ChatUserPreferences userPreferences = user.Preferences;
userPreferences.TabOrder = tabOrdering.ToList();
user.Preferences = userPreferences;
_repository.CommitChanges();
Clients.User(user.Id).updateTabOrder(tabOrdering);
}
private void LogOn(ChatUser user, string clientId, bool reconnecting)
{
if (!reconnecting)
{
// Update the client state
Clients.Caller.id = user.Id;
Clients.Caller.name = user.Name;
Clients.Caller.hash = user.Hash;
Clients.Caller.unreadNotifications = user.Notifications.Count(n => !n.Read);
}
var rooms = new List<RoomViewModel>();
var privateRooms = new List<LobbyRoomViewModel>();
var userViewModel = new UserViewModel(user);
var ownedRooms = user.OwnedRooms.Select(r => r.Key);
foreach (var room in user.Rooms)
{
var isOwner = ownedRooms.Contains(room.Key);
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner);
// Add the caller to the group so they receive messages
Groups.Add(clientId, room.Name);
if (!reconnecting)
{
// Add to the list of room names
rooms.Add(new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Closed = room.Closed
});
}
}
if (!reconnecting)
{
foreach (var r in user.AllowedRooms)
{
privateRooms.Add(new LobbyRoomViewModel
{
Name = r.Name,
Count = _repository.GetOnlineUsers(r).Count(),
Private = r.Private,
Closed = r.Closed,
Topic = r.Topic
});
}
// Initialize the chat with the rooms the user is in
Clients.Caller.logOn(rooms, privateRooms, user.Preferences);
}
}
private void UpdateActivity(ChatUser user, ChatRoom room)
{
UpdateActivity(user);
OnUpdateActivity(user, room);
}
private void UpdateActivity(ChatUser user)
{
_service.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
}
private bool TryHandleCommand(string command, string room)
{
string clientId = Context.ConnectionId;
string userId = Context.User.GetUserId();
var commandManager = new CommandManager(clientId, UserAgent, userId, room, _service, _repository, _cache, this);
return commandManager.TryHandleCommand(command);
}
private void DisconnectClient(string clientId, bool useThreshold = false)
{
string userId = _service.DisconnectClient(clientId);
if (String.IsNullOrEmpty(userId))
{
_logger.Log("Failed to disconnect {0}. No user found", clientId);
return;
}
if (useThreshold)
{
Thread.Sleep(_disconnectThreshold);
}
// Query for the user to get the updated status
ChatUser user = _repository.GetUserById(userId);
// There's no associated user for this client id
if (user == null)
{
_logger.Log("Failed to disconnect {0}:{1}. No user found", userId, clientId);
return;
}
_repository.Reload(user);
_logger.Log("{0}:{1} disconnected", user.Name, Context.ConnectionId);
// The user will be marked as offline if all clients leave
if (user.Status == (int)UserStatus.Offline)
{
_logger.Log("Marking {0} offline", user.Name);
foreach (var room in user.Rooms)
{
var userViewModel = new UserViewModel(user);
Clients.OthersInGroup(room.Name).leave(userViewModel, room.Name);
}
}
}
private void OnUpdateActivity(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).updateActivity(userViewModel, room.Name);
}
private void LeaveRoom(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).leave(userViewModel, room.Name);
foreach (var client in user.ConnectedClients)
{
Groups.Remove(client.Id, room.Name);
}
OnRoomChanged(room);
}
void INotificationService.LogOn(ChatUser user, string clientId)
{
LogOn(user, clientId, reconnecting: true);
}
void INotificationService.KickUser(ChatUser targetUser, ChatRoom room)
{
foreach (var client in targetUser.ConnectedClients)
{
// Kick the user from this room
Clients.Client(client.Id).kick(room.Name);
// Remove the user from this the room group so he doesn't get the leave message
Groups.Remove(client.Id, room.Name);
}
// Tell the room the user left
LeaveRoom(targetUser, room);
}
void INotificationService.OnUserCreated(ChatUser user)
{
// Set some client state
Clients.Caller.name = user.Name;
Clients.Caller.id = user.Id;
Clients.Caller.hash = user.Hash;
// Tell the client a user was created
Clients.Caller.userCreated();
}
void INotificationService.JoinRoom(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
var roomViewModel = new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Welcome = room.Welcome ?? String.Empty,
Closed = room.Closed
};
var isOwner = user.OwnedRooms.Contains(room);
// Tell all clients to join this room
Clients.User(user.Id).joinRoom(roomViewModel);
// Tell the people in this room that you've joined
Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner);
// Notify users of the room count change
OnRoomChanged(room);
foreach (var client in user.ConnectedClients)
{
Groups.Add(client.Id, room.Name);
}
}
void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom)
{
// Build a viewmodel for the room
var roomViewModel = new RoomViewModel
{
Name = targetRoom.Name,
Private = targetRoom.Private,
Closed = targetRoom.Closed,
Topic = targetRoom.Topic ?? String.Empty,
Count = _repository.GetOnlineUsers(targetRoom).Count()
};
// Tell this client it's allowed. Pass down a viewmodel so that we can add the room to the lobby.
Clients.User(targetUser.Id).allowUser(targetRoom.Name, roomViewModel);
// Tell the calling client the granting permission into the room was successful
Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name);
}
void INotificationService.UnallowUser(ChatUser targetUser, ChatRoom targetRoom)
{
// Kick the user from the room when they are unallowed
((INotificationService)this).KickUser(targetUser, targetRoom);
// Tell this client it's no longer allowed
Clients.User(targetUser.Id).unallowUser(targetRoom.Name);
// Tell the calling client the granting permission into the room was successful
Clients.Caller.userUnallowed(targetUser.Name, targetRoom.Name);
}
void INotificationService.AddOwner(ChatUser targetUser, ChatRoom targetRoom)
{
// Tell this client it's an owner
Clients.User(targetUser.Id).makeOwner(targetRoom.Name);
var userViewModel = new UserViewModel(targetUser);
// If the target user is in the target room.
// Tell everyone in the target room that a new owner was added
if (_repository.IsUserInRoom(_cache, targetUser, targetRoom))
{
Clients.Group(targetRoom.Name).addOwner(userViewModel, targetRoom.Name);
}
// Tell the calling client the granting of ownership was successful
Clients.Caller.ownerMade(targetUser.Name, targetRoom.Name);
}
void INotificationService.RemoveOwner(ChatUser targetUser, ChatRoom targetRoom)
{
// Tell this client it's no longer an owner
Clients.User(targetUser.Id).demoteOwner(targetRoom.Name);
var userViewModel = new UserViewModel(targetUser);
// If the target user is in the target room.
// Tell everyone in the target room that the owner was removed
if (_repository.IsUserInRoom(_cache, targetUser, targetRoom))
{
Clients.Group(targetRoom.Name).removeOwner(userViewModel, targetRoom.Name);
}
// Tell the calling client the removal of ownership was successful
Clients.Caller.ownerRemoved(targetUser.Name, targetRoom.Name);
}
void INotificationService.ChangeGravatar(ChatUser user)
{
Clients.Caller.hash = user.Hash;
// Update the calling client
Clients.User(user.Id).gravatarChanged(user.Hash);
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the gravatar
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeGravatar(userViewModel, room.Name);
}
}
void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content)
{
Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name);
}
void INotificationService.SendPrivateMessage(ChatUser fromUser, ChatUser toUser, string messageText)
{
// Send a message to the sender and the sendee
Clients.User(fromUser.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText);
Clients.User(toUser.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText);
}
void INotificationService.PostNotification(ChatRoom room, ChatUser user, string message)
{
Clients.User(user.Id).postNotification(message, room.Name);
}
void INotificationService.ListRooms(ChatUser user)
{
string userId = Context.User.GetUserId();
var userModel = new UserViewModel(user);
Clients.Caller.showUsersRoomList(userModel, user.Rooms.Allowed(userId).Select(r => r.Name));
}
void INotificationService.ListUsers()
{
var users = _repository.Users.Online().Select(s => s.Name).OrderBy(s => s);
Clients.Caller.listUsers(users);
}
void INotificationService.ListUsers(IEnumerable<ChatUser> users)
{
Clients.Caller.listUsers(users.Select(s => s.Name));
}
void INotificationService.ListUsers(ChatRoom room, IEnumerable<string> names)
{
Clients.Caller.showUsersInRoom(room.Name, names);
}
void INotificationService.ListAllowedUsers(ChatRoom room)
{
Clients.Caller.listAllowedUsers(room.Name, room.Private, room.AllowedUsers.Select(s => s.Name));
}
void INotificationService.LockRoom(ChatUser targetUser, ChatRoom room)
{
var userViewModel = new UserViewModel(targetUser);
// Tell everyone that the room's locked
Clients.Clients(_repository.GetAllowedClientIds(room)).lockRoom(userViewModel, room.Name, true);
Clients.AllExcept(_repository.GetAllowedClientIds(room).ToArray()).lockRoom(userViewModel, room.Name, false);
// Tell the caller the room was successfully locked
Clients.Caller.roomLocked(room.Name);
// Notify people of the change
OnRoomChanged(room);
}
void INotificationService.CloseRoom(IEnumerable<ChatUser> users, ChatRoom room)
{
// notify all members of room that it is now closed
foreach (var user in users)
{
Clients.User(user.Id).roomClosed(room.Name);
}
// notify everyone to update their lobby
OnRoomChanged(room);
}
void INotificationService.UnCloseRoom(IEnumerable<ChatUser> users, ChatRoom room)
{
// notify all members of room that it is now re-opened
foreach (var user in users)
{
Clients.User(user.Id).roomUnClosed(room.Name);
}
// notify everyone to update their lobby
OnRoomChanged(room);
}
void INotificationService.LogOut(ChatUser user, string clientId)
{
foreach (var client in user.ConnectedClients)
{
DisconnectClient(client.Id);
Clients.Client(client.Id).logOut();
}
}
void INotificationService.ShowUserInfo(ChatUser user)
{
string userId = Context.User.GetUserId();
Clients.Caller.showUserInfo(new
{
Name = user.Name,
OwnedRooms = user.OwnedRooms
.Allowed(userId)
.Where(r => !r.Closed)
.Select(r => r.Name),
Status = ((UserStatus)user.Status).ToString(),
LastActivity = user.LastActivity,
IsAfk = user.IsAfk,
AfkNote = user.AfkNote,
Note = user.Note,
Hash = user.Hash,
Rooms = user.Rooms.Allowed(userId).Select(r => r.Name)
});
}
void INotificationService.ShowHelp()
{
Clients.Caller.showCommands();
}
void INotificationService.Invite(ChatUser user, ChatUser targetUser, ChatRoom targetRoom)
{
// Send the invite message to the sendee
Clients.User(targetUser.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name);
// Send the invite notification to the sender
Clients.User(user.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name);
}
void INotificationService.NudgeUser(ChatUser user, ChatUser targetUser)
{
// Send a nudge message to the sender and the sendee
Clients.User(targetUser.Id).nudge(user.Name, targetUser.Name, null);
Clients.User(user.Id).nudge(user.Name, targetUser.Name, null);
}
void INotificationService.NudgeRoom(ChatRoom room, ChatUser user)
{
Clients.Group(room.Name).nudge(user.Name, null, room.Name);
}
void INotificationService.LeaveRoom(ChatUser user, ChatRoom room)
{
LeaveRoom(user, room);
}
void INotificationService.OnUserNameChanged(ChatUser user, string oldUserName, string newUserName)
{
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell the user's connected clients that the name changed
Clients.User(user.Id).userNameChanged(userViewModel);
// Notify all users in the rooms
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name);
}
}
void INotificationService.ChangeAfk(ChatUser user)
{
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the note
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeAfk(userViewModel, room.Name);
}
}
void INotificationService.ChangeNote(ChatUser user)
{
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the note
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeNote(userViewModel, room.Name);
}
}
void INotificationService.ChangeFlag(ChatUser user)
{
bool isFlagCleared = String.IsNullOrWhiteSpace(user.Flag);
// Create the view model
var userViewModel = new UserViewModel(user);
// Update the calling client
Clients.User(user.Id).flagChanged(isFlagCleared, userViewModel.Country);
// Tell all users in rooms to change the flag
foreach (var room in user.Rooms)
{
Clients.Group(room.Name).changeFlag(userViewModel, room.Name);
}
}
void INotificationService.ChangeTopic(ChatUser user, ChatRoom room)
{
Clients.Group(room.Name).topicChanged(room.Name, room.Topic ?? String.Empty, user.Name);
// trigger a lobby update
OnRoomChanged(room);
}
void INotificationService.ChangeWelcome(ChatUser user, ChatRoom room)
{
bool isWelcomeCleared = String.IsNullOrWhiteSpace(room.Welcome);
var parsedWelcome = room.Welcome ?? String.Empty;
Clients.User(user.Id).welcomeChanged(isWelcomeCleared, parsedWelcome);
}
void INotificationService.GenerateMeme(ChatUser user, ChatRoom room, string message)
{
Send(message, room.Name);
}
void INotificationService.AddAdmin(ChatUser targetUser)
{
// Tell this client it's an owner
Clients.User(targetUser.Id).makeAdmin();
var userViewModel = new UserViewModel(targetUser);
// Tell all users in rooms to change the admin status
foreach (var room in targetUser.Rooms)
{
Clients.Group(room.Name).addAdmin(userViewModel, room.Name);
}
// Tell the calling client the granting of admin status was successful
Clients.Caller.adminMade(targetUser.Name);
}
void INotificationService.RemoveAdmin(ChatUser targetUser)
{
// Tell this client it's no longer an owner
Clients.User(targetUser.Id).demoteAdmin();
var userViewModel = new UserViewModel(targetUser);
// Tell all users in rooms to change the admin status
foreach (var room in targetUser.Rooms)
{
Clients.Group(room.Name).removeAdmin(userViewModel, room.Name);
}
// Tell the calling client the removal of admin status was successful
Clients.Caller.adminRemoved(targetUser.Name);
}
void INotificationService.BroadcastMessage(ChatUser user, string messageText)
{
// Tell all users in all rooms about this message
foreach (var room in _repository.Rooms)
{
Clients.Group(room.Name).broadcastMessage(messageText, room.Name);
}
}
void INotificationService.ForceUpdate()
{
Clients.All.forceUpdate();
}
private void OnRoomChanged(ChatRoom room)
{
var roomViewModel = new RoomViewModel
{
Name = room.Name,
Private = room.Private,
Closed = room.Closed,
Topic = room.Topic ?? String.Empty,
Count = _repository.GetOnlineUsers(room).Count()
};
// notify all clients who can see the room
if (!room.Private)
{
Clients.All.updateRoom(roomViewModel);
}
else
{
Clients.Clients(_repository.GetAllowedClientIds(room)).updateRoom(roomViewModel);
}
}
private ClientState GetClientState()
{
// New client state
var jabbrState = GetCookieValue("jabbr.state");
ClientState clientState = null;
if (String.IsNullOrEmpty(jabbrState))
{
clientState = new ClientState();
}
else
{
clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState);
}
return clientState;
}
private string GetCookieValue(string key)
{
Cookie cookie;
Context.RequestCookies.TryGetValue(key, out cookie);
string value = cookie != null ? cookie.Value : null;
return value != null ? Uri.UnescapeDataString(value) : null;
}
void INotificationService.BanUser(ChatUser targetUser)
{
var rooms = targetUser.Rooms.Select(x => x.Name);
foreach (var room in rooms)
{
foreach (var client in targetUser.ConnectedClients)
{
// Kick the user from this room
Clients.Client(client.Id).kick(room);
// Remove the user from this the room group so he doesn't get the leave message
Groups.Remove(client.Id, room);
}
}
Clients.User(targetUser.Id).logOut(rooms);
Clients.Caller.banUser(new
{
Name = targetUser.Name
});
}
void INotificationService.UnbanUser(ChatUser targetUser)
{
Clients.Caller.unbanUser(new
{
Name = targetUser.Name
});
}
void INotificationService.CheckBanned()
{
// Get all users that are banned
var users = _repository.Users.Where(u => u.IsBanned)
.Select(u => u.Name)
.OrderBy(u => u);
Clients.Caller.listUsers(users);
}
void INotificationService.CheckBanned(ChatUser user)
{
Clients.Caller.checkBanned(new
{
Name = user.Name,
IsBanned = user.IsBanned
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_repository.Dispose();
}
base.Dispose(disposing);
}
}
}
| |
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Connections.Security
{
internal class DuplexPipeStream : Stream
{
private readonly PipeReader _reader;
private readonly PipeWriter _writer;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public DuplexPipeStream(IDuplexPipe pipe)
{
_reader = pipe.Input;
_writer = pipe.Output;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_reader.Complete();
_writer.Complete();
}
base.Dispose(disposing);
}
public override async ValueTask DisposeAsync()
{
await _reader.CompleteAsync().ConfigureAwait(false);
await _writer.CompleteAsync().ConfigureAwait(false);
}
public override void Flush()
{
FlushAsync().GetAwaiter().GetResult();
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
FlushResult r = await _writer.FlushAsync(cancellationToken).ConfigureAwait(false);
if (r.IsCanceled) throw new OperationCanceledException(cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);
ValueTask<int> t = ReadAsync(buffer.AsMemory(offset, count));
return
t.IsCompleted ? t.GetAwaiter().GetResult() :
t.AsTask().GetAwaiter().GetResult();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
ReadResult result = await _reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (result.IsCanceled)
{
throw new OperationCanceledException();
}
ReadOnlySequence<byte> sequence = result.Buffer;
long bufferLength = sequence.Length;
SequencePosition consumed = sequence.Start;
try
{
if (bufferLength != 0)
{
int actual = (int)Math.Min(bufferLength, buffer.Length);
ReadOnlySequence<byte> slice = actual == bufferLength ? sequence : sequence.Slice(0, actual);
consumed = slice.End;
slice.CopyTo(buffer.Span);
return actual;
}
if (result.IsCompleted)
{
return 0;
}
}
finally
{
_reader.AdvanceTo(consumed);
}
// This is a buggy PipeReader implementation that returns 0 byte reads even though the PipeReader
// isn't completed or canceled.
throw new InvalidOperationException("Read zero bytes unexpectedly");
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return TaskToApm.Begin(ReadAsync(buffer, offset, count), callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
return TaskToApm.End<int>(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
return WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
}
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
FlushResult r = await _writer.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
if (r.IsCanceled) throw new OperationCanceledException(cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return TaskToApm.Begin(WriteAsync(buffer, offset, count), callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
TaskToApm.End(asyncResult);
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
return _reader.CopyToAsync(destination, cancellationToken);
}
private static void ValidateBufferArguments(byte[] buffer, int offset, int size)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > (uint)buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > (uint)(buffer.Length - offset))
{
throw new ArgumentOutOfRangeException(nameof(size));
}
}
/// <summary>
/// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern.
/// </summary>
internal static class TaskToApm
{
/// <summary>
/// Marshals the Task as an IAsyncResult, using the supplied callback and state
/// to implement the APM pattern.
/// </summary>
/// <param name="task">The Task to be marshaled.</param>
/// <param name="callback">The callback to be invoked upon completion.</param>
/// <param name="state">The state to be stored in the IAsyncResult.</param>
/// <returns>An IAsyncResult to represent the task's asynchronous operation.</returns>
public static IAsyncResult Begin(Task task, AsyncCallback callback, object state) =>
new TaskAsyncResult(task, state, callback);
/// <summary>Processes an IAsyncResult returned by Begin.</summary>
/// <param name="asyncResult">The IAsyncResult to unwrap.</param>
public static void End(IAsyncResult asyncResult)
{
if (GetTask(asyncResult) is Task t)
{
t.GetAwaiter().GetResult();
return;
}
ThrowArgumentException(asyncResult);
}
/// <summary>Processes an IAsyncResult returned by Begin.</summary>
/// <param name="asyncResult">The IAsyncResult to unwrap.</param>
public static TResult End<TResult>(IAsyncResult asyncResult)
{
if (GetTask(asyncResult) is Task<TResult> task)
{
return task.GetAwaiter().GetResult();
}
ThrowArgumentException(asyncResult);
return default!; // unreachable
}
/// <summary>Gets the task represented by the IAsyncResult.</summary>
public static Task GetTask(IAsyncResult asyncResult) => (asyncResult as TaskAsyncResult)?._task;
/// <summary>Throws an argument exception for the invalid <paramref name="asyncResult"/>.</summary>
private static void ThrowArgumentException(IAsyncResult asyncResult) =>
throw (asyncResult is null ?
new ArgumentNullException(nameof(asyncResult)) :
new ArgumentException(null, nameof(asyncResult)));
/// <summary>Provides a simple IAsyncResult that wraps a Task.</summary>
/// <remarks>
/// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state,
/// but that's very rare, in particular in a situation where someone cares about allocation, and always
/// using TaskAsyncResult simplifies things and enables additional optimizations.
/// </remarks>
internal sealed class TaskAsyncResult : IAsyncResult
{
/// <summary>The wrapped Task.</summary>
internal readonly Task _task;
/// <summary>Callback to invoke when the wrapped task completes.</summary>
private readonly AsyncCallback _callback;
/// <summary>Initializes the IAsyncResult with the Task to wrap and the associated object state.</summary>
/// <param name="task">The Task to wrap.</param>
/// <param name="state">The new AsyncState value.</param>
/// <param name="callback">Callback to invoke when the wrapped task completes.</param>
internal TaskAsyncResult(Task task, object state, AsyncCallback callback)
{
Debug.Assert(task != null);
_task = task;
AsyncState = state;
if (task.IsCompleted)
{
// Synchronous completion. Invoke the callback. No need to store it.
CompletedSynchronously = true;
callback?.Invoke(this);
}
else if (callback != null)
{
// Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in
// order to avoid running synchronously if the task has already completed by the time we get here but still run
// synchronously as part of the task's completion if the task completes after (the more common case).
_callback = callback;
_task.ConfigureAwait(continueOnCapturedContext: false)
.GetAwaiter()
.OnCompleted(InvokeCallback); // allocates a delegate, but avoids a closure
}
}
/// <summary>Invokes the callback.</summary>
private void InvokeCallback()
{
Debug.Assert(!CompletedSynchronously);
Debug.Assert(_callback != null);
_callback.Invoke(this);
}
/// <summary>Gets a user-defined object that qualifies or contains information about an asynchronous operation.</summary>
public object AsyncState { get; }
/// <summary>Gets a value that indicates whether the asynchronous operation completed synchronously.</summary>
/// <remarks>This is set lazily based on whether the <see cref="_task"/> has completed by the time this object is created.</remarks>
public bool CompletedSynchronously { get; }
/// <summary>Gets a value that indicates whether the asynchronous operation has completed.</summary>
public bool IsCompleted => _task.IsCompleted;
/// <summary>Gets a <see cref="WaitHandle"/> that is used to wait for an asynchronous operation to complete.</summary>
public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;
}
}
}
}
| |
using System;
using CoreUtilities;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using CoreUtilities.Links;
using Layout;
using System.ComponentModel;
//using System.Collections.Generic;
namespace ADD_Button
{
public class NoteDataXML_Button: NoteDataXML
{
#region constants
// public const string NotUsed = "Modifier";
#endregion
#region interface
ToolStripButton ActionButton = null;
#endregion
#region properties
private List<string> primaryDetails=null;
/// <summary>
/// Gets or sets the primary details. // This is actually an Array but only the 'first value' is handled via the menu. The rest has to be edited via the Properties.
/// </summary>
/// <value>
/// The primary details.
/// </value>
[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
public List<string> PrimaryDetails {
get {
return primaryDetails;
}
set {
primaryDetails = value;
}
}
private List<string> secondaryDetails= null;
[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
public List<string> SecondaryDetails {
get {
return secondaryDetails;
}
set {
secondaryDetails = value;
}
}
#endregion
public NoteDataXML_Button () : base()
{
CommonConstructorBehavior ();
}
public NoteDataXML_Button(int height, int width):base(height, width)
{
CommonConstructorBehavior ();
}
public NoteDataXML_Button(NoteDataInterface Note) : base(Note)
{
//this.Notelink = ((NoteDataXML_Checklist)Note).Notelink;
}
public override void CopyNote (NoteDataInterface Note)
{
base.CopyNote (Note);
this.PrimaryDetails = ((NoteDataXML_Button)Note).PrimaryDetails;
this.SecondaryDetails = ((NoteDataXML_Button)Note).SecondaryDetails;
}
protected override void CommonConstructorBehavior ()
{
base.CommonConstructorBehavior ();
Caption = Loc.Instance.GetString ("Button");
if (primaryDetails == null) {
primaryDetails = new System.Collections.Generic.List<string> ();
// primaryDetails.Add ("beep");
}
if (secondaryDetails == null) {
secondaryDetails = new System.Collections.Generic.List<string>();
// secondaryDetails.Add (Constants.BLANK);
}
}
/// <summary>
/// Registers the type.
/// </summary>
public override string RegisterType()
{
return Loc.Instance.GetString("Button");
}
protected override void CaptionChanged (string cap)
{
base.CaptionChanged (cap);
ActionButton.Text = cap;
}
protected override void DoBuildChildren (LayoutPanelBase Layout)
{
base.DoBuildChildren (Layout);
if (PrimaryDetails.Count == 0) {
PrimaryDetails.Add ("beep");
}
if (SecondaryDetails.Count == 0) {
SecondaryDetails.Add (Constants.BLANK);
}
ParentNotePanel.Height = this.CaptionLabel.Height;
this.MaximizeButton.Visible = false;
this.MinimizeButton.Visible = false;
this.captionLabel.Visible = false;
ActionButton = new ToolStripButton();
ActionButton.Text = this.captionLabel.Text;
ActionButton.Click+= HandleActionButtonClick;
CaptionLabel.Items.Insert (0, ActionButton);
ToolStripMenuItem PrimaryDetailLink =
LayoutDetails.BuildMenuPropertyEdit (Loc.Instance.GetString("Primary: {0}"),
PrimaryDetails[0],
Loc.Instance.GetString ("Enter main action (Beep, evenwindows_alpha)."),HandlePrimaryChange );
ToolStripMenuItem SecondaryDetailLink =
LayoutDetails.BuildMenuPropertyEdit (Loc.Instance.GetString("Secondary: {0}"),
SecondaryDetails[0],
Loc.Instance.GetString ("Enter secondary action (Comma delimited list of notes for evenwindows_alpha)."),
HandleSecondaryChange );
properties.DropDownItems.Add (new ToolStripSeparator());
properties.DropDownItems.Add (PrimaryDetailLink);
properties.DropDownItems.Add (SecondaryDetailLink);
}
void HandlePrimaryChange (object sender, KeyEventArgs e)
{
string tablecaption = PrimaryDetails[0];
LayoutDetails.HandleMenuLabelEdit (sender, e, ref tablecaption, SetSaveRequired);
PrimaryDetails[0] = tablecaption;
}
void HandleSecondaryChange (object sender, KeyEventArgs e)
{
string tablecaption = SecondaryDetails[0];
LayoutDetails.HandleMenuLabelEdit (sender, e, ref tablecaption, SetSaveRequired);
SecondaryDetails[0] = tablecaption;
}
void Function_Beep(string secondary)
{
Console.Beep ();
}
static void GetMasterLayoutToUse (ref LayoutPanelBase MyLayout)
{
if (MyLayout.GetIsChild == true) {
LayoutPanelBase MyPossibleLayout = MyLayout.GetAbsoluteParent ();
if (MyPossibleLayout != null) {
if (MyPossibleLayout.GetIsSystemLayout == true) {
// we only override if we have found the system layout? Will this fix
// the issue of not finding correct width of immediate parent?
// IF NOT: only revert to Absolute Layout if a note is not found
MyLayout = MyPossibleLayout;
}
}
}
}
string[] GetNotesToOperateOn (string secondary)
{
return secondary.Split (new char[1] {','}, StringSplitOptions.RemoveEmptyEntries);
}
void Function_EvenWindows (string secondary, bool alpha)
{
if (secondary != Constants.BLANK) {
string[] windows = GetNotesToOperateOn(secondary);
if (windows != null) {
int counter = 0;
LayoutPanelBase MyLayout = Layout;
GetMasterLayoutToUse (ref MyLayout);
// initial implementation just assuming 2 notes and will split 50/50
int Width = MyLayout.Width;
int Height = MyLayout.Height - MyLayout.HeightOfToolbars ();
foreach (string notename in windows) {
if (notename != Constants.BLANK) {
counter++;
NoteDataInterface note = MyLayout.FindNoteByName (notename);
if (note != null) {
note = MyLayout.GoToNote (note);
if (note != null) {
int NewWidth = Width / windows.Length;
note.Width = NewWidth;
note.Height = Height;
//note.ParentNotePanel.Top =0;
int NewTop = 0;
int newLeft = 0;
if (1 == counter) {
newLeft = 0;
} else {
newLeft = ((counter - 1) * NewWidth);
// NewMessage.Show ("Setting " + note.Caption + " " + newLeft.ToString ());
// note.ParentNotePanel.Left = newLeft;
}
if (note is NoteDataXML_SystemOnly) {
//NewMessage.Show ("System Note");
note.Maximize (true);
note.Maximize (false);
}
note.Location = new Point (newLeft, NewTop);
note.UpdateLocation ();
}
}
}
}
}
}
}
void Function_Popup(string secondary)
{
NewMessage.Show (Loc.Instance.GetString ("Message:"), secondary);
}
void Function_Visible(string secondary, bool visible)
{
if (secondary != Constants.BLANK) {
string[] windows = GetNotesToOperateOn(secondary);
if (windows != null) {
int counter = 0;
LayoutPanelBase MyLayout = Layout;
GetMasterLayoutToUse (ref MyLayout);
foreach (string notename in windows) {
if (notename != Constants.BLANK) {
counter++;
NoteDataInterface note = MyLayout.FindNoteByName (notename);
if (note != null) {
note = MyLayout.GoToNote (note);
if (note != null) {
note.Visible = visible;
note.UpdateLocation ();
}
}
}
}
}
}
}
protected override string GetIcon ()
{
return @"%*control_play.png";
}
/// <summary>
/// Function_s the even windows_ across monitors.
///
/// First code will be on the 1st monitor, the seocond on the next
/// Third and further elements ignored.
/// </summary>
/// <param name='secondarycode'>
/// Secondarycode.
/// </param>
/// <param name='alpha'>
/// If set to <c>true</c> alpha.
/// </param>
void Function_EvenWindows_AcrossMonitors (string secondarycode, bool alpha)
{
if (secondarycode != Constants.BLANK) {
string[] windows = GetNotesToOperateOn (secondarycode);
if (windows.Length != 4) {
NewMessage.Show ("The secondary string must be in the format of monitor1offset,monitor2offset,window1ToOpen,Window2ToOpen");
return;
}
int overrideLeftMonitor1 = 0;
if (Int32.TryParse (windows [0], out overrideLeftMonitor1) == false)
NewMessage.Show (Loc.Instance.GetString ("Parse failed 1"));
//NewMessage.Show (overrideLeftMonitor1.ToString ());
int overrideLeftMonitor2 = 0;
if (Int32.TryParse (windows [1], out overrideLeftMonitor2) == false)
NewMessage.Show (Loc.Instance.GetString ("Parse failed 2"));
//NewMessage.Show (overrideLeftMonitor2.ToString ());
if (windows != null) {
// we need to start the counter low because we pass 4 entries in but skip the first two
int counter = -2;
LayoutPanelBase MyLayout = Layout;
GetMasterLayoutToUse (ref MyLayout);
System.Windows.Forms.Screen[] currentScreen = System.Windows.Forms.Screen.AllScreens;
// int Width = MyLayout.Width;
// int Height = MyLayout.Height - MyLayout.HeightOfToolbars ();
foreach (string notename in windows) {
if (notename != Constants.BLANK) {
counter++;
if (counter > 0) {
NoteDataInterface note = MyLayout.FindNoteByName (notename);
if (note != null) {
note = MyLayout.GoToNote (note);
if (note != null) {
int NewWidth = 0;
int NewHeight = 0;
int newLeft = 0;
int NewTop = 0;
int WindowToUse = 0;
// if we have only one monitor then we use it for both notes (which doesn't make sense but is all we can do0
if (counter == 1 || currentScreen.Length == 1) {
// NewMessage.Show ("set to " + overrideLeftMonitor1);
newLeft = overrideLeftMonitor1;
} else {
newLeft = overrideLeftMonitor2;
// 2nd or other, will always try to refer to '2nd' screen
WindowToUse = 1;
}
// string message = String.Format ("Device Name: {0}\nBounds: {1}\nType: {2}\nWorking Area: {3}",
// currentScreen[WindowToUse].DeviceName, currentScreen[WindowToUse].Bounds.ToString (),
// currentScreen[WindowToUse].GetType().ToString (),currentScreen[WindowToUse].WorkingArea.ToString ());
// NewMessage.Show(message);
int buffer = 40;//currentScreen[WindowToUse].
//NewMessage.Show (newLeft.ToString ());
if (0 == newLeft) {
newLeft = currentScreen [WindowToUse].WorkingArea.Left;//+buffer;
}
NewTop = currentScreen [WindowToUse].WorkingArea.Top;//+buffer;
NewWidth = currentScreen [WindowToUse].WorkingArea.Width - buffer;
NewHeight = currentScreen [WindowToUse].WorkingArea.Height - (buffer*2);
note.Width = NewWidth;
note.Height = NewHeight;
if (note is NoteDataXML_SystemOnly) {
//NewMessage.Show ("System Note");
note.Maximize (true);
note.Maximize (false);
}
note.Location = new Point (newLeft, NewTop);
note.UpdateLocation ();
}
}
}
}
}
}
}
}
void HandleActionButtonClick (object sender, EventArgs e)
{
if (ParentNotePanel != null) {
ParentNotePanel.Cursor = Cursors.WaitCursor;
for (int i = 0; i < PrimaryDetails.Count; i++) {
string primarycode = PrimaryDetails [i];
string secondarycode = Constants.BLANK;
try {
secondarycode = SecondaryDetails [i];
} catch (Exception) {
// somtimes this will be empty, and we just ignore it
secondarycode = Constants.BLANK;
}
if (primarycode == "beep") {
Function_Beep (secondarycode);
} else
if (primarycode == "evenwindows_alpha") {
Function_EvenWindows (secondarycode, true);
} else
if (primarycode == "popup") {
Function_Popup (secondarycode);
} else
if (primarycode == "notevisible_true") {
Function_Visible (secondarycode, true);
} else
if (primarycode == "evenwindows_across_monitors_alpha") {
Function_EvenWindows_AcrossMonitors(secondarycode, false);
} else
if (primarycode == "notevisible_false") {
Function_Visible (secondarycode, false);
} else
if (primarycode == "hotkey") {
// how to access this? need to access parent somehow
// a callback probably
// anyway to tie into HOTKEY system for this? actually access those tokens directly? Like how plugins do this?
// idealy I'd want set to Extendview and Arrange my two current windows side by side
LayoutDetails.Instance.ManualRunHotkeyOperation (secondarycode);
}
}
ParentNotePanel.Cursor = Cursors.Default;
}
}
protected override void DoChildAppearance (AppearanceClass app)
{
base.DoChildAppearance (app);
}
public override void Save ()
{
base.Save ();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module Texture Packer Plugin for Unity3D
// @author Osipov Stanislav lacost.st@gmail.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(TPHelper))]
public class TPHelperEditor : Editor {
public bool xss;
private string msg = string.Empty;
private MessageType msgType = MessageType.Info;
//--------------------------------------
// INITIALIZE
//--------------------------------------
void Awake() {
int index = 0;
string[] atlasesNames = TPAssetPostprocessor.atlasesNames;
if(atlasesNames.Length == 0) {
return;
}
if(helper.meshTexture == null) {
setMessage ("TPMeshTexture component missing", MessageType.Error);
return;
}
foreach(string n in atlasesNames) {
if(n.Equals(helper.meshTexture.atlas)) {
helper.atlasID = index;
break;
}
index++;
}
TPAtlas atlas = helper.meshTexture.TextureAtlas;
if(atlas != null) {
index = 0;
string[] textures = atlas.frameNames;
foreach(string n in textures) {
string noExt = n.Substring (0, n.Length - 4);
if(n.Equals(helper.meshTexture.texture) || noExt.Equals(helper.meshTexture.texture)) {
helper.textureID = index;
break;
}
index++;
}
}
helper.OnAtlasChange(atlasesNames[helper.atlasID]);
string[] tx = helper.meshTexture.TextureAtlas.frameNames;
helper.OnTextureChange(tx[helper.textureID]);
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
public override void OnInspectorGUI() {
if(TPAssetPostprocessor.atlasesNames.Length == 0) {
setMessage ("No Atlas Found", MessageType.Error);
}
if(msgType != MessageType.Info) {
EditorGUILayout.HelpBox(msg, msgType);
}
if(msgType != MessageType.Error) {
string[] atlasesNames = TPAssetPostprocessor.atlasesNames;
EditorGUI.BeginChangeCheck();
helper.atlasID = EditorGUILayout.Popup("Atlas: ", helper.atlasID, atlasesNames);
if(EditorGUI.EndChangeCheck()) {
helper.OnAtlasChange(atlasesNames[helper.atlasID]);
if(helper.meshTexture.TextureAtlas == null) {
TPAssetPostprocessor.UpdateAtlasesInfromation();
return;
}
string[] textures = helper.meshTexture.TextureAtlas.frameNames;
helper.textureID = 0;
helper.OnTextureChange(textures[helper.textureID]);
}
if(helper.meshTexture != null) {
TPAtlas atlas = helper.meshTexture.TextureAtlas;
if(atlas != null) {
string[] textures = atlas.frameNames;
EditorGUI.BeginChangeCheck();
helper.textureID = EditorGUILayout.Popup("Texture: ", helper.textureID, textures);
if(EditorGUI.EndChangeCheck()) {
helper.OnTextureChange(textures[helper.textureID]);
}
}
}
helper.replaceMaterial = EditorGUILayout.Toggle ("Replace Material", helper.replaceMaterial);
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button(new GUIContent("Update"), GUILayout.Width(100))) {
TPAssetPostprocessor.UpdateAtlasesInfromation();
if(helper.meshTexture != null) {
TPAtlas atlas = helper.meshTexture.TextureAtlas;
if(atlas != null) {
string[] atlasesNames = TPAssetPostprocessor.atlasesNames;
helper.OnAtlasChange(atlasesNames[helper.atlasID]);
string[] textures = helper.meshTexture.TextureAtlas.frameNames;
helper.OnTextureChange(textures[helper.textureID]);
}
}
}
EditorGUILayout.EndHorizontal();
updateStatus ();
}
private void updateStatus() {
if(helper.meshTexture == null) {
setMessage ("TPMeshTexture component missing", MessageType.Error);
return;
}
if(hasAtlas) {
if(hasTexture) {
setMessage ("Corrects", MessageType.Info);
} else {
setMessage ("No Texture", MessageType.Warning);
}
} else {
setMessage ("No Atlas", MessageType.Warning);
}
}
//--------------------------------------
// GET / SET
//--------------------------------------
public TPHelper helper {
get {
return target as TPHelper;
}
}
public bool hasAtlas {
get {
string[] atlasesNames = TPAssetPostprocessor.atlasesNames;
foreach(string n in atlasesNames) {
string atlasName = helper.meshTexture.atlas;
int index = atlasName.LastIndexOf("/");
if(index != -1) {
index++;
atlasName = atlasName.Substring(index, atlasName.Length - index);
}
if(n.Equals(atlasName)) {
return true;
}
}
return false;
}
}
public bool hasTexture {
get {
TPAtlas atlas = helper.meshTexture.TextureAtlas;
if(atlas != null) {
string[] textures = atlas.frameNames;
foreach(string n in textures) {
string noExt = n.Substring (0, n.Length - 4);
if(n.Equals(helper.meshTexture.texture) || noExt.Equals(helper.meshTexture.texture)) {
return true;
}
}
}
return false;
}
}
//--------------------------------------
// EVENTS
//--------------------------------------
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
private void setMessage(string _msg, MessageType type) {
msg = _msg;
msgType = type;
}
//--------------------------------------
// DESTROY
//--------------------------------------
}
| |
using MQTTnet.Channel;
using MQTTnet.Diagnostics;
using MQTTnet.Exceptions;
using MQTTnet.Formatter;
using MQTTnet.Internal;
using MQTTnet.Packets;
using System;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Diagnostics.Logger;
using MQTTnet.Diagnostics.PacketInspection;
namespace MQTTnet.Adapter
{
public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter
{
const uint ErrorOperationAborted = 0x800703E3;
const int ReadBufferSize = 4096;
readonly byte[] _singleByteBuffer = new byte[1];
readonly byte[] _fixedHeaderBuffer = new byte[2];
readonly MqttPacketInspectorHandler _packetInspectorHandler;
readonly MqttNetSourceLogger _logger;
readonly IMqttChannel _channel;
readonly AsyncLock _syncRoot = new AsyncLock();
long _bytesReceived;
long _bytesSent;
public MqttChannelAdapter(IMqttChannel channel, MqttPacketFormatterAdapter packetFormatterAdapter, IMqttPacketInspector packetInspector, IMqttNetLogger logger)
{
_channel = channel ?? throw new ArgumentNullException(nameof(channel));
PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter));
_packetInspectorHandler = new MqttPacketInspectorHandler(packetInspector, logger);
if (logger == null) throw new ArgumentNullException(nameof(logger));
_logger = logger.WithSource(nameof(MqttChannelAdapter));
}
public string Endpoint => _channel.Endpoint;
public bool IsSecureConnection => _channel.IsSecureConnection;
public X509Certificate2 ClientCertificate => _channel.ClientCertificate;
public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
public long BytesSent => Interlocked.Read(ref _bytesSent);
public long BytesReceived => Interlocked.Read(ref _bytesReceived);
public bool IsReadingPacket { get; private set; }
public async Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
try
{
if (timeout == TimeSpan.Zero)
{
await _channel.ConnectAsync(cancellationToken).ConfigureAwait(false);
}
else
{
await MqttTaskTimeout.WaitAsync(t => _channel.ConnectAsync(t), timeout, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
{
if (IsWrappedException(exception))
{
throw;
}
WrapAndThrowException(exception);
}
}
public async Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
try
{
if (timeout == TimeSpan.Zero)
{
await _channel.DisconnectAsync(cancellationToken).ConfigureAwait(false);
}
else
{
await MqttTaskTimeout.WaitAsync(
t => _channel.DisconnectAsync(t), timeout, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
{
if (IsWrappedException(exception))
{
throw;
}
WrapAndThrowException(exception);
}
}
public async Task SendPacketAsync(MqttBasePacket packet, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
using (await _syncRoot.WaitAsync(cancellationToken).ConfigureAwait(false))
{
// Check for cancellation here again because "WaitAsync" might take some time.
cancellationToken.ThrowIfCancellationRequested();
try
{
var packetData = PacketFormatterAdapter.Encode(packet);
_packetInspectorHandler.BeginSendPacket(packetData);
await _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, cancellationToken).ConfigureAwait(false);
Interlocked.Add(ref _bytesReceived, packetData.Count);
_logger.Verbose("TX ({0} bytes) >>> {1}", packetData.Count, packet);
}
catch (Exception exception)
{
if (IsWrappedException(exception))
{
throw;
}
WrapAndThrowException(exception);
}
finally
{
PacketFormatterAdapter.FreeBuffer();
}
}
}
public async Task<MqttBasePacket> ReceivePacketAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
try
{
_packetInspectorHandler.BeginReceivePacket();
var receivedPacket = await ReceiveAsync(cancellationToken).ConfigureAwait(false);
if (receivedPacket == null || cancellationToken.IsCancellationRequested)
{
return null;
}
_packetInspectorHandler.EndReceivePacket();
Interlocked.Add(ref _bytesSent, receivedPacket.TotalLength);
if (PacketFormatterAdapter.ProtocolVersion == MqttProtocolVersion.Unknown)
{
PacketFormatterAdapter.DetectProtocolVersion(receivedPacket);
}
var packet = PacketFormatterAdapter.Decode(receivedPacket);
if (packet == null)
{
throw new MqttProtocolViolationException("Received malformed packet.");
}
_logger.Verbose("RX ({0} bytes) <<< {1}", receivedPacket.TotalLength, packet);
return packet;
}
catch (OperationCanceledException)
{
}
catch (ObjectDisposedException)
{
}
catch (Exception exception)
{
if (IsWrappedException(exception))
{
throw;
}
WrapAndThrowException(exception);
}
return null;
}
public void ResetStatistics()
{
Interlocked.Exchange(ref _bytesReceived, 0L);
Interlocked.Exchange(ref _bytesSent, 0L);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_channel.Dispose();
_syncRoot.Dispose();
}
base.Dispose(disposing);
}
async Task<ReceivedMqttPacket> ReceiveAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return null;
}
var readFixedHeaderResult = await ReadFixedHeaderAsync(cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
return null;
}
if (readFixedHeaderResult.ConnectionClosed)
{
return null;
}
try
{
IsReadingPacket = true;
var fixedHeader = readFixedHeaderResult.FixedHeader;
if (fixedHeader.RemainingLength == 0)
{
return new ReceivedMqttPacket(fixedHeader.Flags, new MqttPacketBodyReader(new byte[0], 0, 0), 2);
}
var bodyLength = fixedHeader.RemainingLength;
var body = new byte[bodyLength];
var bodyOffset = 0;
var chunkSize = Math.Min(ReadBufferSize, bodyLength);
do
{
var bytesLeft = body.Length - bodyOffset;
if (chunkSize > bytesLeft)
{
chunkSize = bytesLeft;
}
var readBytes = await _channel.ReadAsync(body, bodyOffset, chunkSize, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
return null;
}
if (readBytes == 0)
{
return null;
}
bodyOffset += readBytes;
} while (bodyOffset < bodyLength);
_packetInspectorHandler.FillReceiveBuffer(body);
var bodyReader = new MqttPacketBodyReader(body, 0, bodyLength);
return new ReceivedMqttPacket(fixedHeader.Flags, bodyReader, fixedHeader.TotalLength);
}
finally
{
IsReadingPacket = false;
}
}
async Task<ReadFixedHeaderResult> ReadFixedHeaderAsync(CancellationToken cancellationToken)
{
// The MQTT fixed header contains 1 byte of flags and at least 1 byte for the remaining data length.
// So in all cases at least 2 bytes must be read for a complete MQTT packet.
var buffer = _fixedHeaderBuffer;
var totalBytesRead = 0;
while (totalBytesRead < buffer.Length)
{
var bytesRead = await _channel.ReadAsync(buffer, totalBytesRead, buffer.Length - totalBytesRead, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
return null;
}
if (bytesRead == 0)
{
return new ReadFixedHeaderResult
{
ConnectionClosed = true
};
}
totalBytesRead += bytesRead;
}
_packetInspectorHandler.FillReceiveBuffer(buffer);
var hasRemainingLength = buffer[1] != 0;
if (!hasRemainingLength)
{
return new ReadFixedHeaderResult
{
FixedHeader = new MqttFixedHeader(buffer[0], 0, totalBytesRead)
};
}
var bodyLength = await ReadBodyLengthAsync(buffer[1], cancellationToken).ConfigureAwait(false);
if (!bodyLength.HasValue)
{
return new ReadFixedHeaderResult
{
ConnectionClosed = true
};
}
totalBytesRead += bodyLength.Value;
return new ReadFixedHeaderResult
{
FixedHeader = new MqttFixedHeader(buffer[0], bodyLength.Value, totalBytesRead)
};
}
async Task<int?> ReadBodyLengthAsync(byte initialEncodedByte, CancellationToken cancellationToken)
{
var offset = 0;
var multiplier = 128;
var value = initialEncodedByte & 127;
int encodedByte = initialEncodedByte;
while ((encodedByte & 128) != 0)
{
offset++;
if (offset > 3)
{
throw new MqttProtocolViolationException("Remaining length is invalid.");
}
if (cancellationToken.IsCancellationRequested)
{
return null;
}
var readCount = await _channel.ReadAsync(_singleByteBuffer, 0, 1, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
return null;
}
if (readCount == 0)
{
return null;
}
_packetInspectorHandler.FillReceiveBuffer(_singleByteBuffer);
encodedByte = _singleByteBuffer[0];
value += (encodedByte & 127) * multiplier;
multiplier *= 128;
}
return value;
}
static bool IsWrappedException(Exception exception)
{
return exception is OperationCanceledException ||
exception is MqttCommunicationTimedOutException ||
exception is MqttCommunicationException ||
exception is MqttProtocolViolationException;
}
static void WrapAndThrowException(Exception exception)
{
if (exception is IOException && exception.InnerException is SocketException innerException)
{
exception = innerException;
}
if (exception is SocketException socketException)
{
if (socketException.SocketErrorCode == SocketError.OperationAborted)
{
throw new OperationCanceledException();
}
if (socketException.SocketErrorCode == SocketError.ConnectionAborted)
{
throw new MqttCommunicationException(socketException);
}
}
if (exception is COMException comException)
{
if ((uint)comException.HResult == ErrorOperationAborted)
{
throw new OperationCanceledException();
}
}
throw new MqttCommunicationException(exception);
}
}
}
| |
using System;
using System.Text;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Handlers;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithBodyTests
{
private const string ClientIp = "::1";
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
public ResponseWithBodyTests()
{
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
}
[Fact]
public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_String()
{
// given
var body = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII);
// act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// then
Check.That(response.Message.BodyData.BodyAsString).Equals("01");
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_Bytes()
{
// given
var body = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII);
// act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// then
Check.That(response.Message.BodyData.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 });
Check.That(response.Message.BodyData.BodyAsString).IsNull();
Check.That(response.Message.BodyData.Encoding).IsNull();
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_Encoding()
{
// given
var body = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
var responseBuilder = Response.Create().WithBody("test", null, Encoding.ASCII);
// act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// then
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_Object_Encoding()
{
// given
var body = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
object x = new { value = "test" };
var responseBuilder = Response.Create().WithBodyAsJson(x, Encoding.ASCII);
// act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// then
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_Object_Indented()
{
// given
var body = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
object x = new { message = "Hello" };
var responseBuilder = Response.Create().WithBodyAsJson(x, true);
// act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// then
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
Check.That(response.Message.BodyData.BodyAsJsonIndented).IsEqualTo(true);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_SameAsSource_Encoding()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.SameAsSource, Encoding.ASCII);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response.Message.BodyData.BodyAsJson).IsNull();
Check.That(response.Message.BodyData.BodyAsString).Equals("r");
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_Bytes_Encoding()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.Bytes, Encoding.ASCII);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).IsNull();
Check.That(response.Message.BodyData.BodyAsJson).IsNull();
Check.That(response.Message.BodyData.BodyAsBytes).IsNotNull();
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_Json_Encoding()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
var responseBuilder = Response.Create().WithBody("{ \"value\": 42 }", BodyDestinationFormat.Json, Encoding.ASCII);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).IsNull();
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
Check.That(((dynamic)response.Message.BodyData.BodyAsJson).value).Equals(42);
Check.That(response.Message.BodyData.Encoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_Func()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/test"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithStatusCode(500)
.WithHeader("H1", "X1")
.WithHeader("H2", "X2")
.WithBody(req => $"path: {req.Path}");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response.Message.BodyData.BodyAsJson).IsNull();
Check.That(response.Message.BodyData.Encoding.CodePage).Equals(Encoding.UTF8.CodePage);
Check.That(response.Message.StatusCode).IsEqualTo(500);
Check.That(response.Message.Headers["H1"].ToString()).IsEqualTo("X1");
Check.That(response.Message.Headers["H2"].ToString()).IsEqualTo("X2");
}
[Fact]
public async Task Response_ProvideResponse_WithBody_FuncAsync()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/test"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithStatusCode(500)
.WithHeader("H1", "X1")
.WithHeader("H2", "X2")
.WithBody(async req =>
{
await Task.Delay(1).ConfigureAwait(false);
return $"path: {req.Path}";
});
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response.Message.BodyData.BodyAsJson).IsNull();
Check.That(response.Message.BodyData.Encoding.CodePage).Equals(Encoding.UTF8.CodePage);
Check.That(response.Message.StatusCode).IsEqualTo(500);
Check.That(response.Message.Headers["H1"].ToString()).IsEqualTo("X1");
Check.That(response.Message.Headers["H2"].ToString()).IsEqualTo("X2");
}
[Fact]
public async Task Response_ProvideResponse_WithJsonBodyAndTransform_Func()
{
// Assign
const int request1Id = 1;
const int request2Id = 2;
var request1 = new RequestMessage(new UrlDetails($"http://localhost/test?id={request1Id}"), "GET", ClientIp);
var request2 = new RequestMessage(new UrlDetails($"http://localhost/test?id={request2Id}"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithStatusCode(200)
.WithBodyAsJson(JObject.Parse("{ \"id\": \"{{request.query.id}}\" }"))
.WithTransformer();
// Act
var response1 = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
var response2 = await responseBuilder.ProvideResponseAsync(request2, _settings).ConfigureAwait(false);
// Assert
Check.That(((JToken)response1.Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request1Id);
Check.That(response1.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response1.Message.BodyData.BodyAsString).IsNull();
Check.That(response1.Message.StatusCode).IsEqualTo(200);
Check.That(((JToken)response2.Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request2Id);
Check.That(response2.Message.BodyData.BodyAsBytes).IsNull();
Check.That(response2.Message.BodyData.BodyAsString).IsNull();
Check.That(response2.Message.StatusCode).IsEqualTo(200);
}
[Fact]
public async Task Response_ProvideResponse_WithBodyAsFile()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "PUT", ClientIp, bodyDataAsFile);
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
Check.That(response.Message.StatusCode).IsEqualTo(200);
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
}
[Fact]
public async Task Response_ProvideResponse_WithResponseAsFile()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "GET", ClientIp, bodyDataAsFile);
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
Check.That(response.Message.StatusCode).IsEqualTo(200);
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
}
[Fact]
public async Task Response_ProvideResponse_WithResponseDeleted()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "DELETE", ClientIp, bodyDataAsFile);
var responseBuilder = Response.Create().WithStatusCode(200).WithBody("File deleted.");
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
Check.That(response.Message.StatusCode).IsEqualTo(200);
Check.That(response.Message.BodyData.BodyAsString).Contains("File deleted.");
}
}
}
| |
namespace Microsoft.Azure.Management.Compute.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Describes a Virtual Machine Scale Set.
/// </summary>
public partial class VirtualMachineScaleSet : Resource
{
/// <summary>
/// Initializes a new instance of the VirtualMachineScaleSet class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="sku">The virtual machine scale set sku.</param>
/// <param name="plan">Specifies information about the marketplace
/// image used to create the virtual machine. This element is only used
/// for marketplace images. Before you can use a marketplace image from
/// an API, you must enable the image for programmatic use. In the
/// Azure portal, find the marketplace image that you want to use and
/// then click **Want to deploy programmatically, Get Started ->**.
/// Enter any required information and then click **Save**.</param>
/// <param name="upgradePolicy">The upgrade policy.</param>
/// <param name="automaticRepairsPolicy">Policy for automatic
/// repairs.</param>
/// <param name="virtualMachineProfile">The virtual machine
/// profile.</param>
/// <param name="provisioningState">The provisioning state, which only
/// appears in the response.</param>
/// <param name="overprovision">Specifies whether the Virtual Machine
/// Scale Set should be overprovisioned.</param>
/// <param name="doNotRunExtensionsOnOverprovisionedVMs">When
/// Overprovision is enabled, extensions are launched only on the
/// requested number of VMs which are finally kept. This property will
/// hence ensure that the extensions do not run on the extra
/// overprovisioned VMs.</param>
/// <param name="uniqueId">Specifies the ID which uniquely identifies a
/// Virtual Machine Scale Set.</param>
/// <param name="singlePlacementGroup">When true this limits the scale
/// set to a single placement group, of max size 100 virtual machines.
/// NOTE: If singlePlacementGroup is true, it may be modified to false.
/// However, if singlePlacementGroup is false, it may not be modified
/// to true.</param>
/// <param name="zoneBalance">Whether to force strictly even Virtual
/// Machine distribution cross x-zones in case there is zone
/// outage.</param>
/// <param name="platformFaultDomainCount">Fault Domain count for each
/// placement group.</param>
/// <param name="proximityPlacementGroup">Specifies information about
/// the proximity placement group that the virtual machine scale set
/// should be assigned to. <br><br>Minimum api-version:
/// 2018-04-01.</param>
/// <param name="hostGroup">Specifies information about the dedicated
/// host group that the virtual machine scale set resides in.
/// <br><br>Minimum api-version: 2020-06-01.</param>
/// <param name="additionalCapabilities">Specifies additional
/// capabilities enabled or disabled on the Virtual Machines in the
/// Virtual Machine Scale Set. For instance: whether the Virtual
/// Machines have the capability to support attaching managed data
/// disks with UltraSSD_LRS storage account type.</param>
/// <param name="scaleInPolicy">Specifies the scale-in policy that
/// decides which virtual machines are chosen for removal when a
/// Virtual Machine Scale Set is scaled-in.</param>
/// <param name="identity">The identity of the virtual machine scale
/// set, if configured.</param>
/// <param name="zones">The virtual machine scale set zones. NOTE:
/// Availability zones can only be set when you create the scale
/// set</param>
/// <param name="extendedLocation">The extended location of the Virtual
/// Machine Scale Set.</param>
public VirtualMachineScaleSet(string location, string id, string name, string type, IDictionary<string, string> tags, Sku sku, Plan plan, UpgradePolicy upgradePolicy, AutomaticRepairsPolicy automaticRepairsPolicy, VirtualMachineScaleSetVMProfile virtualMachineProfile, string provisioningState, bool? overprovision, bool? doNotRunExtensionsOnOverprovisionedVMs, string uniqueId, bool? singlePlacementGroup, bool? zoneBalance, int? platformFaultDomainCount, SubResource proximityPlacementGroup, SubResource hostGroup, AdditionalCapabilities additionalCapabilities, ScaleInPolicy scaleInPolicy, VirtualMachineScaleSetIdentity identity, IList<string> zones, ExtendedLocation extendedLocation)
: base(location, id, name, type, tags)
{
Sku = sku;
Plan = plan;
UpgradePolicy = upgradePolicy;
AutomaticRepairsPolicy = automaticRepairsPolicy;
VirtualMachineProfile = virtualMachineProfile;
ProvisioningState = provisioningState;
Overprovision = overprovision;
DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs;
UniqueId = uniqueId;
SinglePlacementGroup = singlePlacementGroup;
ZoneBalance = zoneBalance;
PlatformFaultDomainCount = platformFaultDomainCount;
ProximityPlacementGroup = proximityPlacementGroup;
HostGroup = hostGroup;
AdditionalCapabilities = additionalCapabilities;
ScaleInPolicy = scaleInPolicy;
Identity = identity;
Zones = zones;
ExtendedLocation = extendedLocation;
CustomInit();
}
/// <summary>
/// Initializes a new instance of the VirtualMachineScaleSet class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="sku">The virtual machine scale set sku.</param>
/// <param name="plan">Specifies information about the marketplace
/// image used to create the virtual machine. This element is only used
/// for marketplace images. Before you can use a marketplace image from
/// an API, you must enable the image for programmatic use. In the
/// Azure portal, find the marketplace image that you want to use and
/// then click **Want to deploy programmatically, Get Started ->**.
/// Enter any required information and then click **Save**.</param>
/// <param name="upgradePolicy">The upgrade policy.</param>
/// <param name="automaticRepairsPolicy">Policy for automatic
/// repairs.</param>
/// <param name="virtualMachineProfile">The virtual machine
/// profile.</param>
/// <param name="provisioningState">The provisioning state, which only
/// appears in the response.</param>
/// <param name="overprovision">Specifies whether the Virtual Machine
/// Scale Set should be overprovisioned.</param>
/// <param name="doNotRunExtensionsOnOverprovisionedVMs">When
/// Overprovision is enabled, extensions are launched only on the
/// requested number of VMs which are finally kept. This property will
/// hence ensure that the extensions do not run on the extra
/// overprovisioned VMs.</param>
/// <param name="uniqueId">Specifies the ID which uniquely identifies a
/// Virtual Machine Scale Set.</param>
/// <param name="singlePlacementGroup">When true this limits the scale
/// set to a single placement group, of max size 100 virtual machines.
/// NOTE: If singlePlacementGroup is true, it may be modified to false.
/// However, if singlePlacementGroup is false, it may not be modified
/// to true.</param>
/// <param name="zoneBalance">Whether to force strictly even Virtual
/// Machine distribution cross x-zones in case there is zone
/// outage.</param>
/// <param name="platformFaultDomainCount">Fault Domain count for each
/// placement group.</param>
/// <param name="proximityPlacementGroup">Specifies information about
/// the proximity placement group that the virtual machine scale set
/// should be assigned to. <br><br>Minimum api-version:
/// 2018-04-01.</param>
/// <param name="hostGroup">Specifies information about the dedicated
/// host group that the virtual machine scale set resides in.
/// <br><br>Minimum api-version: 2020-06-01.</param>
/// <param name="additionalCapabilities">Specifies additional
/// capabilities enabled or disabled on the Virtual Machines in the
/// Virtual Machine Scale Set. For instance: whether the Virtual
/// Machines have the capability to support attaching managed data
/// disks with UltraSSD_LRS storage account type.</param>
/// <param name="scaleInPolicy">Specifies the scale-in policy that
/// decides which virtual machines are chosen for removal when a
/// Virtual Machine Scale Set is scaled-in.</param>
/// <param name="identity">The identity of the virtual machine scale
/// set, if configured.</param>
/// <param name="zones">The virtual machine scale set zones. NOTE:
/// Availability zones can only be set when you create the scale
/// set</param>
public VirtualMachineScaleSet(string location, string id, string name, string type, IDictionary<string, string> tags, Sku sku, Plan plan, UpgradePolicy upgradePolicy, AutomaticRepairsPolicy automaticRepairsPolicy, VirtualMachineScaleSetVMProfile virtualMachineProfile, string provisioningState, bool? overprovision, bool? doNotRunExtensionsOnOverprovisionedVMs, string uniqueId, bool? singlePlacementGroup, bool? zoneBalance, int? platformFaultDomainCount, SubResource proximityPlacementGroup, SubResource hostGroup, AdditionalCapabilities additionalCapabilities, ScaleInPolicy scaleInPolicy, VirtualMachineScaleSetIdentity identity, IList<string> zones)
: base(location, id, name, type, tags)
{
Sku = sku;
Plan = plan;
UpgradePolicy = upgradePolicy;
AutomaticRepairsPolicy = automaticRepairsPolicy;
VirtualMachineProfile = virtualMachineProfile;
ProvisioningState = provisioningState;
Overprovision = overprovision;
DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs;
UniqueId = uniqueId;
SinglePlacementGroup = singlePlacementGroup;
ZoneBalance = zoneBalance;
PlatformFaultDomainCount = platformFaultDomainCount;
ProximityPlacementGroup = proximityPlacementGroup;
HostGroup = hostGroup;
AdditionalCapabilities = additionalCapabilities;
ScaleInPolicy = scaleInPolicy;
Identity = identity;
Zones = zones;
CustomInit();
}
/// <summary>
/// Initializes a new instance of the VirtualMachineScaleSet class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="sku">The virtual machine scale set sku.</param>
/// <param name="plan">Specifies information about the marketplace
/// image used to create the virtual machine. This element is only used
/// for marketplace images. Before you can use a marketplace image from
/// an API, you must enable the image for programmatic use. In the
/// Azure portal, find the marketplace image that you want to use and
/// then click **Want to deploy programmatically, Get Started ->**.
/// Enter any required information and then click **Save**.</param>
/// <param name="upgradePolicy">The upgrade policy.</param>
/// <param name="automaticRepairsPolicy">Policy for automatic
/// repairs.</param>
/// <param name="virtualMachineProfile">The virtual machine
/// profile.</param>
/// <param name="provisioningState">The provisioning state, which only
/// appears in the response.</param>
/// <param name="overprovision">Specifies whether the Virtual Machine
/// Scale Set should be overprovisioned.</param>
/// <param name="doNotRunExtensionsOnOverprovisionedVMs">When
/// Overprovision is enabled, extensions are launched only on the
/// requested number of VMs which are finally kept. This property will
/// hence ensure that the extensions do not run on the extra
/// overprovisioned VMs.</param>
/// <param name="uniqueId">Specifies the ID which uniquely identifies a
/// Virtual Machine Scale Set.</param>
/// <param name="singlePlacementGroup">When true this limits the scale
/// set to a single placement group, of max size 100 virtual machines.
/// NOTE: If singlePlacementGroup is true, it may be modified to false.
/// However, if singlePlacementGroup is false, it may not be modified
/// to true.</param>
/// <param name="zoneBalance">Whether to force strictly even Virtual
/// Machine distribution cross x-zones in case there is zone
/// outage.</param>
/// <param name="platformFaultDomainCount">Fault Domain count for each
/// placement group.</param>
/// <param name="proximityPlacementGroup">Specifies information about
/// the proximity placement group that the virtual machine scale set
/// should be assigned to. <br><br>Minimum api-version:
/// 2018-04-01.</param>
/// <param name="hostGroup">Specifies information about the dedicated
/// host group that the virtual machine scale set resides in.
/// <br><br>Minimum api-version: 2020-06-01.</param>
/// <param name="additionalCapabilities">Specifies additional
/// capabilities enabled or disabled on the Virtual Machines in the
/// Virtual Machine Scale Set. For instance: whether the Virtual
/// Machines have the capability to support attaching managed data
/// disks with UltraSSD_LRS storage account type.</param>
/// <param name="scaleInPolicy">Specifies the scale-in policy that
/// decides which virtual machines are chosen for removal when a
/// Virtual Machine Scale Set is scaled-in.</param>
/// <param name="identity">The identity of the virtual machine scale
/// set, if configured.</param>
public VirtualMachineScaleSet(string location, string id, string name, string type, IDictionary<string, string> tags, Sku sku, Plan plan, UpgradePolicy upgradePolicy, AutomaticRepairsPolicy automaticRepairsPolicy, VirtualMachineScaleSetVMProfile virtualMachineProfile, string provisioningState, bool? overprovision, bool? doNotRunExtensionsOnOverprovisionedVMs, string uniqueId, bool? singlePlacementGroup, bool? zoneBalance, int? platformFaultDomainCount, SubResource proximityPlacementGroup, SubResource hostGroup, AdditionalCapabilities additionalCapabilities, ScaleInPolicy scaleInPolicy, VirtualMachineScaleSetIdentity identity)
: base(location, id, name, type, tags)
{
Sku = sku;
Plan = plan;
UpgradePolicy = upgradePolicy;
AutomaticRepairsPolicy = automaticRepairsPolicy;
VirtualMachineProfile = virtualMachineProfile;
ProvisioningState = provisioningState;
Overprovision = overprovision;
DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs;
UniqueId = uniqueId;
SinglePlacementGroup = singlePlacementGroup;
ZoneBalance = zoneBalance;
PlatformFaultDomainCount = platformFaultDomainCount;
ProximityPlacementGroup = proximityPlacementGroup;
HostGroup = hostGroup;
AdditionalCapabilities = additionalCapabilities;
ScaleInPolicy = scaleInPolicy;
Identity = identity;
CustomInit();
}
}
}
| |
//
// CMSync.cs: Implements the managed CMSync infrastructure
//
// Authors: Marek Safar (marek.safar@gmail.com)
//
// Copyright 2012 Xamarin Inc
//
using System;
using System.Runtime.InteropServices;
using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.CoreMedia {
public enum CMClockError
{
None = 0,
MissingRequiredParameter = -12745,
InvalidParameter = -12746,
AllocationFailed = -12747,
UnsupportedOperation = -12756,
}
[Since (6,0)]
public class CMClock : CMClockOrTimebase
{
public CMClock (IntPtr handle) : base (handle)
{
}
internal CMClock (IntPtr handle, bool owns)
: base (handle, owns)
{
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMClockGetHostTimeClock ();
public static CMClock HostTimeClock {
get {
return new CMClock (CMClockGetHostTimeClock (), false);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMClockGetTime (IntPtr clock);
public CMTime CurrentTime {
get {
return CMClockGetTime (Handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMClockError CMAudioClockCreate (IntPtr allocator, out IntPtr clockOut);
public static CMClock CreateAudioClock (out CMClockError clockError)
{
IntPtr ptr;
clockError = CMAudioClockCreate (IntPtr.Zero, out ptr);
return clockError == CMClockError.None ? new CMClock (ptr) : null;
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMClockError CMClockGetAnchorTime (IntPtr clock, out CMTime outClockTime, out CMTime outReferenceClockTime);
public CMClockError GetAnchorTime (out CMTime clockTime, out CMTime referenceClockTime)
{
return CMClockGetAnchorTime (Handle, out clockTime, out referenceClockTime);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMClockMightDrift (IntPtr clock, IntPtr otherClock);
public bool MightDrift (CMClock otherClock)
{
if (otherClock == null)
throw new ArgumentNullException ("otherClock");
return CMClockMightDrift (Handle, otherClock.Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static void CMClockInvalidate (IntPtr clock);
public void Invalidate ()
{
CMClockInvalidate (Handle);
}
[DllImport(Constants.CoreMediaLibrary, EntryPoint="CMClockConvertHostTimeToSystemUnits")]
public extern static ulong ConvertHostTimeToSystemUnits (CMTime hostTime);
[DllImport(Constants.CoreMediaLibrary, EntryPoint="CMClockMakeHostTimeFromSystemUnits")]
public extern static CMTime CreateHostTimeFromSystemUnits (ulong hostTime);
}
public enum CMTimebaseError
{
None = 0,
MissingRequiredParameter = -12748,
InvalidParameter = -12749,
AllocationFailed = -12750,
TimerIntervalTooShort = -12751,
ReadOnly = -12757,
}
[Since (6,0)]
public class CMTimebase : CMClockOrTimebase
{
public CMTimebase (IntPtr handle)
: base (handle)
{
}
private CMTimebase (IntPtr handle, bool owns)
: base (handle, owns)
{
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseCreateWithMasterClock (IntPtr allocator, IntPtr masterClock, out IntPtr timebaseOut);
public CMTimebase (CMClock masterClock)
{
if (masterClock == null)
throw new ArgumentNullException ("masterClock");
var error = CMTimebaseCreateWithMasterClock (IntPtr.Zero, masterClock.Handle, out handle);
if (error != CMTimebaseError.None)
throw new ArgumentException (error.ToString ());
CFObject.CFRetain (Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseCreateWithMasterTimebase (IntPtr allocator, IntPtr masterTimebase, out IntPtr timebaseOut);
public CMTimebase (CMTimebase masterTimebase)
{
if (masterTimebase == null)
throw new ArgumentNullException ("masterTimebase");
var error = CMTimebaseCreateWithMasterTimebase (IntPtr.Zero, masterTimebase.Handle, out handle);
if (error != CMTimebaseError.None)
throw new ArgumentException (error.ToString ());
CFObject.CFRetain (Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static double CMTimebaseGetEffectiveRate (IntPtr timebase);
public double EffectiveRate {
get {
return CMTimebaseGetEffectiveRate (Handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static double CMTimebaseGetRate (IntPtr timebase);
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetRate (IntPtr timebase, double rate);
public double Rate {
get {
return CMTimebaseGetRate (Handle);
}
set {
var error = CMTimebaseSetRate (Handle, value);
if (error != CMTimebaseError.None)
throw new ArgumentException (error.ToString ());
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMTimebaseGetTime (IntPtr timebase);
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetTime (IntPtr timebase, CMTime time);
public new CMTime Time {
get {
return CMTimebaseGetTime (Handle);
}
set {
var error = CMTimebaseSetTime (Handle, value);
if (error != CMTimebaseError.None)
throw new ArgumentException (error.ToString ());
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMTimebaseGetMasterTimebase (IntPtr timebase);
public CMTimebase GetMasterTimebase ()
{
var ptr = CMTimebaseGetMasterTimebase (Handle);
if (ptr == IntPtr.Zero)
return null;
return new CMTimebase (ptr, false);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMTimebaseGetMasterClock (IntPtr timebase);
public CMClock GetMasterClock ()
{
var ptr = CMTimebaseGetMasterClock (Handle);
if (ptr == IntPtr.Zero)
return null;
return new CMClock (ptr, false);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMTimebaseGetMaster (IntPtr timebase);
public CMClockOrTimebase GetMaster ()
{
var ptr = CMTimebaseGetMaster (Handle);
if (ptr == IntPtr.Zero)
return null;
return new CMClockOrTimebase (ptr, false);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMTimebaseGetUltimateMasterClock (IntPtr timebase);
public CMClock GetUltimateMasterClock ()
{
var ptr = CMTimebaseGetUltimateMasterClock (Handle);
if (ptr == IntPtr.Zero)
return null;
return new CMClock (ptr, false);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMTimebaseGetTimeWithTimeScale (IntPtr timebase, CMTimeScale timescale, CMTimeRoundingMethod method);
public CMTime GetTime (CMTimeScale timeScale, CMTimeRoundingMethod roundingMethod)
{
return CMTimebaseGetTimeWithTimeScale (Handle, timeScale, roundingMethod);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetAnchorTime (IntPtr timebase, CMTime timebaseTime, CMTime immediateMasterTime);
public CMTimebaseError SetAnchorTime (CMTime timebaseTime, CMTime immediateMasterTime)
{
return CMTimebaseSetAnchorTime (Handle, timebaseTime, immediateMasterTime);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseGetTimeAndRate (IntPtr timebase, out CMTime time, out double rate);
public CMTimebaseError GetTimeAndRate (out CMTime time, out double rate)
{
return CMTimebaseGetTimeAndRate (Handle, out time, out rate);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetRateAndAnchorTime (IntPtr timebase, double rate, CMTime timebaseTime, CMTime immediateMasterTime);
public CMTimebaseError SetRateAndAnchorTime (double rate, CMTime timebaseTime, CMTime immediateMasterTime)
{
return CMTimebaseSetRateAndAnchorTime (Handle, rate, timebaseTime, immediateMasterTime);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseNotificationBarrier (IntPtr timebase);
public CMTimebaseError NotificationBarrier ()
{
return CMTimebaseNotificationBarrier (handle);
}
public const double VeryLongTimeInterval = 256.0 * 365.0 * 24.0 * 60.0 * 60.0;
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseAddTimer(IntPtr timebase, /*CFRunLoopTimerRef*/ IntPtr timer, /*CFRunLoopRef*/ IntPtr runloop);
public CMTimebaseError AddTimer (NSTimer timer, NSRunLoop runloop)
{
if (timer == null)
throw new ArgumentNullException ("timer");
if (runloop == null)
throw new ArgumentNullException ("runloop");
// FIXME: Crashes inside CoreMedia
return CMTimebaseAddTimer (Handle, timer.Handle, runloop.Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseRemoveTimer (IntPtr timebase, /*CFRunLoopTimerRef*/ IntPtr timer);
public CMTimebaseError RemoveTimer (NSTimer timer)
{
if (timer == null)
throw new ArgumentNullException ("timer");
return CMTimebaseRemoveTimer (Handle, timer.Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetTimerNextFireTime (IntPtr timebase, /*CFRunLoopTimerRef*/ IntPtr timer, CMTime fireTime, uint flags);
public CMTimebaseError SetTimerNextFireTime (NSTimer timer, CMTime fireTime)
{
if (timer == null)
throw new ArgumentNullException ("timer");
return CMTimebaseSetTimerNextFireTime (Handle, timer.Handle, fireTime, 0);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTimebaseError CMTimebaseSetTimerToFireImmediately (IntPtr timebase, /*CFRunLoopTimerRef*/ IntPtr timer);
public CMTimebaseError SetTimerToFireImmediately (NSTimer timer)
{
if (timer == null)
throw new ArgumentNullException ("timer");
return CMTimebaseSetTimerToFireImmediately (Handle, timer.Handle);
}
#endif
//
// Dispatch timers not supported
//
// CMTimebaseAddTimerDispatchSource
// CMTimebaseRemoveTimerDispatchSource
// CMTimebaseSetTimerDispatchSourceNextFireTime
// CMTimebaseSetTimerDispatchSourceToFireImmediately
}
public enum CMSyncError {
None = 0,
MissingRequiredParameter = -12752,
InvalidParameter = -12753,
AllocationFailed = -12754,
RateMustBeNonZero = -12755,
}
public class CMClockOrTimebase : IDisposable, INativeObject
{
internal IntPtr handle;
internal CMClockOrTimebase ()
{
}
public CMClockOrTimebase (IntPtr handle)
{
this.handle = handle;
}
internal CMClockOrTimebase (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (Handle);
this.handle = handle;
}
~CMClockOrTimebase ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (Handle != IntPtr.Zero){
CFObject.CFRelease (Handle);
handle = IntPtr.Zero;
}
}
public IntPtr Handle {
get {
return handle;
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSyncGetTime (IntPtr clockOrTimebase);
public CMTime Time {
get {
return CMSyncGetTime (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static double CMSyncGetRelativeRate (IntPtr ofClockOrTimebase, IntPtr relativeToClockOrTimebase);
public static double GetRelativeRate (CMClockOrTimebase clockOrTimebaseA, CMClockOrTimebase clockOrTimebaseB)
{
if (clockOrTimebaseA == null)
throw new ArgumentNullException ("clockOrTimebaseA");
if (clockOrTimebaseB == null)
throw new ArgumentNullException ("clockOrTimebaseB");
return CMSyncGetRelativeRate (clockOrTimebaseA.Handle, clockOrTimebaseB.Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMSyncError CMSyncGetRelativeRateAndAnchorTime (IntPtr ofClockOrTimebase, IntPtr relativeToClockOrTimebase,
out double outRelativeRate, out CMTime outOfClockOrTimebaseAnchorTime, out CMTime outRelativeToClockOrTimebaseAnchorTime);
public static CMSyncError GetRelativeRateAndAnchorTime (CMClockOrTimebase clockOrTimebaseA, CMClockOrTimebase clockOrTimebaseB, out double relativeRate, out CMTime timeA, out CMTime timeB)
{
if (clockOrTimebaseA == null)
throw new ArgumentNullException ("clockOrTimebaseA");
if (clockOrTimebaseB == null)
throw new ArgumentNullException ("clockOrTimebaseB");
return CMSyncGetRelativeRateAndAnchorTime (clockOrTimebaseA.Handle, clockOrTimebaseB.handle, out relativeRate, out timeA, out timeB);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSyncConvertTime (CMTime time, IntPtr fromClockOrTimebase, IntPtr toClockOrTimebase);
public static CMTime ConvertTime (CMTime time, CMClockOrTimebase from, CMClockOrTimebase to)
{
if (from == null)
throw new ArgumentNullException ("from");
if (to == null)
throw new ArgumentNullException ("to");
return CMSyncConvertTime (time, from.Handle, to.Handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMSyncMightDrift (IntPtr clockOrTimebase1, IntPtr clockOrTimebase2);
public static bool MightDrift (CMClockOrTimebase clockOrTimebaseA, CMClockOrTimebase clockOrTimebaseB)
{
if (clockOrTimebaseA == null)
throw new ArgumentNullException ("clockOrTimebaseA");
if (clockOrTimebaseB == null)
throw new ArgumentNullException ("clockOrTimebaseB");
return CMSyncMightDrift (clockOrTimebaseA.Handle, clockOrTimebaseB.Handle);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Net;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient.Clients;
using OpenLiveWriter.CoreServices.Threading;
using OpenLiveWriter.Extensibility.BlogClient;
namespace OpenLiveWriter.BlogClient
{
public delegate object BlogClientOperation(Blog blog) ;
public sealed class BlogClientHelper
{
public const string BlogHomepageUrlToken = "{blog-homepage-url}";
public const string BlogPostApiUrlToken = "{blog-postapi-url}" ;
public const string BlogIdToken = "{blog-id}" ;
public const string PostIdToken = "{post-id}" ;
public static string GetAbsoluteUrl(string url, string sourceUrl)
{
if ( url == String.Empty )
return String.Empty ;
else if ( url.IndexOf(BlogClientHelper.BlogHomepageUrlToken, StringComparison.OrdinalIgnoreCase) != -1 )
return url ;
else if ( url.IndexOf(BlogClientHelper.BlogPostApiUrlToken, StringComparison.OrdinalIgnoreCase) != -1 )
return url ;
else
return UrlHelper.UrlCombineIfRelative(sourceUrl, url) ;
}
public static string FormatUrl(string url, string homepageUrl, string postApiUrl, string hostBlogId)
{
return FormatUrl(url, homepageUrl, postApiUrl, hostBlogId, null) ;
}
public static string FormatUrl(string url, string homepageUrl, string postApiUrl, string hostBlogId, string postId)
{
if ( homepageUrl != null )
{
homepageUrl = UrlHelper.InsureTrailingSlash(homepageUrl) ;
// If the url starts with a homepage url token, then
// the rest of the URL is basically a relative url from
// the homepage. In this case we need to do special
// processing to make sure that any index document carried
// on the homepage url is not substituted
if ( url.StartsWith(BlogHomepageUrlToken, StringComparison.OrdinalIgnoreCase) && (url.Length > BlogHomepageUrlToken.Length) )
{
string relativePart = url.Substring(BlogHomepageUrlToken.Length) ;
url = UrlHelper.UrlCombine(homepageUrl, relativePart) ;
}
else
{
// note sure why anyone would use the homepage url token
// not at the start, but handle this case anyway
url = url.Replace(BlogHomepageUrlToken, homepageUrl) ;
}
}
if ( postApiUrl != null )
{
url = url.Replace(BlogPostApiUrlToken, postApiUrl );
}
if ( hostBlogId != null )
{
url = url.Replace(BlogIdToken, hostBlogId ) ;
}
if ( postId != null )
{
url = url.Replace(PostIdToken, postId) ;
}
return url ;
}
public static HttpWebResponse SendAuthenticatedHttpRequest( string requestUri, HttpRequestFilter filter, HttpRequestFilter credentialsFilter )
{
// build filter list
ArrayList filters = new ArrayList();
if ( filter != null )
filters.Add(filter) ;
if ( credentialsFilter != null )
filters.Add(credentialsFilter) ;
// send request
try
{
return HttpRequestHelper.SendRequest(
requestUri,
CompoundHttpRequestFilter.Create(filters.ToArray(typeof(HttpRequestFilter)) as HttpRequestFilter[]) ) ;
}
catch(BlogClientOperationCancelledException)
{
// if we are in silent mode and failed to authenticate then try again w/o requiring auth
if ( BlogClientUIContext.SilentModeForCurrentThread )
{
return HttpRequestHelper.SendRequest( requestUri, filter ) ;
}
else
{
throw ;
}
}
}
public static WinInetCredentialsContext GetCredentialsContext(string blogId, string url)
{
using (BlogSettings blogSettings = BlogSettings.ForBlogId(blogId) )
{
IBlogSettingsAccessor settings = blogSettings as IBlogSettingsAccessor ;
return GetCredentialsContext( BlogClientManager.CreateClient(settings), settings.Credentials, url) ;
}
}
public static WinInetCredentialsContext GetCredentialsContext(IBlogClient blogClient, IBlogCredentialsAccessor credentials, string url)
{
// determine cookies and/or network credentials
CookieString cookieString = null ;
NetworkCredential credential = null ;
if ( credentials != null && credentials.Username != String.Empty )
{
credential = new NetworkCredential(credentials.Username, credentials.Password);
}
if ( cookieString != null || credential != null )
return new WinInetCredentialsContext(credential, cookieString);
else
return null ;
}
public static object PerformBlogOperationWithTimeout(string blogId, BlogClientOperation operation, int timeoutMs)
{
return PerformBlogOperationWithTimeout(blogId, operation, timeoutMs, true) ;
}
/// <summary>
/// Perform a blog operation with a timeout. If the operation could not be completed for any reason (including
/// an invalid blog, no credentials, a network error, or a timeout) then null is returned.
/// </summary>
/// <param name="owner"></param>
/// <param name="blogId"></param>
/// <param name="operation"></param>
/// <param name="timeoutMs"></param>
/// <returns></returns>
public static object PerformBlogOperationWithTimeout(string blogId, BlogClientOperation operation, int timeoutMs, bool verifyCredentials)
{
try
{
// null for invalid blogs
if ( !BlogSettings.BlogIdIsValid(blogId) )
return null ;
// null if the user can't authenticate
if ( verifyCredentials )
{
using ( Blog blog = new Blog(blogId) )
{
if ( !blog.VerifyCredentials() )
return null ;
}
}
// fire up the thread
BlogClientOperationThread operationThread = new BlogClientOperationThread(blogId, operation);
Thread thread = ThreadHelper.NewThread(new ThreadStart(operationThread.ThreadMain), "BlogClientOperationThread", true, false, true) ;
thread.Start();
// wait for it to complete
thread.Join(timeoutMs) ;
// return the result
return operationThread.Result ;
}
catch(Exception ex)
{
Trace.WriteLine("Exception occurred performing BlogOperation: " + ex.ToString());
return null ;
}
}
private class BlogClientOperationThread
{
public BlogClientOperationThread(string blogId, BlogClientOperation operation)
{
_blogId = blogId ;
_operation = operation ;
}
public void ThreadMain()
{
try
{
using ( Blog blog = new Blog(_blogId) )
{
_result = _operation(blog) ;
}
}
catch(Exception ex)
{
Debug.WriteLine("Exception occurred performing BlogOperation: " + ex.ToString());
}
}
public object Result
{
get { return _result; }
}
private volatile object _result = null;
private readonly string _blogId ;
private readonly BlogClientOperation _operation ;
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Disable warning CS0108: 'x' hides inherited member 'y'. Use the new keyword if hiding was intended.
#pragma warning disable 0108
namespace Ookii.Dialogs.Interop
{
[ComImport(),
Guid(IIDGuid.IModalWindow),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IModalWindow
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
int Show([In] IntPtr parent);
}
[ComImport(),
Guid(IIDGuid.IFileDialog),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog : IModalWindow
{
// Defined on IModalWindow - repeated here due to requirements of COM interop layer
// --------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
int Show([In] IntPtr parent);
// IFileDialog-Specific interface members
// --------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] NativeMethods.COMDLG_FILTERSPEC[] rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Advise([In, MarshalAs(UnmanagedType.Interface)] IFileDialogEvents pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOptions([In] NativeMethods.FILEOPENDIALOGOPTIONS fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetOptions(out NativeMethods.FILEOPENDIALOGOPTIONS pfos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, NativeMethods.FDAP fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Close([MarshalAs(UnmanagedType.Error)] int hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ClearClientData();
// Not supported: IShellItemFilter is not defined, converting to IntPtr
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport(),
Guid(IIDGuid.IFileOpenDialog),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileOpenDialog : IFileDialog
{
// Defined on IModalWindow - repeated here due to requirements of COM interop layer
// --------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
int Show([In] IntPtr parent);
// Defined on IFileDialog - repeated here due to requirements of COM interop layer
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypes([In] uint cFileTypes, [In] ref NativeMethods.COMDLG_FILTERSPEC rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Advise([In, MarshalAs(UnmanagedType.Interface)] IFileDialogEvents pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOptions([In] NativeMethods.FILEOPENDIALOGOPTIONS fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetOptions(out NativeMethods.FILEOPENDIALOGOPTIONS pfos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, NativeMethods.FDAP fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Close([MarshalAs(UnmanagedType.Error)] int hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ClearClientData();
// Not supported: IShellItemFilter is not defined, converting to IntPtr
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
// Defined by IFileOpenDialog
// ---------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetResults([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppenum);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectedItems([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppsai);
}
[ComImport(),
Guid(IIDGuid.IFileSaveDialog),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileSaveDialog : IFileDialog
{
// Defined on IModalWindow - repeated here due to requirements of COM interop layer
// --------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
int Show([In] IntPtr parent);
// Defined on IFileDialog - repeated here due to requirements of COM interop layer
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypes([In] uint cFileTypes, [In] ref NativeMethods.COMDLG_FILTERSPEC rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Advise([In, MarshalAs(UnmanagedType.Interface)] IFileDialogEvents pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOptions([In] NativeMethods.FILEOPENDIALOGOPTIONS fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetOptions(out NativeMethods.FILEOPENDIALOGOPTIONS pfos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, NativeMethods.FDAP fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Close([MarshalAs(UnmanagedType.Error)] int hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ClearClientData();
// Not supported: IShellItemFilter is not defined, converting to IntPtr
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
// Defined by IFileSaveDialog interface
// -----------------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetSaveAsItem([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
// Not currently supported: IPropertyStore
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetProperties([In, MarshalAs(UnmanagedType.Interface)] IntPtr pStore);
// Not currently supported: IPropertyDescriptionList
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCollectedProperties([In, MarshalAs(UnmanagedType.Interface)] IntPtr pList, [In] int fAppendDefault);
// Not currently supported: IPropertyStore
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetProperties([MarshalAs(UnmanagedType.Interface)] out IntPtr ppStore);
// Not currently supported: IPropertyStore, IFileOperationProgressSink
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ApplyProperties([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In, MarshalAs(UnmanagedType.Interface)] IntPtr pStore, [In, ComAliasName("Interop.wireHWND")] ref IntPtr hwnd, [In, MarshalAs(UnmanagedType.Interface)] IntPtr pSink);
}
[ComImport,
Guid(IIDGuid.IFileDialogEvents),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialogEvents
{
// NOTE: some of these callbacks are cancelable - returning S_FALSE means that
// the dialog should not proceed (e.g. with closing, changing folder); to
// support this, we need to use the PreserveSig attribute to enable us to return
// the proper HRESULT
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
HRESULT OnFileOk([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
PreserveSig]
HRESULT OnFolderChanging([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psiFolder);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnFolderChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnSelectionChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnShareViolation([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, out NativeMethods.FDE_SHAREVIOLATION_RESPONSE pResponse);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnTypeChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnOverwrite([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, out NativeMethods.FDE_OVERWRITE_RESPONSE pResponse);
}
[ComImport,
Guid(IIDGuid.IShellItem),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem
{
// Not supported: IBindCtx
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetDisplayName([In] NativeMethods.SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
[ComImport,
Guid(IIDGuid.IShellItemArray),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItemArray
{
// Not supported: IBindCtx
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetPropertyStore([In] int Flags, [In] ref Guid riid, out IntPtr ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetPropertyDescriptionList([In] ref NativeMethods.PROPERTYKEY keyType, [In] ref Guid riid, out IntPtr ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetAttributes([In] NativeMethods.SIATTRIBFLAGS dwAttribFlags, [In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCount(out uint pdwNumItems);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetItemAt([In] uint dwIndex, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
// Not supported: IEnumShellItems (will use GetCount and GetItemAt instead)
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void EnumItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenumShellItems);
}
[ComImport,
Guid(IIDGuid.IKnownFolder),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IKnownFolder
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetId(out Guid pkfid);
// Not yet supported - adding to fill slot in vtable
void spacer1();
//[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
//void GetCategory(out mbtagKF_CATEGORY pCategory);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetShellItem([In] uint dwFlags, ref Guid riid, out IShellItem ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetPath([In] uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] out string ppszPath);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetPath([In] uint dwFlags, [In, MarshalAs(UnmanagedType.LPWStr)] string pszPath);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetLocation([In] uint dwFlags, [Out, ComAliasName("Interop.wirePIDL")] IntPtr ppidl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolderType(out Guid pftid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetRedirectionCapabilities(out uint pCapabilities);
// Not yet supported - adding to fill slot in vtable
void spacer2();
//[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
//void GetFolderDefinition(out tagKNOWNFOLDER_DEFINITION pKFD);
}
[ComImport,
Guid(IIDGuid.IKnownFolderManager),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IKnownFolderManager
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FolderIdFromCsidl([In] int nCsidl, out Guid pfid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FolderIdToCsidl([In] ref Guid rfid, out int pnCsidl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolderIds([Out] IntPtr ppKFId, [In, Out] ref uint pCount);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder([In] ref Guid rfid, [MarshalAs(UnmanagedType.Interface)] out IKnownFolder ppkf);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolderByName([In, MarshalAs(UnmanagedType.LPWStr)] string pszCanonicalName, [MarshalAs(UnmanagedType.Interface)] out IKnownFolder ppkf);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RegisterFolder([In] ref Guid rfid, [In] ref NativeMethods.KNOWNFOLDER_DEFINITION pKFD);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void UnregisterFolder([In] ref Guid rfid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FindFolderFromPath([In, MarshalAs(UnmanagedType.LPWStr)] string pszPath, [In] NativeMethods.FFFP_MODE mode, [MarshalAs(UnmanagedType.Interface)] out IKnownFolder ppkf);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FindFolderFromIDList([In] IntPtr pidl, [MarshalAs(UnmanagedType.Interface)] out IKnownFolder ppkf);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Redirect([In] ref Guid rfid, [In] IntPtr hwnd, [In] uint Flags, [In, MarshalAs(UnmanagedType.LPWStr)] string pszTargetPath, [In] uint cFolders, [In] ref Guid pExclusion, [MarshalAs(UnmanagedType.LPWStr)] out string ppszError);
}
[ComImport,
Guid(IIDGuid.IFileDialogCustomize),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialogCustomize
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void EnableOpenDropDown([In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddMenu([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddPushButton([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddComboBox([In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddRadioButtonList([In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddCheckButton([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel, [In] bool bChecked);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddEditBox([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddSeparator([In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddText([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetControlLabel([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetControlState([In] int dwIDCtl, [Out] out NativeMethods.CDCONTROLSTATE pdwState);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetControlState([In] int dwIDCtl, [In] NativeMethods.CDCONTROLSTATE dwState);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetEditBoxText([In] int dwIDCtl, [Out] IntPtr ppszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetEditBoxText([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCheckButtonState([In] int dwIDCtl, [Out] out bool pbChecked);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCheckButtonState([In] int dwIDCtl, [In] bool bChecked);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddControlItem([In] int dwIDCtl, [In] int dwIDItem, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RemoveControlItem([In] int dwIDCtl, [In] int dwIDItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RemoveAllControlItems([In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetControlItemState([In] int dwIDCtl, [In] int dwIDItem, [Out] out NativeMethods.CDCONTROLSTATE pdwState);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetControlItemState([In] int dwIDCtl, [In] int dwIDItem, [In] NativeMethods.CDCONTROLSTATE dwState);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectedControlItem([In] int dwIDCtl, [Out] out int pdwIDItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetSelectedControlItem([In] int dwIDCtl, [In] int dwIDItem); // Not valid for OpenDropDown
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void StartVisualGroup([In] int dwIDCtl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void EndVisualGroup();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void MakeProminent([In] int dwIDCtl);
}
[ComImport,
Guid(IIDGuid.IFileDialogControlEvents),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialogControlEvents
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnItemSelected([In, MarshalAs(UnmanagedType.Interface)] IFileDialogCustomize pfdc, [In] int dwIDCtl, [In] int dwIDItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnButtonClicked([In, MarshalAs(UnmanagedType.Interface)] IFileDialogCustomize pfdc, [In] int dwIDCtl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnCheckButtonToggled([In, MarshalAs(UnmanagedType.Interface)] IFileDialogCustomize pfdc, [In] int dwIDCtl, [In] bool bChecked);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void OnControlActivating([In, MarshalAs(UnmanagedType.Interface)] IFileDialogCustomize pfdc, [In] int dwIDCtl);
}
[ComImport,
Guid(IIDGuid.IPropertyStore),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPropertyStore
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCount([Out] out uint cProps);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetAt([In] uint iProp, out NativeMethods.PROPERTYKEY pkey);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetValue([In] ref NativeMethods.PROPERTYKEY key, out object pv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetValue([In] ref NativeMethods.PROPERTYKEY key, [In] ref object pv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Commit();
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: device.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Device {
/// <summary>Holder for reflection information generated from device.proto</summary>
public static partial class DeviceReflection {
#region Descriptor
/// <summary>File descriptor for device.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DeviceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxkZXZpY2UucHJvdG8SBmRldmljZSIHCgVFbXB0eSIYCgZEZXZpY2USDgoG",
"ZGV2aWNlGAEgASgJIi4KC1RlbXBlcmF0dXJlEg4KBmRldmljZRgBIAEoCRIP",
"CgdjZWxjaXVzGAIgASgCIi4KEEVsZWN0cmljaXR5VXNhZ2USDgoGZGV2aWNl",
"GAEgASgJEgoKAmt3GAIgASgDIiYKCEdhc1VzYWdlEg4KBmRldmljZRgBIAEo",
"CRIKCgJtMxgCIAEoAzKJAQoSVGVtcGVyYXR1cmVTZXJ2aWNlEjcKD3NldF90",
"ZW1wZXJhdHVyZRITLmRldmljZS5UZW1wZXJhdHVyZRoNLmRldmljZS5FbXB0",
"eSIAEjoKD2dldF90ZW1wZXJhdHVyZRIOLmRldmljZS5EZXZpY2UaEy5kZXZp",
"Y2UuVGVtcGVyYXR1cmUiADABMowBCgxVc2FnZVNlcnZpY2USRQoYbGF0ZXN0",
"X2VsZWN0cmljaXR5X3VzYWdlEhguZGV2aWNlLkVsZWN0cmljaXR5VXNhZ2Ua",
"DS5kZXZpY2UuRW1wdHkiABI1ChBsYXRlc3RfZ2FzX3VzYWdlEhAuZGV2aWNl",
"Lkdhc1VzYWdlGg0uZGV2aWNlLkVtcHR5IgBCDwoHZXguZ3JwY6ICA0hTV2IG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Device.Empty), global::Device.Empty.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Device.Device), global::Device.Device.Parser, new[]{ "Device_" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Device.Temperature), global::Device.Temperature.Parser, new[]{ "Device", "Celcius" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Device.ElectricityUsage), global::Device.ElectricityUsage.Parser, new[]{ "Device", "Kw" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Device.GasUsage), global::Device.GasUsage.Parser, new[]{ "Device", "M3" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Empty : pb::IMessage<Empty> {
private static readonly pb::MessageParser<Empty> _parser = new pb::MessageParser<Empty>(() => new Empty());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Empty> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Device.DeviceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Empty() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Empty(Empty other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Empty Clone() {
return new Empty(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Empty);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Empty other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Empty other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
public sealed partial class Device : pb::IMessage<Device> {
private static readonly pb::MessageParser<Device> _parser = new pb::MessageParser<Device>(() => new Device());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Device> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Device.DeviceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Device() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Device(Device other) : this() {
device_ = other.device_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Device Clone() {
return new Device(this);
}
/// <summary>Field number for the "device" field.</summary>
public const int Device_FieldNumber = 1;
private string device_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Device_ {
get { return device_; }
set {
device_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Device);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Device other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Device_ != other.Device_) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Device_.Length != 0) hash ^= Device_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Device_.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Device_);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Device_.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Device_);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Device other) {
if (other == null) {
return;
}
if (other.Device_.Length != 0) {
Device_ = other.Device_;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Device_ = input.ReadString();
break;
}
}
}
}
}
public sealed partial class Temperature : pb::IMessage<Temperature> {
private static readonly pb::MessageParser<Temperature> _parser = new pb::MessageParser<Temperature>(() => new Temperature());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Temperature> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Device.DeviceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Temperature() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Temperature(Temperature other) : this() {
device_ = other.device_;
celcius_ = other.celcius_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Temperature Clone() {
return new Temperature(this);
}
/// <summary>Field number for the "device" field.</summary>
public const int DeviceFieldNumber = 1;
private string device_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Device {
get { return device_; }
set {
device_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "celcius" field.</summary>
public const int CelciusFieldNumber = 2;
private float celcius_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Celcius {
get { return celcius_; }
set {
celcius_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Temperature);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Temperature other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Device != other.Device) return false;
if (Celcius != other.Celcius) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Device.Length != 0) hash ^= Device.GetHashCode();
if (Celcius != 0F) hash ^= Celcius.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Device.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Device);
}
if (Celcius != 0F) {
output.WriteRawTag(21);
output.WriteFloat(Celcius);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Device.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Device);
}
if (Celcius != 0F) {
size += 1 + 4;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Temperature other) {
if (other == null) {
return;
}
if (other.Device.Length != 0) {
Device = other.Device;
}
if (other.Celcius != 0F) {
Celcius = other.Celcius;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Device = input.ReadString();
break;
}
case 21: {
Celcius = input.ReadFloat();
break;
}
}
}
}
}
public sealed partial class ElectricityUsage : pb::IMessage<ElectricityUsage> {
private static readonly pb::MessageParser<ElectricityUsage> _parser = new pb::MessageParser<ElectricityUsage>(() => new ElectricityUsage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ElectricityUsage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Device.DeviceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ElectricityUsage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ElectricityUsage(ElectricityUsage other) : this() {
device_ = other.device_;
kw_ = other.kw_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ElectricityUsage Clone() {
return new ElectricityUsage(this);
}
/// <summary>Field number for the "device" field.</summary>
public const int DeviceFieldNumber = 1;
private string device_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Device {
get { return device_; }
set {
device_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "kw" field.</summary>
public const int KwFieldNumber = 2;
private long kw_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Kw {
get { return kw_; }
set {
kw_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ElectricityUsage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ElectricityUsage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Device != other.Device) return false;
if (Kw != other.Kw) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Device.Length != 0) hash ^= Device.GetHashCode();
if (Kw != 0L) hash ^= Kw.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Device.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Device);
}
if (Kw != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Kw);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Device.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Device);
}
if (Kw != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Kw);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ElectricityUsage other) {
if (other == null) {
return;
}
if (other.Device.Length != 0) {
Device = other.Device;
}
if (other.Kw != 0L) {
Kw = other.Kw;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Device = input.ReadString();
break;
}
case 16: {
Kw = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class GasUsage : pb::IMessage<GasUsage> {
private static readonly pb::MessageParser<GasUsage> _parser = new pb::MessageParser<GasUsage>(() => new GasUsage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GasUsage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Device.DeviceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GasUsage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GasUsage(GasUsage other) : this() {
device_ = other.device_;
m3_ = other.m3_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GasUsage Clone() {
return new GasUsage(this);
}
/// <summary>Field number for the "device" field.</summary>
public const int DeviceFieldNumber = 1;
private string device_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Device {
get { return device_; }
set {
device_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "m3" field.</summary>
public const int M3FieldNumber = 2;
private long m3_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long M3 {
get { return m3_; }
set {
m3_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GasUsage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GasUsage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Device != other.Device) return false;
if (M3 != other.M3) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Device.Length != 0) hash ^= Device.GetHashCode();
if (M3 != 0L) hash ^= M3.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Device.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Device);
}
if (M3 != 0L) {
output.WriteRawTag(16);
output.WriteInt64(M3);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Device.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Device);
}
if (M3 != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(M3);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GasUsage other) {
if (other == null) {
return;
}
if (other.Device.Length != 0) {
Device = other.Device;
}
if (other.M3 != 0L) {
M3 = other.M3;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Device = input.ReadString();
break;
}
case 16: {
M3 = input.ReadInt64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Build.Tasks.Xaml
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xaml;
using System.Xaml.Schema;
using System.Reflection;
using System.Runtime;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.IO;
internal class XamlValidatingReader : XamlWrappingReader
{
XamlStackWriter _stack = new XamlStackWriter();
Assembly assembly;
Type definedType;
string rootNamespace;
string localAssemblyName;
string realAssemblyName;
// We use this instead of XamlLanguage.Null, because XamlLanguage uses live types
// where we use ROL
XamlType xNull;
public event EventHandler<ValidationEventArgs> OnValidationError;
public XamlValidatingReader(XamlReader underlyingReader, Assembly assembly, string rootNamespace, string realAssemblyName)
: base(underlyingReader)
{
this.assembly = assembly;
this.definedType = null;
this.rootNamespace = rootNamespace;
this.localAssemblyName = assembly != null ? assembly.GetName().Name : null;
this.realAssemblyName = realAssemblyName;
this.xNull = underlyingReader.SchemaContext.GetXamlType(new XamlTypeName(XamlLanguage.Null));
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Need to catch and log the exception here so that all the errors, including the exception thrown, are surfaced.")]
public override bool Read()
{
if (!base.Read())
{
return false;
}
try
{
if (_stack.Depth == 0)
{
State_AtRoot();
}
else if (_stack.TopFrame.FrameType == XamlStackFrameType.Member)
{
if (_stack.TopFrame.IsSet() && !AllowsMultiple(_stack.TopFrame.Member))
{
State_ExpectEndMember();
}
else
{
State_InsideMember();
}
}
else
{
if (_stack.TopFrame.FrameType != XamlStackFrameType.Object && _stack.TopFrame.FrameType != XamlStackFrameType.GetObject)
{
ValidationError(SR.UnexpectedXaml);
}
State_InsideObject();
}
}
catch (FileLoadException e)
{
if (Fx.IsFatal(e))
{
throw;
}
ValidationError(SR.AssemblyCannotBeResolved(XamlBuildTaskServices.FileNotLoaded));
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ValidationError(e.Message);
}
return true;
}
protected virtual void ValidationError(string message, params object[] args)
{
EventHandler<ValidationEventArgs> handler = OnValidationError;
if (handler != null)
{
string formattedMessage =
(args == null || args.Length == 0) ?
message : string.Format(CultureInfo.InvariantCulture, message, args);
handler(this, new ValidationEventArgs(formattedMessage, LineNumber, LinePosition));
}
}
private void State_AtRoot()
{
switch (NodeType)
{
case XamlNodeType.NamespaceDeclaration:
return;
case XamlNodeType.StartObject:
ValidateUnknown(Type);
break;
default:
ValidationError(SR.UnexpectedXaml);
break;
}
_stack.WriteNode(this);
}
private void State_InsideObject()
{
switch (NodeType)
{
case XamlNodeType.NamespaceDeclaration:
return;
case XamlNodeType.StartMember:
if (_stack.TopFrame.IsSet(Member))
{
ValidationError(SR.UnexpectedXaml);
}
if (_stack.TopFrame.FrameType == XamlStackFrameType.GetObject)
{
ValidateMemberOnGetObject(Member);
}
else
{
ValidateUnknown(Member);
ValidateMemberOnType(Member, _stack.TopFrame.Type);
}
break;
case XamlNodeType.EndObject:
break;
default:
ValidationError(SR.UnexpectedXamlDupMember);
break;
}
_stack.WriteNode(this);
}
private void State_InsideMember()
{
switch (NodeType)
{
case XamlNodeType.NamespaceDeclaration:
return;
case XamlNodeType.StartObject:
ValidateUnknown(Type);
ValidateTypeToMemberOnStack(Type);
break;
case XamlNodeType.GetObject:
ValidateGetObjectOnMember(_stack.TopFrame.Member);
break;
case XamlNodeType.Value:
ValidateValueToMemberOnStack(Value);
break;
case XamlNodeType.EndMember:
break;
default:
ValidationError(SR.UnexpectedXaml);
break;
}
_stack.WriteNode(this);
}
private void State_ExpectEndMember()
{
if (NodeType != XamlNodeType.EndMember)
{
ValidationError(SR.UnexpectedXaml);
}
_stack.WriteNode(this);
}
private void ValidateGetObjectOnMember(XamlMember member)
{
if (member == XamlLanguage.Items || member == XamlLanguage.PositionalParameters)
{
ValidationError(SR.UnexpectedXaml);
}
else if (!member.IsUnknown && member != XamlLanguage.UnknownContent &&
!member.Type.IsCollection && !member.Type.IsDictionary)
{
ValidationError(SR.UnexpectedXaml);
}
}
private void ValidateMemberOnGetObject(XamlMember member)
{
if (member != XamlLanguage.Items)
{
ValidationError(SR.UnexpectedXaml);
}
}
private void ValidateMemberOnType(XamlMember member, XamlType type)
{
if (member.IsUnknown || type.IsUnknown)
{
return;
}
if (member.IsDirective)
{
if (member == XamlLanguage.Items)
{
if (!type.IsCollection && !type.IsDictionary)
{
ValidationError(SR.UnexpectedXamlDictionary(member.Name, GetXamlTypeName(_stack.TopFrame.Type)));
}
}
if (member == XamlLanguage.Class && _stack.Depth > 1)
{
ValidationError(SR.UnexpectedXamlClass);
}
}
else if (member.IsAttachable)
{
if (!type.CanAssignTo(member.TargetType))
{
ValidationError(SR.UnexpectedXamlAttachableMember(member.Name, GetXamlTypeName(member.TargetType)));
}
}
else if (!member.IsDirective && !type.CanAssignTo(member.DeclaringType))
{
ValidationError(SR.UnexpectedXamlMemberNotAssignable(member.Name, GetXamlTypeName(type)));
}
}
private void ValidateTypeToMemberOnStack(XamlType type)
{
if (type.IsUnknown)
{
return;
}
if (type == this.xNull)
{
ValidateValueToMemberOnStack(null);
}
XamlMember member = _stack.TopFrame.Member;
if (member == XamlLanguage.PositionalParameters || type.IsMarkupExtension || member.IsUnknown)
{
return;
}
if (member == XamlLanguage.Items)
{
XamlType collectionType = GetCollectionTypeOnStack();
if (collectionType == null || collectionType.IsUnknown || collectionType.AllowedContentTypes == null)
{
return;
}
if (!collectionType.AllowedContentTypes.Any(contentType => type.CanAssignTo(contentType)))
{
ValidationError(SR.UnassignableCollection(GetXamlTypeName(type), GetXamlTypeName(collectionType.ItemType), GetXamlTypeName(collectionType)));
}
}
else if (member.IsDirective && (member.Type.IsCollection || member.Type.IsDictionary))
{
XamlType collectionType = member.Type;
if (collectionType == null || collectionType.IsUnknown || collectionType.AllowedContentTypes == null)
{
return;
}
if (!collectionType.AllowedContentTypes.Any(contentType => type.CanAssignTo(contentType)))
{
ValidationError(SR.UnassignableCollection(GetXamlTypeName(type), GetXamlTypeName(collectionType.ItemType), GetXamlTypeName(collectionType)));
}
}
else if (!type.CanAssignTo(member.Type))
{
if (member.DeferringLoader != null)
{
return;
}
if (NodeType == XamlNodeType.Value)
{
ValidationError(SR.UnassignableTypes(GetXamlTypeName(type), GetXamlTypeName(member.Type), member.Name));
}
else
{
ValidationError(SR.UnassignableTypesObject(GetXamlTypeName(type), GetXamlTypeName(member.Type), member.Name));
}
}
}
private void ValidateValueToMemberOnStack(object value)
{
XamlMember member = _stack.TopFrame.Member;
if (member.IsUnknown)
{
return;
}
if (value != null)
{
if (member.IsEvent)
{
if (this.definedType != null && this.definedType.GetMethod(value as string,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) == null)
{
ValidationError(SR.UnexpectedXamlEventHandlerNotFound(value, definedType.FullName));
}
return;
}
else if (member == XamlLanguage.Class)
{
string className = value as string;
Fx.Assert(!string.IsNullOrEmpty(className), "ClassName cannot be null");
if (!string.IsNullOrEmpty(this.rootNamespace))
{
className = this.rootNamespace + "." + className;
}
if (this.assembly != null)
{
this.definedType = this.assembly.GetType(className);
}
return;
}
else if (member.TypeConverter != null)
{
return;
}
XamlType typeOfValue = SchemaContext.GetXamlType(value.GetType());
ValidateTypeToMemberOnStack(typeOfValue);
}
else
{
if (member == XamlLanguage.PositionalParameters)
{
return;
}
if (member == XamlLanguage.Items)
{
XamlType collectionType = GetCollectionTypeOnStack();
if (collectionType == null || collectionType.IsUnknown || collectionType.AllowedContentTypes == null)
{
return;
}
if (!collectionType.AllowedContentTypes.Any(contentType => contentType.IsNullable))
{
ValidationError(SR.UnassignableCollection("(null)", GetXamlTypeName(collectionType.ItemType), GetXamlTypeName(collectionType)));
}
}
else
{
if (!member.Type.IsNullable)
{
ValidationError(SR.UnassignableTypes("(null)", GetXamlTypeName(member.Type), member.Name));
}
}
}
}
private bool AllowsMultiple(XamlMember member)
{
return
member == XamlLanguage.Items ||
member == XamlLanguage.PositionalParameters ||
member == XamlLanguage.UnknownContent;
}
private XamlType GetCollectionTypeOnStack()
{
Fx.Assert(_stack.TopFrame.Member == XamlLanguage.Items, "CollectionType should have _Items member");
XamlType result;
if (_stack.FrameAtDepth(_stack.Depth - 1).FrameType == XamlStackFrameType.GetObject)
{
XamlMember member = _stack.FrameAtDepth(_stack.Depth - 2).Member;
if (member.IsUnknown)
{
return null;
}
result = member.Type;
}
else
{
result = _stack.FrameAtDepth(_stack.Depth - 1).Type;
}
Fx.Assert(result.IsUnknown || result.IsCollection || result.IsDictionary,
"Incorrect Collection Type Encountered");
return result;
}
private void ValidateUnknown(XamlMember member)
{
if (member == XamlLanguage.UnknownContent)
{
ValidationError(SR.MemberUnknownContect(GetXamlTypeName(_stack.TopFrame.Type)));
}
else if (member.IsUnknown)
{
bool retryAttachable = false;
XamlType declaringType = member.DeclaringType;
if (_stack.Depth == 1 && declaringType.IsUnknown &&
!string.IsNullOrEmpty(this.rootNamespace) &&
this.definedType != null && declaringType.Name == this.definedType.Name)
{
// Need to handle the case where the namespace of a member on the document root
// is missing the project root namespace
string clrNs;
if (XamlBuildTaskServices.TryExtractClrNs(declaringType.PreferredXamlNamespace, out clrNs))
{
clrNs = string.IsNullOrEmpty(clrNs) ? this.rootNamespace : this.rootNamespace + "." + clrNs;
if (clrNs == this.definedType.Namespace)
{
declaringType = SchemaContext.GetXamlType(this.definedType);
retryAttachable = true;
}
}
}
XamlMember typeMember = declaringType.GetMember(member.Name);
if (typeMember == null && retryAttachable)
{
typeMember = declaringType.GetAttachableMember(member.Name);
}
if (typeMember == null || typeMember.IsUnknown)
{
if (member.IsAttachable)
{
ValidationError(SR.UnresolvedAttachableMember(GetXamlTypeName(member.DeclaringType) + "." + member.Name));
}
else if (member.IsDirective)
{
ValidationError(SR.UnresolvedDirective(member.PreferredXamlNamespace + ":" + member.Name));
}
else
{
// Skip if declaring type is unknown as the member unknown error messages become redundant.
if (declaringType != null && !declaringType.IsUnknown)
{
ValidationError(SR.UnresolvedMember(member.Name, GetXamlTypeName(declaringType)));
}
}
}
}
}
private void ValidateUnknown(XamlType type)
{
if (type.IsUnknown)
{
if (type.IsGeneric)
{
ThrowGenericTypeValidationError(type);
}
else
{
ThrowTypeValidationError(type);
}
}
}
private void ThrowGenericTypeValidationError(XamlType type)
{
IList<XamlType> unresolvedLeafTypeList = new List<XamlType>();
XamlBuildTaskServices.GetUnresolvedLeafTypeArg(type, ref unresolvedLeafTypeList);
if (unresolvedLeafTypeList.Count > 1 || !unresolvedLeafTypeList.Contains(type))
{
string fullTypeName = GetXamlTypeName(type);
ValidationError(SR.UnresolvedGenericType(fullTypeName));
foreach (XamlType xamlType in unresolvedLeafTypeList)
{
ThrowTypeValidationError(xamlType);
}
}
else
{
ThrowTypeValidationError(type);
}
}
private void ThrowTypeValidationError(XamlType type)
{
string typeName, assemblyName, ns;
if (XamlBuildTaskServices.GetTypeNameInAssemblyOrNamespace(type, this.localAssemblyName, this.realAssemblyName, out typeName, out assemblyName, out ns))
{
ValidationError(SR.UnresolvedTypeWithAssemblyName(ns + "." + typeName, assemblyName));
}
else
{
ValidationError(SR.UnresolvedTypeWithNamespace(typeName, ns));
}
}
private string GetXamlTypeName(XamlType type)
{
return XamlBuildTaskServices.GetTypeName(type, this.localAssemblyName, this.realAssemblyName);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.NodejsTools.Debugger.DebugEngine
{
#region Event base classes
internal class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
internal class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
internal class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 m_engine;
private AD7EngineCreateEvent(AD7Engine engine)
{
this.m_engine = engine;
}
public static void Send(AD7Engine engine)
{
var eventObject = new AD7EngineCreateEvent(engine);
engine.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = this.m_engine;
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
internal sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
var eventObject = new AD7ProgramCreateEvent();
engine.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
internal sealed class AD7ExpressionEvaluationCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2
{
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
private readonly IDebugExpression2 _expression;
private readonly IDebugProperty2 _property;
public AD7ExpressionEvaluationCompleteEvent(IDebugExpression2 expression, IDebugProperty2 property)
{
this._expression = expression;
this._property = property;
}
#region IDebugExpressionEvaluationCompleteEvent2 Members
public int GetExpression(out IDebugExpression2 ppExpr)
{
ppExpr = this._expression;
return VSConstants.S_OK;
}
public int GetResult(out IDebugProperty2 ppResult)
{
ppResult = this._property;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
private readonly AD7Module m_module;
private readonly bool m_fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
this.m_module = module;
this.m_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = this.m_module;
if (this.m_fLoad)
{
debugMessage = null; //String.Concat("Loaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 1;
}
else
{
debugMessage = null; // String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 0;
}
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
private readonly uint m_exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
this.m_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = this.m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
private readonly uint m_exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
this.m_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = this.m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
internal sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but running.
internal sealed class AD7LoadCompleteRunningEvent : AD7AsynchronousEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteRunningEvent()
{
}
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
internal sealed class AD7SteppingCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2
{
public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D";
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint m_pendingBreakpoint;
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
this.m_pendingBreakpoint = pendingBreakpoint;
this.m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
var boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = this.m_boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return VSConstants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = this.m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when a bound breakpoint has been unbound in the debuggee.
internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2
{
public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c";
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointUnboundEvent(AD7BoundBreakpoint boundBreakpoint)
{
this.m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointUnboundEvent2 Members
int IDebugBreakpointUnboundEvent2.GetBreakpoint(out IDebugBoundBreakpoint2 ppBP)
{
ppBP = this.m_boundBreakpoint;
return VSConstants.S_OK;
}
int IDebugBreakpointUnboundEvent2.GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason)
{
pdwUnboundReason[0] = enum_BP_UNBOUND_REASON.BPUR_BREAKPOINT_REBIND;
return VSConstants.S_OK;
}
#endregion
}
internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2, IDebugErrorBreakpoint2, IDebugErrorBreakpointResolution2
{
public const string IID = "abb0ca42-f82b-4622-84e4-6903ae90f210";
private AD7Engine m_engine;
private AD7PendingBreakpoint m_pendingBreakpoint;
public AD7BreakpointErrorEvent(AD7PendingBreakpoint pendingBreakpoint, AD7Engine engine)
{
this.m_engine = engine;
this.m_pendingBreakpoint = pendingBreakpoint;
}
#region IDebugBreakpointErrorEvent2 Members
int IDebugBreakpointErrorEvent2.GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP)
{
ppErrorBP = this;
return VSConstants.S_OK;
}
#endregion
#region IDebugErrorBreakpoint2 Members
int IDebugErrorBreakpoint2.GetBreakpointResolution(out IDebugErrorBreakpointResolution2 ppErrorResolution)
{
ppErrorResolution = this;
return VSConstants.S_OK;
}
int IDebugErrorBreakpoint2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBreakpoint)
{
ppPendingBreakpoint = this.m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
#region IDebugErrorBreakpoint2 Members
int IDebugErrorBreakpointResolution2.GetBreakpointType(enum_BP_TYPE[] pBPType)
{
pBPType[0] = enum_BP_TYPE.BPT_CODE;
return VSConstants.S_OK;
}
int IDebugErrorBreakpointResolution2.GetResolutionInfo(enum_BPERESI_FIELDS dwFields, BP_ERROR_RESOLUTION_INFO[] pErrorResolutionInfo)
{
pErrorResolutionInfo[0].dwFields = dwFields;
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_PROGRAM) != 0)
{
pErrorResolutionInfo[0].pProgram = (IDebugProgram2)this.m_engine;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_THREAD) != 0)
{
pErrorResolutionInfo[0].pThread = (IDebugThread2)this.m_engine.MainThread;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_TYPE) != 0)
{
pErrorResolutionInfo[0].dwType = enum_BP_ERROR_TYPE.BPET_GENERAL_WARNING;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_BPRESLOCATION) != 0)
{
pErrorResolutionInfo[0].bpResLocation = new BP_RESOLUTION_LOCATION();
pErrorResolutionInfo[0].bpResLocation.bpType = (uint)enum_BP_TYPE.BPT_CODE;
}
if ((dwFields & enum_BPERESI_FIELDS.BPERESI_MESSAGE) != 0)
{
pErrorResolutionInfo[0].bstrMessage = "No code has been loaded for this code location.";
}
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when the entry point has been hit.
internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "e8414a3e-1642-48ec-829e-5f4040e16da9";
}
// This Event is sent when a breakpoint is hit in the debuggee
internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
private IEnumDebugBoundBreakpoints2 m_boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
this.m_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = this.m_boundBreakpoints;
return VSConstants.S_OK;
}
#endregion
}
internal sealed class AD7DebugExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2
{
public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0";
private readonly string _exception, _description;
private readonly bool _isUnhandled;
private AD7Engine _engine;
public AD7DebugExceptionEvent(string typeName, string description, bool isUnhandled, AD7Engine engine)
{
this._exception = typeName;
this._description = description;
this._isUnhandled = isUnhandled;
this._engine = engine;
}
#region IDebugExceptionEvent2 Members
public int CanPassToDebuggee()
{
return VSConstants.S_FALSE;
}
public int GetException(EXCEPTION_INFO[] pExceptionInfo)
{
pExceptionInfo[0].pProgram = this._engine;
pExceptionInfo[0].guidType = AD7Engine.DebugEngineGuid;
pExceptionInfo[0].bstrExceptionName = this._exception;
if (this._isUnhandled)
{
pExceptionInfo[0].dwState = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
}
else
{
pExceptionInfo[0].dwState = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE;
}
return VSConstants.S_OK;
}
public int GetExceptionDescription(out string pbstrDescription)
{
pbstrDescription = this._description;
return VSConstants.S_OK;
}
public int PassToDebuggee(int fPass)
{
if (fPass != 0)
{
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
#endregion
}
internal sealed class AD7DebugOutputStringEvent2 : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569C4BB1-7B82-46FC-AE28-4536DDAD753E";
private readonly string _output;
public AD7DebugOutputStringEvent2(string output)
{
this._output = output;
}
#region IDebugOutputStringEvent2 Members
public int GetString(out string pbstrString)
{
pbstrString = this._output;
return VSConstants.S_OK;
}
#endregion
}
}
| |
using System;
using System.IO;
namespace Python.Test
{
/// <summary>
/// Supports units tests for method access.
/// </summary>
public class MethodTest
{
public MethodTest()
{
}
public string PublicMethod()
{
return "public";
}
public static string PublicStaticMethod()
{
return "public static";
}
protected string ProtectedMethod()
{
return "protected";
}
protected static string ProtectedStaticMethod()
{
return "protected static";
}
internal string InternalMethod()
{
return "internal";
}
internal static string InternalStaticMethod()
{
return "internal static";
}
private string PrivateMethod()
{
return "private";
}
private static string PrivateStaticMethod()
{
return "private static";
}
/// <summary>
/// Methods to support specific argument conversion unit tests
/// </summary>
public TypeCode TestEnumConversion(TypeCode v)
{
return v;
}
public FileAccess TestFlagsConversion(FileAccess v)
{
return v;
}
public Guid TestStructConversion(Guid v)
{
return v;
}
public Exception TestSubclassConversion(Exception v)
{
return v;
}
public Type[] TestNullArrayConversion(Type[] v)
{
return v;
}
public static string[] TestStringParamsArg(params string[] args)
{
return args;
}
public static object[] TestObjectParamsArg(params object[] args)
{
return args;
}
public static int[] TestValueParamsArg(params int[] args)
{
return args;
}
public static int[] TestOneArgWithParams(string s, params int[] args)
{
return args;
}
public static int[] TestTwoArgWithParams(string s, string x, params int[] args)
{
return args;
}
public static int[] TestOverloadedParams(string v, params int[] args)
{
return args;
}
public static int[] TestOverloadedParams(int v, int[] args)
{
return args;
}
public static bool TestStringOutParams(string s, out string s1)
{
s1 = "output string";
return true;
}
public static bool TestStringRefParams(string s, ref string s1)
{
s1 = "output string";
return true;
}
public static bool TestNonParamsArrayInLastPlace(int i1, int[] i2)
{
return false;
}
public static bool TestNonParamsArrayInLastPlace(int i1, int i2, int i3)
{
return true;
}
public static bool TestValueOutParams(string s, out int i1)
{
i1 = 42;
return true;
}
public static bool TestValueRefParams(string s, ref int i1)
{
i1 = 42;
return true;
}
public static bool TestObjectOutParams(object o, out object o1)
{
o1 = new Exception("test");
return true;
}
public static bool TestObjectRefParams(object o, ref object o1)
{
o1 = new Exception("test");
return true;
}
public static bool TestStructOutParams(object o, out Guid o1)
{
o1 = Guid.NewGuid();
return true;
}
public static bool TestStructRefParams(object o, ref Guid o1)
{
o1 = Guid.NewGuid();
return true;
}
public static void TestVoidSingleOutParam(out int i)
{
i = 42;
}
public static void TestVoidSingleRefParam(ref int i)
{
i = 42;
}
public static int TestSingleDefaultParam(int i = 5)
{
return i;
}
public static int TestTwoDefaultParam(int i = 5, int j = 6)
{
return i + j;
}
public static int TestOneArgAndTwoDefaultParam(int z, int i = 5, int j = 6)
{
return i + j + z;
}
// overload selection test support
public static bool Overloaded(bool v)
{
return v;
}
public static byte Overloaded(byte v)
{
return v;
}
public static sbyte Overloaded(sbyte v)
{
return v;
}
public static char Overloaded(char v)
{
return v;
}
public static short Overloaded(short v)
{
return v;
}
public static int Overloaded(int v)
{
return v;
}
public static long Overloaded(long v)
{
return v;
}
public static ushort Overloaded(ushort v)
{
return v;
}
public static uint Overloaded(uint v)
{
return v;
}
public static ulong Overloaded(ulong v)
{
return v;
}
public static float Overloaded(float v)
{
return v;
}
public static double Overloaded(double v)
{
return v;
}
public static decimal Overloaded(decimal v)
{
return v;
}
public static string Overloaded(string v)
{
return v;
}
public static ShortEnum Overloaded(ShortEnum v)
{
return v;
}
public static object Overloaded(object v)
{
return v;
}
public static InterfaceTest Overloaded(InterfaceTest v)
{
return v;
}
public static ISayHello1 Overloaded(ISayHello1 v)
{
return v;
}
public static bool[] Overloaded(bool[] v)
{
return v;
}
public static byte[] Overloaded(byte[] v)
{
return v;
}
public static sbyte[] Overloaded(sbyte[] v)
{
return v;
}
public static char[] Overloaded(char[] v)
{
return v;
}
public static short[] Overloaded(short[] v)
{
return v;
}
public static int[] Overloaded(int[] v)
{
return v;
}
public static long[] Overloaded(long[] v)
{
return v;
}
public static ushort[] Overloaded(ushort[] v)
{
return v;
}
public static uint[] Overloaded(uint[] v)
{
return v;
}
public static ulong[] Overloaded(ulong[] v)
{
return v;
}
public static float[] Overloaded(float[] v)
{
return v;
}
public static double[] Overloaded(double[] v)
{
return v;
}
public static decimal[] Overloaded(decimal[] v)
{
return v;
}
public static string[] Overloaded(string[] v)
{
return v;
}
public static ShortEnum[] Overloaded(ShortEnum[] v)
{
return v;
}
public static object[] Overloaded(object[] v)
{
return v;
}
public static InterfaceTest[] Overloaded(InterfaceTest[] v)
{
return v;
}
public static ISayHello1[] Overloaded(ISayHello1[] v)
{
return v;
}
public static GenericWrapper<bool> Overloaded(GenericWrapper<bool> v)
{
return v;
}
public static GenericWrapper<byte> Overloaded(GenericWrapper<byte> v)
{
return v;
}
public static GenericWrapper<sbyte> Overloaded(GenericWrapper<sbyte> v)
{
return v;
}
public static GenericWrapper<char> Overloaded(GenericWrapper<char> v)
{
return v;
}
public static GenericWrapper<short> Overloaded(GenericWrapper<short> v)
{
return v;
}
public static GenericWrapper<int> Overloaded(GenericWrapper<int> v)
{
return v;
}
public static GenericWrapper<long> Overloaded(GenericWrapper<long> v)
{
return v;
}
public static GenericWrapper<ushort> Overloaded(GenericWrapper<ushort> v)
{
return v;
}
public static GenericWrapper<uint> Overloaded(GenericWrapper<uint> v)
{
return v;
}
public static GenericWrapper<ulong> Overloaded(GenericWrapper<ulong> v)
{
return v;
}
public static GenericWrapper<float> Overloaded(GenericWrapper<float> v)
{
return v;
}
public static GenericWrapper<double> Overloaded(GenericWrapper<double> v)
{
return v;
}
public static GenericWrapper<decimal> Overloaded(GenericWrapper<decimal> v)
{
return v;
}
public static GenericWrapper<string> Overloaded(GenericWrapper<string> v)
{
return v;
}
public static GenericWrapper<ShortEnum> Overloaded(GenericWrapper<ShortEnum> v)
{
return v;
}
public static GenericWrapper<object> Overloaded(GenericWrapper<object> v)
{
return v;
}
public static GenericWrapper<InterfaceTest> Overloaded(GenericWrapper<InterfaceTest> v)
{
return v;
}
public static GenericWrapper<ISayHello1> Overloaded(GenericWrapper<ISayHello1> v)
{
return v;
}
public static GenericWrapper<bool>[] Overloaded(GenericWrapper<bool>[] v)
{
return v;
}
public static GenericWrapper<byte>[] Overloaded(GenericWrapper<byte>[] v)
{
return v;
}
public static GenericWrapper<sbyte>[] Overloaded(GenericWrapper<sbyte>[] v)
{
return v;
}
public static GenericWrapper<char>[] Overloaded(GenericWrapper<char>[] v)
{
return v;
}
public static GenericWrapper<short>[] Overloaded(GenericWrapper<short>[] v)
{
return v;
}
public static GenericWrapper<int>[] Overloaded(GenericWrapper<int>[] v)
{
return v;
}
public static GenericWrapper<long>[] Overloaded(GenericWrapper<long>[] v)
{
return v;
}
public static GenericWrapper<ushort>[] Overloaded(GenericWrapper<ushort>[] v)
{
return v;
}
public static GenericWrapper<uint>[] Overloaded(GenericWrapper<uint>[] v)
{
return v;
}
public static GenericWrapper<ulong>[] Overloaded(GenericWrapper<ulong>[] v)
{
return v;
}
public static GenericWrapper<float>[] Overloaded(GenericWrapper<float>[] v)
{
return v;
}
public static GenericWrapper<double>[] Overloaded(GenericWrapper<double>[] v)
{
return v;
}
public static GenericWrapper<decimal>[] Overloaded(GenericWrapper<decimal>[] v)
{
return v;
}
public static GenericWrapper<string>[] Overloaded(GenericWrapper<string>[] v)
{
return v;
}
public static GenericWrapper<ShortEnum>[] Overloaded(GenericWrapper<ShortEnum>[] v)
{
return v;
}
public static GenericWrapper<object>[] Overloaded(GenericWrapper<object>[] v)
{
return v;
}
public static GenericWrapper<InterfaceTest>[] Overloaded(GenericWrapper<InterfaceTest>[] v)
{
return v;
}
public static GenericWrapper<ISayHello1>[] Overloaded(GenericWrapper<ISayHello1>[] v)
{
return v;
}
public static int Overloaded(string s, int i, object[] o)
{
return o.Length;
}
public static int Overloaded(string s, int i)
{
return i;
}
public static int Overloaded(int i, string s)
{
return i;
}
}
public class MethodTestSub : MethodTest
{
public MethodTestSub() : base()
{
}
public string PublicMethod(string echo)
{
return echo;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// PLEASE DO NOT EDIT THIS FILE BY HAND!!!
//
// This file has been generated
// by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1
//
// Generation timestamp: 10/21/2013 18:29:23
#pragma warning disable
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=4.0.30319.17929.
//
namespace Microsoft.PowerShell.Cmdletization.Xml
{
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)]
internal partial class PowerShellMetadata
{
private ClassMetadata _classField;
private EnumMetadataEnum[] _enumsField;
/// <remarks/>
public ClassMetadata Class
{
get
{
return this._classField;
}
set
{
this._classField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)]
public EnumMetadataEnum[] Enums
{
get
{
return this._enumsField;
}
set
{
this._enumsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadata
{
private string _versionField;
private string _defaultNounField;
private ClassMetadataInstanceCmdlets _instanceCmdletsField;
private StaticCmdletMetadata[] _staticCmdletsField;
private ClassMetadataData[] _cmdletAdapterPrivateDataField;
private string _cmdletAdapterField;
private string _classNameField;
private string _classVersionField;
/// <remarks/>
public string Version
{
get
{
return this._versionField;
}
set
{
this._versionField = value;
}
}
/// <remarks/>
public string DefaultNoun
{
get
{
return this._defaultNounField;
}
set
{
this._defaultNounField = value;
}
}
/// <remarks/>
public ClassMetadataInstanceCmdlets InstanceCmdlets
{
get
{
return this._instanceCmdletsField;
}
set
{
this._instanceCmdletsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)]
public StaticCmdletMetadata[] StaticCmdlets
{
get
{
return this._staticCmdletsField;
}
set
{
this._staticCmdletsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)]
public ClassMetadataData[] CmdletAdapterPrivateData
{
get
{
return this._cmdletAdapterPrivateDataField;
}
set
{
this._cmdletAdapterPrivateDataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string CmdletAdapter
{
get
{
return this._cmdletAdapterField;
}
set
{
this._cmdletAdapterField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ClassName
{
get
{
return this._classNameField;
}
set
{
this._classNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ClassVersion
{
get
{
return this._classVersionField;
}
set
{
this._classVersionField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadataInstanceCmdlets
{
private GetCmdletParameters _getCmdletParametersField;
private GetCmdletMetadata _getCmdletField;
private InstanceCmdletMetadata[] _cmdletField;
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
/// <remarks/>
public GetCmdletMetadata GetCmdlet
{
get
{
return this._getCmdletField;
}
set
{
this._getCmdletField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Cmdlet")]
public InstanceCmdletMetadata[] Cmdlet
{
get
{
return this._cmdletField;
}
set
{
this._cmdletField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class GetCmdletParameters
{
private PropertyMetadata[] _queryablePropertiesField;
private Association[] _queryableAssociationsField;
private QueryOption[] _queryOptionsField;
private string _defaultCmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)]
public PropertyMetadata[] QueryableProperties
{
get
{
return this._queryablePropertiesField;
}
set
{
this._queryablePropertiesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)]
public Association[] QueryableAssociations
{
get
{
return this._queryableAssociationsField;
}
set
{
this._queryableAssociationsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)]
public QueryOption[] QueryOptions
{
get
{
return this._queryOptionsField;
}
set
{
this._queryOptionsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultCmdletParameterSet
{
get
{
return this._defaultCmdletParameterSetField;
}
set
{
this._defaultCmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class PropertyMetadata
{
private TypeMetadata _typeField;
private PropertyQuery[] _itemsField;
private ItemsChoiceType[] _itemsElementNameField;
private string _propertyNameField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ExcludeQuery", typeof(WildcardablePropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("MaxValueQuery", typeof(PropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("MinValueQuery", typeof(PropertyQuery))]
[System.Xml.Serialization.XmlElementAttribute("RegularQuery", typeof(WildcardablePropertyQuery))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public PropertyQuery[] Items
{
get
{
return this._itemsField;
}
set
{
this._itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName
{
get
{
return this._itemsElementNameField;
}
set
{
this._itemsElementNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PropertyName
{
get
{
return this._propertyNameField;
}
set
{
this._propertyNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class TypeMetadata
{
private string _pSTypeField;
private string _eTSTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSType
{
get
{
return this._pSTypeField;
}
set
{
this._pSTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ETSType
{
get
{
return this._eTSTypeField;
}
set
{
this._eTSTypeField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class Association
{
private AssociationAssociatedInstance _associatedInstanceField;
private string _association1Field;
private string _sourceRoleField;
private string _resultRoleField;
/// <remarks/>
public AssociationAssociatedInstance AssociatedInstance
{
get
{
return this._associatedInstanceField;
}
set
{
this._associatedInstanceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute("Association")]
public string Association1
{
get
{
return this._association1Field;
}
set
{
this._association1Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string SourceRole
{
get
{
return this._sourceRoleField;
}
set
{
this._sourceRoleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ResultRole
{
get
{
return this._resultRoleField;
}
set
{
this._resultRoleField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class AssociationAssociatedInstance
{
private TypeMetadata _typeField;
private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter
{
private bool _errorOnNoMatchField;
private bool _errorOnNoMatchFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ErrorOnNoMatch
{
get
{
return this._errorOnNoMatchField;
}
set
{
this._errorOnNoMatchField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ErrorOnNoMatchSpecified
{
get
{
return this._errorOnNoMatchFieldSpecified;
}
set
{
this._errorOnNoMatchFieldSpecified = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineField;
private bool _valueFromPipelineFieldSpecified;
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
private string[] _cmdletParameterSetsField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipeline
{
get
{
return this._valueFromPipelineField;
}
set
{
this._valueFromPipelineField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineSpecified
{
get
{
return this._valueFromPipelineFieldSpecified;
}
set
{
this._valueFromPipelineFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] CmdletParameterSets
{
get
{
return this._cmdletParameterSetsField;
}
set
{
this._cmdletParameterSetsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForInstanceMethodParameter))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadata
{
private object _allowEmptyCollectionField;
private object _allowEmptyStringField;
private object _allowNullField;
private object _validateNotNullField;
private object _validateNotNullOrEmptyField;
private CmdletParameterMetadataValidateCount _validateCountField;
private CmdletParameterMetadataValidateLength _validateLengthField;
private CmdletParameterMetadataValidateRange _validateRangeField;
private string[] _validateSetField;
private ObsoleteAttributeMetadata _obsoleteField;
private bool _isMandatoryField;
private bool _isMandatoryFieldSpecified;
private string[] _aliasesField;
private string _pSNameField;
private string _positionField;
/// <remarks/>
public object AllowEmptyCollection
{
get
{
return this._allowEmptyCollectionField;
}
set
{
this._allowEmptyCollectionField = value;
}
}
/// <remarks/>
public object AllowEmptyString
{
get
{
return this._allowEmptyStringField;
}
set
{
this._allowEmptyStringField = value;
}
}
/// <remarks/>
public object AllowNull
{
get
{
return this._allowNullField;
}
set
{
this._allowNullField = value;
}
}
/// <remarks/>
public object ValidateNotNull
{
get
{
return this._validateNotNullField;
}
set
{
this._validateNotNullField = value;
}
}
/// <remarks/>
public object ValidateNotNullOrEmpty
{
get
{
return this._validateNotNullOrEmptyField;
}
set
{
this._validateNotNullOrEmptyField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateCount ValidateCount
{
get
{
return this._validateCountField;
}
set
{
this._validateCountField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateLength ValidateLength
{
get
{
return this._validateLengthField;
}
set
{
this._validateLengthField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataValidateRange ValidateRange
{
get
{
return this._validateRangeField;
}
set
{
this._validateRangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)]
public string[] ValidateSet
{
get
{
return this._validateSetField;
}
set
{
this._validateSetField = value;
}
}
/// <remarks/>
public ObsoleteAttributeMetadata Obsolete
{
get
{
return this._obsoleteField;
}
set
{
this._obsoleteField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool IsMandatory
{
get
{
return this._isMandatoryField;
}
set
{
this._isMandatoryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool IsMandatorySpecified
{
get
{
return this._isMandatoryFieldSpecified;
}
set
{
this._isMandatoryFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] Aliases
{
get
{
return this._aliasesField;
}
set
{
this._aliasesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSName
{
get
{
return this._pSNameField;
}
set
{
this._pSNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Position
{
get
{
return this._positionField;
}
set
{
this._positionField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateCount
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateLength
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataValidateRange
{
private string _minField;
private string _maxField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Min
{
get
{
return this._minField;
}
set
{
this._minField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Max
{
get
{
return this._maxField;
}
set
{
this._maxField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ObsoleteAttributeMetadata
{
private string _messageField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Message
{
get
{
return this._messageField;
}
set
{
this._messageField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata
{
private bool _valueFromPipelineField;
private bool _valueFromPipelineFieldSpecified;
private bool _valueFromPipelineByPropertyNameField;
private bool _valueFromPipelineByPropertyNameFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipeline
{
get
{
return this._valueFromPipelineField;
}
set
{
this._valueFromPipelineField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineSpecified
{
get
{
return this._valueFromPipelineFieldSpecified;
}
set
{
this._valueFromPipelineFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool ValueFromPipelineByPropertyName
{
get
{
return this._valueFromPipelineByPropertyNameField;
}
set
{
this._valueFromPipelineByPropertyNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ValueFromPipelineByPropertyNameSpecified
{
get
{
return this._valueFromPipelineByPropertyNameFieldSpecified;
}
set
{
this._valueFromPipelineByPropertyNameFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class QueryOption
{
private TypeMetadata _typeField;
private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField;
private string _optionNameField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string OptionName
{
get
{
return this._optionNameField;
}
set
{
this._optionNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class GetCmdletMetadata
{
private CommonCmdletMetadata _cmdletMetadataField;
private GetCmdletParameters _getCmdletParametersField;
/// <remarks/>
public CommonCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonCmdletMetadata
{
private ObsoleteAttributeMetadata _obsoleteField;
private string _verbField;
private string _nounField;
private string[] _aliasesField;
private ConfirmImpact _confirmImpactField;
private bool _confirmImpactFieldSpecified;
private string _helpUriField;
/// <remarks/>
public ObsoleteAttributeMetadata Obsolete
{
get
{
return this._obsoleteField;
}
set
{
this._obsoleteField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Verb
{
get
{
return this._verbField;
}
set
{
this._verbField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Noun
{
get
{
return this._nounField;
}
set
{
this._nounField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] Aliases
{
get
{
return this._aliasesField;
}
set
{
this._aliasesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public ConfirmImpact ConfirmImpact
{
get
{
return this._confirmImpactField;
}
set
{
this._confirmImpactField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ConfirmImpactSpecified
{
get
{
return this._confirmImpactFieldSpecified;
}
set
{
this._confirmImpactFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")]
public string HelpUri
{
get
{
return this._helpUriField;
}
set
{
this._helpUriField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
public enum ConfirmImpact
{
/// <remarks/>
None,
/// <remarks/>
Low,
/// <remarks/>
Medium,
/// <remarks/>
High,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticCmdletMetadata
{
private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField;
private StaticMethodMetadata[] _methodField;
/// <remarks/>
public StaticCmdletMetadataCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Method")]
public StaticMethodMetadata[] Method
{
get
{
return this._methodField;
}
set
{
this._methodField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata
{
private string _defaultCmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultCmdletParameterSet
{
get
{
return this._defaultCmdletParameterSetField;
}
set
{
this._defaultCmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticMethodMetadata : CommonMethodMetadata
{
private StaticMethodParameterMetadata[] _parametersField;
private string _cmdletParameterSetField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
public StaticMethodParameterMetadata[] Parameters
{
get
{
return this._parametersField;
}
set
{
this._parametersField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string CmdletParameterSet
{
get
{
return this._cmdletParameterSetField;
}
set
{
this._cmdletParameterSetField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata
{
private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CmdletOutputMetadata
{
private object _errorCodeField;
private string _pSNameField;
/// <remarks/>
public object ErrorCode
{
get
{
return this._errorCodeField;
}
set
{
this._errorCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string PSName
{
get
{
return this._pSNameField;
}
set
{
this._pSNameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodParameterMetadata
{
private TypeMetadata _typeField;
private string _parameterNameField;
private string _defaultValueField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ParameterName
{
get
{
return this._parameterNameField;
}
set
{
this._parameterNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DefaultValue
{
get
{
return this._defaultValueField;
}
set
{
this._defaultValueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata
{
private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodMetadata
{
private CommonMethodMetadataReturnValue _returnValueField;
private string _methodNameField;
/// <remarks/>
public CommonMethodMetadataReturnValue ReturnValue
{
get
{
return this._returnValueField;
}
set
{
this._returnValueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string MethodName
{
get
{
return this._methodNameField;
}
set
{
this._methodNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class CommonMethodMetadataReturnValue
{
private TypeMetadata _typeField;
private CmdletOutputMetadata _cmdletOutputMetadataField;
/// <remarks/>
public TypeMetadata Type
{
get
{
return this._typeField;
}
set
{
this._typeField = value;
}
}
/// <remarks/>
public CmdletOutputMetadata CmdletOutputMetadata
{
get
{
return this._cmdletOutputMetadataField;
}
set
{
this._cmdletOutputMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceMethodMetadata : CommonMethodMetadata
{
private InstanceMethodParameterMetadata[] _parametersField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
public InstanceMethodParameterMetadata[] Parameters
{
get
{
return this._parametersField;
}
set
{
this._parametersField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class InstanceCmdletMetadata
{
private CommonCmdletMetadata _cmdletMetadataField;
private InstanceMethodMetadata _methodField;
private GetCmdletParameters _getCmdletParametersField;
/// <remarks/>
public CommonCmdletMetadata CmdletMetadata
{
get
{
return this._cmdletMetadataField;
}
set
{
this._cmdletMetadataField = value;
}
}
/// <remarks/>
public InstanceMethodMetadata Method
{
get
{
return this._methodField;
}
set
{
this._methodField = value;
}
}
/// <remarks/>
public GetCmdletParameters GetCmdletParameters
{
get
{
return this._getCmdletParametersField;
}
set
{
this._getCmdletParametersField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class PropertyQuery
{
private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField;
/// <remarks/>
public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata
{
get
{
return this._cmdletParameterMetadataField;
}
set
{
this._cmdletParameterMetadataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class WildcardablePropertyQuery : PropertyQuery
{
private bool _allowGlobbingField;
private bool _allowGlobbingFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool AllowGlobbing
{
get
{
return this._allowGlobbingField;
}
set
{
this._allowGlobbingField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool AllowGlobbingSpecified
{
get
{
return this._allowGlobbingFieldSpecified;
}
set
{
this._allowGlobbingFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)]
public enum ItemsChoiceType
{
/// <remarks/>
ExcludeQuery,
/// <remarks/>
MaxValueQuery,
/// <remarks/>
MinValueQuery,
/// <remarks/>
RegularQuery,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class ClassMetadataData
{
private string _nameField;
private string _valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this._nameField;
}
set
{
this._nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class EnumMetadataEnum
{
private EnumMetadataEnumValue[] _valueField;
private string _enumNameField;
private string _underlyingTypeField;
private bool _bitwiseFlagsField;
private bool _bitwiseFlagsFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Value")]
public EnumMetadataEnumValue[] Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string EnumName
{
get
{
return this._enumNameField;
}
set
{
this._enumNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string UnderlyingType
{
get
{
return this._underlyingTypeField;
}
set
{
this._underlyingTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool BitwiseFlags
{
get
{
return this._bitwiseFlagsField;
}
set
{
this._bitwiseFlagsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool BitwiseFlagsSpecified
{
get
{
return this._bitwiseFlagsFieldSpecified;
}
set
{
this._bitwiseFlagsFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")]
internal partial class EnumMetadataEnumValue
{
private string _nameField;
private string _valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this._nameField;
}
set
{
this._nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")]
public string Value
{
get
{
return this._valueField;
}
set
{
this._valueField = value;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.NodejsTools.Repl
{
[Export(typeof(IReplCommand))]
internal class NpmReplCommand : IReplCommand
{
#region IReplCommand Members
public async Task<ExecutionResult> Execute(IReplWindow window, string arguments)
{
var projectPath = string.Empty;
var npmArguments = arguments.Trim(' ', '\t');
// Parse project name/directory in square brackets
if (npmArguments.StartsWith("[", StringComparison.Ordinal))
{
var match = Regex.Match(npmArguments, @"(?:[[]\s*\""?\s*)(.*?)(?:\s*\""?\s*[]]\s*)");
projectPath = match.Groups[1].Value;
npmArguments = npmArguments.Substring(match.Length);
}
// Include spaces on either side of npm arguments so that we can more simply detect arguments
// at beginning and end of string (e.g. '--global')
npmArguments = string.Format(CultureInfo.InvariantCulture, " {0} ", npmArguments);
// Prevent running `npm init` without the `-y` flag since it will freeze the repl window,
// waiting for user input that will never come.
if (npmArguments.Contains(" init ") && !(npmArguments.Contains(" -y ") || npmArguments.Contains(" --yes ")))
{
window.WriteError(Resources.ReplWindowNpmInitNoYesFlagWarning);
return ExecutionResult.Failure;
}
var solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
var loadedProjects = solution.EnumerateLoadedProjects(onlyNodeProjects: false);
var projectNameToDirectoryDictionary = new Dictionary<string, Tuple<string, IVsHierarchy>>(StringComparer.OrdinalIgnoreCase);
foreach (var project in loadedProjects)
{
var hierarchy = (IVsHierarchy)project;
var projectResult = hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out var extObject);
if (!ErrorHandler.Succeeded(projectResult))
{
continue;
}
var dteProject = extObject as EnvDTE.Project;
if (dteProject == null)
{
continue;
}
var projectName = dteProject.Name;
if (string.IsNullOrEmpty(projectName))
{
continue;
}
// Try checking the `ProjectHome` property first
var properties = dteProject.Properties;
if (dteProject.Properties != null)
{
EnvDTE.Property projectHome = null;
try
{
projectHome = properties.Item("ProjectHome");
}
catch (ArgumentException)
{
// noop
}
if (projectHome != null)
{
var projectHomeDirectory = projectHome.Value as string;
if (!string.IsNullOrEmpty(projectHomeDirectory))
{
projectNameToDirectoryDictionary.Add(projectName, Tuple.Create(projectHomeDirectory, hierarchy));
continue;
}
}
}
// Otherwise, fall back to using fullname
var projectDirectory = string.IsNullOrEmpty(dteProject.FullName) ? null : Path.GetDirectoryName(dteProject.FullName);
if (!string.IsNullOrEmpty(projectDirectory))
{
projectNameToDirectoryDictionary.Add(projectName, Tuple.Create(projectDirectory, hierarchy));
}
}
Tuple<string, IVsHierarchy> projectInfo;
if (string.IsNullOrEmpty(projectPath) && projectNameToDirectoryDictionary.Count == 1)
{
projectInfo = projectNameToDirectoryDictionary.Values.First();
}
else
{
projectNameToDirectoryDictionary.TryGetValue(projectPath, out projectInfo);
}
NodejsProjectNode nodejsProject = null;
if (projectInfo != null)
{
projectPath = projectInfo.Item1;
if (projectInfo.Item2 != null)
{
nodejsProject = projectInfo.Item2.GetProject().GetNodejsProject();
}
}
var isGlobalCommand = false;
if (string.IsNullOrWhiteSpace(npmArguments) ||
npmArguments.Contains(" -g ") || npmArguments.Contains(" --global "))
{
projectPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
isGlobalCommand = true;
}
// In case someone copies filename
var projectDirectoryPath = File.Exists(projectPath) ? Path.GetDirectoryName(projectPath) : projectPath;
if (!isGlobalCommand && !Directory.Exists(projectDirectoryPath))
{
window.WriteError(Resources.NpmSpecifyValidProject);
return ExecutionResult.Failure;
}
string npmPath;
try
{
npmPath = NpmHelpers.GetPathToNpm(
nodejsProject != null ?
Nodejs.GetAbsoluteNodeExePath(
nodejsProject.ProjectHome,
nodejsProject.GetProjectProperty(NodeProjectProperty.NodeExePath))
: null);
}
catch (NpmNotFoundException)
{
Nodejs.ShowNodejsNotInstalled();
return ExecutionResult.Failure;
}
var npmReplRedirector = new NpmReplRedirector(window);
await ExecuteNpmCommandAsync(
npmReplRedirector,
npmPath,
projectDirectoryPath,
new[] { npmArguments },
null);
if (npmReplRedirector.HasErrors)
{
window.WriteError(string.Format(CultureInfo.CurrentCulture, Resources.NpmReplCommandCompletedWithErrors, arguments));
}
else
{
window.WriteLine(string.Format(CultureInfo.CurrentCulture, Resources.NpmSuccessfullyCompleted, arguments));
}
if (nodejsProject != null)
{
await nodejsProject.CheckForLongPaths(npmArguments);
}
return ExecutionResult.Success;
}
public string Description => Resources.NpmExecuteCommand;
public string Command => "npm";
public object ButtonContent => null;
// TODO: This is duplicated from Npm project
// We should consider using InternalsVisibleTo to avoid code duplication
internal static async Task<IEnumerable<string>> ExecuteNpmCommandAsync(
Redirector redirector,
string pathToNpm,
string executionDirectory,
string[] arguments,
ManualResetEvent cancellationResetEvent)
{
IEnumerable<string> standardOutputLines = null;
using (var process = ProcessOutput.Run(
pathToNpm,
arguments,
executionDirectory,
null,
false,
redirector,
quoteArgs: false,
outputEncoding: Encoding.UTF8 // npm uses UTF-8 regardless of locale if its output is redirected
))
{
var whnd = process.WaitHandle;
if (whnd == null)
{
// Process failed to start, and any exception message has
// already been sent through the redirector
if (redirector != null)
{
redirector.WriteErrorLine("Error - cannot start npm");
}
}
else
{
var handles = cancellationResetEvent != null ? new[] { whnd, cancellationResetEvent } : new[] { whnd };
var i = await Task.Run(() => WaitHandle.WaitAny(handles));
if (i == 0)
{
Debug.Assert(process.ExitCode.HasValue, "npm process has not really exited");
process.Wait();
if (process.StandardOutputLines != null)
{
standardOutputLines = process.StandardOutputLines.ToList();
}
}
else
{
process.Kill();
if (redirector != null)
{
redirector.WriteErrorLine(string.Format(CultureInfo.CurrentCulture,
"\r\n===={0}====\r\n\r\n",
"npm command cancelled"));
}
if (cancellationResetEvent != null)
{
cancellationResetEvent.Reset();
}
throw new OperationCanceledException();
}
}
}
return standardOutputLines;
}
#endregion
internal class NpmReplRedirector : Redirector
{
internal const string ErrorAnsiColor = "\x1b[31;1m";
internal const string WarnAnsiColor = "\x1b[33;22m";
internal const string NormalAnsiColor = "\x1b[39;49m";
private const string ErrorText = "npm ERR!";
private const string WarningText = "npm WARN";
private IReplWindow _window;
public NpmReplRedirector(IReplWindow window)
{
this._window = window;
this.HasErrors = false;
}
public bool HasErrors { get; private set; }
public override void WriteLine(string decodedString)
{
var substring = string.Empty;
var outputString = string.Empty;
if (decodedString.StartsWith(ErrorText, StringComparison.Ordinal))
{
outputString += ErrorAnsiColor + decodedString.Substring(0, ErrorText.Length);
substring = decodedString.Length > ErrorText.Length ? decodedString.Substring(ErrorText.Length) : string.Empty;
this.HasErrors = true;
}
else if (decodedString.StartsWith(WarningText, StringComparison.Ordinal))
{
outputString += WarnAnsiColor + decodedString.Substring(0, WarningText.Length);
substring = decodedString.Length > WarningText.Length ? decodedString.Substring(WarningText.Length) : string.Empty;
}
else
{
substring = decodedString;
}
outputString += NormalAnsiColor + substring;
this._window.WriteLine(outputString);
Debug.WriteLine(decodedString, "REPL npm");
}
public override void WriteErrorLine(string line)
{
this._window.WriteError(line);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Nwc.XmlRpc;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Client.Linden
{
/// <summary>
/// Handles login user (expect user) and logoff user messages from the remote LL login server
/// </summary>
public class LLProxyLoginModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool RegionLoginsEnabled
{
get
{
if (m_firstScene != null)
{
return m_firstScene.CommsManager.GridService.RegionLoginsEnabled;
}
else
{
return false;
}
}
}
protected List<Scene> m_scenes = new List<Scene>();
protected Scene m_firstScene;
protected bool m_enabled = false; // Module is only enabled if running in grid mode
#region IRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig startupConfig = source.Configs["Startup"];
if (startupConfig != null)
{
m_enabled = startupConfig.GetBoolean("gridmode", false);
}
}
public void AddRegion(Scene scene)
{
if (m_firstScene == null)
{
m_firstScene = scene;
if (m_enabled)
{
AddHttpHandlers();
}
}
if (m_enabled)
{
AddScene(scene);
}
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
RemoveScene(scene);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LLProxyLoginModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
/// <summary>
/// Adds "expect_user" and "logoff_user" xmlrpc method handlers
/// </summary>
protected void AddHttpHandlers()
{
//we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change?
MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser);
MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser);
}
protected void AddScene(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
}
}
}
protected void RemoveScene(Scene scene)
{
lock (m_scenes)
{
if (m_scenes.Contains(scene))
{
m_scenes.Remove(scene);
}
}
}
/// <summary>
/// Received from the user server when a user starts logging in. This call allows
/// the region to prepare for direct communication from the client. Sends back an empty
/// xmlrpc response on completion.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["session_id"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.firstname = (string)requestData["firstname"];
agentData.lastname = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agent_id"]);
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
// Appearance
if (requestData["appearance"] != null)
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"]),
(float)Convert.ToDecimal((string)requestData["startpos_y"]),
(float)Convert.ToDecimal((string)requestData["startpos_z"]));
agentData.child = false;
}
XmlRpcResponse resp = new XmlRpcResponse();
if (!RegionLoginsEnabled)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.firstname, agentData.lastname);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
bool success = false;
string denyMess = "";
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
{
denyMess = "User is banned from this region";
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.firstname, agentData.lastname);
}
else
{
string reason;
if (scene.NewUserConnection(agentData, out reason))
{
success = true;
}
else
{
denyMess = String.Format("Login refused by region: {0}", reason);
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
agentData.firstname, agentData.lastname);
}
}
}
else
{
denyMess = "Region not found";
}
if (success)
{
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
else
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = denyMess;
resp.Value = respdata;
}
}
return resp;
}
// Grid Request Processing
/// <summary>
/// Ooops, our Agent must be dead if we're getting this request!
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LogOffUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Debug("[CONNECTION DEBUGGING]: LogOff User Called");
Hashtable requestData = (Hashtable)request.Params[0];
string message = (string)requestData["message"];
UUID agentID = UUID.Zero;
UUID RegionSecret = UUID.Zero;
UUID.TryParse((string)requestData["agent_id"], out agentID);
UUID.TryParse((string)requestData["region_secret"], out RegionSecret);
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
scene.HandleLogOffUserFromGrid(agentID, RegionSecret, message);
}
return new XmlRpcResponse();
}
protected bool TryGetRegion(ulong regionHandle, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionHandle == regionHandle)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// Helper methods for LowLevelAPI tests.
/// </summary>
public static class Helpers
{
/// <summary>
/// Finds slot containing the token that matches criteria specified in Settings class
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <returns>Slot containing the token that matches criteria</returns>
public static uint GetUsableSlot(Pkcs11 pkcs11)
{
CKR rv = CKR.CKR_OK;
// Get list of available slots with token present
uint slotCount = 0;
rv = pkcs11.C_GetSlotList(true, null, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(slotCount > 0);
uint[] slotList = new uint[slotCount];
rv = pkcs11.C_GetSlotList(true, slotList, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Return first slot with token present when both TokenSerial and TokenLabel are null...
if (Settings.TokenSerial == null && Settings.TokenLabel == null)
return slotList[0];
// First slot with token present is OK...
uint? matchingSlot = slotList[0];
// ...unless there are matching criteria specified in Settings class
if (Settings.TokenSerial != null || Settings.TokenLabel != null)
{
matchingSlot = null;
foreach (uint slot in slotList)
{
CK_TOKEN_INFO tokenInfo = new CK_TOKEN_INFO();
rv = pkcs11.C_GetTokenInfo(slot, ref tokenInfo);
if (rv != CKR.CKR_OK)
{
if (rv == CKR.CKR_TOKEN_NOT_RECOGNIZED || rv == CKR.CKR_TOKEN_NOT_PRESENT)
continue;
else
Assert.Fail(rv.ToString());
}
if (!string.IsNullOrEmpty(Settings.TokenSerial))
if (0 != string.Compare(Settings.TokenSerial, ConvertUtils.BytesToUtf8String(tokenInfo.SerialNumber, true), StringComparison.Ordinal))
continue;
if (!string.IsNullOrEmpty(Settings.TokenLabel))
if (0 != string.Compare(Settings.TokenLabel, ConvertUtils.BytesToUtf8String(tokenInfo.Label, true), StringComparison.Ordinal))
continue;
matchingSlot = slot;
break;
}
}
Assert.IsTrue(matchingSlot != null, "Token matching criteria specified in Settings class is not present");
return matchingSlot.Value;
}
/// <summary>
/// Creates the data object.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='objectId'>Output parameter for data object handle</param>
/// <returns>Return value of C_CreateObject</returns>
public static CKR CreateDataObject(Pkcs11 pkcs11, uint session, ref uint objectId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new data object
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");
// Create object
rv = pkcs11.C_CreateObject(session, template, Convert.ToUInt32(template.Length), ref objectId);
// In LowLevelAPI caller has to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates symetric key.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='keyId'>Output parameter for key object handle</param>
/// <returns>Return value of C_GenerateKey</returns>
public static CKR GenerateKey(Pkcs11 pkcs11, uint session, ref uint keyId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new key
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[6];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_DERIVE, true);
template[5] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
rv = pkcs11.C_GenerateKey(session, ref mechanism, template, Convert.ToUInt32(template.Length), ref keyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates asymetric key pair.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='pubKeyId'>Output parameter for public key object handle</param>
/// <param name='privKeyId'>Output parameter for private key object handle</param>
/// <returns>Return value of C_GenerateKeyPair</returns>
public static CKR GenerateKeyPair(Pkcs11 pkcs11, uint session, ref uint pubKeyId, ref uint privKeyId)
{
CKR rv = CKR.CKR_OK;
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = new byte[20];
rv = pkcs11.C_GenerateRandom(session, ckaId, Convert.ToUInt32(ckaId.Length));
if (rv != CKR.CKR_OK)
return rv;
// Prepare attribute template of new public key
CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });
// Prepare attribute template of new private key
CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);
// Generate key pair
rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, Convert.ToUInt32(pubKeyTemplate.Length), privKeyTemplate, Convert.ToUInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < privKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref privKeyTemplate[i].value);
privKeyTemplate[i].valueLen = 0;
}
for (int i = 0; i < pubKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
pubKeyTemplate[i].valueLen = 0;
}
return rv;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
#if !NETSTANDARD
using System.Net.Configuration;
#endif
using System.IO;
using System.Net;
using System.Net.Mail;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class MailTargetTests
{
public MailTargetTests()
{
LogManager.ThrowExceptions = true;
}
[Fact]
public void SimpleEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Single(mock.MessagesSent);
Assert.Equal("server1", mock.Host);
Assert.Equal(27, mock.Port);
Assert.False(mock.EnableSsl);
Assert.Null(mock.Credentials);
var msg = mock.MessagesSent[0];
Assert.Equal("Hello from NLog", msg.Subject);
Assert.Equal("foo@bar.com", msg.From.Address);
Assert.Single(msg.To);
Assert.Equal("bar@foo.com", msg.To[0].Address);
Assert.Equal(2, msg.CC.Count);
Assert.Equal("me@myserver.com", msg.CC[0].Address);
Assert.Equal("you@yourserver.com", msg.CC[1].Address);
Assert.Equal(2, msg.Bcc.Count);
Assert.Equal("foo@myserver.com", msg.Bcc[0].Address);
Assert.Equal("bar@yourserver.com", msg.Bcc[1].Address);
Assert.Equal("Info MyLogger log message 1", msg.Body);
}
[Fact]
public void MailTarget_WithNewlineInSubject_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog\n",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Single(mock.MessagesSent);
var msg = mock.MessagesSent[0];
}
[Fact]
public void NtlmEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Ntlm,
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials);
}
[Fact]
public void BasicAuthEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Basic,
SmtpUserName = "${scopeproperty:username}",
SmtpPassword = "${scopeproperty:password}",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
var logger = logFactory.GetLogger("MyLogger");
using (logger.PushScopeProperty("username", "u1"))
using (logger.PushScopeProperty("password", "p1"))
logger.Info("log message 1");
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
var credential = mock.Credentials as NetworkCredential;
Assert.NotNull(credential);
Assert.Equal("u1", credential.UserName);
Assert.Equal("p1", credential.Password);
Assert.Equal(string.Empty, credential.Domain);
}
[Fact]
public void CsvLayoutTest()
{
var layout = new CsvLayout()
{
Delimiter = CsvColumnDelimiterMode.Semicolon,
WithHeader = true,
Columns =
{
new CsvColumn("name", "${logger}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
}
};
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = layout,
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Single(mock.MessagesSent);
var msg = mock.MessagesSent[0];
string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void PerMessageServer()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}.mydomain.com",
Body = "${message}",
AddNewLines = true,
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1.mydomain.com", mock1.Host);
Assert.Single(mock1.MessagesSent);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("MyLogger2.mydomain.com", mock2.Host);
Assert.Single(mock2.MessagesSent);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void ErrorHandlingTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}",
Body = "${message}",
AddNewLines = true,
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
try
{
LogManager.ThrowExceptions = false;
var exceptions = new List<Exception>();
var exceptions2 = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Null(exceptions[1]);
Assert.NotNull(exceptions2[0]);
Assert.Equal("Some SMTP error.", exceptions2[0].Message);
}
finally
{
LogManager.ThrowExceptions = true;
}
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1", mock1.Host);
Assert.Single(mock1.MessagesSent);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("ERROR", mock2.Host);
Assert.Single(mock2.MessagesSent);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
/// <summary>
/// Tests that it is possible to user different email address for each log message,
/// for example by using ${logger}, ${event-context} or any other layout renderer.
/// </summary>
[Fact]
public void PerMessageAddress()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "${logger}@foo.com",
Body = "${message}",
SmtpServer = "server1.mydomain.com",
AddNewLines = true,
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Single(mock1.MessagesSent);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("MyLogger1@foo.com", msg1.To[0].Address);
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Single(mock2.MessagesSent);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("MyLogger2@foo.com", msg2.To[0].Address);
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void CustomHeaderAndFooter()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = "${message}",
Header = "First event: ${logger}",
Footer = "Last event: ${logger}",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Single(mock.MessagesSent);
var msg = mock.MessagesSent[0];
string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void DefaultSmtpClientTest()
{
var mailTarget = new MailTarget();
var client = mailTarget.CreateSmtpClient();
Assert.IsType<MySmtpClient>(client);
}
[Fact]
public void ReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = true
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void NoReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = false
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void MailTarget_WithPriority_SendsMailWithPrioritySet()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "high"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.High, messageSent.Priority);
}
[Fact]
public void MailTarget_WithoutPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "invalidPriority"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithValidToAndEmptyCC_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
Assert.Single(mmt.CreatedMocks[0].MessagesSent);
}
[Fact]
public void MailTarget_WithValidToAndEmptyBcc_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Bcc = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
Assert.Single(mmt.CreatedMocks[0].MessagesSent);
}
[Fact]
public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.LogFactory.ThrowExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1"));
}
[Fact]
public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.LogFactory.ThrowExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1"));
}
[Fact]
public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "bar@bar.com",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.LogFactory.ThrowExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
Assert.Throws<NLogRuntimeException>(() => logFactory.GetLogger("MyLogger").Info("log message 1"));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
Assert.Throws<NLogConfigurationException>(() =>
new LogFactory().Setup().LoadConfiguration(cfg => {
cfg.LogFactory.ThrowConfigExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
})
);
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() =>
new LogFactory().Setup().LoadConfiguration(cfg => {
cfg.LogFactory.ThrowConfigExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
})
);
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
});
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings()
{
LogManager.ThrowConfigExceptions = true;
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() =>
new LogFactory().Setup().LoadConfiguration(cfg => {
cfg.LogFactory.ThrowConfigExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
})
);
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_ThrowsNLogRuntimeException_if_DeliveryMethodNotSpecified()
{
var mmt = new MockMailTarget()
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() => mmt.InitializeTarget());
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_DeliveryMethod_SpecifiedDeliveryMethod()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget()
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false,
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
};
mmt.InitializeTarget();
mmt.ConfigureMailClient(LogEventInfo.CreateNullEvent(), mmt.CreateSmtpClient());
Assert.NotEqual(mmt.SmtpClientPickUpDirectory, inConfigVal);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True()
{
var mmt = new MockMailTarget()
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
mmt.InitializeTarget();
Assert.True(mmt.UseSystemNetMailSettings);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_WithVirtualPath()
{
var inConfigVal = @"~/App_Data/Mail";
var mmt = new MockMailTarget()
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false,
PickupDirectoryLocation = inConfigVal,
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
};
mmt.InitializeTarget();
mmt.ConfigureMailClient(LogEventInfo.CreateNullEvent(), mmt.CreateSmtpClient());
Assert.NotEqual(inConfigVal, mmt.SmtpClientPickUpDirectory);
var separator = Path.DirectorySeparatorChar;
Assert.Contains(string.Format("{0}App_Data{0}Mail", separator), mmt.SmtpClientPickUpDirectory);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile_dontoverride()
{
var mmt = new MailTarget()
{
From = "nlog@foo.com",
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true,
#if !NETSTANDARD
SmtpSection = new SmtpSection { From = "config@foo.com" }
#endif
};
Assert.Equal("nlog@foo.com", mmt.From.ToString());
new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
});
Assert.Equal("nlog@foo.com", mmt.From.ToString());
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile()
{
#if !NETSTANDARD
var mmt = new MailTarget()
{
From = null,
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true,
SmtpSection = new SmtpSection { From = "config@foo.com" }
};
Assert.Equal("config@foo.com", mmt.From.ToString());
new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
});
Assert.Equal("config@foo.com", mmt.From.ToString());
#endif
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_ReadFromFromConfigFile()
{
#if !NETSTANDARD
var mmt = new MailTarget()
{
From = null,
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false,
SmtpSection = new SmtpSection { From = "config@foo.com" }
};
Assert.Null(mmt.From);
Assert.Throws<NLogConfigurationException>(() =>
new LogFactory().Setup().LoadConfiguration(cfg => {
cfg.LogFactory.ThrowConfigExceptions = true;
cfg.Configuration.AddRuleForAllLevels(mmt);
})
);
#endif
}
[Fact]
public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
var logFactory = new LogFactory().Setup().LoadConfiguration(cfg =>
{
cfg.Configuration.AddRuleForAllLevels(mmt);
}).LogFactory;
logFactory.GetLogger("MyLogger").Info("log message 1");
Assert.Single(mmt.CreatedMocks);
var mock = mmt.CreatedMocks[0];
Assert.Single(mock.MessagesSent);
Assert.Equal($"Message from NLog on {Environment.MachineName}", mock.MessagesSent[0].Subject);
}
public sealed class MockSmtpClient : ISmtpClient
{
public MockSmtpClient()
{
MessagesSent = new List<MailMessage>();
}
public SmtpDeliveryMethod DeliveryMethod { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public int Timeout { get; set; }
public string PickupDirectoryLocation { get; set; }
public ICredentialsByHost Credentials { get; set; }
public bool EnableSsl { get; set; }
public List<MailMessage> MessagesSent { get; private set; }
public void Send(MailMessage msg)
{
if (string.IsNullOrEmpty(Host) && string.IsNullOrEmpty(PickupDirectoryLocation))
{
throw new ApplicationException("[Host/Pickup directory] is null or empty.");
}
MessagesSent.Add(msg);
if (Host == "ERROR")
{
throw new ApplicationException("Some SMTP error.");
}
}
public void Dispose()
{
}
}
public class MockMailTarget : MailTarget
{
public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>();
internal override ISmtpClient CreateSmtpClient()
{
var client = new MockSmtpClient();
CreatedMocks.Add(client);
return client;
}
public new void InitializeTarget()
{
base.InitializeTarget();
}
public string SmtpClientPickUpDirectory => System.Linq.Enumerable.LastOrDefault(CreatedMocks)?.PickupDirectoryLocation;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
using System.IO;
#if !__ANDROID__ && !__IOS__
using System.Configuration;
using System.Net.Configuration;
#endif
public class MailTargetTests : NLogTestBase
{
public MailTargetTests()
{
LogManager.ThrowExceptions = true;
}
[Fact]
public void SimpleEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
Assert.Equal("server1", mock.Host);
Assert.Equal(27, mock.Port);
Assert.False(mock.EnableSsl);
Assert.Null(mock.Credentials);
var msg = mock.MessagesSent[0];
Assert.Equal("Hello from NLog", msg.Subject);
Assert.Equal("foo@bar.com", msg.From.Address);
Assert.Equal(1, msg.To.Count);
Assert.Equal("bar@foo.com", msg.To[0].Address);
Assert.Equal(2, msg.CC.Count);
Assert.Equal("me@myserver.com", msg.CC[0].Address);
Assert.Equal("you@yourserver.com", msg.CC[1].Address);
Assert.Equal(2, msg.Bcc.Count);
Assert.Equal("foo@myserver.com", msg.Bcc[0].Address);
Assert.Equal("bar@yourserver.com", msg.Bcc[1].Address);
Assert.Equal(msg.Body, "Info MyLogger log message 1");
}
[Fact]
public void MailTarget_WithNewlineInSubject_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "me@myserver.com;you@yourserver.com",
Bcc = "foo@myserver.com;bar@yourserver.com",
Subject = "Hello from NLog\n",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
}
[Fact]
public void NtlmEmailTest()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Ntlm,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(CredentialCache.DefaultNetworkCredentials, mock.Credentials);
}
[Fact]
public void BasicAuthEmailTest()
{
try
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
SmtpAuthentication = SmtpAuthenticationMode.Basic,
SmtpUserName = "${mdc:username}",
SmtpPassword = "${mdc:password}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
MappedDiagnosticsContext.Set("username", "u1");
MappedDiagnosticsContext.Set("password", "p1");
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
var credential = mock.Credentials as NetworkCredential;
Assert.NotNull(credential);
Assert.Equal("u1", credential.UserName);
Assert.Equal("p1", credential.Password);
Assert.Equal(string.Empty, credential.Domain);
}
finally
{
MappedDiagnosticsContext.Clear();
}
}
[Fact]
public void CsvLayoutTest()
{
var layout = new CsvLayout()
{
Delimiter = CsvColumnDelimiterMode.Semicolon,
WithHeader = true,
Columns =
{
new CsvColumn("name", "${logger}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
}
};
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = layout,
};
layout.Initialize(null);
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void PerMessageServer()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}.mydomain.com",
Body = "${message}",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1.mydomain.com", mock1.Host);
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("MyLogger2.mydomain.com", mock2.Host);
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void ErrorHandlingTest()
{
LogManager.ThrowExceptions = false;
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "${logger}",
Body = "${message}",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
var exceptions2 = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Null(exceptions[1]);
Assert.NotNull(exceptions2[0]);
Assert.Equal("Some SMTP error.", exceptions2[0].Message);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal("MyLogger1", mock1.Host);
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal("ERROR", mock2.Host);
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("log message 2\n", msg2.Body);
}
/// <summary>
/// Tests that it is possible to user different email address for each log message,
/// for example by using ${logger}, ${event-context} or any other layout renderer.
/// </summary>
[Fact]
public void PerMessageAddress()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "${logger}@foo.com",
Body = "${message}",
SmtpServer = "server1.mydomain.com",
AddNewLines = true,
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
// 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com
Assert.Equal(2, mmt.CreatedMocks.Count);
var mock1 = mmt.CreatedMocks[0];
Assert.Equal(1, mock1.MessagesSent.Count);
var msg1 = mock1.MessagesSent[0];
Assert.Equal("MyLogger1@foo.com", msg1.To[0].Address);
Assert.Equal("log message 1\nlog message 3\n", msg1.Body);
var mock2 = mmt.CreatedMocks[1];
Assert.Equal(1, mock2.MessagesSent.Count);
var msg2 = mock2.MessagesSent[0];
Assert.Equal("MyLogger2@foo.com", msg2.To[0].Address);
Assert.Equal("log message 2\n", msg2.Body);
}
[Fact]
public void CustomHeaderAndFooter()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
SmtpServer = "server1",
AddNewLines = true,
Layout = "${message}",
Header = "First event: ${logger}",
Footer = "Last event: ${logger}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
var msg = mock.MessagesSent[0];
string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n";
Assert.Equal(expectedBody, msg.Body);
}
[Fact]
public void DefaultSmtpClientTest()
{
var mailTarget = new MailTarget();
var client = mailTarget.CreateSmtpClient();
Assert.IsType(typeof(MySmtpClient), client);
}
[Fact]
public void ReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = true
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void NoReplaceNewlinesWithBreakInHtmlMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Body = "${level}${newline}${logger}${newline}${message}",
Html = true,
ReplaceNewlineWithBrTagInHtml = false
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.True(messageSent.IsBodyHtml);
var lines = messageSent.Body.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Assert.True(lines.Length == 3);
}
[Fact]
public void MailTarget_WithPriority_SendsMailWithPrioritySet()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "high"
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.High, messageSent.Priority);
}
[Fact]
public void MailTarget_WithoutPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithInvalidPriority_SendsMailWithNormalPriority()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
Priority = "invalidPriority"
};
mmt.Initialize(null);
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(_ => { }));
var messageSent = mmt.CreatedMocks[0].MessagesSent[0];
Assert.Equal(MailPriority.Normal, messageSent.Priority);
}
[Fact]
public void MailTarget_WithValidToAndEmptyCC_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
CC = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count);
}
[Fact]
public void MailTarget_WithValidToAndEmptyBcc_SendsMail()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@foo.com",
Bcc = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Equal(1, mmt.CreatedMocks.Count);
Assert.Equal(1, mmt.CreatedMocks[0].MessagesSent.Count);
}
[Fact]
public void MailTarget_WithEmptyTo_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
Assert.Throws<NLogRuntimeException>(() => mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)));
}
[Fact]
public void MailTarget_WithEmptyFrom_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
Assert.Throws<NLogRuntimeException>(() => mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)));
}
[Fact]
public void MailTarget_WithEmptySmtpServer_ThrowsNLogRuntimeException()
{
var mmt = new MockMailTarget
{
From = "bar@bar.com",
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
Assert.Throws<NLogRuntimeException>(() => mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedTo_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedFrom_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
To = "foo@bar.com",
Subject = "Hello from NLog",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_should_not_ThrowsConfigException()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
mmt.Initialize(null);
}
[Fact]
public void MailTargetInitialize_WithoutSpecifiedSmtpServer_ThrowsConfigException_if_UseSystemNetMailSettings()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogConfigurationException>(() => mmt.Initialize(null));
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_ThrowsNLogRuntimeException_if_DeliveryMethodNotSpecified()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false
};
Assert.Throws<NLogRuntimeException>(() => mmt.ConfigureMailClient());
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/690
/// </summary>
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_Override_DeliveryMethod_SpecifiedDeliveryMethod()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
PickupDirectoryLocation = @"C:\TEMP",
UseSystemNetMailSettings = false,
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
};
mmt.ConfigureMailClient();
Assert.NotEqual(mmt.PickupDirectoryLocation, inConfigVal);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True()
{
var inConfigVal = @"C:\config";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true
};
mmt.ConfigureMailClient();
Assert.Equal(mmt.SmtpClientPickUpDirectory, inConfigVal);
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_WithVirtualPath()
{
var inConfigVal = @"~/App_Data/Mail";
var mmt = new MockMailTarget(inConfigVal)
{
From = "foo@bar.com",
To = "bar@bar.com",
Subject = "Hello from NLog",
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false,
PickupDirectoryLocation = inConfigVal,
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
};
mmt.ConfigureMailClient();
Assert.NotEqual(inConfigVal, mmt.SmtpClientPickUpDirectory);
var separator = Path.DirectorySeparatorChar;
Assert.Contains(string.Format("{0}App_Data{0}Mail", separator), mmt.SmtpClientPickUpDirectory);
}
#if !__ANDROID__ && !__IOS__
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile_dontoverride()
{
var mmt = new MailTarget()
{
From = "nlog@foo.com",
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true,
SmtpSection = new SmtpSection { From = "config@foo.com" }
};
Assert.Equal("'nlog@foo.com'", mmt.From.ToString());
mmt.Initialize(null);
Assert.Equal("'nlog@foo.com'", mmt.From.ToString());
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile()
{
var mmt = new MailTarget()
{
From = null,
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = true,
SmtpSection = new SmtpSection { From = "config@foo.com" }
};
Assert.Equal("'config@foo.com'", mmt.From.ToString());
mmt.Initialize(null);
Assert.Equal("'config@foo.com'", mmt.From.ToString());
}
[Fact]
public void MailTarget_UseSystemNetMailSettings_False_ReadFromFromConfigFile()
{
var mmt = new MailTarget()
{
From = null,
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}",
UseSystemNetMailSettings = false,
SmtpSection = new SmtpSection { From = "config@foo.com" }
};
Assert.Null(mmt.From);
Assert.Throws <NLogConfigurationException>(() => mmt.Initialize(null));
}
#endif
[Fact]
public void MailTarget_WithoutSubject_SendsMessageWithDefaultSubject()
{
var mmt = new MockMailTarget
{
From = "foo@bar.com",
To = "bar@bar.com",
SmtpServer = "server1",
SmtpPort = 27,
Body = "${level} ${logger} ${message}"
};
mmt.Initialize(null);
var exceptions = new List<Exception>();
mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add));
Assert.Null(exceptions[0]);
Assert.Equal(1, mmt.CreatedMocks.Count);
var mock = mmt.CreatedMocks[0];
Assert.Equal(1, mock.MessagesSent.Count);
Assert.Equal(string.Format("Message from NLog on {0}", Environment.MachineName), mock.MessagesSent[0].Subject);
}
public class MockSmtpClient : ISmtpClient
{
public MockSmtpClient()
{
this.MessagesSent = new List<MailMessage>();
}
public SmtpDeliveryMethod DeliveryMethod { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public int Timeout { get; set; }
public string PickupDirectoryLocation { get; set; }
public ICredentialsByHost Credentials { get; set; }
public bool EnableSsl { get; set; }
public List<MailMessage> MessagesSent { get; private set; }
public void Send(MailMessage msg)
{
if (string.IsNullOrEmpty(this.Host) && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new InvalidOperationException("[Host/Pickup directory] is null or empty.");
}
this.MessagesSent.Add(msg);
if (Host == "ERROR")
{
throw new InvalidOperationException("Some SMTP error.");
}
}
public void Dispose()
{
}
}
public class MockMailTarget : MailTarget
{
private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent.";
public MockSmtpClient Client;
public MockMailTarget()
{
Client = new MockSmtpClient();
}
public MockMailTarget(string configPickUpdirectory)
{
Client = new MockSmtpClient
{
PickupDirectoryLocation = configPickUpdirectory
};
}
public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>();
internal override ISmtpClient CreateSmtpClient()
{
var client = new MockSmtpClient();
CreatedMocks.Add(client);
return client;
}
public void ConfigureMailClient()
{
if (UseSystemNetMailSettings) return;
if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null)
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation"));
}
if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
{
Client.PickupDirectoryLocation = ConvertDirectoryLocation(PickupDirectoryLocation);
}
Client.DeliveryMethod = this.DeliveryMethod;
}
public string SmtpClientPickUpDirectory { get { return Client.PickupDirectoryLocation; } }
}
}
}
#endif
| |
//-----------------------------------------------------------------------
// <copyright file="DelegateFormatter.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer
{
using System;
using System.Linq;
using System.Reflection;
using Utilities;
/// <summary>
/// Formatter for all delegate types.
/// <para />
/// This formatter can handle anything but delegates for dynamic methods.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="BaseFormatter{T}" />
public sealed class DelegateFormatter<T> : BaseFormatter<T> where T : class
{
private static readonly Serializer<object> ObjectSerializer = Serializer.Get<object>();
private static readonly Serializer<string> StringSerializer = Serializer.Get<string>();
private static readonly Serializer<Type> TypeSerializer = Serializer.Get<Type>();
private static readonly Serializer<Type[]> TypeArraySerializer = Serializer.Get<Type[]>();
private static readonly Serializer<Delegate[]> DelegateArraySerializer = Serializer.Get<Delegate[]>();
static DelegateFormatter()
{
if (typeof(Delegate).IsAssignableFrom(typeof(T)) == false)
{
throw new ArgumentException("The type " + typeof(T) + " is not a delegate.");
}
}
/// <summary>
/// Provides the actual implementation for deserializing a value of type <see cref="!:T" />.
/// </summary>
/// <param name="value">The uninitialized value to serialize into. This value will have been created earlier using <see cref="M:OdinSerializer.BaseFormatter`1.GetUninitializedObject" />.</param>
/// <param name="reader">The reader to deserialize with.</param>
protected override void DeserializeImplementation(ref T value, IDataReader reader)
{
string name;
EntryType entry;
Type delegateType = typeof(T);
Type declaringType = null;
object target = null;
string methodName = null;
Type[] signature = null;
Type[] genericArguments = null;
Delegate[] invocationList = null;
while ((entry = reader.PeekEntry(out name)) != EntryType.EndOfNode && entry != EntryType.EndOfArray && entry != EntryType.EndOfStream)
{
switch (name)
{
case "invocationList":
{
invocationList = DelegateArraySerializer.ReadValue(reader);
}
break;
case "target":
{
target = ObjectSerializer.ReadValue(reader);
}
break;
case "declaringType":
{
var t = TypeSerializer.ReadValue(reader);
if (t != null)
{
declaringType = t;
}
}
break;
case "methodName":
{
methodName = StringSerializer.ReadValue(reader);
}
break;
case "delegateType":
{
var t = TypeSerializer.ReadValue(reader);
if (t != null)
{
delegateType = t;
}
}
break;
case "signature":
{
signature = TypeArraySerializer.ReadValue(reader);
}
break;
case "genericArguments":
{
genericArguments = TypeArraySerializer.ReadValue(reader);
}
break;
default:
reader.SkipEntry();
break;
}
}
if (invocationList != null)
{
Delegate combinedDelegate = null;
try
{
combinedDelegate = Delegate.Combine(invocationList);
}
catch (Exception ex)
{
reader.Context.Config.DebugContext.LogError("Recombining delegate invocation list upon deserialization failed with an exception of type " + ex.GetType().GetNiceFullName() + " with the message: " + ex.Message);
}
if (combinedDelegate != null)
{
try
{
value = (T)(object)combinedDelegate;
}
catch (InvalidCastException)
{
reader.Context.Config.DebugContext.LogWarning("Could not cast recombined delegate of type " + combinedDelegate.GetType().GetNiceFullName() + " to expected delegate type " + typeof(T).GetNiceFullName() + ".");
}
}
return;
}
if (declaringType == null)
{
reader.Context.Config.DebugContext.LogWarning("Missing declaring type of delegate on deserialize.");
return;
}
if (methodName == null)
{
reader.Context.Config.DebugContext.LogError("Missing method name of delegate on deserialize.");
return;
}
MethodInfo methodInfo;
bool useSignature = false;
bool wasAmbiguous = false;
if (signature != null)
{
useSignature = true;
for (int i = 0; i < signature.Length; i++)
{
if (signature[i] == null)
{
useSignature = false;
break;
}
}
}
if (useSignature)
{
try
{
methodInfo = declaringType.GetMethod(methodName, Flags.AllMembers, null, signature, null);
}
catch (AmbiguousMatchException)
{
methodInfo = null;
wasAmbiguous = true;
}
}
else
{
try
{
methodInfo = declaringType.GetMethod(methodName, Flags.AllMembers);
}
catch (AmbiguousMatchException)
{
methodInfo = null;
wasAmbiguous = true;
}
}
if (methodInfo == null)
{
if (useSignature)
{
reader.Context.Config.DebugContext.LogWarning("Could not find method with signature " + name + "(" + string.Join(", ", signature.Select(p => p.GetNiceFullName()).ToArray()) + ") on type '" + declaringType.FullName + (wasAmbiguous ? "; resolution was ambiguous between multiple methods" : string.Empty) + ".");
}
else
{
reader.Context.Config.DebugContext.LogWarning("Could not find method with name " + name + " on type '" + declaringType.GetNiceFullName() + (wasAmbiguous ? "; resolution was ambiguous between multiple methods" : string.Empty) + ".");
}
return;
}
if (methodInfo.IsGenericMethodDefinition)
{
if (genericArguments == null)
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is a generic method definition, but no generic arguments were in the serialization data.");
return;
}
int argCount = methodInfo.GetGenericArguments().Length;
if (genericArguments.Length != argCount)
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is a generic method definition, but there is the wrong number of generic arguments in the serialization data.");
return;
}
for (int i = 0; i < genericArguments.Length; i++)
{
if (genericArguments[i] == null)
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is a generic method definition, but one of the serialized generic argument types failed to bind on deserialization.");
return;
}
}
try
{
methodInfo = methodInfo.MakeGenericMethod(genericArguments);
}
catch (Exception ex)
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is a generic method definition, but failed to create generic method from definition, using generic arguments '" + string.Join(", ", genericArguments.Select(p => p.GetNiceFullName()).ToArray()) + "'. Method creation failed with an exception of type " + ex.GetType().GetNiceFullName() + ", with the message: " + ex.Message);
return;
}
}
if (methodInfo.IsStatic)
{
value = (T)(object)Delegate.CreateDelegate(delegateType, methodInfo, false);
}
else
{
Type targetType = methodInfo.DeclaringType;
if (typeof(UnityEngine.Object).IsAssignableFrom(targetType))
{
if ((target as UnityEngine.Object) == null)
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is an instance method, but Unity object target of type '" + targetType.GetNiceFullName() + "' was null on deserialization. Did something destroy it, or did you apply a delegate value targeting a scene-based UnityEngine.Object instance to a prefab?");
return;
}
}
else
{
if (object.ReferenceEquals(target, null))
{
reader.Context.Config.DebugContext.LogWarning("Method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "' of delegate to deserialize is an instance method, but no valid instance target of type '" + targetType.GetNiceFullName() + "' was in the serialization data. Has something been renamed since serialization?");
return;
}
}
value = (T)(object)Delegate.CreateDelegate(delegateType, target, methodInfo, false);
}
if (value == null)
{
reader.Context.Config.DebugContext.LogWarning("Failed to create delegate of type " + delegateType.GetNiceFullName() + " from method '" + declaringType.GetNiceFullName() + "." + methodInfo.GetNiceName() + "'.");
return;
}
this.RegisterReferenceID(value, reader);
this.InvokeOnDeserializingCallbacks(ref value, reader.Context);
}
/// <summary>
/// Provides the actual implementation for serializing a value of type <see cref="!:T" />.
/// </summary>
/// <param name="value">The value to serialize.</param>
/// <param name="writer">The writer to serialize with.</param>
protected override void SerializeImplementation(ref T value, IDataWriter writer)
{
Delegate del = (Delegate)(object)value;
Delegate[] invocationList = del.GetInvocationList();
if (invocationList.Length > 1)
{
// We're serializing an invocation list, not a single delegate
// Serialize that array of delegates instead
DelegateArraySerializer.WriteValue("invocationList", invocationList, writer);
return;
}
// We're serializing just one delegate invocation
MethodInfo methodInfo = del.Method;
if (methodInfo.GetType().Name.Contains("DynamicMethod"))
{
writer.Context.Config.DebugContext.LogError("Cannot serialize delegate made from dynamically emitted method " + methodInfo + ".");
return;
}
if (methodInfo.IsGenericMethodDefinition)
{
writer.Context.Config.DebugContext.LogError("Cannot serialize delegate made from the unresolved generic method definition " + methodInfo + "; how did this even happen? It should not even be possible to have a delegate for a generic method definition that hasn't been turned into a generic method yet.");
return;
}
if (del.Target != null)
{
ObjectSerializer.WriteValue("target", del.Target, writer);
}
TypeSerializer.WriteValue("declaringType", methodInfo.DeclaringType, writer);
StringSerializer.WriteValue("methodName", methodInfo.Name, writer);
TypeSerializer.WriteValue("delegateType", del.GetType(), writer);
ParameterInfo[] parameters;
if (methodInfo.IsGenericMethod)
{
parameters = methodInfo.GetGenericMethodDefinition().GetParameters();
}
else
{
parameters = methodInfo.GetParameters();
}
Type[] signature = new Type[parameters.Length];
for (int i = 0; i < signature.Length; i++)
{
signature[i] = parameters[i].ParameterType;
}
TypeArraySerializer.WriteValue("signature", signature, writer);
if (methodInfo.IsGenericMethod)
{
Type[] genericArguments = methodInfo.GetGenericArguments();
TypeArraySerializer.WriteValue("genericArguments", genericArguments, writer);
}
}
/// <summary>
/// Get an uninitialized object of type <see cref="!:T" />. WARNING: If you override this and return null, the object's ID will not be automatically registered and its OnDeserializing callbacks will not be automatically called, before deserialization begins.
/// You will have to call <see cref="M:OdinSerializer.BaseFormatter`1.RegisterReferenceID(`0,OdinSerializer.IDataReader)" /> and <see cref="M:OdinSerializer.BaseFormatter`1.InvokeOnDeserializingCallbacks(`0,OdinSerializer.DeserializationContext)" /> immediately after creating the object yourself during deserialization.
/// </summary>
/// <returns>
/// An uninitialized object of type <see cref="!:T" />.
/// </returns>
protected override T GetUninitializedObject()
{
return null;
}
}
}
| |
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
namespace ImplemenationCTestTestAdapter.Events
{
[Export(typeof (ITestFileAddRemoveListener))]
public sealed class ProjectItemAddRemoveListener : IVsTrackProjectDocumentsEvents2, IDisposable,
ITestFileAddRemoveListener
{
private readonly IVsTrackProjectDocuments2 _projectDocTracker;
private uint _cookie = VSConstants.VSCOOKIE_NIL;
public event EventHandler<TestFileChangedEventArgs> TestFileChanged;
[ImportingConstructor]
public ProjectItemAddRemoveListener([Import(typeof (SVsServiceProvider))] IServiceProvider serviceProvider)
{
ValidateArg.NotNull(serviceProvider, "serviceProvider");
_projectDocTracker =
serviceProvider.GetService(typeof (SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2;
}
public void StartListeningForTestFileChanges()
{
if (_projectDocTracker != null)
{
var hr = _projectDocTracker.AdviseTrackProjectDocumentsEvents(this, out _cookie);
ErrorHandler.ThrowOnFailure(hr); // do nothing if this fails
}
}
public void StopListeningForTestFileChanges()
{
if (_cookie != VSConstants.VSCOOKIE_NIL && _projectDocTracker != null)
{
int hr = _projectDocTracker.UnadviseTrackProjectDocumentsEvents(_cookie);
ErrorHandler.Succeeded(hr); // do nothing if this fails
_cookie = VSConstants.VSCOOKIE_NIL;
}
}
private int OnNotifyTestFileAddRemove(int changedProjectCount,
IVsProject[] changedProjects,
string[] changedProjectItems,
int[] rgFirstIndices,
TestFileChangedReason reason)
{
// The way these parameters work is:
// rgFirstIndices contains a list of the starting index into the changeProjectItems array for each project listed in the changedProjects list
// Example: if you get two projects, then rgFirstIndices should have two elements, the first element is probably zero since rgFirstIndices would start at zero.
// Then item two in the rgFirstIndices array is where in the changeProjectItems list that the second project's changed items reside.
int projItemIndex = 0;
for (int changeProjIndex = 0; changeProjIndex < changedProjectCount; changeProjIndex++)
{
int endProjectIndex = ((changeProjIndex + 1) == changedProjectCount)
? changedProjectItems.Length
: rgFirstIndices[changeProjIndex + 1];
for (; projItemIndex < endProjectIndex; projItemIndex++)
{
if (changedProjects[changeProjIndex] != null)
{
TestFileChanged?.Invoke(this,
new TestFileChangedEventArgs(changedProjectItems[projItemIndex], reason));
}
}
}
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnAfterAddFilesEx(int cProjects,
int cFiles,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgpszMkDocuments,
VSADDFILEFLAGS[] rgFlags)
{
return OnNotifyTestFileAddRemove(cProjects, rgpProjects, rgpszMkDocuments, rgFirstIndices,
TestFileChangedReason.Added);
}
int IVsTrackProjectDocumentsEvents2.OnAfterRemoveFiles(int cProjects,
int cFiles,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgpszMkDocuments,
VSREMOVEFILEFLAGS[] rgFlags)
{
return OnNotifyTestFileAddRemove(cProjects, rgpProjects, rgpszMkDocuments, rgFirstIndices,
TestFileChangedReason.Removed);
}
int IVsTrackProjectDocumentsEvents2.OnAfterRenameFiles(int cProjects,
int cFiles,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgszMkOldNames,
string[] rgszMkNewNames,
VSRENAMEFILEFLAGS[] rgFlags)
{
OnNotifyTestFileAddRemove(cProjects, rgpProjects, rgszMkOldNames, rgFirstIndices,
TestFileChangedReason.Removed);
return OnNotifyTestFileAddRemove(cProjects, rgpProjects, rgszMkNewNames, rgFirstIndices,
TestFileChangedReason.Added);
}
int IVsTrackProjectDocumentsEvents2.OnAfterAddDirectoriesEx(int cProjects,
int cDirectories,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgpszMkDocuments,
VSADDDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnAfterRemoveDirectories(int cProjects,
int cDirectories,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgpszMkDocuments,
VSREMOVEDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnAfterRenameDirectories(int cProjects,
int cDirs,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgszMkOldNames,
string[] rgszMkNewNames,
VSRENAMEDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnAfterSccStatusChanged(int cProjects,
int cFiles,
IVsProject[] rgpProjects,
int[] rgFirstIndices,
string[] rgpszMkDocuments,
uint[] rgdwSccStatus)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryAddDirectories(IVsProject pProject,
int cDirectories,
string[] rgpszMkDocuments,
VSQUERYADDDIRECTORYFLAGS[] rgFlags,
VSQUERYADDDIRECTORYRESULTS[] pSummaryResult,
VSQUERYADDDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryAddFiles(IVsProject pProject,
int cFiles,
string[] rgpszMkDocuments,
VSQUERYADDFILEFLAGS[] rgFlags,
VSQUERYADDFILERESULTS[] pSummaryResult,
VSQUERYADDFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryRemoveDirectories(IVsProject pProject,
int cDirectories,
string[] rgpszMkDocuments,
VSQUERYREMOVEDIRECTORYFLAGS[] rgFlags,
VSQUERYREMOVEDIRECTORYRESULTS[] pSummaryResult,
VSQUERYREMOVEDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryRemoveFiles(IVsProject pProject,
int cFiles,
string[] rgpszMkDocuments,
VSQUERYREMOVEFILEFLAGS[] rgFlags,
VSQUERYREMOVEFILERESULTS[] pSummaryResult,
VSQUERYREMOVEFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryRenameDirectories(IVsProject pProject,
int cDirs,
string[] rgszMkOldNames,
string[] rgszMkNewNames,
VSQUERYRENAMEDIRECTORYFLAGS[] rgFlags,
VSQUERYRENAMEDIRECTORYRESULTS[] pSummaryResult,
VSQUERYRENAMEDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
int IVsTrackProjectDocumentsEvents2.OnQueryRenameFiles(IVsProject pProject,
int cFiles,
string[] rgszMkOldNames,
string[] rgszMkNewNames,
VSQUERYRENAMEFILEFLAGS[] rgFlags,
VSQUERYRENAMEFILERESULTS[] pSummaryResult,
VSQUERYRENAMEFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{
StopListeningForTestFileChanges();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public static class File
{
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalOpen(path);
return new StreamReader(stream);
}
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path);
return new StreamWriter(stream);
}
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path);
return new StreamWriter(stream);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException("destFileName", SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName, bool overwrite)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException("destFileName", SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
[System.Security.SecuritySafeCritical]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
FileSystem.Current.CopyFile(fullSourceFileName, fullDestFileName, overwrite);
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite accessand cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path)
{
return Create(path, FileStream.DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path, int bufferSize)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
public static FileStream Create(String path, int bufferSize, FileOptions options)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
FileSystem.Current.DeleteFile(fullPath);
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
[System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path)
{
return FileSystem.Current.FileExists(path);
}
public static FileStream Open(String path, FileMode mode)
{
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access)
{
return Open(path, mode, access, FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(path, mode, access, share);
}
internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime)
{
// File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
// ToUniversalTime treats this as local.
if (dateTime.Kind == DateTimeKind.Unspecified)
{
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}
return dateTime.ToUniversalTime();
}
public static void SetCreationTime(String path, DateTime creationTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, creationTimeUtc, asDirectory: false);
}
public static void SetCreationTimeUtc(String path, DateTime creationTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTime), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).UtcDateTime;
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).UtcDateTime;
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).UtcDateTime;
}
[System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetAttributes(fullPath);
}
[System.Security.SecurityCritical]
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetAttributes(fullPath, fileAttributes);
}
[System.Security.SecuritySafeCritical]
public static FileStream OpenRead(String path)
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(String path)
{
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return InternalReadAllText(path, encoding);
}
[System.Security.SecurityCritical]
private static String InternalReadAllText(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalOpen(path, useAsync: false);
using (StreamReader sr = new StreamReader(stream, encoding, true))
return sr.ReadToEnd();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
InternalWriteAllText(path, contents, UTF8NoBOM);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
InternalWriteAllText(path, contents, encoding);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalCreate(path, useAsync: false);
using (StreamWriter sw = new StreamWriter(stream, encoding))
sw.Write(contents);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path);
}
[System.Security.SecurityCritical]
private static byte[] InternalReadAllBytes(String path)
{
// bufferSize == 1 used to avoid unnecessary buffer in FileStream
using (FileStream fs = FileStream.InternalOpen(path, bufferSize: 1, useAsync: false))
{
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(SR.IO_FileTooLong2GB);
int index = 0;
int count = (int)fileLength;
byte[] bytes = new byte[count];
while (count > 0)
{
int n = fs.Read(bytes, index, count);
if (n == 0)
throw __Error.GetEndOfFile();
index += n;
count -= n;
}
return bytes;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllBytes(String path, byte[] bytes)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = FileStream.InternalCreate(path, useAsync: false))
{
fs.Write(bytes, 0, bytes.Length);
}
}
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
Stream stream = FileStream.InternalOpen(path, useAsync: false);
using (StreamReader sr = new StreamReader(stream, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, UTF8NoBOM), contents);
}
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, encoding), contents);
}
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Contract.Requires(writer != null);
Contract.Requires(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
InternalAppendAllText(path, contents, UTF8NoBOM);
}
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
InternalAppendAllText(path, contents, encoding);
}
private static void InternalAppendAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalAppend(path, useAsync: false);
using (StreamWriter sw = new StreamWriter(stream, encoding))
sw.Write(contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, UTF8NoBOM), contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, encoding), contents);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public static void Move(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException("destFileName", SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
if (!InternalExists(fullSourceFileName))
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName);
}
FileSystem.Current.MoveFile(fullSourceFileName, fullDestFileName);
}
private static volatile Encoding _UTF8NoBOM;
private static Encoding UTF8NoBOM
{
get
{
if (_UTF8NoBOM == null)
{
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Interlocked.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;
namespace System.Runtime.Analyzers
{
/// <summary>
/// CA1305: Specify IFormatProvider
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class SpecifyIFormatProviderAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1305";
internal const string Uri = @"https://msdn.microsoft.com/en-us/library/ms182190.aspx";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageIFormatProviderAlternateString = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternateString), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageIFormatProviderAlternate = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternate), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageUICultureString = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageUICultureString), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageUICulture = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageUICulture), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
internal static DiagnosticDescriptor IFormatProviderAlternateStringRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageIFormatProviderAlternateString,
DiagnosticCategory.Globalization,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor IFormatProviderAlternateRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageIFormatProviderAlternate,
DiagnosticCategory.Globalization,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor UICultureStringRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageUICultureString,
DiagnosticCategory.Globalization,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor UICultureRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageUICulture,
DiagnosticCategory.Globalization,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: Uri,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(IFormatProviderAlternateStringRule, IFormatProviderAlternateRule, UICultureStringRule, UICultureRule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterCompilationStartAction(csaContext =>
{
#region "Get All the WellKnown Types and Members"
var iformatProviderType = csaContext.Compilation.GetTypeByMetadataName("System.IFormatProvider");
var cultureInfoType = csaContext.Compilation.GetTypeByMetadataName("System.Globalization.CultureInfo");
if (iformatProviderType == null || cultureInfoType == null)
{
return;
}
var objectType = csaContext.Compilation.GetSpecialType(SpecialType.System_Object);
var stringType = csaContext.Compilation.GetSpecialType(SpecialType.System_String);
var stringFormatMembers = stringType?.GetMembers("Format").OfType<IMethodSymbol>();
var stringFormatMemberWithStringAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
GetParameterInfo(stringType),
GetParameterInfo(objectType));
var stringFormatMemberWithStringObjectAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
GetParameterInfo(stringType),
GetParameterInfo(objectType),
GetParameterInfo(objectType));
var stringFormatMemberWithStringObjectObjectAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
GetParameterInfo(stringType),
GetParameterInfo(objectType),
GetParameterInfo(objectType),
GetParameterInfo(objectType));
var stringFormatMemberWithStringAndParamsObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
GetParameterInfo(stringType),
GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true));
var stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
GetParameterInfo(iformatProviderType),
GetParameterInfo(stringType),
GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true));
var currentCultureProperty = cultureInfoType?.GetMembers("CurrentCulture").OfType<IPropertySymbol>().SingleOrDefault();
var invariantCultureProperty = cultureInfoType?.GetMembers("InvariantCulture").OfType<IPropertySymbol>().SingleOrDefault();
var currentUICultureProperty = cultureInfoType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().SingleOrDefault();
var installedUICultureProperty = cultureInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().SingleOrDefault();
var threadType = csaContext.Compilation.GetTypeByMetadataName("System.Threading.Thread");
var currentThreadCurrentUICultureProperty = threadType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().SingleOrDefault();
var activatorType = csaContext.Compilation.GetTypeByMetadataName("System.Activator");
var resourceManagerType = csaContext.Compilation.GetTypeByMetadataName("System.Resources.ResourceManager");
var computerInfoType = csaContext.Compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Devices.ComputerInfo");
var installedUICulturePropertyOfComputerInfoType = computerInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().SingleOrDefault();
#endregion
csaContext.RegisterOperationAction(oaContext =>
{
var invocationExpression = (IInvocationExpression)oaContext.Operation;
var targetMethod = invocationExpression.TargetMethod;
#region "Exceptions"
if (targetMethod.IsGenericMethod || targetMethod.ContainingType == null || targetMethod.ContainingType.IsErrorType() ||
(targetMethod.ContainingType != null &&
(activatorType != null && activatorType.Equals(targetMethod.ContainingType)) ||
(resourceManagerType != null && resourceManagerType.Equals(targetMethod.ContainingType))))
{
return;
}
#endregion
#region "IFormatProviderAlternateStringRule Only"
if (stringType != null && cultureInfoType != null &&
(targetMethod.Equals(stringFormatMemberWithStringAndObjectParameter) ||
targetMethod.Equals(stringFormatMemberWithStringObjectAndObjectParameter) ||
targetMethod.Equals(stringFormatMemberWithStringObjectObjectAndObjectParameter) ||
targetMethod.Equals(stringFormatMemberWithStringAndParamsObjectParameter)))
{
// Sample message for IFormatProviderAlternateStringRule: Because the behavior of string.Format(string, object) could vary based on the current user's locale settings,
// replace this call in IFormatProviderStringTest.M() with a call to string.Format(IFormatProvider, string, params object[]).
oaContext.ReportDiagnostic(
invocationExpression.Syntax.CreateDiagnostic(
IFormatProviderAlternateStringRule,
targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
return;
}
#endregion
#region "IFormatProviderAlternateStringRule & IFormatProviderAlternateRule"
IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>();
if (methodsWithSameNameAsTargetMethod.Count() > 1)
{
var correctOverloads = methodsWithSameNameAsTargetMethod.GetMethodOverloadsWithDesiredParameterAtLeadingOrTrailing(targetMethod, iformatProviderType);
// If there are two matching overloads, one with CultureInfo as the first parameter and one with CultureInfo as the last parameter,
// report the diagnostic on the overload with CultureInfo as the last parameter, to match the behavior of FxCop.
var correctOverload = correctOverloads
.Where(overload => overload.Parameters.Last().Type.Equals(iformatProviderType))
.FirstOrDefault() ?? correctOverloads.FirstOrDefault();
// Sample message for IFormatProviderAlternateRule: Because the behavior of Convert.ToInt64(string) could vary based on the current user's locale settings,
// replace this call in IFormatProviderStringTest.TestMethod() with a call to Convert.ToInt64(string, IFormatProvider).
if (correctOverload != null)
{
oaContext.ReportDiagnostic(
invocationExpression.Syntax.CreateDiagnostic(
targetMethod.ReturnType.Equals(stringType) ?
IFormatProviderAlternateStringRule :
IFormatProviderAlternateRule,
targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
correctOverload.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
#endregion
#region "UICultureStringRule & UICultureRule"
IEnumerable<int> IformatProviderParameterIndices = GetIndexesOfParameterType(targetMethod, iformatProviderType);
foreach (var index in IformatProviderParameterIndices)
{
var argument = invocationExpression.ArgumentsInParameterOrder[index];
if (argument != null && currentUICultureProperty != null &&
installedUICultureProperty != null && currentThreadCurrentUICultureProperty != null)
{
var semanticModel = oaContext.Compilation.GetSemanticModel(argument.Syntax.SyntaxTree);
var symbol = semanticModel.GetSymbolInfo(argument.Syntax).Symbol;
if (symbol != null &
(symbol.Equals(currentUICultureProperty) ||
symbol.Equals(installedUICultureProperty) ||
symbol.Equals(currentThreadCurrentUICultureProperty) ||
(installedUICulturePropertyOfComputerInfoType != null && symbol.Equals(installedUICulturePropertyOfComputerInfoType))))
{
// Sample message
// 1. UICultureStringRule - 'TestClass.TestMethod()' passes 'Thread.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.CalleeMethod(string, IFormatProvider)'.
// This property returns a culture that is inappropriate for formatting methods.
// 2. UICultureRule -'TestClass.TestMethod()' passes 'CultureInfo.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.Callee(IFormatProvider, string)'.
// This property returns a culture that is inappropriate for formatting methods.
oaContext.ReportDiagnostic(
invocationExpression.Syntax.CreateDiagnostic(
targetMethod.ReturnType.Equals(stringType) ?
UICultureStringRule :
UICultureRule,
oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
symbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
}
#endregion
}, OperationKind.InvocationExpression);
});
}
private IEnumerable<int> GetIndexesOfParameterType(IMethodSymbol targetMethod, INamedTypeSymbol formatProviderType)
{
return targetMethod.Parameters
.Select((Parameter, Index) => new { Parameter, Index })
.Where(x => x.Parameter.Type.Equals(formatProviderType))
.Select(x => x.Index);
}
private ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false)
{
return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams);
}
}
}
| |
using System;
#if V1
using System.Collections;
#else
using System.Collections.Generic;
#endif
using System.Text;
namespace InTheHand.Net.Bluetooth
{
/// <summary>
/// Represents a member of the SDP
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>,
/// Attribute
/// which provides for multi-language strings in a record.
/// </summary>
/// <remarks>
/// “The
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
/// attribute is a list in which each
/// member contains a language identifier, a character encoding identifier, and
/// a base attribute ID for each of the natural languages used in the service
/// record.”
/// </remarks>
public sealed class LanguageBaseItem
{
/// <summary>
/// The primary language is specified to have base attribute ID 0x0100.
/// </summary>
public const ServiceAttributeId PrimaryLanguageBaseAttributeId = (ServiceAttributeId)0x0100;
/// <summary>
/// The Id for the UTF-8 encoding.
/// </summary>
public const Int16 Utf8EncodingId = 106;
/*
* Name: UTF-8 [RFC3629]
* MIBenum: 106
* Source: RFC 3629
* Alias: None
*
*
* Name: windows-1252
* MIBenum: 2252
* Source: Microsoft (http://www.iana.org/assignments/charset-reg/windows-1252) [Wendt]
* Alias: None
*/
private readonly UInt16 m_naturalLanguage;
private readonly ServiceAttributeId m_baseAttrId;
private readonly UInt16 m_encodingId;
//--------------------
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are 0x656E which is "en", and 0x6672 which is "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
[CLSCompliant(false)] // internal use only
public LanguageBaseItem(UInt16 naturalLanguage, UInt16 encodingId, UInt16 baseAttributeId)
: this(naturalLanguage, encodingId, unchecked((ServiceAttributeId)baseAttributeId))
{ }
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are 0x656E which is "en", and 0x6672 which is "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
public LanguageBaseItem(Int16 naturalLanguage, Int16 encodingId, Int16 baseAttributeId)
: this(unchecked((UInt16)naturalLanguage), unchecked((UInt16)encodingId), (ServiceAttributeId)baseAttributeId)
{ }
//----
/// <overloads>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </overloads>
/// -
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are 0x656E which is "en", and 0x6672 which is "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
[CLSCompliant(false)] // internal use only
public LanguageBaseItem(UInt16 naturalLanguage, UInt16 encodingId, ServiceAttributeId baseAttributeId)
{
if (baseAttributeId == 0) {
throw new ArgumentOutOfRangeException("baseAttributeId");
}
m_naturalLanguage = naturalLanguage;
m_baseAttrId = baseAttributeId;
m_encodingId = encodingId;
}
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are 0x656E which is "en", and 0x6672 which is "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
public LanguageBaseItem(Int16 naturalLanguage, Int16 encodingId, ServiceAttributeId baseAttributeId)
:this(unchecked((UInt16)naturalLanguage), unchecked((UInt16)encodingId), baseAttributeId)
{ }
//----
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are "en", and "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
[CLSCompliant(false)]
public LanguageBaseItem(String naturalLanguage, UInt16 encodingId, ServiceAttributeId baseAttributeId)
: this(GetLanguageIdStringAsBytes(naturalLanguage), encodingId, baseAttributeId)
{ }
/// <summary>
/// Initialize a new instance of the <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> class.
/// </summary>
/// -
/// <param name="naturalLanguage">The Natural Language field of the entry.
/// Some example values are "en", and "fr".
/// </param>
/// <param name="encodingId">The IETF Charset identifier for this language.
/// e.g. 3 for US-ASCII and 106 for UTF-8,
/// see <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
/// </param>
/// <param name="baseAttributeId">The base Attribute Id for this language
/// in the record.
/// e.g. 0x100 for the Primary language.
/// </param>
public LanguageBaseItem(String naturalLanguage, Int16 encodingId, ServiceAttributeId baseAttributeId)
: this(GetLanguageIdStringAsBytes(naturalLanguage), unchecked((UInt16)encodingId), baseAttributeId)
{ }
//--------------------
private static UInt16 GetLanguageIdStringAsBytes(String language)
{
if (language.Length != 2) {
throw new ArgumentException(ErrorMsgLangMustAsciiTwoChars);
}
byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(language);
if (strBytes.Length != 2) {
throw new ArgumentException(ErrorMsgLangMustAsciiTwoChars);
}
Int16 net16 = BitConverter.ToInt16(strBytes, 0);
Int16 host16 = System.Net.IPAddress.NetworkToHostOrder(net16);
UInt16 u16 = unchecked((UInt16)host16);
return u16;
}
private string GetLanguageIdBytesAsString()
{
Int16 host16 = unchecked((Int16)m_naturalLanguage);
Int16 net16 = System.Net.IPAddress.HostToNetworkOrder(host16);
byte[] asBytes = BitConverter.GetBytes(net16);
String asString = Encoding.ASCII.GetString(asBytes, 0, asBytes.Length);
return asString;
}
//--------------------
//
/// <summary>
/// Gets the list of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>
/// items in the service record.
/// </summary>
/// -
/// <param name="elementSequence">
/// A <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> holding the
/// data from the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
/// attribute.
/// </param>
/// -
/// <returns>
/// An array of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
/// An array length zero is returned if the service record contains no such attribute.
/// </returns>
/// -
/// <exception cref="T:System.ArgumentException">
/// <paramref name="elementSequence"/> is not of type
/// <see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementSequence"/>.
/// </exception>
/// <exception cref="T:System.Net.ProtocolViolationException">
/// The element sequence contains incorrectly formatted or invalid content,
/// for example it contains the wrong element data types, or doesn't contain
/// the elements in groups of three as required.
/// </exception>
public static LanguageBaseItem[] ParseListFromElementSequence(ServiceElement elementSequence)
{
if (elementSequence.ElementType != ElementType.ElementSequence) {
throw new ArgumentException(ErrorMsgLangBaseListParseNotSequence);
}
#if V1
IList elementList = elementSequence.GetValueAsElementList();
#else
IList<ServiceElement> elementList = elementSequence.GetValueAsElementList();
#endif
int numElements = elementList.Count;
const int ElementsPerItem = 3;
if (numElements == 0 || (numElements % ElementsPerItem) != 0) {
throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotInThrees);
}
int numItems = numElements / ElementsPerItem;
LanguageBaseItem[] items = new LanguageBaseItem[numItems];
for (int i = 0; i < numItems; ++i) {
// Casts are for the non-Generic version.
ServiceElement e1Lang = (ServiceElement)elementList[i * ElementsPerItem];
ServiceElement e2EncId = (ServiceElement)elementList[i * ElementsPerItem + 1];
ServiceElement e3BaseId = (ServiceElement)elementList[i * ElementsPerItem + 2];
if (e1Lang.ElementType != ElementType.UInt16 || e2EncId.ElementType != ElementType.UInt16 || e3BaseId.ElementType != ElementType.UInt16) {
throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotU16);
}
if ((UInt16)e3BaseId.Value == 0) {
throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseBaseInvalid);
}
LanguageBaseItem item = new LanguageBaseItem(
(UInt16)e1Lang.Value, (UInt16)e2EncId.Value, (UInt16)e3BaseId.Value);
items[i] = item;
}
return items;
}
//--------------------
/// <summary>
/// Create a data element for the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
/// attribute
/// from the list of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>
/// </summary>
/// -
/// <param name="list">
/// An array of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
/// </param>
/// -
/// <returns>
/// A <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> holding the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
/// element, to be added to a generally the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>.
/// </returns>
public static ServiceElement CreateElementSequenceFromList(LanguageBaseItem[] list)
{
#if ! V1
IList<ServiceElement> children = new List<ServiceElement>();
#else
IList children = new ArrayList();
#endif
foreach (LanguageBaseItem item in list) {
//String lang = item.NaturalLanguage;
//UInt16 langNumerical = GetLanguageIdStringAsBytes(lang);
UInt16 langNumerical = item.NaturalLanguageAsUInt16;
children.Add(new ServiceElement(ElementType.UInt16,
(UInt16)langNumerical));
children.Add(new ServiceElement(ElementType.UInt16,
(UInt16)item.EncodingId));
children.Add(new ServiceElement(ElementType.UInt16,
(UInt16)item.AttributeIdBase));
}
return new ServiceElement(ElementType.ElementSequence,
children);
}
/// <summary>
/// Create a <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> instance
/// for a primary language of English and a string encoding of UTF-8.
/// </summary>
/// <returns>The <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/> instance.
/// </returns>
public static LanguageBaseItem CreateEnglishUtf8PrimaryLanguageItem()
{
return new LanguageBaseItem("en", LanguageBaseItem.Utf8EncodingId,
LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
//--------------------
/// <summary>
/// Gets the value of the Natural Language field of the entry.
/// </summary>
/// <example>Some example value may be "en", and "fr".</example>
public string NaturalLanguage
{
get
{
return GetLanguageIdBytesAsString();
}
}
/// <summary>
/// Gets the value of the Natural Language field of the entry, as a <see cref="T:System.UInt16"/>.
/// </summary>
/// <example>Some example value may be 0x656e for "en", and 0x6672 for "fr".</example>
[CLSCompliant(false)] //use NaturalLanguageAsInt16
public UInt16 NaturalLanguageAsUInt16 { get { return m_naturalLanguage; } }
/// <summary>
/// Gets the value of the Natural Language field of the entry, as a <see cref="T:System.UInt16"/>.
/// </summary>
/// <example>Some example value may be 0x656e for "en", and 0x6672 for "fr".</example>
public Int16 NaturalLanguageAsInt16 { get { return unchecked((Int16)m_naturalLanguage); } }
/// <summary>
/// Gets the base Attribute Id for this language.
/// </summary>
public ServiceAttributeId AttributeIdBase { get { return m_baseAttrId; } }
//TODO (( ?IETF EncodingId as enum ))
/// <summary>
/// Get the IETF Charset identifier for this language.
/// </summary>
/// -
/// <remarks>
/// <para>Example values are 3 for US-ASCII and 106 for UTF-8.
/// See the full list at <see href="http://www.iana.org/assignments/character-sets"/>
/// </para>
/// </remarks>
/// -
/// <seealso cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingIdAsInt16"/>
[CLSCompliant(false)] //use EncodingIdAsInt16
public UInt16 EncodingId { get { return m_encodingId; } }
/// <summary>
/// Get the IETF Charset identifier for this language, as an Int16.
/// </summary>
/// -
/// <remarks>
/// <para>
/// See <see cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>.
/// </para>
/// </remarks>
/// -
/// <seealso cref="P:InTheHand.Net.Bluetooth.LanguageBaseItem.EncodingId"/>
public Int16 EncodingIdAsInt16 { get { return unchecked((Int16)m_encodingId); } }
//--------------------
/// <summary>
/// Gets an <see cref="T:System.Text.Encoding"/> appropriate for this language base item.
/// </summary>
/// -
/// <returns>The <see cref="T:System.Text.Encoding"/>
/// appropriate for this language base item.
/// </returns>
/// -
/// <remarks>
/// <para>We support the following set of mappings from encoding id to .NET
/// Encoding name.
/// <list type="table">
/// <listheader><term>Id</term><description>Encoding</description></listheader>
/// <item><term>3</term><description>us-ascii</description></item>
/// <item><term>4</term><description>iso-8859-1</description></item>
/// <item><term>5</term><description>iso-8859-2</description></item>
/// <item><term>6</term><description>iso-8859-3</description></item>
/// <item><term>7</term><description>iso-8859-4</description></item>
/// <item><term>8</term><description>iso-8859-5</description></item>
/// <item><term>9</term><description>iso-8859-6</description></item>
/// <item><term>10</term><description>iso-8859-7</description></item>
/// <item><term>11</term><description>iso-8859-8</description></item>
/// <item><term>12</term><description>iso-8859-9</description></item>
/// <item><term>13</term><description>iso-8859-10</description></item>
/// <item><term>106 (0x006a)</term><description>UTF-8</description></item>
/// <item><term>109</term><description>iso-8859-13</description></item>
/// <item><term>110</term><description>iso-8859-14</description></item>
/// <item><term>111</term><description>iso-8859-15</description></item>
/// <item><term>112</term><description>iso-8859-16</description></item>
/// <item><term>1013 (0x03f5)</term><description>unicodeFFFE (UTF-16BE)</description></item>
/// <item><term>1014</term><description>utf-16 (UTF-16LE)</description></item>
/// <item><term>1015</term><description>utf-16 (UTF-16, we assume UTF16-LE)</description></item>
/// <item><term>2252 to 2258 (0x08cc to 0x08d2)</term><description>windows-1252 to Windows-1258</description></item>
/// </list>
/// Note that not all platforms support all these Encodings, for instance on
/// my Windows XP SP2 box iso-8859-10/-14/-16 are not supported. On NETCF on
/// Windows Mobile 5 only five of the ISO-8859 encodings are supported.
/// Regardless I've seen no SDP records that use ISO-8859 encodings so this is
/// not a problem, most records actually use UTF-8.
/// </para>
/// </remarks>
/// -
/// <exception cref="T:System.NotSupportedException">
/// The IETF encoding id for this language base item is currently unknown.
/// If valid, add it to the <c>s_IetfCharsetIdToDotNetEncodingNameTable</c> table,
/// providing a mapping to its Windows code page name.
/// </exception>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="but throws")]
#endif
public Encoding GetEncoding()
{
if (m_encodingId >= 2252 && m_encodingId <= 2258) { // Windows-125x
int num = m_encodingId - 1000;
Encoding enc = Encoding.GetEncoding("windows-" + num.ToString(System.Globalization.CultureInfo.InvariantCulture));
return enc;
}
foreach (IetfCharsetIdToDotNetEncodingNameMap row in s_IetfCharsetIdToDotNetEncodingNameTable) {
if (row.IetfCharsetId == m_encodingId) {
Encoding enc = Encoding.GetEncoding(row.DotNetEncodingName);
return enc;
}
}
//TODO LanguageBaseItem.GetEncoding--NotImplementedException rather than NotSupportedException?
throw new NotSupportedException(
String.Format(System.Globalization.CultureInfo.InvariantCulture,
ErrorMsgFormatUnrecognizedEncodingId,
m_encodingId));
}
//--------------------
private struct IetfCharsetIdToDotNetEncodingNameMap
{
public readonly UInt16 IetfCharsetId;
public readonly String DotNetEncodingName;
internal IetfCharsetIdToDotNetEncodingNameMap(
UInt16 ietfCharsetId_, String DotNetEncodingName_)
{
this.IetfCharsetId = ietfCharsetId_;
this.DotNetEncodingName = DotNetEncodingName_;
}
}
private static readonly IetfCharsetIdToDotNetEncodingNameMap[] s_IetfCharsetIdToDotNetEncodingNameTable ={
//--------
//
new IetfCharsetIdToDotNetEncodingNameMap(3, "us-ascii"),
//--------
//
new IetfCharsetIdToDotNetEncodingNameMap(4, "iso-8859-" + "1"),
new IetfCharsetIdToDotNetEncodingNameMap(5, "iso-8859-" + "2"),
new IetfCharsetIdToDotNetEncodingNameMap(6, "iso-8859-" + "3"),
new IetfCharsetIdToDotNetEncodingNameMap(7, "iso-8859-" + "4"),
new IetfCharsetIdToDotNetEncodingNameMap(8, "iso-8859-" + "5"),
new IetfCharsetIdToDotNetEncodingNameMap(9, "iso-8859-" + "6"),
new IetfCharsetIdToDotNetEncodingNameMap(10, "iso-8859-" + "7"),
new IetfCharsetIdToDotNetEncodingNameMap(11, "iso-8859-" + "8"),
new IetfCharsetIdToDotNetEncodingNameMap(12, "iso-8859-" + "9"),
new IetfCharsetIdToDotNetEncodingNameMap(13, "iso-8859-" + "10"), // not in XpSp2.
//--------
//
new IetfCharsetIdToDotNetEncodingNameMap(106/*0x006a*/, "UTF-8"),
//--------
//
new IetfCharsetIdToDotNetEncodingNameMap(109, "iso-8859-" + "13"),
new IetfCharsetIdToDotNetEncodingNameMap(110, "iso-8859-" + "14"), // not in XpSp2.
new IetfCharsetIdToDotNetEncodingNameMap(111, "iso-8859-" + "15"),
new IetfCharsetIdToDotNetEncodingNameMap(112, "iso-8859-" + "16"), // not in XpSp2.
//--------
// Name: UTF-16BE MIBenum: 1013 = 0x03f5
// Name: UTF-16LE MIBenum: 1014
// Name: UTF-16 MIBenum: 1015
// .NET encoding names:
// 1200 utf-16 Unicode
// 1201 unicodeFFFE Unicode (Big-Endian)
new IetfCharsetIdToDotNetEncodingNameMap(1013, "unicodeFFFE"),
new IetfCharsetIdToDotNetEncodingNameMap(1014, "utf-16"),
// For the id for unspecified use LE to suit Windows' servers.
new IetfCharsetIdToDotNetEncodingNameMap(1015, "utf-16"),
};
/// <exclude/>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")]
#endif
public static String TestAllDefinedEncodingMappingRows(out int numberSuccessful, out int numberFailed)
{
numberSuccessful = 0;
numberFailed = 0;
StringBuilder bldr = new StringBuilder();
foreach (IetfCharsetIdToDotNetEncodingNameMap row in s_IetfCharsetIdToDotNetEncodingNameTable) {
bldr.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
"id: {0}, name: {1}. ", row.IetfCharsetId, row.DotNetEncodingName);
try {
Encoding enc = Encoding.GetEncoding(row.DotNetEncodingName);
bldr.Append("Success");
++numberSuccessful;
} catch (Exception ex) {
bldr.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
"Failed with {0}:{1}", ex.GetType().FullName, ex.Message);
++numberFailed;
}
bldr.Append("\r\n");//no AppendLine on NETCFv1
}
return bldr.ToString();
}
//--------------------------------------------------------------
/// <exclude/>
public const String ErrorMsgLangBaseListParseNotU16
= "Element in LanguageBaseAttributeIdList not type UInt16.";
/// <exclude/>
public const String ErrorMsgLangBaseListParseBaseInvalid
= "Base element in LanguageBaseAttributeIdList has unacceptable value.";
/// <exclude/>
public const String ErrorMsgLangBaseListParseNotSequence
= "LanguageBaseAttributeIdList elementSequence not an ElementSequence.";
/// <exclude/>
public const String ErrorMsgLangBaseListParseNotInThrees
= "LanguageBaseAttributeIdList must contain items in groups of three.";
/// <exclude/>
public const String ErrorMsgFormatUnrecognizedEncodingId
= "Unrecognized character encoding ({0}); add to LanguageBaseItem mapping table.";
/// <exclude/>
public const String ErrorMsgLangMustAsciiTwoChars
= "A language code must be a two byte ASCII string.";
}//class
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Timers.Internal;
#nullable enable
namespace Orleans
{
/// <summary>
/// General pattern for an asynchronous worker that performs a work task, when notified,
/// to service queued work. Each work cycle handles ALL the queued work.
/// If new work arrives during a work cycle, another cycle is scheduled.
/// The worker never executes more than one instance of the work cycle at a time,
/// and consumes no resources when idle. It uses TaskScheduler.Current
/// to schedule the work cycles.
/// </summary>
public abstract class BatchWorker
{
private readonly object lockable = new object();
private DateTime? scheduledNotify;
// Task for the current work cycle, or null if idle
private Task? currentWorkCycle;
// Flag is set to indicate that more work has arrived during execution of the task
private bool moreWork;
// Used to communicate the task for the next work cycle to waiters.
// This value is non-null only if there are waiters.
private TaskCompletionSource<Task>? nextWorkCyclePromise;
private Task? nextWorkCycle;
/// <summary>Implement this member in derived classes to define what constitutes a work cycle</summary>
protected abstract Task Work();
/// <summary>
/// The cancellation used to cancel this batch worker.
/// </summary>
protected CancellationToken CancellationToken { get; set; }
/// <summary>
/// Notify the worker that there is more work.
/// </summary>
public void Notify()
{
lock (lockable)
{
if (currentWorkCycle != null)
{
// lets the current work cycle know that there is more work
moreWork = true;
}
else
{
// start a work cycle
Start();
}
}
}
/// <summary>
/// Instructs the batch worker to run again to check for work, if
/// it has not run again already by then, at specified <paramref name="utcTime"/>.
/// </summary>
/// <param name="utcTime"></param>
public void Notify(DateTime utcTime)
{
var now = DateTime.UtcNow;
if (now >= utcTime)
{
Notify();
}
else
{
lock (lockable)
{
if (!scheduledNotify.HasValue || scheduledNotify.Value > utcTime)
{
scheduledNotify = utcTime;
ScheduleNotify(utcTime, now).Ignore();
}
}
}
}
private async Task ScheduleNotify(DateTime time, DateTime now)
{
await TimerManager.Delay(time - now, this.CancellationToken);
if (scheduledNotify == time)
{
Notify();
}
}
private Task Start()
{
// Clear any scheduled runs
scheduledNotify = null;
// Queue a task that is doing the work
var task = Task.Factory.StartNew(s => ((BatchWorker)s!).Work(), this, default, default, TaskScheduler.Current).Unwrap();
currentWorkCycle = task;
// chain a continuation that checks for more work, on the same scheduler
task.ContinueWith((_, s) => ((BatchWorker)s!).CheckForMoreWork(), this);
return task;
}
/// <summary>
/// Executes at the end of each work cycle on the same task scheduler.
/// </summary>
private void CheckForMoreWork()
{
TaskCompletionSource<Task>? signal;
Task taskToSignal;
lock (lockable)
{
if (moreWork)
{
moreWork = false;
// see if someone created a promise for waiting for the next work cycle
// if so, take it and remove it
signal = this.nextWorkCyclePromise;
this.nextWorkCyclePromise = null;
this.nextWorkCycle = null;
// start the next work cycle
taskToSignal = Start();
}
else
{
currentWorkCycle = null;
return;
}
}
// to be safe, must do the signalling out here so it is not under the lock
signal?.SetResult(taskToSignal);
}
/// <summary>
/// Check if this worker is idle.
/// </summary>
public bool IsIdle() => currentWorkCycle == null;
/// <summary>
/// Wait for the current work cycle, and also the next work cycle if there is currently unserviced work.
/// </summary>
public Task WaitForCurrentWorkToBeServiced()
{
// Figure out exactly what we need to wait for
lock (lockable)
{
if (!moreWork)
{
// Just wait for current work cycle
return currentWorkCycle ?? Task.CompletedTask;
}
else
{
// we need to wait for the next work cycle
// but that task does not exist yet, so we use a promise that signals when the next work cycle is launched
return nextWorkCycle ?? CreateNextWorkCyclePromise();
}
}
}
private Task CreateNextWorkCyclePromise()
{
// it's OK to run any continuations synchrnously because this promise only gets signaled at the very end of CheckForMoreWork
nextWorkCyclePromise = new TaskCompletionSource<Task>();
return nextWorkCycle = nextWorkCyclePromise.Task.Unwrap();
}
/// <summary>
/// Notify the worker that there is more work, and wait for the current work cycle, and also the next work cycle if there is currently unserviced work.
/// </summary>
public Task NotifyAndWaitForWorkToBeServiced()
{
lock (lockable)
{
if (currentWorkCycle != null)
{
moreWork = true;
return nextWorkCycle ?? CreateNextWorkCyclePromise();
}
else
{
return Start();
}
}
}
}
public class BatchWorkerFromDelegate : BatchWorker
{
private readonly Func<Task> work;
public BatchWorkerFromDelegate(Func<Task> work, CancellationToken cancellationToken = default(CancellationToken))
{
this.work = work;
this.CancellationToken = cancellationToken;
}
protected override Task Work()
{
return work();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private class PostProcessor
{
private readonly SemanticModel _semanticModel;
private readonly int _contextPosition;
public PostProcessor(SemanticModel semanticModel, int contextPosition)
{
Contract.ThrowIfNull(semanticModel);
_semanticModel = semanticModel;
_contextPosition = contextPosition;
}
public IEnumerable<StatementSyntax> RemoveRedundantBlock(IEnumerable<StatementSyntax> statements)
{
// it must have only one statement
if (statements.Count() != 1)
{
return statements;
}
// that statement must be a block
var block = statements.Single() as BlockSyntax;
if (block == null)
{
return statements;
}
// we have a block, remove them
return RemoveRedundantBlock(block);
}
private IEnumerable<StatementSyntax> RemoveRedundantBlock(BlockSyntax block)
{
// if block doesn't have any statement
if (block.Statements.Count == 0)
{
// either remove the block if it doesn't have any trivia, or return as it is if
// there are trivia attached to block
return (block.OpenBraceToken.GetAllTrivia().IsEmpty() && block.CloseBraceToken.GetAllTrivia().IsEmpty()) ?
SpecializedCollections.EmptyEnumerable<StatementSyntax>() : SpecializedCollections.SingletonEnumerable<StatementSyntax>(block);
}
// okay transfer asset attached to block to statements
var firstStatement = block.Statements.First();
var firstToken = firstStatement.GetFirstToken(includeZeroWidth: true);
var firstTokenWithAsset = block.OpenBraceToken.CopyAnnotationsTo(firstToken).WithPrependedLeadingTrivia(block.OpenBraceToken.GetAllTrivia());
var lastStatement = block.Statements.Last();
var lastToken = lastStatement.GetLastToken(includeZeroWidth: true);
var lastTokenWithAsset = block.CloseBraceToken.CopyAnnotationsTo(lastToken).WithAppendedTrailingTrivia(block.CloseBraceToken.GetAllTrivia());
// create new block with new tokens
block = block.ReplaceTokens(new[] { firstToken, lastToken }, (o, c) => (o == firstToken) ? firstTokenWithAsset : lastTokenWithAsset);
// return only statements without the wrapping block
return block.Statements;
}
public IEnumerable<StatementSyntax> MergeDeclarationStatements(IEnumerable<StatementSyntax> statements)
{
if (statements.FirstOrDefault() == null)
{
return statements;
}
return MergeDeclarationStatementsWorker(statements);
}
private IEnumerable<StatementSyntax> MergeDeclarationStatementsWorker(IEnumerable<StatementSyntax> statements)
{
var map = new Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>>();
foreach (var statement in statements)
{
if (!IsDeclarationMergable(statement))
{
foreach (var declStatement in GetMergedDeclarationStatements(map))
{
yield return declStatement;
}
yield return statement;
continue;
}
AppendDeclarationStatementToMap(statement as LocalDeclarationStatementSyntax, map);
}
// merge leftover
if (map.Count <= 0)
{
yield break;
}
foreach (var declStatement in GetMergedDeclarationStatements(map))
{
yield return declStatement;
}
}
private void AppendDeclarationStatementToMap(
LocalDeclarationStatementSyntax statement,
Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map)
{
Contract.ThrowIfNull(statement);
var type = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, statement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
Contract.ThrowIfNull(type);
map.GetOrAdd(type, _ => new List<LocalDeclarationStatementSyntax>()).Add(statement);
}
private IEnumerable<LocalDeclarationStatementSyntax> GetMergedDeclarationStatements(
Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map)
{
foreach (var keyValuePair in map)
{
Contract.ThrowIfFalse(keyValuePair.Value.Count > 0);
// merge all variable decl for current type
var variables = new List<VariableDeclaratorSyntax>();
foreach (var statement in keyValuePair.Value)
{
foreach (var variable in statement.Declaration.Variables)
{
variables.Add(variable);
}
}
// and create one decl statement
// use type name from the first decl statement
yield return
SyntaxFactory.LocalDeclarationStatement(
SyntaxFactory.VariableDeclaration(keyValuePair.Value.First().Declaration.Type, SyntaxFactory.SeparatedList(variables)));
}
map.Clear();
}
private bool IsDeclarationMergable(StatementSyntax statement)
{
Contract.ThrowIfNull(statement);
// to be mergable, statement must be
// 1. decl statement without any extra info
// 2. no initialization on any of its decls
// 3. no trivia except whitespace
// 4. type must be known
var declarationStatement = statement as LocalDeclarationStatementSyntax;
if (declarationStatement == null)
{
return false;
}
if (declarationStatement.Modifiers.Count > 0 ||
declarationStatement.IsConst ||
declarationStatement.IsMissing)
{
return false;
}
if (ContainsAnyInitialization(declarationStatement))
{
return false;
}
if (!ContainsOnlyWhitespaceTrivia(declarationStatement))
{
return false;
}
var semanticInfo = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, declarationStatement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
if (semanticInfo == null ||
semanticInfo.TypeKind == TypeKind.Error ||
semanticInfo.TypeKind == TypeKind.Unknown)
{
return false;
}
return true;
}
private bool ContainsAnyInitialization(LocalDeclarationStatementSyntax statement)
{
foreach (var variable in statement.Declaration.Variables)
{
if (variable.Initializer != null)
{
return true;
}
}
return false;
}
private static bool ContainsOnlyWhitespaceTrivia(StatementSyntax statement)
{
foreach (var token in statement.DescendantTokens())
{
foreach (var trivia in token.LeadingTrivia.Concat(token.TrailingTrivia))
{
if (trivia.Kind() != SyntaxKind.WhitespaceTrivia &&
trivia.Kind() != SyntaxKind.EndOfLineTrivia)
{
return false;
}
}
}
return true;
}
public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements)
{
// if we have inline temp variable as service, we could just use that service here.
// since it is not a service right now, do very simple clean up
if (statements.ElementAtOrDefault(2) != null)
{
return statements;
}
var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax;
if (declaration == null || returnStatement == null)
{
return statements;
}
if (declaration.Declaration == null ||
declaration.Declaration.Variables.Count != 1 ||
declaration.Declaration.Variables[0].Initializer == null ||
declaration.Declaration.Variables[0].Initializer.Value == null ||
declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax ||
returnStatement.Expression == null)
{
return statements;
}
if (!ContainsOnlyWhitespaceTrivia(declaration) ||
!ContainsOnlyWhitespaceTrivia(returnStatement))
{
return statements;
}
var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
if (returnStatement.Expression.ToString() != variableName)
{
return statements;
}
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value));
}
public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements)
{
// if we have inline temp variable as service, we could just use that service here.
// since it is not a service right now, do very simple clean up
var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax;
if (declaration == null || assignment == null)
{
return statements;
}
if (ContainsAnyInitialization(declaration) ||
declaration.Declaration == null ||
declaration.Declaration.Variables.Count != 1 ||
assignment.Expression == null ||
assignment.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression)
{
return statements;
}
if (!ContainsOnlyWhitespaceTrivia(declaration) ||
!ContainsOnlyWhitespaceTrivia(assignment))
{
return statements;
}
var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
var assignmentExpression = assignment.Expression as AssignmentExpressionSyntax;
if (assignmentExpression.Left == null ||
assignmentExpression.Right == null ||
assignmentExpression.Left.ToString() != variableName)
{
return statements;
}
var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right));
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
declaration.WithDeclaration(
declaration.Declaration.WithVariables(
SyntaxFactory.SingletonSeparatedList(variable)))).Concat(statements.Skip(2));
}
}
}
}
| |
#define USE_TRACING
using System;
using System.Xml;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.AppControl;
using Google.GData.Extensions.Location;
using Google.GData.Extensions.MediaRss;
namespace Google.GData.YouTube
{
/// <summary>
/// Entry API customization class for defining entries in a YouTubeFeed feed.
/// </summary>
public class YouTubeEntry : YouTubeBaseEntry
{
private ExtensionCollection<YtAccessControl> accessControls;
/// <summary>
/// Constructs a new YouTubeEntry instance
/// </summary>
public YouTubeEntry()
{
ProtocolMajor = VersionDefaults.VersionTwo;
Tracing.TraceMsg("Created YouTubeEntry");
addYouTubeEntryExtensions();
}
/// <summary>
/// property accessor for the Access Control Collection
/// </summary>
public ExtensionCollection<YtAccessControl> AccessControls
{
get
{
if (accessControls == null)
{
accessControls = new ExtensionCollection<YtAccessControl>(this);
}
return accessControls;
}
}
/// <summary>
/// getter/setter for the Episode extension element
/// </summary>
public Episode Episode
{
get
{
return FindExtension(YouTubeNameTable.Episode,
YouTubeNameTable.NSYouTube) as Episode;
}
set
{
ReplaceExtension(YouTubeNameTable.Episode,
YouTubeNameTable.NSYouTube,
value);
}
}
/// <summary>
/// getter/setter for the GeoRssWhere extension element
/// </summary>
public GeoRssWhere Location
{
get
{
return FindExtension(GeoNametable.GeoRssWhereElement,
GeoNametable.NSGeoRss) as GeoRssWhere;
}
set
{
ReplaceExtension(GeoNametable.GeoRssWhereElement,
GeoNametable.NSGeoRss,
value);
}
}
/// <summary>
/// returns the media:rss group container element
/// </summary>
public MediaGroup Media
{
get
{
return FindExtension(MediaRssNameTable.MediaRssGroup,
MediaRssNameTable.NSMediaRss) as MediaGroup;
}
set
{
ReplaceExtension(MediaRssNameTable.MediaRssGroup,
MediaRssNameTable.NSMediaRss,
value);
}
}
/// <summary>
/// returns the yt:statistics element
/// </summary>
/// <returns></returns>
public Statistics Statistics
{
get
{
return FindExtension(YouTubeNameTable.Statistics,
YouTubeNameTable.NSYouTube) as Statistics;
}
set
{
ReplaceExtension(YouTubeNameTable.Statistics,
YouTubeNameTable.NSYouTube,
value);
}
}
/// <summary>
/// property accessor for the Comments
/// </summary>
public Comments Comments
{
get
{
return FindExtension(GDataParserNameTable.XmlCommentsElement,
GDataParserNameTable.gNamespace) as Comments;
}
set
{
ReplaceExtension(GDataParserNameTable.XmlCommentsElement,
GDataParserNameTable.gNamespace, value);
}
}
/// <summary>
/// returns the gd:rating element
/// </summary>
/// <returns></returns>
/// [Obsolete("This is deprecated and replaced by YtRating")]
public Rating Rating
{
get
{
return FindExtension(GDataParserNameTable.XmlRatingElement,
GDataParserNameTable.gNamespace) as Rating;
}
set
{
ReplaceExtension(GDataParserNameTable.XmlRatingElement,
GDataParserNameTable.gNamespace,
value);
}
}
/// <summary>
/// returns the yt:rating element
/// </summary>
/// <returns></returns>
public YtRating YtRating
{
get
{
return FindExtension(YouTubeNameTable.YtRating,
YouTubeNameTable.NSYouTube) as YtRating;
}
set
{
ReplaceExtension(YouTubeNameTable.YtRating,
YouTubeNameTable.NSYouTube,
value);
}
}
/// <summary>
/// returns the ratings link relationship as an atomUri
/// </summary>
public AtomUri RatingsLink
{
get
{
AtomLink link = Links.FindService(YouTubeNameTable.RatingsRelationship, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
set
{
AtomLink link = Links.FindService(YouTubeNameTable.RatingsRelationship, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, YouTubeNameTable.RatingsRelationship);
Links.Add(link);
}
link.HRef = value;
}
}
/// <summary>
/// returns the yt:duration element
/// </summary>
/// <returns></returns>
public Duration Duration
{
get
{
if (Media != null)
{
return Media.Duration;
}
return null;
}
set
{
if (Media == null)
{
Media = new MediaGroup();
}
if (Media.Duration == null)
{
Media.Duration = new Duration();
}
Media.Duration = value;
}
}
/// <summary>
/// Returns the yt:state tag inside of app:control
/// </summary>
public State State
{
get
{
if (AppControl != null)
{
return AppControl.FindExtension(YouTubeNameTable.State,
YouTubeNameTable.NSYouTube) as State;
}
return null;
}
set
{
Dirty = true;
if (AppControl == null)
{
AppControl = new AppControl();
}
AppControl.ReplaceExtension(YouTubeNameTable.State,
YouTubeNameTable.NSYouTube, value);
}
}
/// <summary>
/// property accessor for the VideoID, if applicable
/// </summary>
public string VideoId
{
get
{
if (Media != null && Media.VideoId != null)
{
return Media.VideoId.Value;
}
return null;
}
set
{
if (Media == null)
{
Media = new MediaGroup();
}
if (Media.VideoId == null)
{
Media.VideoId = new VideoId();
}
Media.VideoId.Value = value;
}
}
/// <summary>
/// property accessor for the Uploaded element, if applicable
/// returns the date the video was uplaoded
/// </summary>
public string Uploaded
{
get { return GetExtensionValue(YouTubeNameTable.Uploaded, YouTubeNameTable.NSYouTube); }
set { SetExtensionValue(YouTubeNameTable.Uploaded, YouTubeNameTable.NSYouTube, value); }
}
/// <summary>
/// property accessor for the media:credit element, if applicable
/// The media:credit element identifies who uploaded the video
/// returns the date the video was uplaoded
/// </summary>
public MediaCredit Uploader
{
get
{
MediaGroup media = Media;
if (media != null)
{
return media.Credit;
}
return null;
}
set
{
if (Media == null)
{
Media = new MediaGroup();
}
Media.Credit = value;
}
}
/// <summary>accessor for the related videos feed URI</summary>
/// <returns> </returns>
public AtomUri RelatedVideosUri
{
get
{
AtomLink link = Links.FindService(YouTubeNameTable.RelatedVideo, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
/// <summary>accessor for the video responses feed URI</summary>
/// <returns> </returns>
public AtomUri VideoResponsesUri
{
get
{
AtomLink link = Links.FindService(YouTubeNameTable.ResponseVideo, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
/// <summary>accessor for the video responses feed URI</summary>
/// <returns> </returns>
public AtomUri ComplaintUri
{
get
{
AtomLink link = Links.FindService(YouTubeNameTable.Complaint, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
/// <summary>
/// boolean property shortcut to set the mediagroup/yt:private element. Setting this to true
/// adds the element, if not already there (otherwise nothing happens)
/// setting this to false, removes it
/// it returns if the mediagroup:yt:private element exists, or not
/// </summary>
/// <returns></returns>
public bool Private
{
get
{
Private p = null;
if (Media != null)
{
p = Media.FindExtension(YouTubeNameTable.Private,
YouTubeNameTable.NSYouTube) as Private;
}
return p != null;
}
set
{
Private p = null;
if (Media != null)
{
p = Media.FindExtension(YouTubeNameTable.Private,
YouTubeNameTable.NSYouTube) as Private;
}
if (value)
{
if (p == null)
{
if (Media == null)
{
Media = new MediaGroup();
}
Media.ExtensionElements.Add(new Private());
}
}
else
{
// if we set it to false, we just going to remove the extension
if (p != null)
{
Media.DeleteExtensions(p.XmlName, p.XmlNameSpace);
}
}
}
}
/// <summary>
/// helper method to add extensions to the evententry
/// </summary>
private void addYouTubeEntryExtensions()
{
MediaGroup mg = new MediaGroup();
AddExtension(mg);
GeoRssExtensions.AddExtension(this);
AppControl app = new AppControl();
app.ProtocolMajor = ProtocolMajor;
app.ProtocolMinor = ProtocolMinor;
AppControl acf = FindExtensionFactory(app.XmlName, app.XmlNameSpace) as AppControl;
if (acf == null)
{
// create a default appControl element
acf = new AppControl();
AddExtension(acf);
}
// add the youtube state element
acf.ExtensionFactories.Add(new State());
// things from the gd namespce
AddExtension(new Comments());
AddExtension(new Rating());
// add youtube namespace elements
AddExtension(new Episode());
AddExtension(new Statistics());
AddExtension(new Location());
AddExtension(new Recorded());
AddExtension(new Uploaded());
AddExtension(new YtRating());
AddExtension(new YtAccessControl());
}
/// <summary>
/// Updates this YouTubeEntry.
/// </summary>
/// <returns>the updated YouTubeEntry or null</returns>
public new YouTubeEntry Update()
{
return base.Update() as YouTubeEntry;
}
}
/// <summary>
/// this is a helper class for parsing the category document
/// </summary>
internal class YouTubeCategoryCollection : AtomBase
{
public YouTubeCategoryCollection()
{
ProtocolMajor = VersionDefaults.VersionTwo;
}
/// <summary>Returns the constant representing this XML element.</summary>
public override string XmlName
{
get { return null; }
}
/// <summary>
/// this is the subclassing method for AtomBase derived
/// classes to overload what childelements should be created
/// needed to create CustomLink type objects, like WebContentLink etc
/// </summary>
/// <param name="reader">The XmlReader that tells us what we are working with</param>
/// <param name="parser">the parser is primarily used for nametable comparisons</param>
/// <returns>AtomBase</returns>
public override AtomBase CreateAtomSubElement(XmlReader reader, AtomFeedParser parser)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (parser == null)
{
throw new ArgumentNullException("parser");
}
object localname = reader.LocalName;
if (localname.Equals(parser.Nametable.Category))
{
return new YouTubeCategory();
}
return base.CreateAtomSubElement(reader, parser);
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// SchoolDistrict
/// </summary>
[DataContract]
public partial class SchoolDistrict : IEquatable<SchoolDistrict>
{
/// <summary>
/// Initializes a new instance of the <see cref="SchoolDistrict" /> class.
/// </summary>
/// <param name="NcesDistrictId">NcesDistrictId.</param>
/// <param name="Name">Name.</param>
/// <param name="TotalSchools">TotalSchools.</param>
/// <param name="DistrictType">DistrictType.</param>
/// <param name="Metro">Metro.</param>
/// <param name="AreaInSqM">AreaInSqM.</param>
/// <param name="SupervisoryUnionId">SupervisoryUnionId.</param>
/// <param name="DistrictEnrollment">DistrictEnrollment.</param>
/// <param name="DistrictUrl">DistrictUrl.</param>
public SchoolDistrict(string NcesDistrictId = null, string Name = null, string TotalSchools = null, string DistrictType = null, string Metro = null, string AreaInSqM = null, string SupervisoryUnionId = null, string DistrictEnrollment = null, string DistrictUrl = null)
{
this.NcesDistrictId = NcesDistrictId;
this.Name = Name;
this.TotalSchools = TotalSchools;
this.DistrictType = DistrictType;
this.Metro = Metro;
this.AreaInSqM = AreaInSqM;
this.SupervisoryUnionId = SupervisoryUnionId;
this.DistrictEnrollment = DistrictEnrollment;
this.DistrictUrl = DistrictUrl;
}
/// <summary>
/// Gets or Sets NcesDistrictId
/// </summary>
[DataMember(Name="ncesDistrictId", EmitDefaultValue=false)]
public string NcesDistrictId { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets TotalSchools
/// </summary>
[DataMember(Name="totalSchools", EmitDefaultValue=false)]
public string TotalSchools { get; set; }
/// <summary>
/// Gets or Sets DistrictType
/// </summary>
[DataMember(Name="districtType", EmitDefaultValue=false)]
public string DistrictType { get; set; }
/// <summary>
/// Gets or Sets Metro
/// </summary>
[DataMember(Name="metro", EmitDefaultValue=false)]
public string Metro { get; set; }
/// <summary>
/// Gets or Sets AreaInSqM
/// </summary>
[DataMember(Name="areaInSqM", EmitDefaultValue=false)]
public string AreaInSqM { get; set; }
/// <summary>
/// Gets or Sets SupervisoryUnionId
/// </summary>
[DataMember(Name="supervisoryUnionId", EmitDefaultValue=false)]
public string SupervisoryUnionId { get; set; }
/// <summary>
/// Gets or Sets DistrictEnrollment
/// </summary>
[DataMember(Name="districtEnrollment", EmitDefaultValue=false)]
public string DistrictEnrollment { get; set; }
/// <summary>
/// Gets or Sets DistrictUrl
/// </summary>
[DataMember(Name="districtUrl", EmitDefaultValue=false)]
public string DistrictUrl { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SchoolDistrict {\n");
sb.Append(" NcesDistrictId: ").Append(NcesDistrictId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" TotalSchools: ").Append(TotalSchools).Append("\n");
sb.Append(" DistrictType: ").Append(DistrictType).Append("\n");
sb.Append(" Metro: ").Append(Metro).Append("\n");
sb.Append(" AreaInSqM: ").Append(AreaInSqM).Append("\n");
sb.Append(" SupervisoryUnionId: ").Append(SupervisoryUnionId).Append("\n");
sb.Append(" DistrictEnrollment: ").Append(DistrictEnrollment).Append("\n");
sb.Append(" DistrictUrl: ").Append(DistrictUrl).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as SchoolDistrict);
}
/// <summary>
/// Returns true if SchoolDistrict instances are equal
/// </summary>
/// <param name="other">Instance of SchoolDistrict to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SchoolDistrict other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.NcesDistrictId == other.NcesDistrictId ||
this.NcesDistrictId != null &&
this.NcesDistrictId.Equals(other.NcesDistrictId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.TotalSchools == other.TotalSchools ||
this.TotalSchools != null &&
this.TotalSchools.Equals(other.TotalSchools)
) &&
(
this.DistrictType == other.DistrictType ||
this.DistrictType != null &&
this.DistrictType.Equals(other.DistrictType)
) &&
(
this.Metro == other.Metro ||
this.Metro != null &&
this.Metro.Equals(other.Metro)
) &&
(
this.AreaInSqM == other.AreaInSqM ||
this.AreaInSqM != null &&
this.AreaInSqM.Equals(other.AreaInSqM)
) &&
(
this.SupervisoryUnionId == other.SupervisoryUnionId ||
this.SupervisoryUnionId != null &&
this.SupervisoryUnionId.Equals(other.SupervisoryUnionId)
) &&
(
this.DistrictEnrollment == other.DistrictEnrollment ||
this.DistrictEnrollment != null &&
this.DistrictEnrollment.Equals(other.DistrictEnrollment)
) &&
(
this.DistrictUrl == other.DistrictUrl ||
this.DistrictUrl != null &&
this.DistrictUrl.Equals(other.DistrictUrl)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.NcesDistrictId != null)
hash = hash * 59 + this.NcesDistrictId.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.TotalSchools != null)
hash = hash * 59 + this.TotalSchools.GetHashCode();
if (this.DistrictType != null)
hash = hash * 59 + this.DistrictType.GetHashCode();
if (this.Metro != null)
hash = hash * 59 + this.Metro.GetHashCode();
if (this.AreaInSqM != null)
hash = hash * 59 + this.AreaInSqM.GetHashCode();
if (this.SupervisoryUnionId != null)
hash = hash * 59 + this.SupervisoryUnionId.GetHashCode();
if (this.DistrictEnrollment != null)
hash = hash * 59 + this.DistrictEnrollment.GetHashCode();
if (this.DistrictUrl != null)
hash = hash * 59 + this.DistrictUrl.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Holds individual statistic details
/// </summary>
public class Stat : IDisposable
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static readonly char[] DisallowedShortNameCharacters = { '.' };
/// <summary>
/// Category of this stat (e.g. cache, scene, etc).
/// </summary>
public string Category { get; private set; }
/// <summary>
/// Containing name for this stat.
/// FIXME: In the case of a scene, this is currently the scene name (though this leaves
/// us with a to-be-resolved problem of non-unique region names).
/// </summary>
/// <value>
/// The container.
/// </value>
public string Container { get; private set; }
public StatType StatType { get; private set; }
public MeasuresOfInterest MeasuresOfInterest { get; private set; }
/// <summary>
/// Action used to update this stat when the value is requested if it's a pull type.
/// </summary>
public Action<Stat> PullAction { get; private set; }
public StatVerbosity Verbosity { get; private set; }
public string ShortName { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public virtual string UnitName { get; private set; }
public virtual double Value
{
get
{
// Asking for an update here means that the updater cannot access this value without infinite recursion.
// XXX: A slightly messy but simple solution may be to flick a flag so we can tell if this is being
// called by the pull action and just return the value.
if (StatType == StatType.Pull)
PullAction(this);
return m_value;
}
set
{
m_value = value;
}
}
private double m_value;
/// <summary>
/// Historical samples for calculating measures of interest average.
/// </summary>
/// <remarks>
/// Will be null if no measures of interest require samples.
/// </remarks>
private Queue<double> m_samples;
/// <summary>
/// Maximum number of statistical samples.
/// </summary>
/// <remarks>
/// At the moment this corresponds to 1 minute since the sampling rate is every 2.5 seconds as triggered from
/// the main Watchdog.
/// </remarks>
private static int m_maxSamples = 24;
public Stat(
string shortName,
string name,
string description,
string unitName,
string category,
string container,
StatType type,
Action<Stat> pullAction,
StatVerbosity verbosity)
: this(
shortName,
name,
description,
unitName,
category,
container,
type,
MeasuresOfInterest.None,
pullAction,
verbosity)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name='shortName'>Short name for the stat. Must not contain spaces. e.g. "LongFrames"</param>
/// <param name='name'>Human readable name for the stat. e.g. "Long frames"</param>
/// <param name='description'>Description of stat</param>
/// <param name='unitName'>
/// Unit name for the stat. Should be preceeded by a space if the unit name isn't normally appeneded immediately to the value.
/// e.g. " frames"
/// </param>
/// <param name='category'>Category under which this stat should appear, e.g. "scene". Do not capitalize.</param>
/// <param name='container'>Entity to which this stat relates. e.g. scene name if this is a per scene stat.</param>
/// <param name='type'>Push or pull</param>
/// <param name='pullAction'>Pull stats need an action to update the stat on request. Push stats should set null here.</param>
/// <param name='moi'>Measures of interest</param>
/// <param name='verbosity'>Verbosity of stat. Controls whether it will appear in short stat display or only full display.</param>
public Stat(
string shortName,
string name,
string description,
string unitName,
string category,
string container,
StatType type,
MeasuresOfInterest moi,
Action<Stat> pullAction,
StatVerbosity verbosity)
{
if (StatsManager.SubCommands.Contains(category))
throw new Exception(
string.Format("Stat cannot be in category '{0}' since this is reserved for a subcommand", category));
foreach (char c in DisallowedShortNameCharacters)
{
if (shortName.IndexOf(c) != -1)
shortName = shortName.Replace(c, '#');
// throw new Exception(string.Format("Stat name {0} cannot contain character {1}", shortName, c));
}
ShortName = shortName;
Name = name;
Description = description;
UnitName = unitName;
Category = category;
Container = container;
StatType = type;
if (StatType == StatType.Push && pullAction != null)
throw new Exception("A push stat cannot have a pull action");
else
PullAction = pullAction;
MeasuresOfInterest = moi;
if ((moi & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
m_samples = new Queue<double>(m_maxSamples);
Verbosity = verbosity;
}
// IDisposable.Dispose()
public virtual void Dispose()
{
return;
}
/// <summary>
/// Record a value in the sample set.
/// </summary>
/// <remarks>
/// Do not call this if MeasuresOfInterest.None
/// </remarks>
public void RecordValue()
{
double newValue = Value;
lock (m_samples)
{
if (m_samples.Count >= m_maxSamples)
m_samples.Dequeue();
// m_log.DebugFormat("[STAT]: Recording value {0} for {1}", newValue, Name);
m_samples.Enqueue(newValue);
}
}
public virtual string ToConsoleString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(
"{0}.{1}.{2} : {3}{4}",
Category,
Container,
ShortName,
Value,
string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName));
AppendMeasuresOfInterest(sb);
return sb.ToString();
}
public virtual OSDMap ToOSDMap()
{
OSDMap ret = new OSDMap();
ret.Add("StatType", "Stat"); // used by overloading classes to denote type of stat
ret.Add("Category", OSD.FromString(Category));
ret.Add("Container", OSD.FromString(Container));
ret.Add("ShortName", OSD.FromString(ShortName));
ret.Add("Name", OSD.FromString(Name));
ret.Add("Description", OSD.FromString(Description));
ret.Add("UnitName", OSD.FromString(UnitName));
ret.Add("Value", OSD.FromReal(Value));
double lastChangeOverTime, averageChangeOverTime;
if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
{
ret.Add("LastChangeOverTime", OSD.FromReal(lastChangeOverTime));
ret.Add("AverageChangeOverTime", OSD.FromReal(averageChangeOverTime));
}
return ret;
}
// Compute the averages over time and return same.
// Return 'true' if averages were actually computed. 'false' if no average info.
public bool ComputeMeasuresOfInterest(out double lastChangeOverTime, out double averageChangeOverTime)
{
bool ret = false;
lastChangeOverTime = 0;
averageChangeOverTime = 0;
if ((MeasuresOfInterest & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
{
double totalChange = 0;
double? penultimateSample = null;
double? lastSample = null;
lock (m_samples)
{
// m_log.DebugFormat(
// "[STAT]: Samples for {0} are {1}",
// Name, string.Join(",", m_samples.Select(s => s.ToString()).ToArray()));
foreach (double s in m_samples)
{
if (lastSample != null)
totalChange += s - (double)lastSample;
penultimateSample = lastSample;
lastSample = s;
}
}
if (lastSample != null && penultimateSample != null)
{
lastChangeOverTime
= ((double)lastSample - (double)penultimateSample) / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
}
int divisor = m_samples.Count <= 1 ? 1 : m_samples.Count - 1;
averageChangeOverTime = totalChange / divisor / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
ret = true;
}
return ret;
}
protected void AppendMeasuresOfInterest(StringBuilder sb)
{
double lastChangeOverTime = 0;
double averageChangeOverTime = 0;
if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
{
sb.AppendFormat(
", {0:0.##}{1}/s, {2:0.##}{3}/s",
lastChangeOverTime,
string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName),
averageChangeOverTime,
string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName));
}
}
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
******************************************************************************/
using System;
using UnityEngine;
using RSUnityToolkit;
[System.Serializable]
public class SmoothingUtility : System.Object
{
private SmoothingTypes _type3D;
private SmoothingTypes _type2D;
private SmoothingTypes _type1D;
private float _factor3D;
private float _factor2D;
private float _factor1D;
private PXCMDataSmoothing _dataSmoothing;
private PXCMDataSmoothing.Smoother3D _smoother3D;
private PXCMDataSmoothing.Smoother2D _smoother2D;
private PXCMDataSmoothing.Smoother1D _smoother1D;
private bool _initialized = false;
public enum SmoothingTypes
{
Spring,
Stabilizer,
Weighted,
Quadratic
}
public SmoothingUtility()
{
}
public void Dispose()
{
if (_smoother1D != null)
{
_smoother1D.Dispose();
}
if (_smoother2D != null)
{
_smoother2D.Dispose();
}
if (_smoother3D != null)
{
_smoother3D.Dispose();
}
if (_dataSmoothing != null)
{
_dataSmoothing.Dispose();
}
}
~SmoothingUtility()
{
}
public bool Init()
{
if (!_initialized && SenseToolkitManager.Instance != null)
{
SenseToolkitManager.Instance.AddDisposeFunction(Dispose);
_initialized = true;
}
return _initialized;
}
public Quaternion ProcessSmoothing(SmoothingTypes type, float factor, Quaternion vec)
{
Init();
Vector3 vec3 = new Vector3(vec.x, vec.y, vec.z);
vec3 = ProcessSmoothing(type, factor, vec3);
float w = vec.w;
w = ProcessSmoothing(type, factor, w);
return new Quaternion(vec3.x, vec3.y, vec3.z, w);
}
public Vector3 ProcessSmoothing(SmoothingTypes type, float factor, Vector3 vec)
{
Init();
if (_dataSmoothing == null)
{
SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMDataSmoothing>(out _dataSmoothing);
}
if (_smoother3D == null || _type3D != type || factor != _factor3D)
{
if (_smoother3D != null)
{
_smoother3D.Dispose();
}
CreateSmootherType(type, factor, out _smoother3D);
_type3D = type;
_factor3D = factor;
}
PXCMPoint3DF32 point = new PXCMPoint3DF32(){x = vec.x, y = vec.y, z = vec.z};
_smoother3D.AddSample(point);
point = _smoother3D.GetSample();
return new Vector3(point.x, point.y, point.z);
}
public Vector2 ProcessSmoothing(SmoothingTypes type, float factor, Vector2 vec)
{
Init();
if (_dataSmoothing == null)
{
SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMDataSmoothing>(out _dataSmoothing);
}
if (_smoother2D == null || _type2D != type || factor != _factor2D)
{
if (_smoother2D != null)
{
_smoother2D.Dispose();
}
CreateSmootherType(type, factor, out _smoother2D);
_type2D = type;
_factor2D = factor;
}
PXCMPointF32 point = new PXCMPointF32(){x = vec.x, y = vec.y};
_smoother2D.AddSample(point);
point = _smoother2D.GetSample();
return new Vector2(point.x, point.y);
}
public float ProcessSmoothing(SmoothingTypes type, float factor, float sample)
{
Init();
if (_dataSmoothing == null)
{
SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMDataSmoothing>(out _dataSmoothing);
}
if (_smoother1D == null || _type1D != type || factor != _factor1D)
{
if (_smoother1D != null)
{
_smoother1D.Dispose();
}
CreateSmootherType(type, factor, out _smoother1D);
_type1D = type;
_factor1D = factor;
}
_smoother1D.AddSample(sample);
sample = _smoother1D.GetSample();
return sample;
}
private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMDataSmoothing.Smoother3D smoother)
{
switch (type)
{
case SmoothingTypes.Quadratic:
smoother = _dataSmoothing.Create3DQuadratic(factor);
break;
case SmoothingTypes.Stabilizer:
smoother = _dataSmoothing.Create3DStabilizer(7, factor);
break;
case SmoothingTypes.Weighted:
smoother = _dataSmoothing.Create3DWeighted((int)factor);
break;
case SmoothingTypes.Spring:
default:
smoother = _dataSmoothing.Create3DSpring(factor);
break;
}
}
private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMDataSmoothing.Smoother2D smoother)
{
switch (type)
{
case SmoothingTypes.Quadratic:
smoother = _dataSmoothing.Create2DQuadratic(factor);
break;
case SmoothingTypes.Stabilizer:
smoother = _dataSmoothing.Create2DStabilizer(7, factor);
break;
case SmoothingTypes.Weighted:
smoother = _dataSmoothing.Create2DWeighted((int)factor);
break;
case SmoothingTypes.Spring:
default:
smoother = _dataSmoothing.Create2DSpring(factor);
break;
}
}
private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMDataSmoothing.Smoother1D smoother)
{
switch (type)
{
case SmoothingTypes.Quadratic:
smoother = _dataSmoothing.Create1DQuadratic(factor);
break;
case SmoothingTypes.Stabilizer:
smoother = _dataSmoothing.Create1DStabilizer(7, factor);
break;
case SmoothingTypes.Weighted:
smoother = _dataSmoothing.Create1DWeighted((int)factor);
break;
case SmoothingTypes.Spring:
default:
smoother = _dataSmoothing.Create1DSpring(factor);
break;
}
}
}
| |
using Microsoft.EntityFrameworkCore.Migrations;
namespace VodManager.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DataStore",
columns: table => new
{
Key = table.Column<string>(nullable: false),
Type = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataStore", x => new { x.Key, x.Type });
});
migrationBuilder.CreateTable(
name: "RunChangedEvents",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
RunID = table.Column<int>(nullable: false),
Timestamp = table.Column<long>(nullable: false),
GameName = table.Column<string>(nullable: true),
CategoryName = table.Column<string>(nullable: true),
PlayerNamesTwitch = table.Column<string>(nullable: true),
DataProcessed = table.Column<bool>(nullable: false),
RunProcessed = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RunChangedEvents", x => x.ID);
});
migrationBuilder.CreateTable(
name: "SceneEvents",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Timestamp = table.Column<long>(nullable: false),
SceneName = table.Column<string>(nullable: true),
SceneEventType = table.Column<int>(nullable: false),
TwitchPastBroadcastID = table.Column<long>(nullable: false),
TwitchPastBroadcastStartTimestamp = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SceneEvents", x => x.ID);
});
migrationBuilder.CreateTable(
name: "TimerEvents",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Timestamp = table.Column<long>(nullable: false),
TimerEventType = table.Column<int>(nullable: false),
TwitchPastBroadcastID = table.Column<long>(nullable: false),
TwitchPastBroadcastStartTimestamp = table.Column<long>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TimerEvents", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Runs",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
RelevantEventID = table.Column<int>(nullable: false),
StartTimestamp = table.Column<long>(nullable: false),
EndTimestamp = table.Column<long>(nullable: false),
TwitchPastBroadcastID = table.Column<long>(nullable: false),
TwitchPastBroadcastStartTimestamp = table.Column<long>(nullable: false),
ManuallyModified = table.Column<bool>(nullable: false),
DoProcess = table.Column<bool>(nullable: false),
Ignore = table.Column<bool>(nullable: false),
TweetedAbout = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Runs", x => x.ID);
table.ForeignKey(
name: "FK_Runs_RunChangedEvents_RelevantEventID",
column: x => x.RelevantEventID,
principalTable: "RunChangedEvents",
principalColumn: "ID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Videos",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
SortID = table.Column<int>(nullable: false),
RunID = table.Column<int>(nullable: true),
ProcessLog = table.Column<string>(nullable: true),
DoneProcessing = table.Column<bool>(nullable: false),
FilePath = table.Column<string>(nullable: true),
Title = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
Tags = table.Column<string>(nullable: true),
Game = table.Column<string>(nullable: true),
YouTubeID = table.Column<string>(nullable: true),
YouTubePublishTimestamp = table.Column<long>(nullable: true),
YouTubePublic = table.Column<bool>(nullable: true),
UploadLog = table.Column<string>(nullable: true),
DoneUploading = table.Column<bool>(nullable: false),
Modified = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Videos", x => x.ID);
table.ForeignKey(
name: "FK_Videos_Runs_RunID",
column: x => x.RunID,
principalTable: "Runs",
principalColumn: "ID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_RunChangedEvents_Timestamp",
table: "RunChangedEvents",
column: "Timestamp");
migrationBuilder.CreateIndex(
name: "IX_Runs_RelevantEventID",
table: "Runs",
column: "RelevantEventID");
migrationBuilder.CreateIndex(
name: "IX_SceneEvents_Timestamp",
table: "SceneEvents",
column: "Timestamp");
migrationBuilder.CreateIndex(
name: "IX_SceneEvents_TwitchPastBroadcastStartTimestamp",
table: "SceneEvents",
column: "TwitchPastBroadcastStartTimestamp");
migrationBuilder.CreateIndex(
name: "IX_SceneEvents_Timestamp_SceneEventType",
table: "SceneEvents",
columns: new[] { "Timestamp", "SceneEventType" });
migrationBuilder.CreateIndex(
name: "IX_TimerEvents_Timestamp",
table: "TimerEvents",
column: "Timestamp");
migrationBuilder.CreateIndex(
name: "IX_TimerEvents_TwitchPastBroadcastStartTimestamp",
table: "TimerEvents",
column: "TwitchPastBroadcastStartTimestamp");
migrationBuilder.CreateIndex(
name: "IX_TimerEvents_Timestamp_TimerEventType",
table: "TimerEvents",
columns: new[] { "Timestamp", "TimerEventType" });
migrationBuilder.CreateIndex(
name: "IX_Videos_RunID",
table: "Videos",
column: "RunID");
migrationBuilder.CreateIndex(
name: "IX_Videos_SortID",
table: "Videos",
column: "SortID");
migrationBuilder.CreateIndex(
name: "IX_Videos_YouTubeID",
table: "Videos",
column: "YouTubeID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataStore");
migrationBuilder.DropTable(
name: "SceneEvents");
migrationBuilder.DropTable(
name: "TimerEvents");
migrationBuilder.DropTable(
name: "Videos");
migrationBuilder.DropTable(
name: "Runs");
migrationBuilder.DropTable(
name: "RunChangedEvents");
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// Defines available log levels.
/// </summary>
[TypeConverter(typeof(Attributes.LogLevelTypeConverter))]
public sealed class LogLevel : IComparable, IEquatable<LogLevel>, IConvertible
{
/// <summary>
/// Trace log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Trace = new LogLevel("Trace", 0);
/// <summary>
/// Debug log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Debug = new LogLevel("Debug", 1);
/// <summary>
/// Info log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Info = new LogLevel("Info", 2);
/// <summary>
/// Warn log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Warn = new LogLevel("Warn", 3);
/// <summary>
/// Error log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Error = new LogLevel("Error", 4);
/// <summary>
/// Fatal log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Fatal = new LogLevel("Fatal", 5);
/// <summary>
/// Off log level.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
public static readonly LogLevel Off = new LogLevel("Off", 6);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
private static readonly IList<LogLevel> allLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal, Off }.AsReadOnly();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")]
private static readonly IList<LogLevel> allLoggingLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal }.AsReadOnly();
/// <summary>
/// Gets all the available log levels (Trace, Debug, Info, Warn, Error, Fatal, Off).
/// </summary>
public static IEnumerable<LogLevel> AllLevels => allLevels;
/// <summary>
/// Gets all the log levels that can be used to log events (Trace, Debug, Info, Warn, Error, Fatal)
/// i.e <c>LogLevel.Off</c> is excluded.
/// </summary>
public static IEnumerable<LogLevel> AllLoggingLevels => allLoggingLevels;
private readonly int _ordinal;
private readonly string _name;
/// <summary>
/// Initializes a new instance of <see cref="LogLevel"/>.
/// </summary>
/// <param name="name">The log level name.</param>
/// <param name="ordinal">The log level ordinal number.</param>
private LogLevel(string name, int ordinal)
{
_name = name;
_ordinal = ordinal;
}
/// <summary>
/// Gets the name of the log level.
/// </summary>
public string Name => _name;
internal static LogLevel MaxLevel => Fatal;
internal static LogLevel MinLevel => Trace;
/// <summary>
/// Gets the ordinal of the log level.
/// </summary>
public int Ordinal => _ordinal;
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is equal to the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal == level2.Ordinal</c>.</returns>
public static bool operator ==(LogLevel level1, LogLevel level2)
{
if (ReferenceEquals(level1, null))
{
return ReferenceEquals(level2, null);
}
if (ReferenceEquals(level2, null))
{
return false;
}
return level1.Ordinal == level2.Ordinal;
}
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is not equal to the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal != level2.Ordinal</c>.</returns>
public static bool operator !=(LogLevel level1, LogLevel level2)
{
if (ReferenceEquals(level1, null))
{
return !ReferenceEquals(level2, null);
}
if (ReferenceEquals(level2, null))
{
return true;
}
return level1.Ordinal != level2.Ordinal;
}
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is greater than the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal > level2.Ordinal</c>.</returns>
public static bool operator >(LogLevel level1, LogLevel level2)
{
if (level1 == null) { throw new ArgumentNullException(nameof(level1)); }
if (level2 == null) { throw new ArgumentNullException(nameof(level2)); }
return level1.Ordinal > level2.Ordinal;
}
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is greater than or equal to the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal >= level2.Ordinal</c>.</returns>
public static bool operator >=(LogLevel level1, LogLevel level2)
{
if (level1 == null) { throw new ArgumentNullException(nameof(level1)); }
if (level2 == null) { throw new ArgumentNullException(nameof(level2)); }
return level1.Ordinal >= level2.Ordinal;
}
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is less than the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal < level2.Ordinal</c>.</returns>
public static bool operator <(LogLevel level1, LogLevel level2)
{
if (level1 == null) { throw new ArgumentNullException(nameof(level1)); }
if (level2 == null) { throw new ArgumentNullException(nameof(level2)); }
return level1.Ordinal < level2.Ordinal;
}
/// <summary>
/// Compares two <see cref="LogLevel"/> objects
/// and returns a value indicating whether
/// the first one is less than or equal to the second one.
/// </summary>
/// <param name="level1">The first level.</param>
/// <param name="level2">The second level.</param>
/// <returns>The value of <c>level1.Ordinal <= level2.Ordinal</c>.</returns>
public static bool operator <=(LogLevel level1, LogLevel level2)
{
if (level1 == null) { throw new ArgumentNullException(nameof(level1)); }
if (level2 == null) { throw new ArgumentNullException(nameof(level2)); }
return level1.Ordinal <= level2.Ordinal;
}
/// <summary>
/// Gets the <see cref="LogLevel"/> that corresponds to the specified ordinal.
/// </summary>
/// <param name="ordinal">The ordinal.</param>
/// <returns>The <see cref="LogLevel"/> instance. For 0 it returns <see cref="LogLevel.Trace"/>, 1 gives <see cref="LogLevel.Debug"/> and so on.</returns>
public static LogLevel FromOrdinal(int ordinal)
{
switch (ordinal)
{
case 0:
return Trace;
case 1:
return Debug;
case 2:
return Info;
case 3:
return Warn;
case 4:
return Error;
case 5:
return Fatal;
case 6:
return Off;
default:
throw new ArgumentException("Invalid ordinal.");
}
}
/// <summary>
/// Returns the <see cref="T:NLog.LogLevel"/> that corresponds to the supplied <see langword="string" />.
/// </summary>
/// <param name="levelName">The textual representation of the log level.</param>
/// <returns>The enumeration value.</returns>
public static LogLevel FromString(string levelName)
{
if (levelName == null)
{
throw new ArgumentNullException(nameof(levelName));
}
if (levelName.Equals("Trace", StringComparison.OrdinalIgnoreCase))
{
return Trace;
}
if (levelName.Equals("Debug", StringComparison.OrdinalIgnoreCase))
{
return Debug;
}
if (levelName.Equals("Info", StringComparison.OrdinalIgnoreCase))
{
return Info;
}
if (levelName.Equals("Warn", StringComparison.OrdinalIgnoreCase))
{
return Warn;
}
if (levelName.Equals("Error", StringComparison.OrdinalIgnoreCase))
{
return Error;
}
if (levelName.Equals("Fatal", StringComparison.OrdinalIgnoreCase))
{
return Fatal;
}
if (levelName.Equals("Off", StringComparison.OrdinalIgnoreCase))
{
return Off;
}
if (levelName.Equals("None", StringComparison.OrdinalIgnoreCase))
{
return Off; // .NET Core Microsoft Extension Logging
}
if (levelName.Equals("Information", StringComparison.OrdinalIgnoreCase))
{
return Info; // .NET Core Microsoft Extension Logging
}
if (levelName.Equals("Warning", StringComparison.OrdinalIgnoreCase))
{
return Warn; // .NET Core Microsoft Extension Logging
}
throw new ArgumentException($"Unknown log level: {levelName}");
}
/// <summary>
/// Returns a string representation of the log level.
/// </summary>
/// <returns>Log level name.</returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return Ordinal;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>Value of <c>true</c> if the specified <see cref="System.Object"/> is equal to
/// this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
LogLevel other = obj as LogLevel;
if ((object)other == null)
{
return false;
}
return Ordinal == other.Ordinal;
}
/// <summary>
/// Determines whether the specified <see cref="NLog.LogLevel"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="NLog.LogLevel"/> to compare with this instance.</param>
/// <returns>Value of <c>true</c> if the specified <see cref="NLog.LogLevel"/> is equal to
/// this instance; otherwise, <c>false</c>.</returns>
public bool Equals(LogLevel other)
{
return other != null && Ordinal == other.Ordinal;
}
/// <summary>
/// Compares the level to the other <see cref="LogLevel"/> object.
/// </summary>
/// <param name="obj">
/// The object object.
/// </param>
/// <returns>
/// A value less than zero when this logger's <see cref="Ordinal"/> is
/// less than the other logger's ordinal, 0 when they are equal and
/// greater than zero when this ordinal is greater than the
/// other ordinal.
/// </returns>
public int CompareTo(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
// The code below does NOT account if the casting to LogLevel returns null. This is
// because as this class is sealed and does not provide any public constructors it
// is impossible to create a invalid instance.
LogLevel level = (LogLevel)obj;
return Ordinal - level.Ordinal;
}
#region Implementation of IConvertible
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_ordinal);
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException();
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(_ordinal);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException();
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_ordinal);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return _ordinal;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_ordinal);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_ordinal);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_ordinal);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_ordinal);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_ordinal);
}
string IConvertible.ToString(IFormatProvider provider)
{
return _name;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(string))
return Name;
else
return Convert.ChangeType(_ordinal, conversionType, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_ordinal);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_ordinal);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_ordinal);
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StructuredTree.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// The structured tree.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.StructuredData
{
#region
using System.Collections.Generic;
using Configuration;
using Diagnostics;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using SecurityModel;
using Sitecore.Data;
using Sitecore.Data.Indexing;
using Sitecore.Data.Items;
using Sitecore.Search;
#endregion
/// <summary>
/// The structured tree.
/// </summary>
public class StructuredTree
{
#region Fields
/// <summary>
/// The current folder.
/// </summary>
private readonly Item CurrentFolder;
/// <summary>
/// The folder master item.
/// </summary>
private readonly TemplateItem FolderMasterItem;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="StructuredTree"/> class.
/// </summary>
/// <param name="structuredTreeRootItem">
/// The structured tree root item.
/// </param>
public StructuredTree(Item structuredTreeRootItem)
{
Assert.ArgumentNotNull(structuredTreeRootItem, "structuredTreeRootItem");
Database db = structuredTreeRootItem.Database;
this.FolderMasterItem = db.Templates["Ecommerce/StructuredData/StructuredData StructuredFolder"];
this.StructuredTreeRootItem = structuredTreeRootItem;
string id = this.StructuredTreeRootItem["enumeratorCurrentFolder"];
if (!string.IsNullOrEmpty(id))
{
Item itm = db.GetItem(id);
if (itm != null)
{
this.CurrentFolder = itm;
return;
}
}
if (this.CurrentFolder == null)
{
this.CurrentFolder = this.StructuredTreeRootItem;
}
}
#endregion
#region Private properties
/// <summary>
/// Gets the item limit in folder.
/// </summary>
/// <value>The item limit in folder.</value>
private int StructuredDataFolderLevels
{
get
{
if (this.StructuredTreeRootItem != null)
{
int val;
int.TryParse(this.StructuredTreeRootItem["StructuredDataFolderLevels"], out val);
if (val != 0)
{
return val;
}
}
// return default value.
return 4;
}
}
/// <summary>
/// Gets or sets the structured tree root item.
/// </summary>
/// <value>The structured tree root item.</value>
private Item StructuredTreeRootItem { get; set; }
#endregion
#region Public methods
/// <summary>
/// Adds an item to the structured tree root.
/// The item is placed at the
/// </summary>
/// <param name="item">
/// The item.
/// </param>
public void AddItem(Item item)
{
string id = new ShortID(item.ID).ToString();
Item currentNode = this.StructuredTreeRootItem;
int level = 1;
foreach (char letter in id)
{
Item child = currentNode.Children[letter.ToString()];
if (child == null)
{
using (new SecurityDisabler())
{
using (new EditContext(currentNode))
{
child = currentNode.Add(letter.ToString(), this.FolderMasterItem);
}
}
}
currentNode = child;
if (level == this.StructuredDataFolderLevels)
{
item.MoveTo(currentNode);
return;
}
level += 1;
}
}
/// <summary>
/// Gets the indexes from the Use Search Form Settings
/// </summary>
/// <returns>
/// Returns Indexes.
/// </returns>
public List<string> GetIndexes()
{
if (this.StructuredTreeRootItem != null)
{
List<string> indexes = new List<string>();
// Find the Indexes/Index item which holds the id of the search Index or Indexes to use.
string indexIDs = this.StructuredTreeRootItem["Use Search Form Settings"];
if (!string.IsNullOrEmpty(indexIDs))
{
string[] indexesString = indexIDs.Split('|');
foreach (string index in indexesString)
{
Item indexItem = this.StructuredTreeRootItem.Database.GetItem(index);
if (indexItem != null)
{
string indexName = indexItem["name"];
if (!string.IsNullOrEmpty(indexName))
{
indexes.Add(indexItem["name"]);
}
}
}
}
return indexes;
}
return null;
}
/// <summary>
/// Gets the items from the GetIndexes()
/// </summary>
/// <param name="queryString">
/// The query string.
/// </param>
/// <param name="useQueryParser">
/// if set to <c>true</c> [use query parser].
/// </param>
/// <returns>
/// Returns Query Result
/// </returns>
public QueryResult GetItems(string queryString, bool useQueryParser)
{
// Result object used to pass result and errormessages back to sender.
QueryResult result = new QueryResult();
List<string> indexes = this.GetIndexes();
string[] resultItemIds = null;
foreach (string indexName in indexes)
{
string database = "master";
HighResTimer timer = new HighResTimer(true);
// get the specified index
Sitecore.Search.Index searchIndex = SearchManager.GetIndex(indexName);
// get the database to perform the search in..
Database db = Factory.GetDatabase(database);
SearchHits hits;
try
{
if (useQueryParser)
{
using (IndexSearchContext searchContext = searchIndex.CreateSearchContext())
{
// get a new standard analyser so we can create a query..
Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
QueryParser queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, queryString, analyzer);
Query qry = queryParser.Query("_content");
hits = searchContext.Search(qry, int.MaxValue);
}
}
else
{
using (IndexSearchContext searchContext = searchIndex.CreateSearchContext())
{
// perform the search and get the results back as a Hits list..
hits = searchContext.Search(queryString, int.MaxValue);
}
}
result.Success = true;
resultItemIds = new string[hits.Length];
int i = 0;
foreach (Document document in hits.Documents)
{
string str = document.Get("_docID");
resultItemIds[i++] = str;
}
}
catch (ParseException e)
{
result.ErrorMessage = e.Message;
result.ParseException = e;
result.Success = false;
}
}
result.Result = resultItemIds;
return result;
}
/// <summary>
/// Gets the templates in indexes.
/// </summary>
/// <returns>
/// Returns templates.
/// </returns>
public List<string> GetTemplatesInIndexes()
{
if (this.StructuredTreeRootItem != null)
{
List<string> templates = new List<string>();
// Find the Indexes/Index item which holds the id of the search Index or Indexes to use.
List<string> indexes = this.GetIndexes();
foreach (string index in indexes)
{
Item indexItem = this.StructuredTreeRootItem.Database.GetItem(index);
if (indexItem != null)
{
string indexName = indexItem["includeItemOfTemplates"];
if (!string.IsNullOrEmpty(indexName))
{
templates.Add(indexItem["name"]);
}
}
}
return templates;
}
return null;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
public class QuestAndEventsExample : MonoBehaviour {
public GameObject avatar;
private Texture defaulttexture;
public Texture2D pieIcon;
public DefaultPreviewButton connectButton;
public SA_Label playerLabel;
public DefaultPreviewButton[] ConnectionDependedntButtons;
//example, replase with your ID
private const string EVENT_ID = "CgkIipfs2qcGEAIQDQ";
//example, replase with your ID
private const string QUEST_ID = "CgkIipfs2qcGEAIQDg";
void Start() {
playerLabel.text = "Player Disconnected";
defaulttexture = avatar.GetComponent<Renderer>().material.mainTexture;
//listen for GooglePlayConnection events
GooglePlayConnection.ActionPlayerConnected += OnPlayerConnected;
GooglePlayConnection.ActionPlayerDisconnected += OnPlayerDisconnected;
GooglePlayConnection.ActionConnectionResultReceived += OnConnectionResult;
//listen for events, we will use action in this example
GooglePlayEvents.Instance.OnEventsLoaded += OnEventsLoaded;
GooglePlayQuests.Instance.OnQuestsAccepted += OnQuestsAccepted;
GooglePlayQuests.Instance.OnQuestsCompleted += OnQuestsCompleted;
GooglePlayQuests.Instance.OnQuestsLoaded += OnQuestsLoaded;
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
//checking if player already connected
OnPlayerConnected ();
}
}
private void ConncetButtonPress() {
Debug.Log("GooglePlayManager State -> " + GooglePlayConnection.State.ToString());
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
SA_StatusBar.text = "Disconnecting from Play Service...";
GooglePlayConnection.Instance.Disconnect ();
} else {
SA_StatusBar.text = "Connecting to Play Service...";
GooglePlayConnection.Instance.Connect ();
}
}
void FixedUpdate() {
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
if(GooglePlayManager.Instance.player.icon != null) {
avatar.GetComponent<Renderer>().material.mainTexture = GooglePlayManager.Instance.player.icon;
}
} else {
avatar.GetComponent<Renderer>().material.mainTexture = defaulttexture;
}
string title = "Connect";
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
title = "Disconnect";
foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) {
btn.EnabledButton();
}
} else {
foreach(DefaultPreviewButton btn in ConnectionDependedntButtons) {
btn.DisabledButton();
}
if(GooglePlayConnection.State == GPConnectionState.STATE_DISCONNECTED || GooglePlayConnection.State == GPConnectionState.STATE_UNCONFIGURED) {
title = "Connect";
} else {
title = "Connecting..";
}
}
connectButton.text = title;
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
public void LoadEvents() {
GooglePlayEvents.Instance.LoadEvents();
}
public void IncrementEvent() {
GooglePlayEvents.Instance.SumbitEvent(EVENT_ID);
}
public void ShowAllQuests() {
GooglePlayQuests.Instance.ShowQuests();
}
public void ShowAcceptedQuests() {
GooglePlayQuests.Instance.ShowQuests(GP_QuestsSelect.SELECT_ACCEPTED);
}
public void ShowCompletedQuests() {
GooglePlayQuests.Instance.ShowQuests(GP_QuestsSelect.SELECT_COMPLETED);
}
public void ShowOpenQuests() {
GooglePlayQuests.Instance.ShowQuests(GP_QuestsSelect.SELECT_OPEN);
}
public void AcceptQuest() {
GooglePlayQuests.Instance.AcceptQuest(QUEST_ID);
}
public void LoadQuests() {
GooglePlayQuests.Instance.LoadQuests(GP_QuestSortOrder.SORT_ORDER_ENDING_SOON_FIRST);
}
//--------------------------------------
// EVENTS
//--------------------------------------
private void OnEventsLoaded (GooglePlayResult result) {
Debug.Log ("Total Events: " + GooglePlayEvents.Instance.Events.Count);
AN_PoupsProxy.showMessage ("Events Loaded", "Total Events: " + GooglePlayEvents.Instance.Events.Count);
SA_StatusBar.text = "OnEventsLoaded: " + result.Response.ToString();
foreach(GP_Event ev in GooglePlayEvents.Instance.Events) {
Debug.Log(ev.Id);
Debug.Log(ev.Description);
Debug.Log(ev.FormattedValue);
Debug.Log(ev.Value);
Debug.Log(ev.IconImageUrl);
Debug.Log(ev.icon);
}
}
private void OnQuestsAccepted (GP_QuestResult result) {
AN_PoupsProxy.showMessage ("On Quests Accepted", "Quests Accepted, ID: " + result.GetQuest().Id);
SA_StatusBar.text = "OnQuestsAccepted: " + result.Response.ToString();
}
private void OnQuestsCompleted (GP_QuestResult result) {
Debug.Log ("Quests Completed, Reward: " + result.GetQuest().RewardData);
AN_PoupsProxy.showMessage ("On Quests Completed", "Quests Completed, Reward: " + result.GetQuest().RewardData);
SA_StatusBar.text = "OnQuestsCompleted: " + result.Response.ToString();
}
private void OnQuestsLoaded (GooglePlayResult result) {
Debug.Log ("Total Quests: " + GooglePlayQuests.Instance.GetQuests().Count);
AN_PoupsProxy.showMessage ("Quests Loaded", "Total Quests: " + GooglePlayQuests.Instance.GetQuests().Count);
SA_StatusBar.text = "OnQuestsLoaded: " + result.Response.ToString();
foreach(GP_Quest quest in GooglePlayQuests.Instance.GetQuests()) {
Debug.Log(quest.Id);
}
}
private void OnPlayerDisconnected() {
SA_StatusBar.text = "Player Disconnected";
playerLabel.text = "Player Disconnected";
}
private void OnPlayerConnected() {
SA_StatusBar.text = "Player Connected";
playerLabel.text = GooglePlayManager.Instance.player.name;
}
private void OnConnectionResult(GooglePlayConnectionResult result) {
SA_StatusBar.text = "ConnectionResul: " + result.code.ToString();
Debug.Log(result.code.ToString());
}
void OnDestroy() {
GooglePlayConnection.ActionPlayerConnected -= OnPlayerConnected;
GooglePlayConnection.ActionPlayerDisconnected -= OnPlayerDisconnected;
GooglePlayConnection.ActionConnectionResultReceived -= OnConnectionResult;
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using FileHelpers.Core;
namespace FileHelpers
{
/// <summary>
/// Record read from the file for processing
/// </summary>
/// <remarks>
/// The data inside the LIneInfo may be reset during processing,
/// for example on read next line. Do not rely on this class
/// containing all data from a record for all time. It is designed
/// to read data sequentially.
/// </remarks>
[DebuggerDisplay("{DebuggerDisplayStr()}")]
internal sealed class LineInfo
{
//public static readonly LineInfo Empty = new LineInfo(string.Empty);
#region " Constructor "
//static readonly char[] mEmptyChars = new char[] {};
/// <summary>
/// Create a line info with data from line
/// </summary>
/// <param name="line"></param>
public LineInfo(string line)
{
mReader = null;
mLineStr = line;
//mLine = line == null ? mEmptyChars : line.ToCharArray();
mCurrentPos = 0;
}
#endregion
/// <summary>
/// Return part of line, Substring
/// </summary>
/// <param name="from">Start position (zero offset)</param>
/// <param name="count">Number of characters to extract</param>
/// <returns>substring from line</returns>
public string Substring(int from, int count)
{
return mLineStr.Substring(from, count);
}
#region " Internal Fields "
//internal string mLine;
//internal char[] mLine;
/// <summary>
/// Record read from reader
/// </summary>
internal string mLineStr;
/// <summary>
/// Reader that got the string
/// </summary>
internal ForwardReader mReader;
/// <summary>
/// Where we are processing records from
/// </summary>
internal int mCurrentPos;
/// <summary>
/// List of whitespace characters that we want to skip
/// </summary>
internal static readonly char[] WhitespaceChars = new char[] {
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005',
'\u2006', '\u2007', '\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
};
#endregion
/// <summary>
/// Debugger display string
/// </summary>
/// <returns></returns>
private string DebuggerDisplayStr()
{
if (IsEOL())
return "<EOL>";
else
return CurrentString;
}
/// <summary>
/// Extract a single field from the system
/// </summary>
public string CurrentString
{
get { return mLineStr.Substring(mCurrentPos, mLineStr.Length - mCurrentPos); }
}
/// <summary>
/// If we have extracted more that the field contains.
/// </summary>
/// <returns>True if end of line</returns>
public bool IsEOL()
{
return mCurrentPos >= mLineStr.Length;
}
/// <summary>
/// Amount of data left to process
/// </summary>
public int CurrentLength
{
get { return mLineStr.Length - mCurrentPos; }
}
/// <summary>
/// Is there only whitespace left in the record?
/// </summary>
/// <returns>True if only whitespace</returns>
public bool EmptyFromPos()
{
// Check if the chars at pos or right are empty ones
int length = mLineStr.Length;
int pos = mCurrentPos;
while (pos < length &&
Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0)
pos++;
return pos >= length;
}
/// <summary>
/// Delete any of these characters from beginning of the record
/// </summary>
/// <param name="toTrim"></param>
public void TrimStart(char[] toTrim)
{
Array.Sort(toTrim);
TrimStartSorted(toTrim);
}
/// <summary>
/// Move the record pointer along skipping these characters
/// </summary>
/// <param name="toTrim">Sorted array of character to skip</param>
private void TrimStartSorted(char[] toTrim)
{
// Move the pointer to the first non to Trim char
int length = mLineStr.Length;
while (mCurrentPos < length &&
Array.BinarySearch(toTrim, mLineStr[mCurrentPos]) >= 0)
mCurrentPos++;
}
public bool StartsWith(string str)
{
// Returns true if the string begin with str
if (mCurrentPos >= mLineStr.Length)
return false;
else {
return
mCompare.Compare(mLineStr,
mCurrentPos,
str.Length,
str,
0,
str.Length,
CompareOptions.OrdinalIgnoreCase) == 0;
}
}
/// <summary>
/// Check that the record begins with a value ignoring whitespace
/// </summary>
/// <param name="str">String to check for</param>
/// <returns>True if record begins with</returns>
public bool StartsWithTrim(string str)
{
int length = mLineStr.Length;
int pos = mCurrentPos;
while (pos < length &&
Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0)
pos++;
return mCompare.Compare(mLineStr, pos, str, 0, CompareOptions.OrdinalIgnoreCase) == 0;
}
/// <summary>
/// get The next line from the system and reset the line pointer to zero
/// </summary>
public void ReadNextLine()
{
mLineStr = mReader.ReadNextLine();
//mLine = mLineStr.ToCharArray();
mCurrentPos = 0;
}
private static readonly CompareInfo mCompare = ComparerCache.CreateComparer();
/// <summary>
/// Find the location of the next string in record
/// </summary>
/// <param name="foundThis">String we are looking for</param>
/// <returns>Position of the next one</returns>
public int IndexOf(string foundThis)
{
return mCompare.IndexOf(mLineStr, foundThis, mCurrentPos, CompareOptions.Ordinal);
}
/// <summary>
/// Reset the string back to the original line and reset the line pointer
/// </summary>
/// <remarks>If the input is multi line, this will read next record and remove the original data</remarks>
/// <param name="line">Line to use</param>
internal void ReLoad(string line)
{
//mLine = line == null ? mEmptyChars : line.ToCharArray();
mLineStr = line;
mCurrentPos = 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using System.Text;
using System.Net;
namespace System.DirectoryServices.AccountManagement
{
internal class SidList
{
internal SidList(List<byte[]> sidListByteFormat) : this(sidListByteFormat, null, null)
{
}
internal SidList(List<byte[]> sidListByteFormat, string target, NetCred credentials)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} ByteFormat SIDs", sidListByteFormat.Count);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: Targetting {0} ", (target != null) ? target : "local store");
// Build the list of SIDs to resolve
IntPtr hUser = IntPtr.Zero;
int sidCount = sidListByteFormat.Count;
IntPtr[] pSids = new IntPtr[sidCount];
for (int i = 0; i < sidCount; i++)
{
pSids[i] = Utils.ConvertByteArrayToIntPtr(sidListByteFormat[i]);
}
try
{
if (credentials != null)
{
Utils.BeginImpersonation(credentials, out hUser);
}
TranslateSids(target, pSids);
}
finally
{
if (hUser != IntPtr.Zero)
Utils.EndImpersonation(hUser);
}
}
internal SidList(UnsafeNativeMethods.SID_AND_ATTR[] sidAndAttr)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} Sid+Attr SIDs", sidAndAttr.Length);
// Build the list of SIDs to resolve
int sidCount = sidAndAttr.Length;
IntPtr[] pSids = new IntPtr[sidCount];
for (int i = 0; i < sidCount; i++)
{
pSids[i] = sidAndAttr[i].pSid;
}
TranslateSids(null, pSids);
}
protected void TranslateSids(string target, IntPtr[] pSids)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", pSids.Length);
// if there are no SIDs to translate return
if (pSids.Length == 0)
{
return;
}
// Build the list of SIDs to resolve
int sidCount = pSids.Length;
// Translate the SIDs in bulk
IntPtr pOA = IntPtr.Zero;
IntPtr pPolicyHandle = IntPtr.Zero;
IntPtr pDomains = IntPtr.Zero;
UnsafeNativeMethods.LSA_TRUST_INFORMATION[] domains;
IntPtr pNames = IntPtr.Zero;
UnsafeNativeMethods.LSA_TRANSLATED_NAME[] names;
try
{
//
// Get the policy handle
//
UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES();
pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES)));
Marshal.StructureToPtr(oa, pOA, false);
int err = 0;
if (target == null)
{
err = UnsafeNativeMethods.LsaOpenPolicy(
IntPtr.Zero,
pOA,
0x800, // POLICY_LOOKUP_NAMES
ref pPolicyHandle);
}
else
{
// Build an entry. Note that LSA_UNICODE_STRING.length is in bytes,
// while PtrToStringUni expects a length in characters.
UnsafeNativeMethods.LSA_UNICODE_STRING_Managed lsaTargetString = new UnsafeNativeMethods.LSA_UNICODE_STRING_Managed();
lsaTargetString.buffer = target;
lsaTargetString.length = (ushort)(target.Length * 2);
lsaTargetString.maximumLength = lsaTargetString.length;
IntPtr lsaTargetPr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_UNICODE_STRING)));
try
{
Marshal.StructureToPtr(lsaTargetString, lsaTargetPr, false);
err = UnsafeNativeMethods.LsaOpenPolicy(
lsaTargetPr,
pOA,
0x800, // POLICY_LOOKUP_NAMES
ref pPolicyHandle);
}
finally
{
if (lsaTargetPr != IntPtr.Zero)
{
UnsafeNativeMethods.LSA_UNICODE_STRING lsaTargetUnmanagedPtr =
(UnsafeNativeMethods.LSA_UNICODE_STRING)Marshal.PtrToStructure(lsaTargetPr, typeof(UnsafeNativeMethods.LSA_UNICODE_STRING));
if (lsaTargetUnmanagedPtr.buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(lsaTargetUnmanagedPtr.buffer);
lsaTargetUnmanagedPtr.buffer = IntPtr.Zero;
}
Marshal.FreeHGlobal(lsaTargetPr);
}
}
}
if (err != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err);
throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
Debug.Assert(pPolicyHandle != IntPtr.Zero);
//
// Translate the SIDs
//
err = UnsafeNativeMethods.LsaLookupSids(
pPolicyHandle,
sidCount,
pSids,
out pDomains,
out pNames);
// ignore error STATUS_SOME_NOT_MAPPED = 0x00000107 and
// STATUS_NONE_MAPPED = 0xC0000073
if (err != 0 &&
err != 263 &&
err != -1073741709)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err);
throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
//
// Get the group names in managed form
//
names = new UnsafeNativeMethods.LSA_TRANSLATED_NAME[sidCount];
IntPtr pCurrentName = pNames;
for (int i = 0; i < sidCount; i++)
{
names[i] = (UnsafeNativeMethods.LSA_TRANSLATED_NAME)
Marshal.PtrToStructure(pCurrentName, typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME));
pCurrentName = new IntPtr(pCurrentName.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME)));
}
//
// Get the domain names in managed form
//
// Extract LSA_REFERENCED_DOMAIN_LIST.Entries
UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST referencedDomains = (UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST)Marshal.PtrToStructure(pDomains, typeof(UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST));
int domainCount = referencedDomains.entries;
// Extract LSA_REFERENCED_DOMAIN_LIST.Domains, by iterating over the array and marshalling
// each native LSA_TRUST_INFORMATION into a managed LSA_TRUST_INFORMATION.
domains = new UnsafeNativeMethods.LSA_TRUST_INFORMATION[domainCount];
IntPtr pCurrentDomain = referencedDomains.domains;
for (int i = 0; i < domainCount; i++)
{
domains[i] = (UnsafeNativeMethods.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION));
pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION)));
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount);
//
// Build the list of entries
//
Debug.Assert(names.Length == sidCount);
for (int i = 0; i < names.Length; i++)
{
UnsafeNativeMethods.LSA_TRANSLATED_NAME name = names[i];
// Build an entry. Note that LSA_UNICODE_STRING.length is in bytes,
// while PtrToStringUni expects a length in characters.
SidListEntry entry = new SidListEntry();
Debug.Assert(name.name.length % 2 == 0);
entry.name = Marshal.PtrToStringUni(name.name.buffer, name.name.length / 2);
// Get the domain associated with this name
Debug.Assert(name.domainIndex < domains.Length);
if (name.domainIndex >= 0)
{
UnsafeNativeMethods.LSA_TRUST_INFORMATION domain = domains[name.domainIndex];
Debug.Assert(domain.name.length % 2 == 0);
entry.sidIssuerName = Marshal.PtrToStringUni(domain.name.buffer, domain.name.length / 2);
}
entry.pSid = pSids[i];
_entries.Add(entry);
}
// Sort the list so they are oriented by the issuer name.
// this.entries.Sort( new SidListComparer());
}
finally
{
if (pDomains != IntPtr.Zero)
UnsafeNativeMethods.LsaFreeMemory(pDomains);
if (pNames != IntPtr.Zero)
UnsafeNativeMethods.LsaFreeMemory(pNames);
if (pPolicyHandle != IntPtr.Zero)
UnsafeNativeMethods.LsaClose(pPolicyHandle);
if (pOA != IntPtr.Zero)
Marshal.FreeHGlobal(pOA);
}
}
private readonly List<SidListEntry> _entries = new List<SidListEntry>();
public SidListEntry this[int index]
{
get { return _entries[index]; }
}
public int Length
{
get { return _entries.Count; }
}
public void RemoveAt(int index)
{
_entries[index].Dispose();
_entries.RemoveAt(index);
}
public void Clear()
{
foreach (SidListEntry sl in _entries)
sl.Dispose();
_entries.Clear();
}
}
/******
class SidListComparer : IComparer<SidListEntry>
{
public int Compare(SidListEntry entry1, SidListEntry entry2)
{
return ( string.Compare( entry1.sidIssuerName, entry2.sidIssuerName, true, CultureInfo.InvariantCulture));
}
}
********/
internal class SidListEntry : IDisposable
{
public IntPtr pSid = IntPtr.Zero;
public string name;
public string sidIssuerName;
//
// IDisposable
//
public virtual void Dispose()
{
if (pSid != IntPtr.Zero)
{
Marshal.FreeHGlobal(pSid);
pSid = IntPtr.Zero;
}
}
}
}
| |
// 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.
//
// Why this file exists:
//
// Because the Reflection base types have so many overridable members, it becomes impossible to distinguish
// members we decided not to override vs. those we forgot to override. It would be nice if C# had a construct to
// tell the reader (and Intellisense) that we've made an explicit decision *not* to override an inherited member,
// but since it doesn't, we'll make do with this instead.
//
// In DEBUG builds, we'll add a base-delegating override so that it's clear we made an explicit decision
// to accept the base class's implementation and that we don't get Intelli-spammed with the same dozen override suggestions
// every time we add a new subclass or a new abstract to an existing base class. In RELEASE builds, we'll #if'd
// these out to avoid the extra metadata and runtime cost. That way, every overridable member is accounted
// for (i.e. the codebase should always be kept in a state where hitting "override" + SPACE never brings up
// additional suggestions in Intellisense.)
//
// We also do this for types that override abstract members with another abstract override to keep their own Intellisense spam-free.
//
// Why this file is named "UnoverriddenApis":
//
// Because "U" appears late in an alphabetical sort. So when I press F12 to go to a type definition, this file doesn't jump
// ahead of the ones I'm much more likely to be interested in.
//
using System.IO;
using System.Security;
using System.Collections.Generic;
namespace System.Reflection.TypeLoading
{
internal abstract partial class RoAssembly
{
#if DEBUG
// RoAssembly objects are unified in the TypeLoader object. So reference equality is the same as semantic equality.
public sealed override bool Equals(object o) => base.Equals(o);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override FileStream[] GetFiles() => base.GetFiles();
public sealed override AssemblyName GetName() => base.GetName();
public sealed override Type GetType(string name) => base.GetType(name);
public sealed override Type GetType(string name, bool throwOnError) => base.GetType(name, throwOnError);
public sealed override IEnumerable<Module> Modules => base.Modules;
public sealed override SecurityRuleSet SecurityRuleSet => base.SecurityRuleSet;
#endif //DEBUG
}
internal abstract partial class RoModule
{
#if DEBUG
// RoModule objects are unified in the RoAssembly object. So reference equality is the same as semantic equality.
public sealed override bool Equals(object o) => base.Equals(o);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override Type GetType(string className) => base.GetType(className);
public sealed override Type GetType(string className, bool ignoreCase) => base.GetType(className, ignoreCase);
public sealed override Type[] FindTypes(TypeFilter filter, object filterCriteria) => base.FindTypes(filter, filterCriteria);
#endif //DEBUG
}
internal abstract partial class RoType
{
#if DEBUG
// RoTypes objects are unified for desktop compat. So reference equality is the same as semantic equality.
public sealed override bool Equals(object o) => base.Equals(o);
public sealed override bool Equals(Type o) => base.Equals(o);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) => base.FindInterfaces(filter, filterCriteria);
public sealed override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) => base.FindMembers(memberType, bindingAttr, filter, filterCriteria);
public sealed override EventInfo[] GetEvents() => base.GetEvents();
protected sealed override bool IsContextfulImpl() => base.IsContextfulImpl();
public sealed override bool IsSubclassOf(Type c) => base.IsSubclassOf(c);
protected sealed override bool IsMarshalByRefImpl() => base.IsMarshalByRefImpl();
public sealed override bool IsInstanceOfType(object o) => base.IsInstanceOfType(o);
public sealed override bool IsSerializable => base.IsSerializable;
public sealed override bool IsEquivalentTo(Type other) => base.IsEquivalentTo(other); // Note: If we enable COM type equivalence, this is no longer the correct implementation.
public sealed override bool IsSignatureType => base.IsSignatureType;
public sealed override IEnumerable<ConstructorInfo> DeclaredConstructors => base.DeclaredConstructors;
public sealed override IEnumerable<EventInfo> DeclaredEvents => base.DeclaredEvents;
public sealed override IEnumerable<FieldInfo> DeclaredFields => base.DeclaredFields;
public sealed override IEnumerable<MemberInfo> DeclaredMembers => base.DeclaredMembers;
public sealed override IEnumerable<MethodInfo> DeclaredMethods => base.DeclaredMethods;
public sealed override IEnumerable<TypeInfo> DeclaredNestedTypes => base.DeclaredNestedTypes;
public sealed override IEnumerable<PropertyInfo> DeclaredProperties => base.DeclaredProperties;
public sealed override EventInfo GetDeclaredEvent(string name) => base.GetDeclaredEvent(name);
public sealed override FieldInfo GetDeclaredField(string name) => base.GetDeclaredField(name);
public sealed override MethodInfo GetDeclaredMethod(string name) => base.GetDeclaredMethod(name);
public sealed override TypeInfo GetDeclaredNestedType(string name) => base.GetDeclaredNestedType(name);
public sealed override PropertyInfo GetDeclaredProperty(string name) => base.GetDeclaredProperty(name);
public sealed override IEnumerable<MethodInfo> GetDeclaredMethods(string name) => base.GetDeclaredMethods(name);
public sealed override string GetEnumName(object value) => base.GetEnumName(value);
public sealed override string[] GetEnumNames() => base.GetEnumNames();
public sealed override bool IsEnumDefined(object value) => base.IsEnumDefined(value);
#endif //DEBUG
}
internal abstract partial class RoDefinitionType
{
#if DEBUG
public abstract override bool IsGenericTypeDefinition { get; }
internal abstract override RoModule GetRoModule();
protected abstract override string ComputeName();
protected abstract override string ComputeNamespace();
protected abstract override TypeAttributes ComputeAttributeFlags();
protected abstract override RoType ComputeDeclaringType();
internal abstract override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
internal abstract override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
public abstract override int MetadataToken { get; }
protected internal abstract override RoType ComputeEnumUnderlyingType();
internal abstract override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter);
#endif //DEBUG
}
internal abstract partial class RoHasElementType
{
#if DEBUG
protected abstract override bool IsArrayImpl();
public abstract override bool IsSZArray { get; }
public abstract override bool IsVariableBoundArray { get; }
protected abstract override bool IsByRefImpl();
protected abstract override bool IsPointerImpl();
public abstract override int GetArrayRank();
protected abstract override TypeAttributes ComputeAttributeFlags();
protected abstract override RoType ComputeBaseTypeWithoutDesktopQuirk();
protected abstract override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces();
internal abstract override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter);
internal abstract override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType);
#endif //DEBUG
}
internal abstract partial class RoGenericParameterType
{
#if DEBUG
public abstract override bool IsGenericTypeParameter { get; }
public abstract override bool IsGenericMethodParameter { get; }
protected abstract override string ComputeName();
public abstract override MethodBase DeclaringMethod { get; }
protected abstract override RoType ComputeDeclaringType();
internal abstract override RoModule GetRoModule();
public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; }
public abstract override int MetadataToken { get; }
public abstract override GenericParameterAttributes GenericParameterAttributes { get; }
internal abstract override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
internal abstract override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
#endif //DEBUG
}
internal abstract partial class RoEvent
{
#if DEBUG
public sealed override MemberTypes MemberType => base.MemberType;
public sealed override MethodInfo AddMethod => base.AddMethod;
public sealed override MethodInfo RemoveMethod => base.RemoveMethod;
public sealed override MethodInfo RaiseMethod => base.RaiseMethod;
#endif //DEBUG
}
internal abstract partial class RoField
{
#if DEBUG
public sealed override MemberTypes MemberType => base.MemberType;
#endif //DEBUG
}
internal abstract partial class RoMethod
{
#if DEBUG
public sealed override MemberTypes MemberType => base.MemberType;
#endif //DEBUG
}
internal abstract partial class RoConstructor
{
#if DEBUG
public sealed override MemberTypes MemberType => base.MemberType;
public sealed override Type[] GetGenericArguments() => base.GetGenericArguments();
#endif //DEBUG
}
internal abstract partial class RoProperty
{
#if DEBUG
public sealed override MemberTypes MemberType => base.MemberType;
public sealed override MethodInfo GetMethod => base.GetMethod;
public sealed override MethodInfo SetMethod => base.SetMethod;
public sealed override object GetValue(object obj, object[] index) => base.GetValue(obj, index);
public sealed override void SetValue(object obj, object value, object[] index) => base.SetValue(obj, value, index);
#endif //DEBUG
}
internal abstract partial class RoCustomAttributeData
{
#if DEBUG
public sealed override bool Equals(object obj) => base.Equals(obj);
public sealed override int GetHashCode() => base.GetHashCode();
#endif //DEBUG
}
internal abstract partial class RoMethodBody
{
#if DEBUG
public sealed override bool Equals(object obj) => base.Equals(obj);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override string ToString() => base.ToString();
#endif //DEBUG
}
internal sealed partial class RoLocalVariableInfo
{
#if DEBUG
public sealed override bool Equals(object obj) => base.Equals(obj);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override string ToString() => base.ToString();
#endif //DEBUG
}
internal sealed partial class RoExceptionHandlingClause
{
#if DEBUG
public sealed override bool Equals(object obj) => base.Equals(obj);
public sealed override int GetHashCode() => base.GetHashCode();
public sealed override string ToString() => base.ToString();
#endif //DEBUG
}
}
| |
//
// TextEntryBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Xwt.Backends;
using System;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.Foundation;
using MonoMac.AppKit;
#else
using Foundation;
using AppKit;
#endif
namespace Xwt.Mac
{
public class TextEntryBackend: ViewBackend<NSView,ITextEntryEventSink>, ITextEntryBackend
{
int cacheSelectionStart, cacheSelectionLength;
bool checkMouseSelection;
public TextEntryBackend ()
{
}
internal TextEntryBackend (MacComboBox field)
{
ViewObject = field;
}
public override void Initialize ()
{
base.Initialize ();
if (ViewObject is MacComboBox) {
((MacComboBox)ViewObject).SetEntryEventSink (EventSink);
} else {
var view = new CustomTextField (EventSink, ApplicationContext);
ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view);
MultiLine = false;
}
canGetFocus = Widget.AcceptsFirstResponder ();
Frontend.MouseEntered += delegate {
checkMouseSelection = true;
};
Frontend.MouseExited += delegate {
checkMouseSelection = false;
HandleSelectionChanged ();
};
Frontend.MouseMoved += delegate {
if (checkMouseSelection)
HandleSelectionChanged ();
};
}
protected override void OnSizeToFit ()
{
Container.SizeToFit ();
}
CustomAlignedContainer Container {
get { return base.Widget as CustomAlignedContainer; }
}
public new NSTextField Widget {
get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; }
}
protected override Size GetNaturalSize ()
{
var s = base.GetNaturalSize ();
return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height);
}
#region ITextEntryBackend implementation
public string Text {
get {
return Widget.StringValue;
}
set {
Widget.StringValue = value ?? string.Empty;
}
}
public Alignment TextAlignment {
get {
return Widget.Alignment.ToAlignment ();
}
set {
Widget.Alignment = value.ToNSTextAlignment ();
}
}
public bool ReadOnly {
get {
return !Widget.Editable;
}
set {
Widget.Editable = !value;
}
}
public bool ShowFrame {
get {
return Widget.Bordered;
}
set {
Widget.Bordered = value;
}
}
public string PlaceholderText {
get {
return ((NSTextFieldCell) Widget.Cell).PlaceholderString;
}
set {
((NSTextFieldCell) Widget.Cell).PlaceholderString = value;
}
}
public bool MultiLine {
get {
if (Widget is MacComboBox)
return false;
return Widget.Cell.UsesSingleLineMode;
}
set {
if (Widget is MacComboBox)
return;
if (value) {
Widget.Cell.UsesSingleLineMode = false;
Widget.Cell.Scrollable = false;
Widget.Cell.Wraps = true;
} else {
Widget.Cell.UsesSingleLineMode = true;
Widget.Cell.Scrollable = true;
Widget.Cell.Wraps = false;
}
Container.ExpandVertically = value;
}
}
public int CursorPosition {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionStart {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionLength {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Length;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (SelectionStart, value);
HandleSelectionChanged ();
}
}
public string SelectedText {
get {
if (Widget.CurrentEditor == null)
return String.Empty;
int start = SelectionStart;
int end = start + SelectionLength;
if (start == end) return String.Empty;
try {
return Text.Substring (start, end - start);
} catch {
return String.Empty;
}
}
set {
int cacheSelStart = SelectionStart;
int pos = cacheSelStart;
if (SelectionLength > 0) {
Text = Text.Remove (pos, SelectionLength).Insert (pos, value);
}
SelectionStart = pos;
SelectionLength = value.Length;
HandleSelectionChanged ();
}
}
void HandleSelectionChanged ()
{
if (cacheSelectionStart != SelectionStart ||
cacheSelectionLength != SelectionLength) {
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
}
public void SetCompletions (string[] completions)
{
}
#endregion
#region Gross Hack
// The 'Widget' property is not virtual and the one on the base class holds
// the 'CustomAlignedContainer' object and *not* the NSTextField object. As
// such everything that uses the 'Widget' property in the base class might be
// working on the wrong object. The focus methods definitely need to work on
// the NSTextField directly, so i've overridden those and made them interact
// with the NSTextField instead of the CustomAlignedContainer.
bool canGetFocus = true;
public override bool CanGetFocus {
get { return canGetFocus; }
set { canGetFocus = value && Widget.AcceptsFirstResponder (); }
}
public override void SetFocus ()
{
if (Widget.Window != null && CanGetFocus)
Widget.Window.MakeFirstResponder (Widget);
}
public override bool HasFocus {
get {
return Widget.Window != null && Widget.Window.FirstResponder == Widget;
}
}
#endregion
}
class CustomTextField: NSTextField, IViewObject
{
ITextEntryEventSink eventSink;
ApplicationContext context;
CustomCell cell;
public CustomTextField (ITextEntryEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
this.Cell = cell = new CustomCell {
BezelStyle = NSTextFieldBezelStyle.Square,
Bezeled = true,
DrawsBackground = true,
BackgroundColor = NSColor.White,
Editable = true,
EventSink = eventSink,
Context = context,
};
}
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
public override void DidChange (NSNotification notification)
{
base.DidChange (notification);
context.InvokeUserCode (delegate {
eventSink.OnChanged ();
eventSink.OnSelectionChanged ();
});
}
class CustomCell : NSTextFieldCell
{
CustomEditor editor;
public ApplicationContext Context {
get; set;
}
public ITextEntryEventSink EventSink {
get; set;
}
public CustomCell ()
{
}
public override NSTextView FieldEditorForView (NSView aControlView)
{
if (editor == null) {
editor = new CustomEditor {
Context = this.Context,
EventSink = this.EventSink,
FieldEditor = true,
Editable = true,
DrawsBackground = true,
BackgroundColor = NSColor.White,
};
}
return editor;
}
}
class CustomEditor : NSTextView
{
public ApplicationContext Context {
get; set;
}
public ITextEntryEventSink EventSink {
get; set;
}
public CustomEditor ()
{
}
public override void KeyDown (NSEvent theEvent)
{
Context.InvokeUserCode (delegate {
EventSink.OnKeyPressed (theEvent.ToXwtKeyEventArgs ());
});
base.KeyDown (theEvent);
}
nint cachedCursorPosition;
public override void KeyUp (NSEvent theEvent)
{
if (cachedCursorPosition != SelectedRange.Location) {
cachedCursorPosition = SelectedRange.Location;
Context.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
EventSink.OnKeyReleased (theEvent.ToXwtKeyEventArgs ());
});
}
base.KeyUp (theEvent);
}
public override bool BecomeFirstResponder ()
{
var result = base.BecomeFirstResponder ();
if (result) {
Context.InvokeUserCode (() => {
EventSink.OnGotFocus ();
});
}
return result;
}
public override bool ResignFirstResponder ()
{
var result = base.ResignFirstResponder ();
if (result) {
Context.InvokeUserCode (() => {
EventSink.OnLostFocus ();
});
}
return result;
}
}
}
}
| |
using System;
using System.Data;
//using System.Windows.Forms;
using System.Text;
using System.ComponentModel;
namespace Provider.VistaDB
{
/// <summary>
/// Table column definition.
/// </summary>
public class VistaDBColumn
{
private string name;
private VistaDBType vistaDBType;
private Type type;
private int dataSize;
private short columnWidth;
private short columnDecimals;//
private bool allowNull;
private bool readOnly;
private bool primaryKey;
private bool unique;
private bool identity;
private double identityStep;//
private string identityValue;//
private string columnCaption;
private string columnDescription;//
private bool packed;
private bool hidden;
private bool encrypted;
private bool unicode;
private bool reservedWord;
internal VistaDBColumn(string _name,
VistaDBType _vistaDBType,
int _dataSize,
short _columnWidth,
short _columnDecimals,
bool _allowNull,
bool _readOnly,
bool _primaryKey,
bool _unique,
bool _identity,
double _identityStep,
string _identityValue,
string _columnCaption,
string _columnDescription,
bool _reservedWord,
bool _packed,
bool _hidden,
bool _encrypted,
bool _unicode)
{
name = _name;
vistaDBType = _vistaDBType;
type = VistaDBAPI.GetFieldType(vistaDBType);
dataSize = _dataSize;
columnWidth = _columnWidth;
columnDecimals = _columnDecimals;
allowNull = _allowNull;
readOnly = _readOnly;
primaryKey = _primaryKey;
unique = _unique;
identity = _identity;
identityStep = _identityStep;
identityValue = _identityValue;
columnCaption = _columnCaption;
columnDescription = _columnDescription;
reservedWord = _reservedWord;
packed = _packed;
hidden = _hidden;
encrypted = _encrypted;
unicode = _unicode;
}
/// <summary>
/// Column name.
/// </summary>
public string Name
{
get
{
return name;
}
set
{
}
}
/// <summary>
/// VistaDBType for the column.
/// </summary>
public VistaDBType VistaDBType
{
get
{
return vistaDBType;
}
set
{
}
}
/// <summary>
/// Column type.
/// </summary>
public Type Type
{
get
{
return type;
}
set
{
}
}
/// <summary>
/// Physical size of column.
/// </summary>
public int DataSize
{
get
{
return dataSize;
}
set
{
}
}
/// <summary>
/// Returns the column width. Useful for Varchar and Character column types.
/// </summary>
public short ColumnWidth
{
get
{
return columnWidth;
}
set
{
}
}
/// <summary>
/// Returns the column decimals.
/// </summary>
public short ColumnDecimals
{
get
{
return columnDecimals;
}
set
{
}
}
/// <summary>
/// Returns true if column can store NULL values.
/// </summary>
public bool AllowNull
{
get
{
return allowNull;
}
set
{
}
}
/// <summary>
/// Returns true if the column is readonly.
/// </summary>
public bool ReadOnly
{
get
{
return readOnly;
}
set
{
}
}
/// <summary>
/// Returns true if the column participates in the Primary Key index.
/// </summary>
public bool PrimaryKey
{
get
{
return primaryKey;
}
set
{
}
}
/// <summary>
/// Returns true if the column participates in the Unique index
/// </summary>
public bool Unique
{
get
{
return unique;
}
set
{
}
}
/// <summary>
/// Returns true if the column is an Identity field.
/// </summary>
public bool Identity
{
get
{
return identity;
}
set
{
}
}
/// <summary>
/// Returns increment step for identity
/// </summary>
public double IdentityStep
{
get
{
return identityStep;
}
set
{
}
}
/// <summary>
/// Returns current value for identity
/// </summary>
public string IdentityValue
{
get
{
return identityValue;
}
set
{
}
}
/// <summary>
/// Returns the Caption for the column.
/// </summary>
public string ColumnCaption
{
get
{
return columnCaption;
}
set
{
}
}
/// <summary>
/// Returns the column description
/// </summary>
public string ColumnDescription
{
get
{
return columnDescription;
}
set
{
}
}
/// <summary>
/// Returns true if column name is reserved word
/// </summary>
public bool ReservedWord
{
get
{
return reservedWord;
}
set
{
}
}
/// <summary>
/// Return true if column is packed
/// </summary>
public bool Packed
{
get
{
return this.packed;
}
set
{
}
}
/// <summary>
/// Return true if column marked as hidden
/// </summary>
public bool Hidden
{
get
{
return this.hidden;
}
set
{
}
}
/// <summary>
/// Return encrypted if column encrypted
/// </summary>
public bool Encrypted
{
get
{
return this.encrypted;
}
set
{
}
}
/// <summary>
/// Not supported property. Always return false.
/// </summary>
public bool Unicode
{
get
{
return this.unicode;
}
set
{
}
}
}
/// <summary>
/// V-SQL query class
/// </summary>
internal abstract class VistaDBSQLQuery
{
protected int rowsAffected;
protected int recordCount;
protected string commandText;
protected bool opened;
protected int columnCount;
protected string password;
protected int errorNumber;
protected VistaDBColumn[] columns;
protected VistaDBSQLConnection parent;
protected static object syncRoot = new object();
public VistaDBSQLQuery(VistaDBSQLConnection p)
{
rowsAffected = 0;
recordCount = 0;
commandText = "";
columnCount = 0;
password = "";
errorNumber = 0;
parent = p;
opened = false;
Columns = new VistaDBColumnCollection(this);
}
public abstract void CreateQuery();
public abstract void FreeQuery();
/// <summary>
/// Used internally.
/// </summary>
public void DropQuery()
{
this.parent.DropQuery(this);
}
/// <summary>
/// Destructor
/// </summary>
~VistaDBSQLQuery()
{
try
{
Close();
}
finally
{
this.columns = null;
FreeQuery();
}
}
///////////////////////////////////////////////////////////
////////////////Open and prepare SQL functions/////////////
///////////////////////////////////////////////////////////
/// <summary>
/// Open a V-SQL query. Open is used with SELECT statements only.
/// </summary>
public abstract void Open();
/// <summary>
/// Close a V-SQL query.
/// </summary>
public abstract void Close();
/// <summary>
/// Execute a V-SQL query that does not return a result set. These include INSERT, DELETE and UPDATE.
/// </summary>
public abstract void ExecSQL();
////////////////////////////////////////////////////////////
////////////////Data and parameter functions////////////////
////////////////////////////////////////////////////////////
/// <summary>
/// Set a V-SQL parameter.
/// </summary>
/// <param name="paramName">Parameter name.</param>
/// <param name="dataType">Parameter data type.</param>
/// <param name="value">Data value</param>
public abstract void SetParameter(string paramName, VistaDBType dataType, object value);
/// <summary>
/// Returns True if the V-SQL parameter value is NULL.
/// </summary>
public abstract bool ParamIsNull(string pName);
/// <summary>
/// Set a V-SQL parameter value to NULL.
/// </summary>
public abstract void SetParamNull(string pName, VistaDBType type);
/// <summary>
/// Returns if the V-SQL query has been opened. Applies to SELECT statements only.
/// </summary>
public bool Opened
{
get
{
return this.opened;
}
}
//////////////////////////////////////////////////////////
///////////////Navigation functions///////////////////////
//////////////////////////////////////////////////////////
/// <summary>
/// Go to the first row in the dataset.
/// </summary>
/// <returns>False if current position doesn't change</returns>
public abstract bool First();
/// <summary>
/// Go to the next row in dataset
/// </summary>
/// <returns>False if current position doesn't change</returns>
public abstract bool Next();
/// <summary>
/// End of file. Tests if a row movement function has placed the row pointer beyond the last row in the dataset.
/// </summary>
public abstract bool Eof
{
get;
}
//////////////////////////////////////////////////////////
///////////////////Meta data functions////////////////////
//////////////////////////////////////////////////////////
/// <summary>
/// Return the number of rows affected.
/// </summary>
public int RowsAffected
{
get
{
return this.rowsAffected;
}
}
/// <summary>
/// Return the column count for the V-SQL query.
/// </summary>
public int ColumnCount
{
get
{
return this.columnCount;
}
}
/// <summary>
/// The collection of column objects in the V-SQL query.
/// </summary>
public class VistaDBColumnCollection
{
private VistaDBSQLQuery parent;
public VistaDBColumnCollection(VistaDBSQLQuery p)
{
this.parent = p;
}
/// <summary>
/// Gets the column object at the specified offset.
/// </summary>
public VistaDBColumn this[int i]
{
get
{
if( i < 0 || i > parent.columns.GetUpperBound(0) )
return null;
else
return this.parent.columns[i];
}
}
/// <summary>
/// Gets the number of columns in the collection.
/// </summary>
public int Count
{
get
{
return this.parent.columns.Length;
}
}
}
/// <summary>
/// Column objects in the collection.
/// </summary>
public readonly VistaDBColumnCollection Columns;
/// <summary>
/// Returns the value of the column at the given position in the table schema. The first column is 1.
/// </summary>
public abstract object GetValue(int fieldNo);
/// <summary>
/// Returns the number of records retrieved by the last V-SQL query statement. Applies to SELECT.
/// </summary>
public int RecordCount
{
get
{
return this.recordCount;
}
}
/// <summary>
/// Gets or sets the V-SQL query statement to be executed.
/// </summary>
public string SQL
{
get
{
return this.commandText;
}
set
{
this.commandText = value;
}
}
public abstract bool IsNull(int columnNumber);
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Generic;
using FluentMigrator.Runner.Helpers;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
namespace FluentMigrator.Runner.Generators.Oracle
{
public class OracleGenerator : GenericGenerator, IOracleGenerator
{
public OracleGenerator()
: this(false)
{
}
public OracleGenerator(bool useQuotedIdentifiers)
: this(GetQuoter(useQuotedIdentifiers))
{
}
public OracleGenerator(
[NotNull] OracleQuoterBase quoter)
: this(quoter, new OptionsWrapper<GeneratorOptions>(new GeneratorOptions()))
{
}
public OracleGenerator(
[NotNull] OracleQuoterBase quoter,
[NotNull] IOptions<GeneratorOptions> generatorOptions)
: base(new OracleColumn(quoter), quoter, new OracleDescriptionGenerator(), generatorOptions)
{
}
public OracleGenerator(
[NotNull] IColumn column,
[NotNull] OracleQuoterBase quoter,
[NotNull] IOptions<GeneratorOptions> generatorOptions)
: base(column, quoter, new OracleDescriptionGenerator(), generatorOptions)
{
}
protected OracleGenerator(
[NotNull] IColumn column,
[NotNull] OracleQuoterBase quoter,
[NotNull] IDescriptionGenerator descriptionGenerator,
[NotNull] IOptions<GeneratorOptions> generatorOptions)
: base(column, quoter, descriptionGenerator, generatorOptions)
{
}
protected static OracleQuoterBase GetQuoter(bool useQuotedIdentifiers)
{
return useQuotedIdentifiers ? new OracleQuoterQuotedIdentifier() : new OracleQuoter();
}
public override string DropTable
{
get
{
return "DROP TABLE {0}";
}
}
public override string Generate(DeleteTableExpression expression)
{
return string.Format(DropTable, ExpandTableName(Quoter.QuoteTableName(expression.SchemaName),Quoter.QuoteTableName(expression.TableName)));
}
public override string Generate(CreateSequenceExpression expression)
{
var result = new StringBuilder("CREATE SEQUENCE ");
var seq = expression.Sequence;
if (string.IsNullOrEmpty(seq.SchemaName))
{
result.AppendFormat(Quoter.QuoteSequenceName(seq.Name));
}
else
{
result.AppendFormat("{0}", Quoter.QuoteSequenceName(seq.Name, seq.SchemaName));
}
if (seq.Increment.HasValue)
{
result.AppendFormat(" INCREMENT BY {0}", seq.Increment);
}
if (seq.MinValue.HasValue)
{
result.AppendFormat(" MINVALUE {0}", seq.MinValue);
}
if (seq.MaxValue.HasValue)
{
result.AppendFormat(" MAXVALUE {0}", seq.MaxValue);
}
if (seq.StartWith.HasValue)
{
result.AppendFormat(" START WITH {0}", seq.StartWith);
}
const long MINIMUM_CACHE_VALUE = 2;
if (seq.Cache.HasValue)
{
if (seq.Cache.Value < MINIMUM_CACHE_VALUE)
{
return CompatibilityMode.HandleCompatibilty("Oracle does not support Cache value equal to 1; if you intended to disable caching, set Cache to null. For information on Oracle limitations, see: https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/CREATE-SEQUENCE.html#GUID-E9C78A8C-615A-4757-B2A8-5E6EFB130571__GUID-7E390BE1-2F6C-4E5A-9D5C-5A2567D636FB");
}
result.AppendFormat(" CACHE {0}", seq.Cache);
}
else
{
result.Append(" NOCACHE");
}
if (seq.Cycle)
{
result.Append(" CYCLE");
}
return result.ToString();
}
public override string AddColumn
{
get { return "ALTER TABLE {0} ADD {1}"; }
}
public override string AlterColumn
{
get { return "ALTER TABLE {0} MODIFY {1}"; }
}
public override string RenameTable
{
get { return "ALTER TABLE {0} RENAME TO {1}"; }
}
public override string InsertData
{
get { return "INTO {0} ({1}) VALUES ({2})"; }
}
private static string ExpandTableName(string schema, string table)
{
return string.IsNullOrEmpty(schema) ? table : string.Concat(schema,".",table);
}
private static string WrapStatementInExecuteImmediateBlock(string statement)
{
if (string.IsNullOrEmpty(statement))
{
return string.Empty;
}
return string.Format("EXECUTE IMMEDIATE '{0}';", FormatHelper.FormatSqlEscape(statement));
}
private static string WrapInBlock(string sql)
{
if (string.IsNullOrEmpty(sql))
{
return string.Empty;
}
return string.Format("BEGIN {0} END;", sql);
}
private string InnerGenerate(CreateTableExpression expression)
{
var tableName = Quoter.QuoteTableName(expression.TableName);
var schemaName = Quoter.QuoteSchemaName(expression.SchemaName);
return string.Format("CREATE TABLE {0} ({1})",ExpandTableName(schemaName,tableName), Column.Generate(expression.Columns, tableName));
}
protected override StringBuilder AppendSqlStatementEndToken(StringBuilder stringBuilder)
{
return stringBuilder.AppendLine().AppendLine(";");
}
public override string Generate(CreateTableExpression expression)
{
var descriptionStatements = DescriptionGenerator.GenerateDescriptionStatements(expression);
var statements = descriptionStatements as string[] ?? descriptionStatements.ToArray();
if (!statements.Any())
{
return InnerGenerate(expression);
}
var wrappedCreateTableStatement = WrapStatementInExecuteImmediateBlock(InnerGenerate(expression));
var createTableWithDescriptionsBuilder = new StringBuilder(wrappedCreateTableStatement);
foreach (var descriptionStatement in statements)
{
if (!string.IsNullOrEmpty(descriptionStatement))
{
var wrappedStatement = WrapStatementInExecuteImmediateBlock(descriptionStatement);
createTableWithDescriptionsBuilder.Append(wrappedStatement);
}
}
return WrapInBlock(createTableWithDescriptionsBuilder.ToString());
}
public override string Generate(AlterTableExpression expression)
{
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
{
return base.Generate(expression);
}
return descriptionStatement;
}
public override string Generate(CreateColumnExpression expression)
{
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
return base.Generate(expression);
var wrappedCreateColumnStatement = WrapStatementInExecuteImmediateBlock(base.Generate(expression));
var createColumnWithDescriptionBuilder = new StringBuilder(wrappedCreateColumnStatement);
createColumnWithDescriptionBuilder.Append(WrapStatementInExecuteImmediateBlock(descriptionStatement));
return WrapInBlock(createColumnWithDescriptionBuilder.ToString());
}
public override string Generate(AlterColumnExpression expression)
{
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
return base.Generate(expression);
var wrappedAlterColumnStatement = WrapStatementInExecuteImmediateBlock(base.Generate(expression));
var alterColumnWithDescriptionBuilder = new StringBuilder(wrappedAlterColumnStatement);
alterColumnWithDescriptionBuilder.Append(WrapStatementInExecuteImmediateBlock(descriptionStatement));
return WrapInBlock(alterColumnWithDescriptionBuilder.ToString());
}
public override string Generate(InsertDataExpression expression)
{
var columnNames = new List<string>();
var columnValues = new List<string>();
var insertStrings = new List<string>();
foreach (InsertionDataDefinition row in expression.Rows)
{
columnNames.Clear();
columnValues.Clear();
foreach (KeyValuePair<string, object> item in row)
{
columnNames.Add(Quoter.QuoteColumnName(item.Key));
columnValues.Add(Quoter.QuoteValue(item.Value));
}
string columns = string.Join(", ", columnNames.ToArray());
string values = string.Join(", ", columnValues.ToArray());
insertStrings.Add(string.Format(InsertData, ExpandTableName(Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName)), columns, values));
}
return "INSERT ALL " + string.Join(" ", insertStrings.ToArray()) + " SELECT 1 FROM DUAL";
}
public override string Generate(AlterDefaultConstraintExpression expression)
{
return string.Format(AlterColumn, Quoter.QuoteTableName(expression.TableName), Column.Generate(new ColumnDefinition
{
ModificationType = ColumnModificationType.Alter,
Name = expression.ColumnName,
DefaultValue = expression.DefaultValue
}));
}
public override string Generate(DeleteDefaultConstraintExpression expression)
{
return Generate(new AlterDefaultConstraintExpression
{
TableName = expression.TableName,
ColumnName = expression.ColumnName,
DefaultValue = null
});
}
public override string Generate(DeleteIndexExpression expression)
{
var quotedSchema = Quoter.QuoteSchemaName(expression.Index.SchemaName);
var quotedIndex = Quoter.QuoteIndexName(expression.Index.Name);
var indexName = string.IsNullOrEmpty(quotedSchema) ? quotedIndex : $"{quotedSchema}.{quotedIndex}";
return string.Format("DROP INDEX {0}", indexName);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class PublicKeyTests
{
private static PublicKey GetTestRsaKey()
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
return cert.PublicKey;
}
}
private static PublicKey GetTestDsaKey()
{
using (var cert = new X509Certificate2(TestData.DssCer))
{
return cert.PublicKey;
}
}
private static PublicKey GetTestECDsaKey()
{
using (var cert = new X509Certificate2(TestData.ECDsa256Certificate))
{
return cert.PublicKey;
}
}
/// <summary>
/// First parameter is the cert, the second is a hash of "Hello"
/// </summary>
public static IEnumerable<object[]> BrainpoolCurves
{
get
{
#if uap
yield break;
#else
yield return new object[] {
TestData.ECDsabrainpoolP160r1_CertificatePemBytes,
"9145C79DD4DF758EB377D13B0DB81F83CE1A63A4099DDC32FE228B06EB1F306423ED61B6B4AF4691".HexToByteArray() };
yield return new object[] {
TestData.ECDsabrainpoolP160r1_ExplicitCertificatePemBytes,
"6D74F1C9BCBBA5A25F67E670B3DABDB36C24E8FAC3266847EB2EE7E3239208ADC696BB421AB380B4".HexToByteArray() };
#endif
}
}
[Fact]
public static void TestOid_RSA()
{
PublicKey pk = GetTestRsaKey();
Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value);
}
[Fact]
public static void TestOid_DSA()
{
PublicKey pk = GetTestDsaKey();
Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value);
}
[Fact]
public static void TestOid_ECDSA()
{
PublicKey pk = GetTestECDsaKey();
Assert.Equal("1.2.840.10045.2.1", pk.Oid.Value);
}
[Fact]
public static void TestPublicKey_Key_RSA()
{
PublicKey pk = GetTestRsaKey();
using (AsymmetricAlgorithm alg = pk.Key)
{
Assert.NotNull(alg);
Assert.Same(alg, pk.Key);
Assert.Equal(2048, alg.KeySize);
Assert.IsAssignableFrom(typeof(RSA), alg);
VerifyKey_RSA( /* cert */ null, (RSA)alg);
}
}
[Fact]
public static void TestPublicKey_Key_DSA()
{
PublicKey pk = GetTestDsaKey();
using (AsymmetricAlgorithm alg = pk.Key)
{
Assert.NotNull(alg);
Assert.Same(alg, pk.Key);
Assert.Equal(1024, alg.KeySize);
Assert.IsAssignableFrom(typeof(DSA), alg);
VerifyKey_DSA((DSA)alg);
}
}
[Fact]
public static void TestPublicKey_Key_ECDSA()
{
PublicKey pk = GetTestECDsaKey();
Assert.Throws<NotSupportedException>(() => pk.Key);
}
private static void VerifyKey_DSA(DSA dsa)
{
DSAParameters dsaParameters = dsa.ExportParameters(false);
byte[] expected_g = (
"859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481584413" +
"E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310FEFD518" +
"AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0DAFDA0" +
"79BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D05431D").HexToByteArray();
byte[] expected_p = (
"871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180511D0DCEB8B97928" +
"5708C800FC10CB15337A4AC1A48ED31394072015A7A6B525986B49E5E1139737" +
"A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA41E8F0763AA613E29" +
"C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DFB33C44D2F2DBE819").HexToByteArray();
byte[] expected_q = "E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D".HexToByteArray();
byte[] expected_y = (
"089A43F439B924BEF3529D8D6206D1FCA56A55CAF52B41D6CE371EBF07BDA132" +
"C8EADC040007FCF4DA06C1F30504EBD8A77D301F5A4702F01F0D2A0707AC1DA3" +
"8DD3251883286E12456234DA62EDA0DF5FE2FA07CD5B16F3638BECCA7786312D" +
"A7D3594A4BB14E353884DA0E9AECB86E3C9BDB66FCA78EA85E1CC3F2F8BF0963").HexToByteArray();
Assert.Equal(expected_g, dsaParameters.G);
Assert.Equal(expected_p, dsaParameters.P);
Assert.Equal(expected_q, dsaParameters.Q);
Assert.Equal(expected_y, dsaParameters.Y);
}
[Fact]
public static void TestEncodedKeyValue_RSA()
{
byte[] expectedPublicKey = (
"3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" +
"407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" +
"137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" +
"b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" +
"109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" +
"2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" +
"2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" +
"84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" +
"0b950005b14f6571c50203010001").HexToByteArray();
PublicKey pk = GetTestRsaKey();
Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData);
}
[Fact]
public static void TestEncodedKeyValue_DSA()
{
byte[] expectedPublicKey = (
"028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" +
"bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" +
"ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" +
"86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" +
"bf0963").HexToByteArray();
PublicKey pk = GetTestDsaKey();
Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData);
}
[Fact]
public static void TestEncodedKeyValue_ECDSA()
{
// Uncompressed key (04), then the X coord, then the Y coord.
string expectedPublicKeyHex =
"04" +
"448D98EE08AEBA0D8B40F3C6DBD500E8B69F07C70C661771655228EA5A178A91" +
"0EF5CB1759F6F2E062021D4F973F5BB62031BE87AE915CFF121586809E3219AF";
PublicKey pk = GetTestECDsaKey();
Assert.Equal(expectedPublicKeyHex, pk.EncodedKeyValue.RawData.ByteArrayToHex());
}
[Fact]
public static void TestEncodedParameters_RSA()
{
PublicKey pk = GetTestRsaKey();
// RSA has no key parameters, so the answer is always
// DER:NULL (type 0x05, length 0x00)
Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData);
}
[Fact]
public static void TestEncodedParameters_DSA()
{
byte[] expectedParameters = (
"3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" +
"511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" +
"986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" +
"1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" +
"B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" +
"818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" +
"584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" +
"EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" +
"DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" +
"05431D").HexToByteArray();
PublicKey pk = GetTestDsaKey();
Assert.Equal(expectedParameters, pk.EncodedParameters.RawData);
}
[Fact]
public static void TestEncodedParameters_ECDSA()
{
// OID: 1.2.840.10045.3.1.7
string expectedParametersHex = "06082A8648CE3D030107";
PublicKey pk = GetTestECDsaKey();
Assert.Equal(expectedParametersHex, pk.EncodedParameters.RawData.ByteArrayToHex());
}
[Fact]
public static void TestKey_RSA()
{
using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate))
{
RSA rsa = cert.GetRSAPublicKey();
VerifyKey_RSA(cert, rsa);
}
}
private static void VerifyKey_RSA(X509Certificate2 cert, RSA rsa)
{
RSAParameters rsaParameters = rsa.ExportParameters(false);
byte[] expectedModulus = (
"E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" +
"51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" +
"EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" +
"C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" +
"1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" +
"94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" +
"C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" +
"E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray();
byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 };
byte[] originalModulus = rsaParameters.Modulus;
byte[] originalExponent = rsaParameters.Exponent;
if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) ||
!expectedExponent.SequenceEqual(rsaParameters.Exponent))
{
Console.WriteLine("Modulus or Exponent not equal");
rsaParameters = rsa.ExportParameters(false);
if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) ||
!expectedExponent.SequenceEqual(rsaParameters.Exponent))
{
Console.WriteLine("Second call to ExportParameters did not produce valid data either");
}
if (cert != null)
{
rsa = cert.GetRSAPublicKey();
rsaParameters = rsa.ExportParameters(false);
if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) ||
!expectedExponent.SequenceEqual(rsaParameters.Exponent))
{
Console.WriteLine("New key handle ExportParameters was not successful either");
}
}
}
Assert.Equal(expectedModulus, originalModulus);
Assert.Equal(expectedExponent, originalExponent);
}
[Fact]
public static void TestKey_RSA384_ValidatesSignature()
{
byte[] signature =
{
0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C,
0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44,
0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68,
0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06,
0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4,
0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C,
};
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes))
using (RSA rsa = cert.GetRSAPublicKey())
{
Assert.True(rsa.VerifyData(helloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
}
}
[Theory, MemberData(nameof(BrainpoolCurves))]
public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed)
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
try
{
using (var cert = new X509Certificate2(curveData))
{
using (ECDsa ec = cert.GetECDsaPublicKey())
{
Assert.Equal(160, ec.KeySize);
// The public key should be unable to sign.
Assert.ThrowsAny<CryptographicException>(() => ec.SignData(helloBytes, HashAlgorithmName.SHA256));
}
}
}
catch (CryptographicException)
{
// Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail.
Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10);
Assert.False(PlatformDetection.IsUbuntu1604);
Assert.False(PlatformDetection.IsUbuntu1610);
}
}
[Fact]
public static void TestECDsaPublicKey()
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
Assert.Equal(384, publicKey.KeySize);
// The public key should be unable to sign.
Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256));
}
}
[Fact]
public static void TestECDsaPublicKey_ValidatesSignature()
{
// This signature was produced as the output of ECDsaCng.SignData with the same key
// on .NET 4.6. Ensure it is verified here as a data compatibility test.
//
// Note that since ECDSA signatures contain randomness as an input, this value is unlikely
// to be reproduced by another equivalent program.
byte[] existingSignature =
{
// r:
0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27,
0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6,
0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3,
0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11,
0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5,
0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F,
// s:
0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E,
0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34,
0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3,
0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB,
0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93,
0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96,
};
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
using (var cert = new X509Certificate2(TestData.ECDsa384Certificate))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
Assert.Equal(384, publicKey.KeySize);
bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256);
Assert.True(isSignatureValid, "isSignatureValid");
}
}
[Theory, MemberData(nameof(BrainpoolCurves))]
public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature)
{
byte[] helloBytes = Encoding.ASCII.GetBytes("Hello");
try
{
using (var cert = new X509Certificate2(curveData))
{
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
Assert.Equal(160, publicKey.KeySize);
// It is an Elliptic Curve Cryptography public key.
Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);
bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256);
Assert.True(isSignatureValid, "isSignatureValid");
unchecked
{
--existingSignature[existingSignature.Length - 1];
}
isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256);
Assert.False(isSignatureValid, "isSignatureValidNeg");
}
}
}
catch (CryptographicException)
{
// Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail.
Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10);
Assert.False(PlatformDetection.IsUbuntu1604);
Assert.False(PlatformDetection.IsUbuntu1610);
}
}
[Fact]
public static void TestECDsaPublicKey_NonSignatureCert()
{
using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement))
using (ECDsa publicKey = cert.GetECDsaPublicKey())
{
// It is an Elliptic Curve Cryptography public key.
Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);
// But, due to KeyUsage, it shouldn't be used for ECDSA.
Assert.Null(publicKey);
}
}
[Fact]
public static void TestECDsa224PublicKey()
{
using (var cert = new X509Certificate2(TestData.ECDsa224Certificate))
{
// It is an Elliptic Curve Cryptography public key.
Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);
ECDsa ecdsa;
try
{
ecdsa = cert.GetECDsaPublicKey();
}
catch (CryptographicException)
{
// Windows 7, Windows 8, CentOS.
return;
}
// Other Unix
using (ecdsa)
{
byte[] data = ByteUtils.AsciiBytes("Hello");
byte[] signature = (
// r
"8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" +
// s
"5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray();
Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1));
}
}
}
#if netcoreapp
[Fact]
public static void TestDSAPublicKey()
{
using (var cert = new X509Certificate2(TestData.DssCer))
using (DSA pubKey = cert.GetDSAPublicKey())
{
Assert.NotNull(pubKey);
VerifyKey_DSA(pubKey);
}
}
[Fact]
public static void TestDSAPublicKey_VerifiesSignature()
{
byte[] data = { 1, 2, 3, 4, 5 };
byte[] wrongData = { 0xFE, 2, 3, 4, 5 };
byte[] signature =
"B06E26CFC939F25B864F52ABD3288222363A164259B0027FFC95DBC88F9204F7A51A901F3005C9F7".HexToByteArray();
using (var cert = new X509Certificate2(TestData.Dsa1024Cert))
using (DSA pubKey = cert.GetDSAPublicKey())
{
Assert.True(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies signature");
Assert.False(pubKey.VerifyData(wrongData, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered data");
signature[0] ^= 0xFF;
Assert.False(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered signature");
}
}
[Fact]
public static void TestDSAPublicKey_RSACert()
{
using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes))
using (DSA pubKey = cert.GetDSAPublicKey())
{
Assert.Null(pubKey);
}
}
[Fact]
public static void TestDSAPublicKey_ECDSACert()
{
using (var cert = new X509Certificate2(TestData.ECDsa256Certificate))
using (DSA pubKey = cert.GetDSAPublicKey())
{
Assert.Null(pubKey);
}
}
#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void TestKey_ECDsaCng256()
{
TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void TestKey_ECDsaCng384()
{
TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void TestKey_ECDsaCng521()
{
TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void TestKey_BrainpoolP160r1()
{
if (PlatformDetection.WindowsVersion >= 10)
{
TestKey_ECDsaCng(TestData.ECDsabrainpoolP160r1_CertificatePemBytes, TestData.ECDsabrainpoolP160r1_PublicKey);
}
}
private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected)
{
#if !uap
using (X509Certificate2 cert = new X509Certificate2(certBytes))
{
ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey());
CngKey k = e.Key;
byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob);
using (BinaryReader br = new BinaryReader(new MemoryStream(blob)))
{
int magic = br.ReadInt32();
int cbKey = br.ReadInt32();
Assert.Equal(expected.QX.Length, cbKey);
byte[] qx = br.ReadBytes(cbKey);
byte[] qy = br.ReadBytes(cbKey);
Assert.Equal<byte>(expected.QX, qx);
Assert.Equal<byte>(expected.QY, qy);
}
}
#endif // !uap
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace System.Net.Security
{
internal class SslState
{
private static int s_uniqueNameInteger = 123;
private static AsyncProtocolCallback s_partialFrameCallback = new AsyncProtocolCallback(PartialFrameCallback);
private static AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback);
private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private RemoteCertValidationCallback _certValidationDelegate;
private LocalCertSelectionCallback _certSelectionDelegate;
private Stream _innerStream;
// TODO (Issue #3114): Implement using TPL instead of APM.
private StreamAsyncHelper _innerStreamAPM;
private _SslStream _secureStream;
private FixedSizeReader _reader;
private int _nestedAuth;
private SecureChannel _context;
private bool _handshakeCompleted;
private bool _certValidationFailed;
private Interop.SecurityStatus _securityStatus;
private Exception _exception;
private enum CachedSessionStatus : byte
{
Unknown = 0,
IsNotCached = 1,
IsCached = 2,
Renegotiated = 3
}
private CachedSessionStatus _CachedSession;
// This block is used by rehandshake code to buffer data decryptred with the old key.
private byte[] _queuedReadData;
private int _queuedReadCount;
private bool _pendingReHandshake;
private const int MaxQueuedReadBytes = 1024 * 128;
//
// This block is used to rule the >>re-handshakes<< that are concurent with read/write io requests.
//
private const int LockNone = 0;
private const int LockWrite = 1;
private const int LockHandshake = 2;
private const int LockPendingWrite = 3;
private const int LockRead = 4;
private const int LockPendingRead = 6;
private int _lockWriteState;
private object _queuedWriteStateRequest;
private int _lockReadState;
private object _queuedReadStateRequest;
private readonly EncryptionPolicy _encryptionPolicy;
//
// The public Client and Server classes enforce the parameters rules before
// calling into this .ctor.
//
internal SslState(Stream innerStream, RemoteCertValidationCallback certValidationCallback, LocalCertSelectionCallback certSelectionCallback, EncryptionPolicy encryptionPolicy)
{
_innerStream = innerStream;
_innerStreamAPM = new StreamAsyncHelper(innerStream);
_reader = new FixedSizeReader(innerStream);
_certValidationDelegate = certValidationCallback;
_certSelectionDelegate = certSelectionCallback;
_encryptionPolicy = encryptionPolicy;
}
//
//
//
internal void ValidateCreateContext(bool isServer, string targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertRevocationStatus)
{
ValidateCreateContext(isServer, targetHost, enabledSslProtocols, serverCertificate, clientCertificates, remoteCertRequired,
checkCertRevocationStatus, !isServer);
}
internal void ValidateCreateContext(bool isServer, string targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertRevocationStatus, bool checkCertName)
{
//
// We don't support SSL alerts right now, hence any exception is fatal and cannot be retried.
//
if (_exception != null)
{
throw _exception;
}
if (Context != null && Context.IsValidContext)
{
throw new InvalidOperationException(SR.net_auth_reauth);
}
if (Context != null && IsServer != isServer)
{
throw new InvalidOperationException(SR.net_auth_client_server);
}
if (targetHost == null)
{
throw new ArgumentNullException("targetHost");
}
if (isServer)
{
enabledSslProtocols &= (SslProtocols)Interop.SChannel.ServerProtocolMask;
if (serverCertificate == null)
{
throw new ArgumentNullException("serverCertificate");
}
}
else
{
enabledSslProtocols &= (SslProtocols)Interop.SChannel.ClientProtocolMask;
}
if ((int)enabledSslProtocols == 0)
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "SslProtocolType"), "sslProtocolType");
}
if (clientCertificates == null)
{
clientCertificates = new X509CertificateCollection();
}
if (targetHost.Length == 0)
{
targetHost = "?" + Interlocked.Increment(ref s_uniqueNameInteger).ToString(NumberFormatInfo.InvariantInfo);
}
_exception = null;
try
{
_context = new SecureChannel(targetHost, isServer, (int)enabledSslProtocols, serverCertificate, clientCertificates, remoteCertRequired,
checkCertName, checkCertRevocationStatus, _encryptionPolicy, _certSelectionDelegate);
}
catch (Win32Exception e)
{
throw new AuthenticationException(SR.net_auth_SSPI, e);
}
}
internal bool IsAuthenticated
{
get
{
return _context != null && _context.IsValidContext && _exception == null && HandshakeCompleted;
}
}
internal bool IsMutuallyAuthenticated
{
get
{
return
IsAuthenticated &&
(Context.IsServer ? Context.LocalServerCertificate : Context.LocalClientCertificate) != null &&
Context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/
}
}
internal bool RemoteCertRequired
{
get
{
return Context == null || Context.RemoteCertRequired;
}
}
internal bool IsServer
{
get
{
return Context != null && Context.IsServer;
}
}
//
// SSL related properties
//
internal void SetCertValidationDelegate(RemoteCertValidationCallback certValidationCallback)
{
_certValidationDelegate = certValidationCallback;
}
//
// This will return selected local cert for both client/server streams
//
internal X509Certificate LocalCertificate
{
get
{
CheckThrow(true);
return InternalLocalCertificate;
}
}
private X509Certificate InternalLocalCertificate
{
get
{
return Context.IsServer ? Context.LocalServerCertificate : Context.LocalClientCertificate;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
return (Context == null) ? null : Context.GetChannelBinding(kind);
}
internal bool CheckCertRevocationStatus
{
get
{
return Context != null && Context.CheckCertRevocationStatus;
}
}
internal Interop.SecurityStatus LastSecurityStatus
{
get { return _securityStatus; }
}
internal bool IsCertValidationFailed
{
get
{
return _certValidationFailed;
}
}
internal bool DataAvailable
{
get
{
return IsAuthenticated && (SecureStream.DataAvailable || _queuedReadCount != 0);
}
}
internal CipherAlgorithmType CipherAlgorithm
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return CipherAlgorithmType.None;
}
return (CipherAlgorithmType)info.DataCipherAlg;
}
}
internal int CipherStrength
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return 0;
}
return info.DataKeySize;
}
}
internal HashAlgorithmType HashAlgorithm
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return (HashAlgorithmType)0;
}
return (HashAlgorithmType)info.DataHashAlg;
}
}
internal int HashStrength
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return 0;
}
return info.DataHashKeySize;
}
}
internal ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return (ExchangeAlgorithmType)0;
}
return (ExchangeAlgorithmType)info.KeyExchangeAlg;
}
}
internal int KeyExchangeStrength
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return 0;
}
return info.KeyExchKeySize;
}
}
internal SslProtocols SslProtocol
{
get
{
CheckThrow(true);
SslConnectionInfo info = Context.ConnectionInfo;
if (info == null)
{
return SslProtocols.None;
}
SslProtocols proto = (SslProtocols)info.Protocol;
SslProtocols ret = SslProtocols.None;
// Restore client/server bits so the result maps exactly on published constants.
if ((proto & SslProtocols.Ssl2) != 0)
{
ret |= SslProtocols.Ssl2;
}
if ((proto & SslProtocols.Ssl3) != 0)
{
ret |= SslProtocols.Ssl3;
}
if ((proto & SslProtocols.Tls) != 0)
{
ret |= SslProtocols.Tls;
}
if ((proto & SslProtocols.Tls11) != 0)
{
ret |= SslProtocols.Tls11;
}
if ((proto & SslProtocols.Tls12) != 0)
{
ret |= SslProtocols.Tls12;
}
return ret;
}
}
internal Stream InnerStream
{
get
{
return _innerStream;
}
}
internal StreamAsyncHelper InnerStreamAPM
{
get
{
return _innerStreamAPM;
}
}
internal _SslStream SecureStream
{
get
{
CheckThrow(true);
if (_secureStream == null)
{
Interlocked.CompareExchange<_SslStream>(ref _secureStream, new _SslStream(this), null);
}
return _secureStream;
}
}
internal int HeaderSize
{
get
{
return Context.HeaderSize;
}
}
internal int MaxDataSize
{
get
{
return Context.MaxDataSize;
}
}
private Exception SetException(Exception e)
{
if (_exception == null)
{
_exception = e;
}
if (_exception != null && Context != null)
{
Context.Close();
}
return _exception;
}
private bool HandshakeCompleted
{
get
{
return _handshakeCompleted;
}
}
private SecureChannel Context
{
get
{
return _context;
}
}
internal void CheckThrow(bool authSucessCheck)
{
if (_exception != null)
{
throw _exception;
}
if (authSucessCheck && !IsAuthenticated)
{
throw new InvalidOperationException(SR.net_auth_noauth);
}
}
internal void Flush()
{
InnerStream.Flush();
}
//
// This is to not depend on GC&SafeHandle class if the context is not needed anymore.
//
internal void Close()
{
_exception = new ObjectDisposedException("SslStream");
if (Context != null)
{
Context.Close();
}
}
internal Interop.SecurityStatus EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer, out int outSize)
{
CheckThrow(true);
return Context.Encrypt(buffer, offset, count, ref outBuffer, out outSize);
}
internal Interop.SecurityStatus DecryptData(byte[] buffer, ref int offset, ref int count)
{
CheckThrow(true);
return PrivateDecryptData(buffer, ref offset, ref count);
}
private Interop.SecurityStatus PrivateDecryptData(byte[] buffer, ref int offset, ref int count)
{
return Context.Decrypt(buffer, ref offset, ref count);
}
//
// Called by re-handshake if found data decrypted with the old key
//
private Exception EnqueueOldKeyDecryptedData(byte[] buffer, int offset, int count)
{
lock (this)
{
if (_queuedReadCount + count > MaxQueuedReadBytes)
{
return new IOException(SR.Format(SR.net_auth_ignored_reauth, MaxQueuedReadBytes.ToString(NumberFormatInfo.CurrentInfo)));
}
if (count != 0)
{
// This is inefficient yet simple and that should be a rare case of receiving data encrypted with "old" key.
_queuedReadData = EnsureBufferSize(_queuedReadData, _queuedReadCount, _queuedReadCount + count);
Buffer.BlockCopy(buffer, offset, _queuedReadData, _queuedReadCount, count);
_queuedReadCount += count;
FinishHandshakeRead(LockHandshake);
}
}
return null;
}
//
// When re-handshaking the "old" key decrypted data are queued until the handshake is done.
// When stream calls for decryption we will feed it queued data left from "old" encryption key.
//
// Must be called under the lock in case concurent handshake is going.
//
internal int CheckOldKeyDecryptedData(byte[] buffer, int offset, int count)
{
CheckThrow(true);
if (_queuedReadData != null)
{
// This is inefficient yet simple and should be a REALLY rare case.
int toCopy = Math.Min(_queuedReadCount, count);
Buffer.BlockCopy(_queuedReadData, 0, buffer, offset, toCopy);
_queuedReadCount -= toCopy;
if (_queuedReadCount == 0)
{
_queuedReadData = null;
}
else
{
Buffer.BlockCopy(_queuedReadData, toCopy, _queuedReadData, 0, _queuedReadCount);
}
return toCopy;
}
return -1;
}
//
// This method assumes that a SSPI context is already in a good shape.
// For example it is either a fresh context or already authenticated context that needs renegotiation.
//
internal void ProcessAuthentication(LazyAsyncResult lazyResult)
{
if (Interlocked.Exchange(ref _nestedAuth, 1) == 1)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate"));
}
try
{
CheckThrow(false);
AsyncProtocolRequest asyncRequest = null;
if (lazyResult != null)
{
asyncRequest = new AsyncProtocolRequest(lazyResult);
asyncRequest.Buffer = null;
#if DEBUG
lazyResult._DebugAsyncChain = asyncRequest;
#endif
}
// A trick to discover and avoid cached sessions.
_CachedSession = CachedSessionStatus.Unknown;
ForceAuthentication(Context.IsServer, null, asyncRequest);
// Not aync so the connection is completed at this point.
if (lazyResult == null && Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_selected_cipher_suite,
"ProcessAuthentication",
SslProtocol,
CipherAlgorithm,
CipherStrength,
HashAlgorithm,
HashStrength,
KeyExchangeAlgorithm,
KeyExchangeStrength));
}
}
finally
{
if (lazyResult == null || _exception != null)
{
_nestedAuth = 0;
}
}
}
//
// This is used to reply on re-handshake when received SEC_I_RENEGOTIATE on Read().
//
internal void ReplyOnReAuthentication(byte[] buffer)
{
lock (this)
{
// Note we are already inside the read, so checking for already going concurent handshake.
_lockReadState = LockHandshake;
if (_pendingReHandshake)
{
// A concurent handshake is pending, resume.
FinishRead(buffer);
return;
}
}
// Start rehandshake from here.
// Forcing async mode. The caller will queue another Read as soon as we return using its preferred
// calling convention, which will be woken up when the handshake completes. The callback is just
// to capture any SocketErrors that happen during the handshake so they can be surfaced from the Read.
AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(new LazyAsyncResult(this, null, new AsyncCallback(RehandshakeCompleteCallback)));
// Buffer contains a result from DecryptMessage that will be passed to ISC/ASC
asyncRequest.Buffer = buffer;
ForceAuthentication(false, buffer, asyncRequest);
}
//
// This method attempts to start authentication.
// Incoming buffer is either null or is the result of "renegotiate" decrypted message
// If write is in progress the method will either wait or be put on hold
//
private void ForceAuthentication(bool receiveFirst, byte[] buffer, AsyncProtocolRequest asyncRequest)
{
if (CheckEnqueueHandshake(buffer, asyncRequest))
{
// Async handshake is enqueued and will resume later.
return;
}
// Either Sync handshake is ready to go or async handshake won the race over write.
// This will tell that we don't know the framing yet (what SSL version is)
_Framing = Framing.Unknown;
try
{
if (receiveFirst)
{
// Listen for a client blob.
StartReceiveBlob(buffer, asyncRequest);
}
else
{
// We start with the first blob.
StartSendBlob(buffer, (buffer == null ? 0 : buffer.Length), asyncRequest);
}
}
catch (Exception e)
{
// Failed auth, reset the framing if any.
_Framing = Framing.Unknown;
_handshakeCompleted = false;
if (SetException(e) == e)
{
throw;
}
else
{
throw _exception;
}
}
finally
{
if (_exception != null)
{
// This a failed handshake. Release waiting IO if any.
FinishHandshake(null, null);
}
}
}
internal void EndProcessAuthentication(IAsyncResult result)
{
if (result == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = result as LazyAsyncResult;
if (lazyResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
}
if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
}
InternalEndProcessAuthentication(lazyResult);
// Connection is completed at this point.
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_selected_cipher_suite,
"EndProcessAuthentication",
SslProtocol,
CipherAlgorithm,
CipherStrength,
HashAlgorithm,
HashStrength,
KeyExchangeAlgorithm,
KeyExchangeStrength));
}
}
//
//
//
internal void InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
{
// No "artificial" timeouts implemented so far, InnerStream controls that.
lazyResult.InternalWaitForCompletion();
Exception e = lazyResult.Result as Exception;
if (e != null)
{
// Failed auth, reset the framing if any.
_Framing = Framing.Unknown;
_handshakeCompleted = false;
throw SetException(e);
}
}
//
// Client side starts here, but server also loops through this method.
//
private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest)
{
ProtocolToken message = Context.NextMessage(incoming, 0, count);
_securityStatus = message.Status;
if (message.Size != 0)
{
if (Context.IsServer && _CachedSession == CachedSessionStatus.Unknown)
{
//
//[Schannel] If the first call to ASC returns a token less than 200 bytes,
// then it's a reconnect (a handshake based on a cache entry).
//
_CachedSession = message.Size < 200 ? CachedSessionStatus.IsCached : CachedSessionStatus.IsNotCached;
}
if (_Framing == Framing.Unified)
{
_Framing = DetectFraming(message.Payload, message.Payload.Length);
}
if (asyncRequest == null)
{
InnerStream.Write(message.Payload, 0, message.Size);
}
else
{
asyncRequest.AsyncState = message;
IAsyncResult ar = InnerStreamAPM.BeginWrite(message.Payload, 0, message.Size, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
#if DEBUG
asyncRequest._DebugAsyncChain = ar;
#endif
return;
}
InnerStreamAPM.EndWrite(ar);
}
}
CheckCompletionBeforeNextReceive(message, asyncRequest);
}
//
// This will check and logically complete / fail the auth handshake.
//
private void CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
{
if (message.Failed)
{
StartSendAuthResetSignal(null, asyncRequest, new AuthenticationException(SR.net_auth_SSPI, message.GetException()));
return;
}
else if (message.Done && !_pendingReHandshake)
{
if (!CompleteHandshake())
{
StartSendAuthResetSignal(null, asyncRequest, new AuthenticationException(SR.net_ssl_io_cert_validation, null));
return;
}
// Release waiting IO if any. Presumably it should not throw.
// Otheriwse application may get not expected type of the exception.
FinishHandshake(null, asyncRequest);
return;
}
StartReceiveBlob(message.Payload, asyncRequest);
}
//
// Server side starts here, but client also loops through this method.
//
private void StartReceiveBlob(byte[] buffer, AsyncProtocolRequest asyncRequest)
{
if (_pendingReHandshake)
{
if (CheckEnqueueHandshakeRead(ref buffer, asyncRequest))
{
return;
}
if (!_pendingReHandshake)
{
// Renegotiate: proceed to the next step.
ProcessReceivedBlob(buffer, buffer.Length, asyncRequest);
return;
}
}
//This is first server read.
buffer = EnsureBufferSize(buffer, 0, SecureChannel.ReadHeaderSize);
int readBytes = 0;
if (asyncRequest == null)
{
readBytes = _reader.ReadPacket(buffer, 0, SecureChannel.ReadHeaderSize);
}
else
{
asyncRequest.SetNextRequest(buffer, 0, SecureChannel.ReadHeaderSize, s_partialFrameCallback);
_reader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return;
}
readBytes = asyncRequest.Result;
}
StartReadFrame(buffer, readBytes, asyncRequest);
}
//
private void StartReadFrame(byte[] buffer, int readBytes, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// EOF received
throw new IOException(SR.net_auth_eof);
}
if (_Framing == Framing.Unknown)
{
_Framing = DetectFraming(buffer, readBytes);
}
int restBytes = GetRemainingFrameSize(buffer, readBytes);
if (restBytes < 0)
{
throw new IOException(SR.net_ssl_io_frame);
}
if (restBytes == 0)
{
// EOF received
throw new AuthenticationException(SR.net_auth_eof, null);
}
buffer = EnsureBufferSize(buffer, readBytes, readBytes + restBytes);
if (asyncRequest == null)
{
restBytes = _reader.ReadPacket(buffer, readBytes, restBytes);
}
else
{
asyncRequest.SetNextRequest(buffer, readBytes, restBytes, s_readFrameCallback);
_reader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return;
}
restBytes = asyncRequest.Result;
if (restBytes == 0)
{
//EOF received: fail.
readBytes = 0;
}
}
ProcessReceivedBlob(buffer, readBytes + restBytes, asyncRequest);
}
private void ProcessReceivedBlob(byte[] buffer, int count, AsyncProtocolRequest asyncRequest)
{
if (count == 0)
{
// EOF received.
throw new AuthenticationException(SR.net_auth_eof, null);
}
if (_pendingReHandshake)
{
int offset = 0;
Interop.SecurityStatus status = PrivateDecryptData(buffer, ref offset, ref count);
if (status == Interop.SecurityStatus.OK)
{
Exception e = EnqueueOldKeyDecryptedData(buffer, offset, count);
if (e != null)
{
StartSendAuthResetSignal(null, asyncRequest, e);
return;
}
_Framing = Framing.Unknown;
StartReceiveBlob(buffer, asyncRequest);
return;
}
else if (status != Interop.SecurityStatus.Renegotiate)
{
// Fail re-handshake.
ProtocolToken message = new ProtocolToken(null, status);
StartSendAuthResetSignal(null, asyncRequest, new AuthenticationException(SR.net_auth_SSPI, message.GetException()));
return;
}
// We expect only handshake messages from now.
_pendingReHandshake = false;
if (offset != 0)
{
Buffer.BlockCopy(buffer, offset, buffer, 0, count);
}
}
StartSendBlob(buffer, count, asyncRequest);
}
//
// This is to reset auth state on remote side.
// If this write succeeds we will allow auth retrying.
//
private void StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
{
if (message == null || message.Size == 0)
{
//
// We don't have an alert to send so cannot retry and fail prematurely.
//
throw exception;
}
if (asyncRequest == null)
{
InnerStream.Write(message.Payload, 0, message.Size);
}
else
{
asyncRequest.AsyncState = exception;
IAsyncResult ar = InnerStreamAPM.BeginWrite(message.Payload, 0, message.Size, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
InnerStreamAPM.EndWrite(ar);
}
throw exception;
}
// - Loads the channel parameters
// - Optionally verifies the Remote Certificate
// - Sets HandshakeCompleted flag
// - Sets the guarding event if other thread is waiting for
// handshake completino
//
// - Returns false if failed to verify the Remote Cert
//
private bool CompleteHandshake()
{
GlobalLog.Enter("CompleteHandshake");
Context.ProcessHandshakeSuccess();
if (!Context.VerifyRemoteCertificate(_certValidationDelegate))
{
_handshakeCompleted = false;
_certValidationFailed = true;
GlobalLog.Leave("CompleteHandshake", false);
return false;
}
_certValidationFailed = false;
_handshakeCompleted = true;
GlobalLog.Leave("CompleteHandshake", true);
return true;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
AsyncProtocolRequest asyncRequest;
SslState sslState;
#if DEBUG
try
{
#endif
asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
sslState = (SslState)asyncRequest.AsyncObject;
#if DEBUG
}
catch (Exception exception)
{
if (!ExceptionCheck.IsFatal(exception))
{
GlobalLog.Assert("SslState::WriteCallback", "Exception while decoding context. type:" + exception.GetType().ToString() + " message:" + exception.Message);
}
throw;
}
#endif
// Async completion.
try
{
sslState.InnerStreamAPM.EndWrite(transportResult);
// Special case for an error notification.
object asyncState = asyncRequest.AsyncState;
Exception exception = asyncState as Exception;
if (exception != null)
{
throw exception;
}
sslState.CheckCompletionBeforeNextReceive((ProtocolToken)asyncState, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
sslState.FinishHandshake(e, asyncRequest);
}
}
private static void PartialFrameCallback(AsyncProtocolRequest asyncRequest)
{
GlobalLog.Print("SslState::PartialFrameCallback()");
// Async ONLY completion.
SslState sslState = (SslState)asyncRequest.AsyncObject;
try
{
sslState.StartReadFrame(asyncRequest.Buffer, asyncRequest.Result, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
sslState.FinishHandshake(e, asyncRequest);
}
}
//
//
private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest)
{
GlobalLog.Print("SslState::ReadFrameCallback()");
// Async ONLY completion.
SslState sslState = (SslState)asyncRequest.AsyncObject;
try
{
if (asyncRequest.Result == 0)
{
//EOF received: will fail.
asyncRequest.Offset = 0;
}
sslState.ProcessReceivedBlob(asyncRequest.Buffer, asyncRequest.Offset + asyncRequest.Result, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
sslState.FinishHandshake(e, asyncRequest);
}
}
private bool CheckEnqueueHandshakeRead(ref byte[] buffer, AsyncProtocolRequest request)
{
LazyAsyncResult lazyResult = null;
lock (this)
{
if (_lockReadState == LockPendingRead)
{
return false;
}
int lockState = Interlocked.Exchange(ref _lockReadState, LockHandshake);
if (lockState != LockRead)
{
return false;
}
if (request != null)
{
_queuedReadStateRequest = request;
return true;
}
lazyResult = new LazyAsyncResult(null, null, /*must be */ null);
_queuedReadStateRequest = lazyResult;
}
// Need to exit from lock before waiting.
lazyResult.InternalWaitForCompletion();
buffer = (byte[])lazyResult.Result;
return false;
}
private void FinishHandshakeRead(int newState)
{
lock (this)
{
// Lock is redundant here. Included for clarity.
int lockState = Interlocked.Exchange(ref _lockReadState, newState);
if (lockState != LockPendingRead)
{
return;
}
_lockReadState = LockRead;
object obj = _queuedReadStateRequest;
if (obj == null)
{
// Other thread did not get under the lock yet.
return;
}
_queuedReadStateRequest = null;
if (obj is LazyAsyncResult)
{
((LazyAsyncResult)obj).InvokeCallback();
}
else
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CompleteRequestWaitCallback), obj);
}
}
}
// Returns:
// -1 - proceed
// 0 - queued
// X - some bytes are ready, no need for IO
internal int CheckEnqueueRead(byte[] buffer, int offset, int count, AsyncProtocolRequest request)
{
int lockState = Interlocked.CompareExchange(ref _lockReadState, LockRead, LockNone);
if (lockState != LockHandshake)
{
// Proceed, no concurent handshake is ongoing so no need for a lock.
return CheckOldKeyDecryptedData(buffer, offset, count);
}
LazyAsyncResult lazyResult = null;
lock (this)
{
int result = CheckOldKeyDecryptedData(buffer, offset, count);
if (result != -1)
{
return result;
}
// Check again under lock.
if (_lockReadState != LockHandshake)
{
// The other thread has finished before we grabbed the lock.
_lockReadState = LockRead;
return -1;
}
_lockReadState = LockPendingRead;
if (request != null)
{
// Request queued.
_queuedReadStateRequest = request;
return 0;
}
lazyResult = new LazyAsyncResult(null, null, /*must be */ null);
_queuedReadStateRequest = lazyResult;
}
// Need to exit from lock before waiting.
lazyResult.InternalWaitForCompletion();
lock (this)
{
return CheckOldKeyDecryptedData(buffer, offset, count);
}
}
internal void FinishRead(byte[] renegotiateBuffer)
{
int lockState = Interlocked.CompareExchange(ref _lockReadState, LockNone, LockRead);
if (lockState != LockHandshake)
{
return;
}
lock (this)
{
LazyAsyncResult ar = _queuedReadStateRequest as LazyAsyncResult;
if (ar != null)
{
_queuedReadStateRequest = null;
ar.InvokeCallback(renegotiateBuffer);
}
else
{
AsyncProtocolRequest request = (AsyncProtocolRequest)_queuedReadStateRequest;
request.Buffer = renegotiateBuffer;
_queuedReadStateRequest = null;
ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncResumeHandshakeRead), request);
}
}
}
// Returns:
// true - operation queued
// false - operation can proceed
internal bool CheckEnqueueWrite(AsyncProtocolRequest asyncRequest)
{
// Clear previous request.
_queuedWriteStateRequest = null;
int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockWrite, LockNone);
if (lockState != LockHandshake)
{
// Proceed with write.
return false;
}
LazyAsyncResult lazyResult = null;
lock (this)
{
if (_lockWriteState != LockHandshake)
{
// Handshake has completed before we grabbed the lock.
CheckThrow(true);
return false;
}
_lockWriteState = LockPendingWrite;
// Still pending, wait or enqueue.
if (asyncRequest != null)
{
_queuedWriteStateRequest = asyncRequest;
return true;
}
lazyResult = new LazyAsyncResult(null, null, /*must be */null);
_queuedWriteStateRequest = lazyResult;
}
// Need to exit from lock before waiting.
lazyResult.InternalWaitForCompletion();
CheckThrow(true);
return false;
}
internal void FinishWrite()
{
int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockNone, LockWrite);
if (lockState != LockHandshake)
{
return;
}
lock (this)
{
object obj = _queuedWriteStateRequest;
if (obj == null)
{
// A repeated call.
return;
}
_queuedWriteStateRequest = null;
if (obj is LazyAsyncResult)
{
// Sync handshake is waiting on other thread.
((LazyAsyncResult)obj).InvokeCallback();
}
else
{
// Async handshake is pending, start it on other thread.
// Consider: we could start it in on this thread but that will delay THIS write completion
ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncResumeHandshake), obj);
}
}
}
// Returns:
// true - operation queued
// false - operation can proceed
private bool CheckEnqueueHandshake(byte[] buffer, AsyncProtocolRequest asyncRequest)
{
LazyAsyncResult lazyResult = null;
lock (this)
{
if (_lockWriteState == LockPendingWrite)
{
return false;
}
int lockState = Interlocked.Exchange(ref _lockWriteState, LockHandshake);
if (lockState != LockWrite)
{
// Proceed with handshake.
return false;
}
if (asyncRequest != null)
{
asyncRequest.Buffer = buffer;
_queuedWriteStateRequest = asyncRequest;
return true;
}
lazyResult = new LazyAsyncResult(null, null, /*must be*/null);
_queuedWriteStateRequest = lazyResult;
}
lazyResult.InternalWaitForCompletion();
return false;
}
private void FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
{
try
{
lock (this)
{
if (e != null)
{
SetException(e);
}
// Release read if any.
FinishHandshakeRead(LockNone);
// If there is a pending write we want to keep it's lock state.
int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockNone, LockHandshake);
if (lockState != LockPendingWrite)
{
return;
}
_lockWriteState = LockWrite;
object obj = _queuedWriteStateRequest;
if (obj == null)
{
// We finished before Write has grabbed the lock.
return;
}
_queuedWriteStateRequest = null;
if (obj is LazyAsyncResult)
{
// Sync write is waiting on other thread.
((LazyAsyncResult)obj).InvokeCallback();
}
else
{
// Async write is pending, start it on other thread.
// Consider: we could start it in on this thread but that will delay THIS handshake completion
ThreadPool.QueueUserWorkItem(new WaitCallback(CompleteRequestWaitCallback), obj);
}
}
}
finally
{
if (asyncRequest != null)
{
if (e != null)
{
asyncRequest.CompleteWithError(e);
}
else
{
asyncRequest.CompleteUser();
}
}
}
}
private static byte[] EnsureBufferSize(byte[] buffer, int copyCount, int size)
{
if (buffer == null || buffer.Length < size)
{
byte[] saved = buffer;
buffer = new byte[size];
if (saved != null && copyCount != 0)
{
Buffer.BlockCopy(saved, 0, buffer, 0, copyCount);
}
}
return buffer;
}
private enum Framing
{
Unknown = 0,
BeforeSSL3,
SinceSSL3,
Unified,
Invalid
}
// This is set on the first packet to figure out the framing style.
private Framing _Framing = Framing.Unknown;
// SSL3/TLS protocol frames definitions.
private enum FrameType : byte
{
ChangeCipherSpec = 20,
Alert = 21,
Handshake = 22,
AppData = 23
}
// We need at least 5 bytes to determine what we have.
private Framing DetectFraming(byte[] bytes, int length)
{
/* PCTv1.0 Hello starts with
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* PCT1_CLIENT_HELLO (must be equal)
* PCT1_CLIENT_VERSION_MSB (if version greater than PCTv1)
* PCT1_CLIENT_VERSION_LSB (if version greater than PCTv1)
*
* ... PCT hello ...
*/
/* Microsft Unihello starts with
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* SSL2_CLIENT_HELLO (must be equal)
* SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3)
* SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3)
*
* ... SSLv2 Compatible Hello ...
*/
/* SSLv2 CLIENT_HELLO starts with
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* SSL2_CLIENT_HELLO (must be equal)
* SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3)
* SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3)
*
* ... SSLv2 CLIENT_HELLO ...
*/
/* SSLv2 SERVER_HELLO starts with
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* SSL2_SERVER_HELLO (must be equal)
* SSL2_SESSION_ID_HIT (ignore)
* SSL2_CERTIFICATE_TYPE (ignore)
* SSL2_CLIENT_VERSION_MSB (if version greater than SSLv2) ( or v3)
* SSL2_CLIENT_VERSION_LSB (if version greater than SSLv2) ( or v3)
*
* ... SSLv2 SERVER_HELLO ...
*/
/* SSLv3 Type 2 Hello starts with
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* SSL2_CLIENT_HELLO (must be equal)
* SSL2_CLIENT_VERSION_MSB (if version greater than SSLv3)
* SSL2_CLIENT_VERSION_LSB (if version greater than SSLv3)
*
* ... SSLv2 Compatible Hello ...
*/
/* SSLv3 Type 3 Hello starts with
* 22 (HANDSHAKE MESSAGE)
* VERSION MSB
* VERSION LSB
* RECORD_LENGTH_MSB (ignore)
* RECORD_LENGTH_LSB (ignore)
* HS TYPE (CLIENT_HELLO)
* 3 bytes HS record length
* HS Version
* HS Version
*/
/* SSLv2 message codes
* SSL_MT_ERROR 0
* SSL_MT_CLIENT_HELLO 1
* SSL_MT_CLIENT_MASTER_KEY 2
* SSL_MT_CLIENT_FINISHED 3
* SSL_MT_SERVER_HELLO 4
* SSL_MT_SERVER_VERIFY 5
* SSL_MT_SERVER_FINISHED 6
* SSL_MT_REQUEST_CERTIFICATE 7
* SSL_MT_CLIENT_CERTIFICATE 8
*/
int version = -1;
GlobalLog.Assert((bytes != null && bytes.Length > 0), "SslState::DetectFraming()|Header buffer is not allocated will boom shortly.");
// If the first byte is SSL3 HandShake, then check if we have a SSLv3 Type3 client hello.
if (bytes[0] == (byte)FrameType.Handshake || bytes[0] == (byte)FrameType.AppData
|| bytes[0] == (byte)FrameType.Alert)
{
if (length < 3)
{
return Framing.Invalid;
}
#if TRACE_VERBOSE
if (bytes[1] != 3)
{
GlobalLog.Print("WARNING: SslState::DetectFraming() SSL protocol is > 3, trying SSL3 framing in retail = " + bytes[1].ToString("x", NumberFormatInfo.InvariantInfo));
}
#endif
version = (bytes[1] << 8) | bytes[2];
if (version < 0x300 || version >= 0x500)
{
return Framing.Invalid;
}
//
// This is an SSL3 Framing
//
return Framing.SinceSSL3;
}
#if TRACE_VERBOSE
if ((bytes[0] & 0x80) == 0)
{
// We have a three-byte header format
GlobalLog.Print("WARNING: SslState::DetectFraming() SSL v <=2 HELLO has no high bit set for 3 bytes header, we are broken, received byte = " + bytes[0].ToString("x", NumberFormatInfo.InvariantInfo));
}
#endif
if (length < 3)
{
return Framing.Invalid;
}
if (bytes[2] > 8)
{
return Framing.Invalid;
}
if (bytes[2] == 0x1) // SSL_MT_CLIENT_HELLO
{
if (length >= 5)
{
version = (bytes[3] << 8) | bytes[4];
}
}
else if (bytes[2] == 0x4) // SSL_MT_SERVER_HELLO
{
if (length >= 7)
{
version = (bytes[5] << 8) | bytes[6];
}
}
if (version != -1)
{
// If this is the first packet, the client may start with an SSL2 packet
// but stating that the version is 3.x, so check the full range.
// For the subsequent packets we assume that an SSL2 packet should have a 2.x version.
if (_Framing == Framing.Unknown)
{
if (version != 0x0002 && (version < 0x200 || version >= 0x500))
{
return Framing.Invalid;
}
}
else
{
if (version != 0x0002)
{
return Framing.Invalid;
}
}
}
// When server has replied the framing is already fixed depending on the prior client packet
if (!Context.IsServer || _Framing == Framing.Unified)
{
return Framing.BeforeSSL3;
}
return Framing.Unified; // Will use Ssl2 just for this frame.
}
//
// This is called from SslStream class too.
internal int GetRemainingFrameSize(byte[] buffer, int dataSize)
{
GlobalLog.Enter("GetRemainingFrameSize", "dataSize = " + dataSize);
int payloadSize = -1;
switch (_Framing)
{
case Framing.Unified:
case Framing.BeforeSSL3:
if (dataSize < 2)
{
throw new System.IO.IOException(SR.net_ssl_io_frame);
}
// Note: Cannot detect version mismatch for <= SSL2
if ((buffer[0] & 0x80) != 0)
{
// Two bytes
payloadSize = (((buffer[0] & 0x7f) << 8) | buffer[1]) + 2;
payloadSize -= dataSize;
}
else
{
// Three bytes
payloadSize = (((buffer[0] & 0x3f) << 8) | buffer[1]) + 3;
payloadSize -= dataSize;
}
break;
case Framing.SinceSSL3:
if (dataSize < 5)
{
throw new System.IO.IOException(SR.net_ssl_io_frame);
}
payloadSize = ((buffer[3] << 8) | buffer[4]) + 5;
payloadSize -= dataSize;
break;
default:
break;
}
GlobalLog.Leave("GetRemainingFrameSize", payloadSize);
return payloadSize;
}
//
// Called with no user stack.
//
private void AsyncResumeHandshake(object state)
{
AsyncProtocolRequest request = state as AsyncProtocolRequest;
Debug.Assert(request != null, "Expected an AsyncProtocolRequest reference.");
try
{
ForceAuthentication(Context.IsServer, request.Buffer, request);
}
catch (Exception e)
{
request.CompleteWithError(e);
}
}
//
// Called with no user stack.
//
private void AsyncResumeHandshakeRead(object state)
{
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)state;
try
{
if (_pendingReHandshake)
{
// Resume as read a blob.
StartReceiveBlob(asyncRequest.Buffer, asyncRequest);
}
else
{
// Resume as process the blob.
ProcessReceivedBlob(asyncRequest.Buffer, asyncRequest.Buffer == null ? 0 : asyncRequest.Buffer.Length, asyncRequest);
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
FinishHandshake(e, asyncRequest);
}
}
//
// Called with no user stack.
//
private void CompleteRequestWaitCallback(object state)
{
AsyncProtocolRequest request = (AsyncProtocolRequest)state;
// Force async completion.
if (request.MustCompleteSynchronously)
{
throw new InternalException();
}
request.CompleteRequest(0);
}
private void RehandshakeCompleteCallback(IAsyncResult result)
{
LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;
GlobalLog.Assert(lazyAsyncResult != null, "SslState::RehandshakeCompleteCallback()|result is null!");
GlobalLog.Assert(lazyAsyncResult.InternalPeekCompleted, "SslState::RehandshakeCompleteCallback()|result is not completed!");
// If the rehandshake succeeded, FinishHandshake has already been called; if there was a SocketException
// during the handshake, this gets called directly from FixedSizeReader, and we need to call
// FinishHandshake to wake up the Read that triggered this rehandshake so the error gets back to the caller
Exception exception = lazyAsyncResult.InternalWaitForCompletion() as Exception;
if (exception != null)
{
// We may be calling FinishHandshake reentrantly, as FinishHandshake can call
// asyncRequest.CompleteWithError, which will result in this method being called.
// This is not a problem because:
//
// 1. We pass null as the asyncRequest parameter, so this second call to FinishHandshake won't loop
// back here.
//
// 2. _QueuedWriteStateRequest and _QueuedReadStateRequest are set to null after the first call,
// so, we won't invoke their callbacks again.
//
// 3. SetException won't overwrite an already-set _Exception.
//
// 4. There are three possibilites for _LockReadState and _LockWriteState:
//
// a. They were set back to None by the first call to FinishHandshake, and this will set them to
// None again: a no-op.
//
// b. They were set to None by the first call to FinishHandshake, but as soon as the lock was given
// up, another thread took a read/write lock. Calling FinishHandshake again will set them back
// to None, but that's fine because that thread will be throwing _Exception before it actually
// does any reading or writing and setting them back to None in a catch block anyways.
//
// c. If there is a Read/Write going on another thread, and the second FinishHandshake clears its
// read/write lock, it's fine because no other Read/Write can look at the lock until the current
// one gives up _SslStream._NestedRead/Write, and no handshake will look at the lock because
// handshakes are only triggered in response to successful reads (which won't happen once
// _Exception is set).
FinishHandshake(exception, null);
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.Account.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Account.Api.Tests
{
public class RoleTests
{
public static RoleController Fixture()
{
RoleController controller = new RoleController(new RoleRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Account.Entities.Role role = Fixture().Get(0);
Assert.NotNull(role);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Account.Entities.Role role = Fixture().GetFirst();
Assert.NotNull(role);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Account.Entities.Role role = Fixture().GetPrevious(0);
Assert.NotNull(role);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Account.Entities.Role role = Fixture().GetNext(0);
Assert.NotNull(role);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Account.Entities.Role role = Fixture().GetLast();
Assert.NotNull(role);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Account.Entities.Role> roles = Fixture().Get(new int[] { });
Assert.NotNull(roles);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Http.Dependencies;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.Api.Insfrastructure.Commands;
using ReMi.Api.Insfrastructure.Security;
using ReMi.BusinessEntities.Auth;
using ReMi.Common.Utils;
using ReMi.Common.WebApi.Tracking;
using ReMi.Contracts.Cqrs.Commands;
using ReMi.TestUtils.UnitTests;
namespace ReMi.Api.Tests.Infrastructure.Commands
{
public class CommandDispatcherTest : TestClassFor<CommandDispatcher>
{
private Mock<IDependencyResolver> _dependencyResolverMock;
private Mock<IHandleCommand<TestCommand>> _handleCommandMock;
private Mock<ICommandTracker> _commandTrackerMock;
private Mock<ISerialization> _serializationMock;
private Mock<IApplicationSettings> _applicationSettingsMock;
protected override CommandDispatcher ConstructSystemUnderTest()
{
return new CommandDispatcher
{
DependencyResolver = _dependencyResolverMock.Object,
CommandTracker = _commandTrackerMock.Object,
Serialization = _serializationMock.Object,
ApplicationSettings = _applicationSettingsMock.Object
};
}
protected override void TestInitialize()
{
_handleCommandMock = new Mock<IHandleCommand<TestCommand>>();
_commandTrackerMock = new Mock<ICommandTracker>();
_serializationMock = new Mock<ISerialization>(MockBehavior.Strict);
_applicationSettingsMock = new Mock<IApplicationSettings>();
_applicationSettingsMock.SetupGet(x => x.LogJsonFormatted).Returns(true);
_dependencyResolverMock = new Mock<IDependencyResolver>();
_dependencyResolverMock.Setup(o => o.GetService(typeof(IHandleCommand<TestCommand>)))
.Returns(_handleCommandMock.Object);
base.TestInitialize();
}
[Test]
[ExpectedException(typeof(Exception))]
public void Send_ShouldRaiseException_WhenCantPopulateContext()
{
Thread.CurrentPrincipal = null;
var command = new TestCommand();
var task = Sut.Send(command);
task.Wait();
_handleCommandMock.Verify(x => x.Handle(command));
}
[Test]
public void Send_ShouldPopulateCommandContext_WhenCommandIsSent()
{
var account = Builder<Account>.CreateNew()
.With(o => o.ExternalId, Guid.NewGuid())
.With(o => o.FullName, RandomData.RandomString(20))
.With(o => o.Role, Builder<Role>.CreateNew()
.With(r => r.Name, RandomData.RandomString(10))
.Build())
.Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
var command = new TestCommand();
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
var task = Sut.Send(command);
task.Wait();
_handleCommandMock.Verify(
x => x.Handle(It.Is<TestCommand>(o =>
o.CommandContext != null
&& o.CommandContext.UserId == account.ExternalId
&& o.CommandContext.UserName == account.FullName
&& o.CommandContext.UserRole == account.Role.Name
)));
}
[Test]
public void Send_ShouldRunProperCommandHandler_WhenCommandIsSent()
{
var command = new TestCommand { CommandContext = new CommandContext { Id = Guid.NewGuid(), UserName = "remi" } };
var account = Builder<Account>.CreateNew().Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
var task = Sut.Send(command);
task.Wait();
_handleCommandMock.Verify(x => x.Handle(command));
_commandTrackerMock.Verify(x => x.CreateTracker(command.CommandContext.Id, "TestCommand"));
_commandTrackerMock.Verify(x => x.Started(command.CommandContext.Id));
_commandTrackerMock.Verify(x => x.Finished(command.CommandContext.Id, null));
_serializationMock.Verify(x => x.ToJson(It.IsAny<object>(), It.IsAny<IEnumerable<string>>(), It.IsAny<bool>()), Times.Once);
}
[Test]
public void Send_ShouldCreateTracker_BeforeHandleCommand()
{
var command = new TestCommand { CommandContext = new CommandContext { Id = Guid.NewGuid(), UserName = "remi" } };
var account = Builder<Account>.CreateNew().Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
var callOrder = 0;
var createTrackerOrder = -1;
var handleCommandOrder = -1;
_handleCommandMock.Setup(x => x.Handle(command)).Callback(() => handleCommandOrder = callOrder++);
_commandTrackerMock.Setup(x => x.CreateTracker(command.CommandContext.Id, "TestCommand")).Callback(() => createTrackerOrder = callOrder++);
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
var task = Sut.Send(command);
task.Wait();
Assert.AreEqual(createTrackerOrder, 0);
Assert.AreEqual(handleCommandOrder, 1);
}
[Test]
public void Send_ShouldRunProperCommandHandler_WhenCommandIsSync()
{
var command = new TestCommand { CommandContext = new CommandContext { Id = Guid.NewGuid(), UserName = "remi", IsSynchronous = true } };
var account = Builder<Account>.CreateNew().Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
var task = Sut.Send(command);
Assert.IsNull(task);
_handleCommandMock.Verify(x => x.Handle(command));
_commandTrackerMock.Verify(x => x.CreateTracker(command.CommandContext.Id, "TestCommand"));
_commandTrackerMock.Verify(x => x.Started(command.CommandContext.Id));
_commandTrackerMock.Verify(x => x.Finished(command.CommandContext.Id, null));
}
[Test]
public void Send_ShouldHandleCommandInDifferentThread_WhenCommandIsAsync()
{
var command = new TestCommand { CommandContext = new CommandContext { Id = Guid.NewGuid(), UserName = "remi" } };
var account = Builder<Account>.CreateNew().Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
var handleThreadId = -1;
_handleCommandMock.Setup(x => x.Handle(command)).Callback(() => handleThreadId = Thread.CurrentThread.ManagedThreadId);
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
var task = Sut.Send(command);
task.Wait();
Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, handleThreadId);
}
[Test]
public void Send_ShouldHandleCommandInDifferentThread_WhenCommandIsSync()
{
var command = new TestCommand { CommandContext = new CommandContext { Id = Guid.NewGuid(), UserName = "remi", IsSynchronous = true } };
var account = Builder<Account>.CreateNew().Build();
Thread.CurrentPrincipal = new RequestPrincipal(account);
var handleThreadId = -1;
_handleCommandMock.Setup(x => x.Handle(command)).Callback(() => handleThreadId = Thread.CurrentThread.ManagedThreadId);
_serializationMock.Setup(x => x.ToJson(command, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>()))
.Returns("json data");
Sut.Send(command);
Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handleThreadId);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Send_ShouldThrowArgumentNullException_WhenNullCommandIsSent()
{
Sut.Send((TestCommand)null);
}
public class TestCommand : ICommand
{
public CommandContext CommandContext { get; set; }
}
public class CommandHandlerTest<T> : IHandleCommand<T> where T : ICommand
{
private readonly IHandleCommand<TestCommand> _injectedImplementation;
public CommandHandlerTest(IHandleCommand<TestCommand> injectedImplementation)
{
_injectedImplementation = injectedImplementation;
}
public void Handle(T command)
{
_injectedImplementation.Handle(command as TestCommand);
}
}
}
}
| |
// 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.ComponentModel;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
var expected = PlatformDetection.IsWindowsNanoServer ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal; // For some reason we're BelowNormal initially on Nano
Assert.Equal(expected, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void ProcessStart_TryExitCommandAsFileName_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "exit", Arguments = "42" }));
}
[Fact]
public void ProcessStart_UseShellExecuteFalse_FilenameIsUrl_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "https://www.github.com/corefx" }));
}
[Fact]
public void ProcessStart_TryOpenFolder_UseShellExecuteIsFalse_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = Path.GetTempPath() }));
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // OSX doesn't support throwing on Process.Start
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // UWP overrides WorkingDirectory (https://github.com/dotnet/corefx/pull/25266#issuecomment-347719832).
public void TestStartWithBadWorkingDirectory()
{
string program;
string workingDirectory;
if (PlatformDetection.IsWindows)
{
program = "powershell.exe";
workingDirectory = @"C:\does-not-exist";
}
else
{
program = "uname";
workingDirectory = "/does-not-exist";
}
if (IsProgramInstalled(program))
{
var psi = new ProcessStartInfo
{
FileName = program,
UseShellExecute = false,
WorkingDirectory = workingDirectory
};
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(psi));
Assert.NotEqual(0, e.NativeErrorCode);
}
else
{
Console.WriteLine($"Program {program} is not installed on this machine.");
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
[OuterLoop("Launches File Explorer")]
public void ProcessStart_UseShellExecuteTrue_OpenMissingFile_Throws()
{
string fileToOpen = Path.Combine(Environment.CurrentDirectory, "_no_such_file.TXT");
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }));
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
[InlineData(true)]
[InlineData(false)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
[OuterLoop("Launches File Explorer")]
public void ProcessStart_UseShellExecute_OnWindows_DoesNotThrow(bool isFolder)
{
string fileToOpen;
if (isFolder)
{
fileToOpen = Environment.CurrentDirectory;
}
else
{
fileToOpen = GetTestFilePath() + ".txt";
File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnWindows_DoesNotThrow)}");
}
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
{
if (isFolder)
{
Assert.Null(px);
}
else
{
if (px != null) // sometimes process is null
{
Assert.Equal("notepad", px.ProcessName);
px.Kill();
Assert.True(px.WaitForExit(WaitInMS));
}
}
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
// Try twice, since it's possible that the system clock could be adjusted backwards between when we snapshot it
// and when the process ends, but vanishingly unlikely that would happen twice.
DateTime timeBeforeProcessStart = DateTime.MaxValue;
Process p = null;
for (int i = 0; i <= 1; i++)
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
if (p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart)
break;
}
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
public void TestId()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
public void TestMachineName()
{
CreateDefaultProcess();
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
public void TestMainModule()
{
Process p = Process.GetCurrentProcess();
// On UAP casing may not match - we use Path.GetFileName(exePath) instead of kernel32!GetModuleFileNameEx which is not available on UAP
Func<string, string> normalize = PlatformDetection.IsUap ?
(Func<string, string>)((s) => s.ToLowerInvariant()) :
(s) => s;
Assert.True(p.Modules.Count > 0);
Assert.Equal(normalize(HostRunnerName), normalize(p.MainModule.ModuleName));
Assert.EndsWith(normalize(HostRunnerName), normalize(p.MainModule.FileName));
Assert.Equal(normalize(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName)), normalize(p.MainModule.ToString()));
}
[Fact]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet64()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
public void TestProcessorTime()
{
CreateDefaultProcess();
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[Fact]
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(1);
for (int i = 0; i < 2; i++)
{
Process p = CreateProcessPortable(RemotelyInvokable.ReadLine);
Assert.Throws<InvalidOperationException>(() => p.StartTime);
DateTime testStartTime = DateTime.Now;
p.StartInfo.RedirectStandardInput = true;
p.Start();
Assert.Equal(p.StartTime, p.StartTime);
DateTime processStartTime = p.StartTime;
using (StreamWriter writer = p.StandardInput)
{
writer.WriteLine("start");
}
Assert.True(p.WaitForExit(WaitInMS));
DateTime testEndTime = DateTime.Now;
bool hasTimeChanged = testEndTime < testStartTime;
if (i != 0 || !hasTimeChanged)
{
Assert.InRange(processStartTime, testStartTime - allowedWindow, testEndTime + allowedWindow);
break;
}
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
CreateDefaultProcess();
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Theory]
[InlineData((ProcessPriorityClass)0)]
[InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)]
public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass)
{
var process = new Process();
Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass);
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestProcessName()
{
CreateDefaultProcess();
string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner;
Assert.Equal(Path.GetFileNameWithoutExtension(expected), Path.GetFileNameWithoutExtension(_process.ProcessName), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
public void TestSafeHandle()
{
CreateDefaultProcess();
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestSessionId()
{
CreateDefaultProcess();
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcessById()
{
CreateDefaultProcess();
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
public void GetProcesses_InvalidMachineName_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Process.GetProcesses(Guid.NewGuid().ToString()));
}
[Fact]
public void GetProcesses_RemoteMachinePath_ReturnsExpected()
{
try
{
Process[] processes = Process.GetProcesses(Environment.MachineName + "." + Domain.GetComputerDomain());
Assert.NotEmpty(processes);
}
catch (ActiveDirectoryObjectNotFoundException)
{
//This will be thrown when the executing machine is not domain-joined, i.e. in CI
}
catch (PlatformNotSupportedException)
{
//System.DirectoryServices is not supported on all platforms
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
try
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Retrieving information about local processes is not supported on uap")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
void TestRemoteProccess(Process remoteProcess)
{
Assert.Equal(currentProccess.Id, remoteProcess.Id);
Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
try
{
TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1"));
TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single());
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
process.Start();
// Processes are not hosted by dotnet in the full .NET Framework.
string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : RunnerName;
Assert.Equal(expectedFileName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
process.Start();
// .NET Core fixes a bug where Process.StartInfo for a unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
var startInfo = new ProcessStartInfo();
process.StartInfo = startInfo;
Assert.Equal(startInfo, process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo());
}
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetGet_ReturnsExpected()
{
var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) };
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
[Fact]
public void StartInfo_SetNull_ThrowsArgumentNullException()
{
var process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
[Fact]
public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = Process.GetCurrentProcess();
// .NET Core fixes a bug where Process.StartInfo for an unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Non applicable for uap - RemoteInvoke works differently")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
[InlineData("\"\" b \"\"", ",b,")]
[InlineData("\"\"\"\" b c", "\",b,c")]
[InlineData("c\"\"\"\" b \"\"\\", "c\",b,\\")]
[InlineData("\"\"c \"\"b\"\" d\"\\", "c,b,d\\")]
[InlineData("\"\"a\"\" b d", "a,b,d")]
[InlineData("b d \"\"a\"\" ", "b,d,a")]
[InlineData("\\\"\\\"a\\\"\\\" b d", "\"\"a\"\",b,d")]
[InlineData("b d \\\"\\\"a\\\"\\\"", "b,d,\"\"a\"\"")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
var options = new RemoteInvokeOptions
{
Start = true,
StartInfo = new ProcessStartInfo { RedirectStandardOutput = true }
};
using (RemoteInvokeHandle handle = RemoteInvokeRaw((Func<string, string, string, int>)RemotelyInvokable.ConcatThreeArguments, inputArguments, options))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "GC has different behavior on Mono")]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException_WindowsNonUap()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[Fact]
// CloseMainWindow is a no-op and always returns false on Unix or Uap.
public void CloseMainWindow_NotStarted_ReturnsFalse_UapOrNonWindows()
{
if (PlatformDetection.IsWindows && !PlatformDetection.IsUap)
return;
var process = new Process();
Assert.False(process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain); // This writes junk to the Console but with this overload, we can't prevent that.
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
Assert.True(p.WaitForExit(WaitInMS));
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
var startInfo = new ProcessStartInfo()
{
FileName = "exe",
UserName = "dummyUser",
PasswordInClearText = "Value",
Password = AsSecureString("Value"),
UseShellExecute = false
};
var process = new Process() { StartInfo = startInfo };
AssertExtensions.Throws<ArgumentException>(null, () => process.Start());
}
[Fact]
public void TestLongProcessIsWorking()
{
// Sanity check for CreateProcessLong
Process p = CreateProcessLong();
p.Start();
Thread.Sleep(500);
Assert.False(p.HasExited);
p.Kill();
p.WaitForExit();
Assert.True(p.HasExited);
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// UInt64.System.IConvertible.ToType(Type,provider)
/// </summary>
public class UInt64IConvertibleToType
{
public static int Main()
{
UInt64IConvertibleToType ui64icttype = new UInt64IConvertibleToType();
TestLibrary.TestFramework.BeginTestCase("UInt64IConvertibleToType");
if (ui64icttype.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:UInt64 MinValue to Type of string");
try
{
UInt64 uintA = UInt64.MinValue;
IConvertible iConvert = (IConvertible)(uintA);
string strA = (string)iConvert.ToType(typeof(string), null);
if (strA != uintA.ToString())
{
TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:UInt64 MinValue to Type of bool");
try
{
UInt64 uintA = UInt64.MinValue;
IConvertible iConvert = (IConvertible)(uintA);
bool boolA = (bool)iConvert.ToType(typeof(bool), null);
if (boolA)
{
TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:UInt64 MaxValue to Type of bool");
try
{
UInt64 uintA = UInt64.MaxValue;
IConvertible iConvert = (IConvertible)(uintA);
bool boolA = (bool)iConvert.ToType(typeof(bool), null);
if (!boolA)
{
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4:Convert a random UInt64 to Type of double,decimal and single");
try
{
UInt64 uintA = this.GetInt64(0, UInt64.MaxValue); ;
IConvertible iConvert = (IConvertible)(uintA);
Double doubleA = (Double)iConvert.ToType(typeof(Double), null);
Decimal decimalA = (Decimal)iConvert.ToType(typeof(Decimal), null);
Single singleA = (Single)iConvert.ToType(typeof(Single), null);
if (doubleA != uintA || decimalA != uintA || singleA != uintA)
{
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5:UInt64 between MinValue to Int32.Max to Type of Int32");
try
{
UInt64 uintA = this.GetInt64(0, Int32.MaxValue);
IConvertible iConvert = (IConvertible)(uintA);
Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null);
if (int32A != (Int32)uintA)
{
TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6:UInt64 between MinValue to Int16.Max to Type of Int16");
try
{
UInt64 uintA = this.GetInt64(0, Int16.MaxValue + 1);
IConvertible iConvert = (IConvertible)(uintA);
Int16 int16A = (Int16)iConvert.ToType(typeof(Int16), null);
if (int16A != (Int16)uintA)
{
TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7:UInt64 between MinValue and SByte.Max to Type of SByte");
try
{
UInt64 uintA = this.GetInt64(0, SByte.MaxValue + 1);
IConvertible iConvert = (IConvertible)(uintA);
SByte sbyteA = (SByte)iConvert.ToType(typeof(SByte), null);
if (sbyteA != (SByte)uintA)
{
TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8:UInt64 between MinValue and Byte.Max to Type of Byte");
try
{
UInt64 uintA = this.GetInt64(0, Byte.MaxValue + 1);
IConvertible iConvert = (IConvertible)(uintA);
Byte byteA = (Byte)iConvert.ToType(typeof(Byte), null);
if (byteA != (Byte)uintA)
{
TestLibrary.TestFramework.LogError("015", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:UInt64 between Int32.MaxValue and UInt64.MaxValue to Type of Int32");
try
{
UInt64 uintA = this.GetInt64((ulong)Int32.MaxValue + 1, UInt64.MaxValue);
IConvertible iConvert = (IConvertible)(uintA);
Int32 int32A = (Int32)iConvert.ToType(typeof(Int32), null);
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The argument type is a null reference");
try
{
UInt64 uintA = 100;
IConvertible iConvert = (IConvertible)(uintA);
object oBject = (Int16)iConvert.ToType(null, null);
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestObject
private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public partial class TcpClient : IDisposable
{
private readonly AddressFamily _family;
private Socket _clientSocket;
private NetworkStream _dataStream;
private bool _cleanedUp = false;
private bool _active;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", family);
}
// Validate parameter
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
}
_family = family;
InitializeClientSocket();
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", acceptedSocket);
}
_clientSocket = acceptedSocket;
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get { return _active; }
set { _active = value; }
}
public int Available { get { return AvailableCore; } }
public bool Connected { get { return ConnectedCore; } }
public bool ExclusiveAddressUse
{
get { return ExclusiveAddressUseCore; }
set { ExclusiveAddressUseCore = value; }
}
public Task ConnectAsync(IPAddress address, int port)
{
return Task.Factory.FromAsync(
(targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
address,
port,
state: this);
}
public Task ConnectAsync(string host, int port)
{
return ConnectAsyncCore(host, port);
}
public Task ConnectAsync(IPAddress[] addresses, int port)
{
return ConnectAsyncCore(addresses, port);
}
private IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", address);
}
IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
private void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndConnect", asyncResult);
}
Client.EndConnect(asyncResult);
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndConnect", null);
}
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "GetStream", "");
}
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
if (_dataStream == null)
{
_dataStream = new NetworkStream(_clientSocket, true);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "GetStream", _dataStream);
}
return _dataStream;
}
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
if (_cleanedUp)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
return;
}
if (disposing)
{
IDisposable dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = _clientSocket;
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Dispose();
_clientSocket = null;
}
}
}
GC.SuppressFinalize(this);
}
_cleanedUp = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
}
public void Dispose()
{
Dispose(true);
}
~TcpClient()
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.Finalization);
using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
#if DEBUG
}
#endif
}
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get { return ReceiveBufferSizeCore; }
set { ReceiveBufferSizeCore = value; }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get { return SendBufferSizeCore; }
set { SendBufferSizeCore = value; }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get { return ReceiveTimeoutCore; }
set { ReceiveTimeoutCore = value; }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get { return SendTimeoutCore; }
set { SendTimeoutCore = value; }
}
// Gets or sets the value of the connection's linger option.
public LingerOption LingerState
{
get { return LingerStateCore; }
set { LingerStateCore = value; }
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get { return NoDelayCore; }
set { NoDelayCore = value; }
}
private Socket CreateSocket()
{
return new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace api.securecall.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2003
//
// File: mediaeventshelper.cs
//
//------------------------------------------------------------------------------
using System;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using MS.Internal;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Media.Composition;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
#region MediaEventsHelper
/// <summary>
/// MediaEventsHelper
/// Provides helper methods for media event related tasks
/// </summary>
internal class MediaEventsHelper : IInvokable
{
#region Constructors and Finalizers
/// <summary>
/// Constructor
/// </summary>
internal MediaEventsHelper(MediaPlayer mediaPlayer)
{
_mediaOpened = new DispatcherOperationCallback(OnMediaOpened);
this.DispatcherMediaOpened += _mediaOpened;
_mediaFailed = new DispatcherOperationCallback(OnMediaFailed);
this.DispatcherMediaFailed += _mediaFailed;
_mediaPrerolled = new DispatcherOperationCallback(OnMediaPrerolled);
this.DispatcherMediaPrerolled += _mediaPrerolled;
_mediaEnded = new DispatcherOperationCallback(OnMediaEnded);
this.DispatcherMediaEnded += _mediaEnded;
_bufferingStarted = new DispatcherOperationCallback(OnBufferingStarted);
this.DispatcherBufferingStarted += _bufferingStarted;
_bufferingEnded = new DispatcherOperationCallback(OnBufferingEnded);
this.DispatcherBufferingEnded += _bufferingEnded;
_scriptCommand = new DispatcherOperationCallback(OnScriptCommand);
this.DispatcherScriptCommand += _scriptCommand;
_newFrame = new DispatcherOperationCallback(OnNewFrame);
this.DispatcherMediaNewFrame += _newFrame;
SetSender(mediaPlayer);
}
#endregion
#region Static Methods
/// <summary>
/// Create
/// </summary>
/// <SecurityNote>
/// Critical: This function hooks up and exposes the unmanaged proxy that
/// sinks events from windows media
/// </SecurityNote>
[SecurityCritical]
internal static void CreateMediaEventsHelper(MediaPlayer mediaPlayer,
out MediaEventsHelper eventsHelper,
out SafeMILHandle unmanagedProxy)
{
eventsHelper = new MediaEventsHelper(mediaPlayer);
// Created with ref count = 1. Since this object does not hold on
// to the unmanaged proxy, the lifetime is now controlled by whoever
// called CreateMediaEventsHelper.
unmanagedProxy = EventProxyWrapper.CreateEventProxyWrapper(eventsHelper);
}
#endregion
#region Internal Methods / Properties / Events
/// <summary>
/// Changes the sender of all events
/// </summary>
internal void SetSender(MediaPlayer sender)
{
Debug.Assert((sender != null), "Sender is null");
Debug.Assert((sender.Dispatcher != null), "Dispatcher is null");
_sender = sender;
_dispatcher = sender.Dispatcher;
}
/// <summary>
/// Raised when error is encountered.
/// </summary>
internal event EventHandler<ExceptionEventArgs> MediaFailed
{
add
{
_mediaFailedHelper.AddEvent(value);
}
remove
{
_mediaFailedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when media loading is complete
/// </summary>
internal event EventHandler MediaOpened
{
add
{
_mediaOpenedHelper.AddEvent(value);
}
remove
{
_mediaOpenedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when media prerolling is complete
/// </summary>
internal event EventHandler MediaPrerolled
{
add
{
_mediaPrerolledHelper.AddEvent(value);
}
remove
{
_mediaPrerolledHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when media playback is finished
/// </summary>
internal event EventHandler MediaEnded
{
add
{
_mediaEndedHelper.AddEvent(value);
}
remove
{
_mediaEndedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when buffering begins
/// </summary>
internal event EventHandler BufferingStarted
{
add
{
_bufferingStartedHelper.AddEvent(value);
}
remove
{
_bufferingStartedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when buffering is complete
/// </summary>
internal event EventHandler BufferingEnded
{
add
{
_bufferingEndedHelper.AddEvent(value);
}
remove
{
_bufferingEndedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when a script command that is embedded in the media is reached.
/// </summary>
internal event EventHandler<MediaScriptCommandEventArgs> ScriptCommand
{
add
{
_scriptCommandHelper.AddEvent(value);
}
remove
{
_scriptCommandHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when a requested media frame is reached.
/// </summary>
internal event EventHandler NewFrame
{
add
{
_newFrameHelper.AddEvent(value);
}
remove
{
_newFrameHelper.RemoveEvent(value);
}
}
internal void RaiseMediaFailed(Exception e)
{
if (DispatcherMediaFailed != null)
{
_dispatcher.BeginInvoke(
DispatcherPriority.Normal,
DispatcherMediaFailed,
new ExceptionEventArgs(e));
}
}
#endregion
#region IInvokable
/// <summary>
/// Raises an event
/// </summary>
void IInvokable.RaiseEvent(byte[] buffer, int cb)
{
const int S_OK = 0;
AVEvent avEventType = AVEvent.AVMediaNone;
int failureHr = S_OK;
int size = 0;
//
// Minumum size is the event enum, the error hresult and two
// string lengths (as integers)
//
size = sizeof(int) * 4;
//
// The data could be larger, that is benign, in the case that we have
// strings appended it will be.
//
if (cb < size)
{
Debug.Assert((cb == size), "Invalid event packet");
return;
}
MemoryStream memStream = new MemoryStream(buffer);
using (BinaryReader reader = new BinaryReader(memStream))
{
//
// Unpack the event and the errorHResult
//
avEventType = (AVEvent)reader.ReadUInt32();
failureHr = (int)reader.ReadUInt32();
switch(avEventType)
{
case AVEvent.AVMediaOpened:
if (DispatcherMediaOpened != null)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, DispatcherMediaOpened, null);
}
break;
case AVEvent.AVMediaFailed:
RaiseMediaFailed(HRESULT.ConvertHRToException(failureHr));
break;
case AVEvent.AVMediaBufferingStarted:
if (DispatcherBufferingStarted != null)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, DispatcherBufferingStarted, null);
}
break;
case AVEvent.AVMediaBufferingEnded:
if (DispatcherBufferingEnded != null)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, DispatcherBufferingEnded, null);
}
break;
case AVEvent.AVMediaEnded:
if (DispatcherMediaEnded != null)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, DispatcherMediaEnded, null);
}
break;
case AVEvent.AVMediaPrerolled:
if (DispatcherMediaPrerolled != null)
{
_dispatcher.BeginInvoke(DispatcherPriority.Normal, DispatcherMediaPrerolled, null);
}
break;
case AVEvent.AVMediaScriptCommand:
HandleScriptCommand(reader);
break;
case AVEvent.AVMediaNewFrame:
if (DispatcherMediaNewFrame != null)
{
//
// We set frame updates to background because media is high frequency and bandwidth enough
// to interfere dramatically with input.
//
_dispatcher.BeginInvoke(DispatcherPriority.Background, DispatcherMediaNewFrame, null);
}
break;
default:
//
// Default case intentionally not handled.
//
break;
}
}
}
#endregion
#region Private Methods / Events
/// <summary>
/// Handle the parsing of script commands coming up from media that
/// supports them. Then binary reader at this point will be positioned
/// at the first of the string lengths encoded in the structure.
/// </summary>
private
void
HandleScriptCommand(
BinaryReader reader
)
{
int parameterTypeLength = (int)reader.ReadUInt32();
int parameterValueLength = (int)reader.ReadUInt32();
if (DispatcherScriptCommand != null)
{
string parameterType = GetStringFromReader(reader, parameterTypeLength);
string parameterValue = GetStringFromReader(reader, parameterValueLength);
_dispatcher.BeginInvoke(
DispatcherPriority.Normal,
DispatcherScriptCommand,
new MediaScriptCommandEventArgs(
parameterType,
parameterValue));
}
}
/// <summary>
/// Reads in a sequence of unicode characters from a binary
/// reader and inserts them into a StringBuilder. From this
/// a string is returned.
/// </summary>
private
string
GetStringFromReader(
BinaryReader reader,
int stringLength
)
{
//
// Set the initial capacity of the string builder to stringLength
//
StringBuilder stringBuilder = new StringBuilder(stringLength);
//
// Also set the actual length, this allows the string to be indexed
// to that point.
//
stringBuilder.Length = stringLength;
for(int i = 0; i < stringLength; i++)
{
stringBuilder[i] = (char)reader.ReadUInt16();
}
return stringBuilder.ToString();
}
/// <summary>
/// Media Opened event comes through here
/// </summary>
/// <param name="o">Null argument</param>
private object OnMediaOpened(object o)
{
_mediaOpenedHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// MediaPrerolled event comes through here
/// </summary>
/// <param name="o">Null argument</param>
private object OnMediaPrerolled(object o)
{
_mediaPrerolledHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// MediaEnded event comes through here
/// </summary>
/// <param name="o">Null argument</param>
private object OnMediaEnded(object o)
{
_mediaEndedHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// BufferingStarted event comes through here
/// </summary>
/// <param name="o">Null argument</param>
private object OnBufferingStarted(object o)
{
_bufferingStartedHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// BufferingEnded event comes through here
/// </summary>
/// <param name="o">Null argument</param>
private object OnBufferingEnded(object o)
{
_bufferingEndedHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// MediaFailed event comes through here
/// </summary>
/// <param name="o">EventArgs</param>
private object OnMediaFailed(object o)
{
ExceptionEventArgs e = (ExceptionEventArgs)o;
_mediaFailedHelper.InvokeEvents(_sender, e);
return null;
}
/// <summary>
/// Script commands come through here.
/// </summary>
/// <param name ="o">EventArgs</param>
private object OnScriptCommand(object o)
{
MediaScriptCommandEventArgs e = (MediaScriptCommandEventArgs)o;
_scriptCommandHelper.InvokeEvents(_sender, e);
return null;
}
/// <summary>
/// New frames come through here.
/// </summary>
private object OnNewFrame(object e)
{
_newFrameHelper.InvokeEvents(_sender, null);
return null;
}
/// <summary>
/// Raised by a media when it encounters an error.
/// </summary>
/// <remarks>
/// Argument passed into the callback is a System.Exception
/// </remarks>
private event DispatcherOperationCallback DispatcherMediaFailed;
/// <summary>
/// Raised by a media when its done loading.
/// </summary>
private event DispatcherOperationCallback DispatcherMediaOpened;
/// <summary>
/// Raised by a media when its done prerolling.
/// </summary>
private event DispatcherOperationCallback DispatcherMediaPrerolled;
/// <summary>
/// Raised by a media when its done playback.
/// </summary>
private event DispatcherOperationCallback DispatcherMediaEnded;
/// <summary>
/// Raised by a media when buffering begins.
/// </summary>
private event DispatcherOperationCallback DispatcherBufferingStarted;
/// <summary>
/// Raised by a media when buffering finishes.
/// </summary>
private event DispatcherOperationCallback DispatcherBufferingEnded;
/// <summary>
/// Raised by media when a particular scripting event is received.
/// </summary>
private event DispatcherOperationCallback DispatcherScriptCommand;
/// <summary>
/// Raised whenever a new frame is displayed that has been requested.
/// This is only required for effects.
/// </summary>
private event DispatcherOperationCallback DispatcherMediaNewFrame;
#endregion
#region Private Data Members
/// <summary>
/// Sender of all events
/// </summary>
private MediaPlayer _sender;
/// <summary>
/// Dispatcher of this object
/// </summary>
private Dispatcher _dispatcher;
/// <summary>
/// for catching MediaOpened events
/// </summary>
private DispatcherOperationCallback _mediaOpened;
/// <summary>
/// for catching MediaFailed events
/// </summary>
private DispatcherOperationCallback _mediaFailed;
/// <summary>
/// for catching MediaPrerolled events
/// </summary>
private DispatcherOperationCallback _mediaPrerolled;
/// <summary>
/// for catching MediaEnded events
/// </summary>
private DispatcherOperationCallback _mediaEnded;
/// <summary>
/// for catching BufferingStarted events
/// </summary>
private DispatcherOperationCallback _bufferingStarted;
/// <summary>
/// for catching BufferingEnded events
/// </summary>
private DispatcherOperationCallback _bufferingEnded;
/// <summary>
/// for catching script command events.
/// </summary>
private DispatcherOperationCallback _scriptCommand;
/// <summary>
/// For catching new frame notifications.
/// </summary>
private DispatcherOperationCallback _newFrame;
/// <summary>
/// Helper for MediaFailed events
/// </summary>
private UniqueEventHelper<ExceptionEventArgs> _mediaFailedHelper = new UniqueEventHelper<ExceptionEventArgs>();
/// <summary>
/// Helper for MediaOpened events
/// </summary>
private UniqueEventHelper _mediaOpenedHelper = new UniqueEventHelper();
/// <summary>
/// Helper for MediaPrerolled events
/// </summary>
private UniqueEventHelper _mediaPrerolledHelper = new UniqueEventHelper();
/// <summary>
/// Helper for MediaEnded events
/// </summary>
private UniqueEventHelper _mediaEndedHelper = new UniqueEventHelper();
/// <summary>
/// Helper for BufferingStarted events
/// </summary>
private UniqueEventHelper _bufferingStartedHelper = new UniqueEventHelper();
/// <summary>
/// Helper for BufferingEnded events
/// </summary>
private UniqueEventHelper _bufferingEndedHelper = new UniqueEventHelper();
/// <summary>
/// Helper for the script command events
/// </summary>
private UniqueEventHelper<MediaScriptCommandEventArgs> _scriptCommandHelper = new UniqueEventHelper<MediaScriptCommandEventArgs>();
/// <summary>
/// Helper for the NewFrame events.
/// </summary>
private UniqueEventHelper _newFrameHelper = new UniqueEventHelper();
#endregion
}
#endregion
};
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Iscsi
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
internal enum Digest
{
[ProtocolKeyValue("None")]
None,
[ProtocolKeyValue("CRC32C")]
Crc32c
}
internal sealed class Connection : IDisposable
{
#region Parameters
private const string InitiatorNameParameter = "InitiatorName";
private const string SessionTypeParameter = "SessionType";
private const string AuthMethodParameter = "AuthMethod";
private const string HeaderDigestParameter = "HeaderDigest";
private const string DataDigestParameter = "DataDigest";
private const string MaxRecvDataSegmentLengthParameter = "MaxRecvDataSegmentLength";
private const string DefaultTime2WaitParameter = "DefaultTime2Wait";
private const string DefaultTime2RetainParameter = "DefaultTime2Retain";
private const string SendTargetsParameter = "SendTargets";
private const string TargetNameParameter = "TargetName";
private const string TargetAddressParameter = "TargetAddress";
private const string NoneValue = "None";
private const string ChapValue = "CHAP";
#endregion
private Session _session;
private Stream _stream;
private Authenticator[] _authenticators;
private ushort _id;
private uint _expectedStatusSequenceNumber = 1;
private LoginStages _loginStage = LoginStages.SecurityNegotiation;
/// <summary>
/// The set of all 'parameters' we've negotiated.
/// </summary>
private Dictionary<string, string> _negotiatedParameters;
public Connection(Session session, TargetAddress address, Authenticator[] authenticators)
{
_session = session;
_authenticators = authenticators;
#if NETCORE
TcpClient client = new TcpClient();
client.ConnectAsync(address.NetworkAddress, address.NetworkPort).Wait();
#else
TcpClient client = new TcpClient(address.NetworkAddress, address.NetworkPort);
#endif
client.NoDelay = true;
_stream = client.GetStream();
_id = session.NextConnectionId();
// Default negotiated values
HeaderDigest = Digest.None;
DataDigest = Digest.None;
MaxInitiatorTransmitDataSegmentLength = 131072;
MaxTargetReceiveDataSegmentLength = 8192;
_negotiatedParameters = new Dictionary<string, string>();
NegotiateSecurity();
NegotiateFeatures();
}
#region Protocol Features
[ProtocolKey("HeaderDigest", "None", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, UsedForDiscovery = true)]
public Digest HeaderDigest { get; set; }
[ProtocolKey("DataDigest", "None", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, UsedForDiscovery = true)]
public Digest DataDigest { get; set; }
[ProtocolKey("MaxRecvDataSegmentLength", "8192", KeyUsagePhase.OperationalNegotiation, KeySender.Initiator, KeyType.Declarative)]
internal int MaxInitiatorTransmitDataSegmentLength { get; set; }
[ProtocolKey("MaxRecvDataSegmentLength", "8192", KeyUsagePhase.OperationalNegotiation, KeySender.Target, KeyType.Declarative)]
internal int MaxTargetReceiveDataSegmentLength { get; set; }
#endregion
internal ushort Id
{
get { return _id; }
}
internal Session Session
{
get { return _session; }
}
internal LoginStages CurrentLoginStage
{
get { return _loginStage; }
}
internal LoginStages NextLoginStage
{
get
{
switch (_loginStage)
{
case LoginStages.SecurityNegotiation:
return LoginStages.LoginOperationalNegotiation;
case LoginStages.LoginOperationalNegotiation:
return LoginStages.FullFeaturePhase;
default:
return LoginStages.FullFeaturePhase;
}
}
}
internal uint ExpectedStatusSequenceNumber
{
get { return _expectedStatusSequenceNumber; }
}
public void Dispose()
{
Close(LogoutReason.CloseConnection);
}
public void Close(LogoutReason reason)
{
LogoutRequest req = new LogoutRequest(this);
byte[] packet = req.GetBytes(reason);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
ProtocolDataUnit pdu = ReadPdu();
LogoutResponse resp = ParseResponse<LogoutResponse>(pdu);
if (resp.Response != LogoutResponseCode.ClosedSuccessfully)
{
throw new InvalidProtocolException("Target indicated failure during logout: " + resp.Response);
}
_stream.Dispose();
}
/// <summary>
/// Sends an SCSI command (aka task) to a LUN via the connected target.
/// </summary>
/// <param name="cmd">The command to send.</param>
/// <param name="outBuffer">The data to send with the command.</param>
/// <param name="outBufferOffset">The offset of the first byte to send.</param>
/// <param name="outBufferCount">The number of bytes to send, if any.</param>
/// <param name="inBuffer">The buffer to fill with returned data.</param>
/// <param name="inBufferOffset">The first byte to fill with returned data.</param>
/// <param name="inBufferMax">The maximum amount of data to receive.</param>
/// <returns>The number of bytes received.</returns>
public int Send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax)
{
CommandRequest req = new CommandRequest(this, cmd.TargetLun);
int toSend = Math.Min(Math.Min(outBufferCount, _session.ImmediateData ? _session.FirstBurstLength : 0), MaxTargetReceiveDataSegmentLength);
byte[] packet = req.GetBytes(cmd, outBuffer, outBufferOffset, toSend, true, inBufferMax != 0, outBufferCount != 0, (uint)(outBufferCount != 0 ? outBufferCount : inBufferMax));
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
int numApproved = 0;
int numSent = toSend;
int pktsSent = 0;
while (numSent < outBufferCount)
{
ProtocolDataUnit pdu = ReadPdu();
ReadyToTransferPacket resp = ParseResponse<ReadyToTransferPacket>(pdu);
numApproved = (int)resp.DesiredTransferLength;
uint targetTransferTag = resp.TargetTransferTag;
while (numApproved > 0)
{
toSend = Math.Min(Math.Min(outBufferCount - numSent, numApproved), MaxTargetReceiveDataSegmentLength);
DataOutPacket pkt = new DataOutPacket(this, cmd.TargetLun);
packet = pkt.GetBytes(outBuffer, outBufferOffset + numSent, toSend, toSend == numApproved, pktsSent++, (uint)numSent, targetTransferTag);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
numApproved -= toSend;
numSent += toSend;
}
}
bool isFinal = false;
int numRead = 0;
while (!isFinal)
{
ProtocolDataUnit pdu = ReadPdu();
if (pdu.OpCode == OpCode.ScsiResponse)
{
Response resp = ParseResponse<Response>(pdu);
if (resp.StatusPresent && resp.Status == ScsiStatus.CheckCondition)
{
ushort senseLength = Utilities.ToUInt16BigEndian(pdu.ContentData, 0);
byte[] senseData = new byte[senseLength];
Array.Copy(pdu.ContentData, 2, senseData, 0, senseLength);
throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure", senseData);
}
else if (resp.StatusPresent && resp.Status != ScsiStatus.Good)
{
throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure");
}
isFinal = resp.Header.FinalPdu;
}
else if (pdu.OpCode == OpCode.ScsiDataIn)
{
DataInPacket resp = ParseResponse<DataInPacket>(pdu);
if (resp.StatusPresent && resp.Status != ScsiStatus.Good)
{
throw new ScsiCommandException(resp.Status, "Target indicated SCSI failure");
}
if (resp.ReadData != null)
{
Array.Copy(resp.ReadData, 0, inBuffer, (int)(inBufferOffset + resp.BufferOffset), resp.ReadData.Length);
numRead += resp.ReadData.Length;
}
isFinal = resp.Header.FinalPdu;
}
}
_session.NextTaskTag();
_session.NextCommandSequenceNumber();
return numRead;
}
public T Send<T>(ScsiCommand cmd, byte[] buffer, int offset, int count, int expected)
where T : ScsiResponse, new()
{
byte[] tempBuffer = new byte[expected];
int numRead = Send(cmd, buffer, offset, count, tempBuffer, 0, expected);
T result = new T();
result.ReadFrom(tempBuffer, 0, numRead);
return result;
}
public TargetInfo[] EnumerateTargets()
{
TextBuffer parameters = new TextBuffer();
parameters.Add(SendTargetsParameter, "All");
byte[] paramBuffer = new byte[parameters.Size];
parameters.WriteTo(paramBuffer, 0);
TextRequest req = new TextRequest(this);
byte[] packet = req.GetBytes(0, paramBuffer, 0, paramBuffer.Length, true);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
ProtocolDataUnit pdu = ReadPdu();
TextResponse resp = ParseResponse<TextResponse>(pdu);
TextBuffer buffer = new TextBuffer();
if (resp.TextData != null)
{
buffer.ReadFrom(resp.TextData, 0, resp.TextData.Length);
}
List<TargetInfo> targets = new List<TargetInfo>();
string currentTarget = null;
List<TargetAddress> currentAddresses = null;
foreach (var line in buffer.Lines)
{
if (currentTarget == null)
{
if (line.Key != TargetNameParameter)
{
throw new InvalidProtocolException("Unexpected response parameter " + line.Key + " expected " + TargetNameParameter);
}
currentTarget = line.Value;
currentAddresses = new List<TargetAddress>();
}
else if (line.Key == TargetNameParameter)
{
targets.Add(new TargetInfo(currentTarget, currentAddresses.ToArray()));
currentTarget = line.Value;
currentAddresses.Clear();
}
else if (line.Key == TargetAddressParameter)
{
currentAddresses.Add(TargetAddress.Parse(line.Value));
}
}
if (currentTarget != null)
{
targets.Add(new TargetInfo(currentTarget, currentAddresses.ToArray()));
}
return targets.ToArray();
}
internal void SeenStatusSequenceNumber(uint number)
{
if (number != 0 && number != _expectedStatusSequenceNumber)
{
throw new InvalidProtocolException("Unexpected status sequence number " + number + ", expected " + _expectedStatusSequenceNumber);
}
_expectedStatusSequenceNumber = number + 1;
}
private void NegotiateSecurity()
{
_loginStage = LoginStages.SecurityNegotiation;
//
// Establish the contents of the request
//
TextBuffer parameters = new TextBuffer();
GetParametersToNegotiate(parameters, KeyUsagePhase.SecurityNegotiation, _session.SessionType);
_session.GetParametersToNegotiate(parameters, KeyUsagePhase.SecurityNegotiation);
string authParam = _authenticators[0].Identifier;
for (int i = 1; i < _authenticators.Length; ++i)
{
authParam += "," + _authenticators[i].Identifier;
}
parameters.Add(AuthMethodParameter, authParam);
//
// Send the request...
//
byte[] paramBuffer = new byte[parameters.Size];
parameters.WriteTo(paramBuffer, 0);
LoginRequest req = new LoginRequest(this);
byte[] packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
//
// Read the response...
//
TextBuffer settings = new TextBuffer();
ProtocolDataUnit pdu = ReadPdu();
LoginResponse resp = ParseResponse<LoginResponse>(pdu);
if (resp.StatusCode != LoginStatusCode.Success)
{
throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode);
}
if (resp.Continue)
{
MemoryStream ms = new MemoryStream();
ms.Write(resp.TextData, 0, resp.TextData.Length);
while (resp.Continue)
{
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
ms.Write(resp.TextData, 0, resp.TextData.Length);
}
settings.ReadFrom(ms.ToArray(), 0, (int)ms.Length);
}
else if (resp.TextData != null)
{
settings.ReadFrom(resp.TextData, 0, resp.TextData.Length);
}
Authenticator authenticator = null;
for (int i = 0; i < _authenticators.Length; ++i)
{
if (settings[AuthMethodParameter] == _authenticators[i].Identifier)
{
authenticator = _authenticators[i];
break;
}
}
settings.Remove(AuthMethodParameter);
settings.Remove("TargetPortalGroupTag");
if (authenticator == null)
{
throw new LoginException("iSCSI Target specified an unsupported authentication method: " + settings[AuthMethodParameter]);
}
parameters = new TextBuffer();
ConsumeParameters(settings, parameters);
while (!resp.Transit)
{
//
// Send the request...
//
parameters = new TextBuffer();
authenticator.GetParameters(parameters);
paramBuffer = new byte[parameters.Size];
parameters.WriteTo(paramBuffer, 0);
req = new LoginRequest(this);
packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
//
// Read the response...
//
settings = new TextBuffer();
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
if (resp.StatusCode != LoginStatusCode.Success)
{
throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode);
}
if (resp.TextData != null && resp.TextData.Length != 0)
{
if (resp.Continue)
{
MemoryStream ms = new MemoryStream();
ms.Write(resp.TextData, 0, resp.TextData.Length);
while (resp.Continue)
{
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
ms.Write(resp.TextData, 0, resp.TextData.Length);
}
settings.ReadFrom(ms.ToArray(), 0, (int)ms.Length);
}
else
{
settings.ReadFrom(resp.TextData, 0, resp.TextData.Length);
}
authenticator.SetParameters(settings);
}
}
if (resp.NextStage != NextLoginStage)
{
throw new LoginException("iSCSI Target wants to transition to a different login stage: " + resp.NextStage + " (expected: " + NextLoginStage + ")");
}
_loginStage = resp.NextStage;
}
private void NegotiateFeatures()
{
//
// Send the request...
//
TextBuffer parameters = new TextBuffer();
GetParametersToNegotiate(parameters, KeyUsagePhase.OperationalNegotiation, _session.SessionType);
_session.GetParametersToNegotiate(parameters, KeyUsagePhase.OperationalNegotiation);
byte[] paramBuffer = new byte[parameters.Size];
parameters.WriteTo(paramBuffer, 0);
LoginRequest req = new LoginRequest(this);
byte[] packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
//
// Read the response...
//
TextBuffer settings = new TextBuffer();
ProtocolDataUnit pdu = ReadPdu();
LoginResponse resp = ParseResponse<LoginResponse>(pdu);
if (resp.StatusCode != LoginStatusCode.Success)
{
throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode);
}
if (resp.Continue)
{
MemoryStream ms = new MemoryStream();
ms.Write(resp.TextData, 0, resp.TextData.Length);
while (resp.Continue)
{
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
ms.Write(resp.TextData, 0, resp.TextData.Length);
}
settings.ReadFrom(ms.ToArray(), 0, (int)ms.Length);
}
else if (resp.TextData != null)
{
settings.ReadFrom(resp.TextData, 0, resp.TextData.Length);
}
parameters = new TextBuffer();
ConsumeParameters(settings, parameters);
while (!resp.Transit || parameters.Count != 0)
{
paramBuffer = new byte[parameters.Size];
parameters.WriteTo(paramBuffer, 0);
req = new LoginRequest(this);
packet = req.GetBytes(paramBuffer, 0, paramBuffer.Length, true);
_stream.Write(packet, 0, packet.Length);
_stream.Flush();
//
// Read the response...
//
settings = new TextBuffer();
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
if (resp.StatusCode != LoginStatusCode.Success)
{
throw new LoginException("iSCSI Target indicated login failure: " + resp.StatusCode);
}
parameters = new TextBuffer();
if (resp.TextData != null)
{
if (resp.Continue)
{
MemoryStream ms = new MemoryStream();
ms.Write(resp.TextData, 0, resp.TextData.Length);
while (resp.Continue)
{
pdu = ReadPdu();
resp = ParseResponse<LoginResponse>(pdu);
ms.Write(resp.TextData, 0, resp.TextData.Length);
}
settings.ReadFrom(ms.ToArray(), 0, (int)ms.Length);
}
else
{
settings.ReadFrom(resp.TextData, 0, resp.TextData.Length);
}
ConsumeParameters(settings, parameters);
}
}
if (resp.NextStage != NextLoginStage)
{
throw new LoginException("iSCSI Target wants to transition to a different login stage: " + resp.NextStage + " (expected: " + NextLoginStage + ")");
}
_loginStage = resp.NextStage;
}
private ProtocolDataUnit ReadPdu()
{
ProtocolDataUnit pdu = ProtocolDataUnit.ReadFrom(_stream, HeaderDigest != Digest.None, DataDigest != Digest.None);
if (pdu.OpCode == OpCode.Reject)
{
RejectPacket pkt = new RejectPacket();
pkt.Parse(pdu);
throw new IscsiException("Target sent reject packet, reason " + pkt.Reason);
}
return pdu;
}
private void GetParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase, SessionType sessionType)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null)
{
object value = propInfo.GetGetMethod(true).Invoke(this, null);
if (attr.ShouldTransmit(value, propInfo.PropertyType, phase, sessionType == SessionType.Discovery))
{
parameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
private void ConsumeParameters(TextBuffer inParameters, TextBuffer outParameters)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null && (attr.Sender & KeySender.Target) != 0)
{
if (inParameters[attr.Name] != null)
{
object value = ProtocolKeyAttribute.GetValueAsObject(inParameters[attr.Name], propInfo.PropertyType);
propInfo.GetSetMethod(true).Invoke(this, new object[] { value });
inParameters.Remove(attr.Name);
if (attr.Type == KeyType.Negotiated && !_negotiatedParameters.ContainsKey(attr.Name))
{
value = propInfo.GetGetMethod(true).Invoke(this, null);
outParameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
_session.ConsumeParameters(inParameters, outParameters);
foreach (var param in inParameters.Lines)
{
outParameters.Add(param.Key, "NotUnderstood");
}
}
private T ParseResponse<T>(ProtocolDataUnit pdu)
where T : BaseResponse, new()
{
BaseResponse resp;
switch (pdu.OpCode)
{
case OpCode.LoginResponse:
resp = new LoginResponse();
break;
case OpCode.LogoutResponse:
resp = new LogoutResponse();
break;
case OpCode.ReadyToTransfer:
resp = new ReadyToTransferPacket();
break;
case OpCode.Reject:
resp = new RejectPacket();
break;
case OpCode.ScsiDataIn:
resp = new DataInPacket();
break;
case OpCode.ScsiResponse:
resp = new Response();
break;
case OpCode.TextResponse:
resp = new TextResponse();
break;
default:
throw new InvalidProtocolException("Unrecognized response opcode: " + pdu.OpCode);
}
resp.Parse(pdu);
if (resp.StatusPresent)
{
SeenStatusSequenceNumber(resp.StatusSequenceNumber);
}
T result = resp as T;
if (result == null)
{
throw new InvalidProtocolException("Unexpected response, expected " + typeof(T) + ", got " + result.GetType());
}
return result;
}
}
}
| |
/*
Copyright 2014 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace DriveProxy.API
{
partial class DriveService
{
protected internal class MimeType
{
private static IDictionary<string, string> _knownTypes;
public static IDictionary<string, string> KnownTypes
{
get
{
if (_knownTypes == null)
{
_knownTypes = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
#region Big list of mime types
//NOTES
//-This real list is entirely dependent on what is installed on a user's machine
//-This list is sourced from a sample workspace, and we may need to convert it to a registry looks/hard coded list later
//-Combination of values from Windows 7 Registry and C:\Windows\System32\inetsrv\config\applicationHost.config
//-some added, including .7z and .dat
{".323", "text/h323"},
{".3g2", "video/3gpp2"},
{".3gp", "video/3gpp"},
{".3gp2", "video/3gpp2"},
{".3gpp", "video/3gpp"},
{".7z", "application/x-7z-compressed"},
{".aa", "audio/audible"},
{".AAC", "audio/aac"},
{".aaf", "application/octet-stream"},
{".aax", "audio/vnd.audible.aax"},
{".ac3", "audio/ac3"},
{".aca", "application/octet-stream"},
{".accda", "application/msaccess.addin"},
{".accdb", "application/msaccess"},
{".accdc", "application/msaccess.cab"},
{".accde", "application/msaccess"},
{".accdr", "application/msaccess.runtime"},
{".accdt", "application/msaccess"},
{".accdw", "application/msaccess.webapplication"},
{".accft", "application/msaccess.ftemplate"},
{".acx", "application/internet-property-stream"},
{".AddIn", "text/xml"},
{".ade", "application/msaccess"},
{".adobebridge", "application/x-bridge-url"},
{".adp", "application/msaccess"},
{".ADT", "audio/vnd.dlna.adts"},
{".ADTS", "audio/aac"},
{".afm", "application/octet-stream"},
{".ai", "application/postscript"},
{".aif", "audio/x-aiff"},
{".aifc", "audio/aiff"},
{".aiff", "audio/aiff"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".amc", "application/x-mpeg"},
{".application", "application/x-ms-application"},
{".art", "image/x-jg"},
{".asa", "application/xml"},
{".asax", "application/xml"},
{".ascx", "application/xml"},
{".asd", "application/octet-stream"},
{".asf", "video/x-ms-asf"},
{".ashx", "application/xml"},
{".asi", "application/octet-stream"},
{".asm", "text/plain"},
{".asmx", "application/xml"},
{".aspx", "application/xml"},
{".asr", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".atom", "application/atom+xml"},
{".au", "audio/basic"},
{".avi", "video/x-msvideo"},
{".axs", "application/olescript"},
{".bas", "text/plain"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".cab", "application/octet-stream"},
{".caf", "audio/x-caf"},
{".calx", "application/vnd.ms-office.calx"},
{".cat", "application/vnd.ms-pki.seccat"},
{".cc", "text/plain"},
{".cd", "text/plain"},
{".cdda", "audio/aiff"},
{".cdf", "application/x-cdf"},
{".cer", "application/x-x509-ca-cert"},
{".chm", "application/octet-stream"},
{".class", "application/x-java-applet"},
{".clp", "application/x-msclip"},
{".cmx", "image/x-cmx"},
{".cnf", "text/plain"},
{".cod", "image/cis-cod"},
{".config", "application/xml"},
{".contact", "text/x-ms-contact"},
{".coverage", "application/xml"},
{".cpio", "application/x-cpio"},
{".cpp", "text/plain"},
{".crd", "application/x-mscardfile"},
{".crl", "application/pkix-crl"},
{".crt", "application/x-x509-ca-cert"},
{".cs", "text/plain"},
{".csdproj", "text/plain"},
{".csh", "application/x-csh"},
{".csproj", "text/plain"},
{".css", "text/css"},
{".csv", "text/csv"},
{".cur", "application/octet-stream"},
{".cxx", "text/plain"},
{".dat", "application/octet-stream"},
{".datasource", "application/xml"},
{".dbproj", "text/plain"},
{".dcr", "application/x-director"},
{".def", "text/plain"},
{".deploy", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dgml", "application/xml"},
{".dib", "image/bmp"},
{".dif", "video/x-dv"},
{".dir", "application/x-director"},
{".disco", "text/xml"},
{".dll", "application/x-msdownload"},
{".dll.config", "text/xml"},
{".dlm", "text/dlm"},
{".doc", "application/msword"},
{".docm", "application/vnd.ms-word.document.macroEnabled.12"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dot", "application/msword"},
{".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dsp", "application/octet-stream"},
{".dsw", "text/plain"},
{".dtd", "text/xml"},
{".dtsConfig", "text/xml"},
{".dv", "video/x-dv"},
{".dvi", "application/x-dvi"},
{".dwf", "drawing/x-dwf"},
{".dwp", "application/octet-stream"},
{".dxr", "application/x-director"},
{".eml", "message/rfc822"},
{".emz", "application/octet-stream"},
{".eot", "application/octet-stream"},
{".eps", "application/postscript"},
{".etl", "application/etl"},
{".etx", "text/x-setext"},
{".evy", "application/envoy"},
{".exe", "application/octet-stream"},
{".exe.config", "text/xml"},
{".fdf", "application/vnd.fdf"},
{".fif", "application/fractals"},
{".filters", "Application/xml"},
{".fla", "application/octet-stream"},
{".flr", "x-world/x-vrml"},
{".flv", "video/x-flv"},
{".fsscript", "application/fsharp-script"},
{".fsx", "application/fsharp-script"},
{".generictest", "application/xml"},
{".gif", "image/gif"},
{".group", "text/x-ms-group"},
{".gsm", "audio/x-gsm"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".hdf", "application/x-hdf"},
{".hdml", "text/x-hdml"},
{".hhc", "application/x-oleobject"},
{".hhk", "application/octet-stream"},
{".hhp", "application/octet-stream"},
{".hlp", "application/winhlp"},
{".hpp", "text/plain"},
{".hqx", "application/mac-binhex40"},
{".hta", "application/hta"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".htt", "text/webviewhtml"},
{".hxa", "application/xml"},
{".hxc", "application/xml"},
{".hxd", "application/octet-stream"},
{".hxe", "application/xml"},
{".hxf", "application/xml"},
{".hxh", "application/octet-stream"},
{".hxi", "application/octet-stream"},
{".hxk", "application/xml"},
{".hxq", "application/octet-stream"},
{".hxr", "application/octet-stream"},
{".hxs", "application/octet-stream"},
{".hxt", "text/html"},
{".hxv", "application/xml"},
{".hxw", "application/octet-stream"},
{".hxx", "text/plain"},
{".i", "text/plain"},
{".ico", "image/x-icon"},
{".ics", "application/octet-stream"},
{".idl", "text/plain"},
{".ief", "image/ief"},
{".iii", "application/x-iphone"},
{".inc", "text/plain"},
{".inf", "application/octet-stream"},
{".inl", "text/plain"},
{".ins", "application/x-internet-signup"},
{".ipa", "application/x-itunes-ipa"},
{".ipg", "application/x-itunes-ipg"},
{".ipproj", "text/plain"},
{".ipsw", "application/x-itunes-ipsw"},
{".iqy", "text/x-ms-iqy"},
{".isp", "application/x-internet-signup"},
{".ite", "application/x-itunes-ite"},
{".itlp", "application/x-itunes-itlp"},
{".itms", "application/x-itunes-itms"},
{".itpc", "application/x-itunes-itpc"},
{".IVF", "video/x-ivf"},
{".jar", "application/java-archive"},
{".java", "application/octet-stream"},
{".jck", "application/liquidmotion"},
{".jcz", "application/liquidmotion"},
{".jfif", "image/pjpeg"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpb", "application/octet-stream"},
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".jsx", "text/jscript"},
{".jsxbin", "text/plain"},
{".latex", "application/x-latex"},
{".library-ms", "application/windows-library+xml"},
{".lit", "application/x-ms-reader"},
{".loadtest", "application/xml"},
{".lpk", "application/octet-stream"},
{".lsf", "video/x-la-asf"},
{".lst", "text/plain"},
{".lsx", "video/x-la-asf"},
{".lzh", "application/octet-stream"},
{".m13", "application/x-msmediaview"},
{".m14", "application/x-msmediaview"},
{".m1v", "video/mpeg"},
{".m2t", "video/vnd.dlna.mpeg-tts"},
{".m2ts", "video/vnd.dlna.mpeg-tts"},
{".m2v", "video/mpeg"},
{".m3u", "audio/x-mpegurl"},
{".m3u8", "audio/x-mpegurl"},
{".m4a", "audio/m4a"},
{".m4b", "audio/m4b"},
{".m4p", "audio/m4p"},
{".m4r", "audio/x-m4r"},
{".m4v", "video/x-m4v"},
{".mac", "image/x-macpaint"},
{".mak", "text/plain"},
{".man", "application/x-troff-man"},
{".manifest", "application/x-ms-manifest"},
{".map", "text/plain"},
{".master", "application/xml"},
{".mda", "application/msaccess"},
{".mdb", "application/x-msaccess"},
{".mde", "application/msaccess"},
{".mdp", "application/octet-stream"},
{".me", "application/x-troff-me"},
{".mfp", "application/x-shockwave-flash"},
{".mht", "message/rfc822"},
{".mhtml", "message/rfc822"},
{".mid", "audio/mid"},
{".midi", "audio/mid"},
{".mix", "application/octet-stream"},
{".mk", "text/plain"},
{".mmf", "application/x-smaf"},
{".mno", "text/xml"},
{".mny", "application/x-msmoney"},
{".mod", "video/mpeg"},
{".mov", "video/quicktime"},
{".movie", "video/x-sgi-movie"},
{".mp2", "video/mpeg"},
{".mp2v", "video/mpeg"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mp4v", "video/mp4"},
{".mpa", "video/mpeg"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpf", "application/vnd.ms-mediapackage"},
{".mpg", "video/mpeg"},
{".mpp", "application/vnd.ms-project"},
{".mpv2", "video/mpeg"},
{".mqv", "video/quicktime"},
{".ms", "application/x-troff-ms"},
{".msi", "application/octet-stream"},
{".mso", "application/octet-stream"},
{".mts", "video/vnd.dlna.mpeg-tts"},
{".mtx", "application/xml"},
{".mvb", "application/x-msmediaview"},
{".mvc", "application/x-miva-compiled"},
{".mxp", "application/x-mmxp"},
{".nc", "application/x-netcdf"},
{".nsc", "video/x-ms-asf"},
{".nws", "message/rfc822"},
{".ocx", "application/octet-stream"},
{".oda", "application/oda"},
{".odc", "text/x-ms-odc"},
{".odh", "text/plain"},
{".odl", "text/plain"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/oleobject"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".one", "application/onenote"},
{".onea", "application/onenote"},
{".onepkg", "application/onenote"},
{".onetmp", "application/onenote"},
{".onetoc", "application/onenote"},
{".onetoc2", "application/onenote"},
{".orderedtest", "application/xml"},
{".osdx", "application/opensearchdescription+xml"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7b", "application/x-pkcs7-certificates"},
{".p7c", "application/pkcs7-mime"},
{".p7m", "application/pkcs7-mime"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7s", "application/pkcs7-signature"},
{".pbm", "image/x-portable-bitmap"},
{".pcast", "application/x-podcast"},
{".pct", "image/pict"},
{".pcx", "application/octet-stream"},
{".pcz", "application/octet-stream"},
{".pdf", "application/pdf"},
{".pfb", "application/octet-stream"},
{".pfm", "application/octet-stream"},
{".pfx", "application/x-pkcs12"},
{".pgm", "image/x-portable-graymap"},
{".pic", "image/pict"},
{".pict", "image/pict"},
{".pkgdef", "text/plain"},
{".pkgundef", "text/plain"},
{".pko", "application/vnd.ms-pki.pko"},
{".pls", "audio/scpls"},
{".pma", "application/x-perfmon"},
{".pmc", "application/x-perfmon"},
{".pml", "application/x-perfmon"},
{".pmr", "application/x-perfmon"},
{".pmw", "application/x-perfmon"},
{".png", "image/png"},
{".pnm", "image/x-portable-anymap"},
{".pnt", "image/x-macpaint"},
{".pntg", "image/x-macpaint"},
{".pnz", "image/png"},
{".pot", "application/vnd.ms-powerpoint"},
{".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppa", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{".ppm", "image/x-portable-pixmap"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prf", "application/pics-rules"},
{".prm", "application/octet-stream"},
{".prx", "application/octet-stream"},
{".ps", "application/postscript"},
{".psc1", "application/PowerShell"},
{".psd", "application/octet-stream"},
{".psess", "application/xml"},
{".psm", "application/octet-stream"},
{".psp", "application/octet-stream"},
{".pub", "application/x-mspublisher"},
{".pwz", "application/vnd.ms-powerpoint"},
{".qht", "text/x-html-insertion"},
{".qhtm", "text/x-html-insertion"},
{".qt", "video/quicktime"},
{".qti", "image/x-quicktime"},
{".qtif", "image/x-quicktime"},
{".qtl", "application/x-quicktimeplayer"},
{".qxd", "application/octet-stream"},
{".ra", "audio/x-pn-realaudio"},
{".ram", "audio/x-pn-realaudio"},
{".rar", "application/octet-stream"},
{".ras", "image/x-cmu-raster"},
{".rat", "application/rat-file"},
{".rc", "text/plain"},
{".rc2", "text/plain"},
{".rct", "text/plain"},
{".rdlc", "application/xml"},
{".resx", "application/xml"},
{".rf", "image/vnd.rn-realflash"},
{".rgb", "image/x-rgb"},
{".rgs", "text/plain"},
{".rm", "application/vnd.rn-realmedia"},
{".rmi", "audio/mid"},
{".rmp", "application/vnd.rn-rn_music_package"},
{".roff", "application/x-troff"},
{".rpm", "audio/x-pn-realaudio-plugin"},
{".rqy", "text/x-ms-rqy"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".ruleset", "application/xml"},
{".s", "text/plain"},
{".safariextz", "application/x-safari-safariextz"},
{".scd", "application/x-msschedule"},
{".sct", "text/scriptlet"},
{".sd2", "audio/x-sd2"},
{".sdp", "application/sdp"},
{".sea", "application/octet-stream"},
{".searchConnector-ms", "application/windows-search-connector+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".settings", "application/xml"},
{".sgimb", "application/x-sgimb"},
{".sgml", "text/sgml"},
{".sh", "application/x-sh"},
{".shar", "application/x-shar"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".sitemap", "application/xml"},
{".skin", "application/xml"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".slk", "application/vnd.ms-excel"},
{".sln", "text/plain"},
{".slupkg-ms", "application/x-ms-license"},
{".smd", "audio/x-smd"},
{".smi", "application/octet-stream"},
{".smx", "audio/x-smd"},
{".smz", "audio/x-smd"},
{".snd", "audio/basic"},
{".snippet", "application/xml"},
{".snp", "application/octet-stream"},
{".sol", "text/plain"},
{".sor", "text/plain"},
{".spc", "application/x-pkcs7-certificates"},
{".spl", "application/futuresplash"},
{".src", "application/x-wais-source"},
{".srf", "text/plain"},
{".SSISDeploymentManifest", "text/xml"},
{".ssm", "application/streamingmedia"},
{".sst", "application/vnd.ms-pki.certstore"},
{".stl", "application/vnd.ms-pki.stl"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".svc", "application/xml"},
{".swf", "application/x-shockwave-flash"},
{".t", "application/x-troff"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".testrunconfig", "application/xml"},
{".testsettings", "application/xml"},
{".tex", "application/x-tex"},
{".texi", "application/x-texinfo"},
{".texinfo", "application/x-texinfo"},
{".tgz", "application/x-compressed"},
{".thmx", "application/vnd.ms-officetheme"},
{".thn", "application/octet-stream"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".tlh", "text/plain"},
{".tli", "text/plain"},
{".toc", "application/octet-stream"},
{".tr", "application/x-troff"},
{".trm", "application/x-msterminal"},
{".trx", "application/xml"},
{".ts", "video/vnd.dlna.mpeg-tts"},
{".tsv", "text/tab-separated-values"},
{".ttf", "application/octet-stream"},
{".tts", "video/vnd.dlna.mpeg-tts"},
{".txt", "text/plain"},
{".u32", "application/octet-stream"},
{".uls", "text/iuls"},
{".user", "text/plain"},
{".ustar", "application/x-ustar"},
{".vb", "text/plain"},
{".vbdproj", "text/plain"},
{".vbk", "video/mpeg"},
{".vbproj", "text/plain"},
{".vbs", "text/vbscript"},
{".vcf", "text/x-vcard"},
{".vcproj", "Application/xml"},
{".vcs", "text/plain"},
{".vcxproj", "Application/xml"},
{".vddproj", "text/plain"},
{".vdp", "text/plain"},
{".vdproj", "text/plain"},
{".vdx", "application/vnd.ms-visio.viewer"},
{".vml", "text/xml"},
{".vscontent", "application/xml"},
{".vsct", "text/xml"},
{".vsd", "application/vnd.visio"},
{".vsi", "application/ms-vsi"},
{".vsix", "application/vsix"},
{".vsixlangpack", "text/xml"},
{".vsixmanifest", "text/xml"},
{".vsmdi", "application/xml"},
{".vspscc", "text/plain"},
{".vss", "application/vnd.visio"},
{".vsscc", "text/plain"},
{".vssettings", "text/xml"},
{".vssscc", "text/plain"},
{".vst", "application/vnd.visio"},
{".vstemplate", "text/xml"},
{".vsto", "application/x-ms-vsto"},
{".vsw", "application/vnd.visio"},
{".vsx", "application/vnd.visio"},
{".vtx", "application/vnd.visio"},
{".wav", "audio/wav"},
{".wave", "audio/wav"},
{".wax", "audio/x-ms-wax"},
{".wbk", "application/msword"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wcm", "application/vnd.ms-works"},
{".wdb", "application/vnd.ms-works"},
{".wdp", "image/vnd.ms-photo"},
{".webarchive", "application/x-safari-webarchive"},
{".webtest", "application/xml"},
{".wiq", "application/xml"},
{".wiz", "application/msword"},
{".wks", "application/vnd.ms-works"},
{".WLMP", "application/wlmoviemaker"},
{".wlpginstall", "application/x-wlpg-detect"},
{".wlpginstall3", "application/x-wlpg3-detect"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wmd", "application/x-ms-wmd"},
{".wmf", "application/x-msmetafile"},
{".wml", "text/vnd.wap.wml"},
{".wmlc", "application/vnd.wap.wmlc"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wmp", "video/x-ms-wmp"},
{".wmv", "video/x-ms-wmv"},
{".wmx", "video/x-ms-wmx"},
{".wmz", "application/x-ms-wmz"},
{".wpl", "application/vnd.ms-wpl"},
{".wps", "application/vnd.ms-works"},
{".wri", "application/x-mswrite"},
{".wrl", "x-world/x-vrml"},
{".wrz", "x-world/x-vrml"},
{".wsc", "text/scriptlet"},
{".wsdl", "text/xml"},
{".wvx", "video/x-ms-wvx"},
{".x", "application/directx"},
{".xaf", "x-world/x-vrml"},
{".xaml", "application/xaml+xml"},
{".xap", "application/x-silverlight-app"},
{".xbap", "application/x-ms-xbap"},
{".xbm", "image/x-xbitmap"},
{".xdr", "text/plain"},
{".xht", "application/xhtml+xml"},
{".xhtml", "application/xhtml+xml"},
{".xla", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{".xlc", "application/vnd.ms-excel"},
{".xld", "application/vnd.ms-excel"},
{".xlk", "application/vnd.ms-excel"},
{".xll", "application/vnd.ms-excel"},
{".xlm", "application/vnd.ms-excel"},
{".xls", "application/vnd.ms-excel"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xlt", "application/vnd.ms-excel"},
{".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xlw", "application/vnd.ms-excel"},
{".xml", "text/xml"},
{".xmta", "application/xml"},
{".xof", "x-world/x-vrml"},
{".XOML", "text/plain"},
{".xpm", "image/x-xpixmap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".xrm-ms", "text/xml"},
{".xsc", "application/xml"},
{".xsd", "text/xml"},
{".xsf", "text/xml"},
{".xsl", "text/xml"},
{".xslt", "text/xml"},
{".xsn", "application/octet-stream"},
{".xss", "application/xml"},
{".xtp", "application/octet-stream"},
{".xwd", "image/x-xwindowdump"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
#endregion
};
}
return _knownTypes;
}
}
public static string Folder
{
get { return "application/vnd.google-apps.folder"; }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This test tests that we throw TypeLoadException when trying to load explicit generic class/struct, since we do not allow
// explicit generic types anymore.
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public class Gen1<T>
{
// multiple fields, first generic
[FieldOffset(0)] public T t;
[FieldOffset(16)]public int _int0 = 0;
}
[StructLayout(LayoutKind.Explicit)]
public class Gen2<T>
{
// single field, generic
[FieldOffset(0)] public T t;
}
[StructLayout(LayoutKind.Explicit)]
public class Gen3<T>
{
// single field, not generic
[FieldOffset(0)] public int t;
}
[StructLayout(LayoutKind.Explicit)]
public class Gen4<T>
{
// multiple generic fields
[FieldOffset(0)] public T t1;
[FieldOffset(16)] public T t2;
[FieldOffset(32)] public T t3;
}
[StructLayout(LayoutKind.Explicit)]
public struct Gen5<T>
{
// multiple fields, generic is not first in a struct
[FieldOffset(0)] public int t1;
[FieldOffset(16)] public T t2;
}
[StructLayout(LayoutKind.Explicit)]
public struct Gen6<T>
{
// single generic field in a struct
[FieldOffset(0)] public T t1;
}
[StructLayout(LayoutKind.Sequential)]
public struct Gen8<T>
{
// single generic field in a struct
public T t1;
public int i;
}
[StructLayout(LayoutKind.Explicit)]
public class Gen7<T>
{
// nested sequential struct inside explicit struct
[FieldOffset(0)]
public Gen8<int> struct_Gen8;
[FieldOffset(0)] public T t;
}
class Test
{
public static void goGen1()
{
Gen1<int> gen1 = new Gen1<int>();
gen1.t = 5;
Console.WriteLine("Gen1: FAIL");
}
public static void goGen2()
{
Gen2<int> gen2 = new Gen2<int>();
gen2.t = 5;
Console.WriteLine("Gen2: FAIL");
}
public static void goGen3()
{
Gen3<int> gen3 = new Gen3<int>();
gen3.t = 5;
Console.WriteLine("Gen3: FAIL");
}
public static void goGen4()
{
Gen4<int> gen4 = new Gen4<int>();
gen4.t1 = 5;
Console.WriteLine("Gen4: FAIL");
}
public static void goGen5(){
Gen5<int> gen5 = new Gen5<int>();
gen5.t1 = 5;
Console.WriteLine("Gen5: FAIL");
}
public static void goGen6(){
Gen6<int> gen6 = new Gen6<int>();
gen6.t1 = 5;
Console.WriteLine("Gen6: FAIL");
}
public static void goGen7(){
Gen7<int> gen7 = new Gen7<int>();
gen7.t = 5;
gen7.struct_Gen8 = new Gen8<int>();
Console.WriteLine("Gen7: FAIL");
}
static int Main(string[] args)
{
bool pass = true;
try
{
goGen1();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen1: PASS");
}
try
{
goGen2();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen2: PASS");
}
try
{
goGen3();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen3: PASS");
}
try
{
goGen4();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen4: PASS");
}
try
{
goGen5();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen5: PASS");
}
try
{
goGen6();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen6: PASS");
}
try
{
goGen7();
pass = false;
}
catch(TypeLoadException)
{
Console.WriteLine("Gen7: PASS");
}
if(pass)
{
Console.WriteLine("Test passed");
return 100;
}
else
{
Console.WriteLine("Test failed");
return 101;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
namespace Godot
{
/// <summary>
/// 2-element structure that can be used to represent 2D grid coordinates or pairs of integers.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2i : IEquatable<Vector2i>
{
/// <summary>
/// Enumerated index values for the axes.
/// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>.
/// </summary>
public enum Axis
{
X = 0,
Y
}
/// <summary>
/// The vector's X component. Also accessible by using the index position `[0]`.
/// </summary>
public int x;
/// <summary>
/// The vector's Y component. Also accessible by using the index position `[1]`.
/// </summary>
public int y;
/// <summary>
/// Access vector components using their index.
/// </summary>
/// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`.</value>
public int this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
x = value;
return;
case 1:
y = value;
return;
default:
throw new IndexOutOfRangeException();
}
}
}
/// <summary>
/// Returns a new vector with all components in absolute values (i.e. positive).
/// </summary>
/// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns>
public Vector2i Abs()
{
return new Vector2i(Mathf.Abs(x), Mathf.Abs(y));
}
/// <summary>
/// Returns this vector's angle with respect to the X axis, or (1, 0) vector, in radians.
///
/// Equivalent to the result of <see cref="Mathf.Atan2(real_t, real_t)"/> when
/// called with the vector's `y` and `x` as parameters: `Mathf.Atan2(v.y, v.x)`.
/// </summary>
/// <returns>The angle of this vector, in radians.</returns>
public real_t Angle()
{
return Mathf.Atan2(y, x);
}
/// <summary>
/// Returns the angle to the given vector, in radians.
/// </summary>
/// <param name="to">The other vector to compare this vector to.</param>
/// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleTo(Vector2i to)
{
return Mathf.Atan2(Cross(to), Dot(to));
}
/// <summary>
/// Returns the angle between the line connecting the two points and the X axis, in radians.
/// </summary>
/// <param name="to">The other vector to compare this vector to.</param>
/// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleToPoint(Vector2i to)
{
return Mathf.Atan2(y - to.y, x - to.x);
}
/// <summary>
/// Returns the aspect ratio of this vector, the ratio of `x` to `y`.
/// </summary>
/// <returns>The `x` component divided by the `y` component.</returns>
public real_t Aspect()
{
return x / (real_t)y;
}
/// <summary>
/// Returns the cross product of this vector and `b`.
/// </summary>
/// <param name="b">The other vector.</param>
/// <returns>The cross product vector.</returns>
public int Cross(Vector2i b)
{
return x * b.y - y * b.x;
}
/// <summary>
/// Returns the squared distance between this vector and `b`.
/// This method runs faster than <see cref="DistanceTo"/>, so prefer it if
/// you need to compare vectors or need the squared distance for some formula.
/// </summary>
/// <param name="b">The other vector to use.</param>
/// <returns>The squared distance between the two vectors.</returns>
public int DistanceSquaredTo(Vector2i b)
{
return (b - this).LengthSquared();
}
/// <summary>
/// Returns the distance between this vector and `b`.
/// </summary>
/// <param name="b">The other vector to use.</param>
/// <returns>The distance between the two vectors.</returns>
public real_t DistanceTo(Vector2i b)
{
return (b - this).Length();
}
/// <summary>
/// Returns the dot product of this vector and `b`.
/// </summary>
/// <param name="b">The other vector to use.</param>
/// <returns>The dot product of the two vectors.</returns>
public int Dot(Vector2i b)
{
return x * b.x + y * b.y;
}
/// <summary>
/// Returns the length (magnitude) of this vector.
/// </summary>
/// <returns>The length of this vector.</returns>
public real_t Length()
{
int x2 = x * x;
int y2 = y * y;
return Mathf.Sqrt(x2 + y2);
}
/// <summary>
/// Returns the squared length (squared magnitude) of this vector.
/// This method runs faster than <see cref="Length"/>, so prefer it if
/// you need to compare vectors or need the squared length for some formula.
/// </summary>
/// <returns>The squared length of this vector.</returns>
public int LengthSquared()
{
int x2 = x * x;
int y2 = y * y;
return x2 + y2;
}
/// <summary>
/// Returns the axis of the vector's largest value. See <see cref="Axis"/>.
/// If both components are equal, this method returns <see cref="Axis.X"/>.
/// </summary>
/// <returns>The index of the largest axis.</returns>
public Axis MaxAxis()
{
return x < y ? Axis.Y : Axis.X;
}
/// <summary>
/// Returns the axis of the vector's smallest value. See <see cref="Axis"/>.
/// If both components are equal, this method returns <see cref="Axis.Y"/>.
/// </summary>
/// <returns>The index of the smallest axis.</returns>
public Axis MinAxis()
{
return x < y ? Axis.X : Axis.Y;
}
/// <summary>
/// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `mod`.
/// </summary>
/// <param name="mod">A value representing the divisor of the operation.</param>
/// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `mod`.</returns>
public Vector2i PosMod(int mod)
{
Vector2i v = this;
v.x = Mathf.PosMod(v.x, mod);
v.y = Mathf.PosMod(v.y, mod);
return v;
}
/// <summary>
/// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `modv`'s components.
/// </summary>
/// <param name="modv">A vector representing the divisors of the operation.</param>
/// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `modv`'s components.</returns>
public Vector2i PosMod(Vector2i modv)
{
Vector2i v = this;
v.x = Mathf.PosMod(v.x, modv.x);
v.y = Mathf.PosMod(v.y, modv.y);
return v;
}
/// <summary>
/// Returns a vector with each component set to one or negative one, depending
/// on the signs of this vector's components, or zero if the component is zero,
/// by calling <see cref="Mathf.Sign(int)"/> on each component.
/// </summary>
/// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns>
public Vector2i Sign()
{
Vector2i v = this;
v.x = Mathf.Sign(v.x);
v.y = Mathf.Sign(v.y);
return v;
}
/// <summary>
/// Returns a vector rotated 90 degrees counter-clockwise
/// compared to the original, with the same length.
/// </summary>
/// <returns>The perpendicular vector.</returns>
public Vector2 Perpendicular()
{
return new Vector2(y, -x);
}
// Constants
private static readonly Vector2i _zero = new Vector2i(0, 0);
private static readonly Vector2i _one = new Vector2i(1, 1);
private static readonly Vector2i _up = new Vector2i(0, -1);
private static readonly Vector2i _down = new Vector2i(0, 1);
private static readonly Vector2i _right = new Vector2i(1, 0);
private static readonly Vector2i _left = new Vector2i(-1, 0);
/// <summary>
/// Zero vector, a vector with all components set to `0`.
/// </summary>
/// <value>Equivalent to `new Vector2i(0, 0)`</value>
public static Vector2i Zero { get { return _zero; } }
/// <summary>
/// One vector, a vector with all components set to `1`.
/// </summary>
/// <value>Equivalent to `new Vector2i(1, 1)`</value>
public static Vector2i One { get { return _one; } }
/// <summary>
/// Up unit vector. Y is down in 2D, so this vector points -Y.
/// </summary>
/// <value>Equivalent to `new Vector2i(0, -1)`</value>
public static Vector2i Up { get { return _up; } }
/// <summary>
/// Down unit vector. Y is down in 2D, so this vector points +Y.
/// </summary>
/// <value>Equivalent to `new Vector2i(0, 1)`</value>
public static Vector2i Down { get { return _down; } }
/// <summary>
/// Right unit vector. Represents the direction of right.
/// </summary>
/// <value>Equivalent to `new Vector2i(1, 0)`</value>
public static Vector2i Right { get { return _right; } }
/// <summary>
/// Left unit vector. Represents the direction of left.
/// </summary>
/// <value>Equivalent to `new Vector2i(-1, 0)`</value>
public static Vector2i Left { get { return _left; } }
/// <summary>
/// Constructs a new <see cref="Vector2i"/> with the given components.
/// </summary>
/// <param name="x">The vector's X component.</param>
/// <param name="y">The vector's Y component.</param>
public Vector2i(int x, int y)
{
this.x = x;
this.y = y;
}
/// <summary>
/// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2i"/>.
/// </summary>
/// <param name="vi">The existing <see cref="Vector2i"/>.</param>
public Vector2i(Vector2i vi)
{
this.x = vi.x;
this.y = vi.y;
}
/// <summary>
/// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2"/>
/// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
/// </summary>
/// <param name="v">The <see cref="Vector2"/> to convert.</param>
public Vector2i(Vector2 v)
{
this.x = Mathf.RoundToInt(v.x);
this.y = Mathf.RoundToInt(v.y);
}
public static Vector2i operator +(Vector2i left, Vector2i right)
{
left.x += right.x;
left.y += right.y;
return left;
}
public static Vector2i operator -(Vector2i left, Vector2i right)
{
left.x -= right.x;
left.y -= right.y;
return left;
}
public static Vector2i operator -(Vector2i vec)
{
vec.x = -vec.x;
vec.y = -vec.y;
return vec;
}
public static Vector2i operator *(Vector2i vec, int scale)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2i operator *(int scale, Vector2i vec)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2i operator *(Vector2i left, Vector2i right)
{
left.x *= right.x;
left.y *= right.y;
return left;
}
public static Vector2i operator /(Vector2i vec, int divisor)
{
vec.x /= divisor;
vec.y /= divisor;
return vec;
}
public static Vector2i operator /(Vector2i vec, Vector2i divisorv)
{
vec.x /= divisorv.x;
vec.y /= divisorv.y;
return vec;
}
public static Vector2i operator %(Vector2i vec, int divisor)
{
vec.x %= divisor;
vec.y %= divisor;
return vec;
}
public static Vector2i operator %(Vector2i vec, Vector2i divisorv)
{
vec.x %= divisorv.x;
vec.y %= divisorv.y;
return vec;
}
public static Vector2i operator &(Vector2i vec, int and)
{
vec.x &= and;
vec.y &= and;
return vec;
}
public static Vector2i operator &(Vector2i vec, Vector2i andv)
{
vec.x &= andv.x;
vec.y &= andv.y;
return vec;
}
public static bool operator ==(Vector2i left, Vector2i right)
{
return left.Equals(right);
}
public static bool operator !=(Vector2i left, Vector2i right)
{
return !left.Equals(right);
}
public static bool operator <(Vector2i left, Vector2i right)
{
if (left.x.Equals(right.x))
{
return left.y < right.y;
}
return left.x < right.x;
}
public static bool operator >(Vector2i left, Vector2i right)
{
if (left.x.Equals(right.x))
{
return left.y > right.y;
}
return left.x > right.x;
}
public static bool operator <=(Vector2i left, Vector2i right)
{
if (left.x.Equals(right.x))
{
return left.y <= right.y;
}
return left.x <= right.x;
}
public static bool operator >=(Vector2i left, Vector2i right)
{
if (left.x.Equals(right.x))
{
return left.y >= right.y;
}
return left.x >= right.x;
}
public static implicit operator Vector2(Vector2i value)
{
return new Vector2(value.x, value.y);
}
public static explicit operator Vector2i(Vector2 value)
{
return new Vector2i(value);
}
public override bool Equals(object obj)
{
if (obj is Vector2i)
{
return Equals((Vector2i)obj);
}
return false;
}
public bool Equals(Vector2i other)
{
return x == other.x && y == other.y;
}
public override int GetHashCode()
{
return y.GetHashCode() ^ x.GetHashCode();
}
public override string ToString()
{
return String.Format("({0}, {1})", new object[]
{
this.x.ToString(),
this.y.ToString()
});
}
public string ToString(string format)
{
return String.Format("({0}, {1})", new object[]
{
this.x.ToString(format),
this.y.ToString(format)
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ExampleWebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
Copyright (c) 2006- DEVSENSE
Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections.Generic;
using PHP.Core;
using System.Diagnostics;
using PHP.Core.Parsers;
namespace PHP.Core.AST
{
#region WhileStmt
/// <summary>
/// Represents a while-loop statement.
/// </summary>
[Serializable]
public sealed class WhileStmt : Statement
{
public enum Type { While, Do };
/// <summary>Type of statement</summary>
public Type LoopType { get { return type; } }
private Type type;
/// <summary>
/// Condition or a <B>null</B> reference for unbounded loop.
/// </summary>
public Expression CondExpr { get { return condExpr; } internal set { condExpr = value; } }
private Expression condExpr;
/// <summary>Body of loop</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
private Statement/*!*/ body;
public WhileStmt(Text.Span span, Type type, Expression/*!*/ condExpr, Statement/*!*/ body)
: base(span)
{
Debug.Assert(condExpr != null && body != null);
this.type = type;
this.condExpr = condExpr;
this.body = body;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitWhileStmt(this);
}
}
#endregion
#region ForStmt
/// <summary>
/// Represents a for-loop statement.
/// </summary>
[Serializable]
public sealed class ForStmt : Statement
{
private readonly List<Expression>/*!*/ initExList;
private readonly List<Expression>/*!*/ condExList;
private readonly List<Expression>/*!*/ actionExList;
private Statement/*!*/ body;
/// <summary>List of expressions used for initialization</summary>
public List<Expression> /*!*/ InitExList { get { return initExList; } }
/// <summary>List of expressions used as condition</summary>
public List<Expression> /*!*/ CondExList { get { return condExList; } }
/// <summary>List of expressions used to incrent iterator</summary>
public List<Expression> /*!*/ ActionExList { get { return actionExList; } }
/// <summary>Body of statement</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
public ForStmt(Text.Span p, List<Expression>/*!*/ initExList, List<Expression>/*!*/ condExList,
List<Expression>/*!*/ actionExList, Statement/*!*/ body)
: base(p)
{
Debug.Assert(initExList != null && condExList != null && actionExList != null && body != null);
this.initExList = initExList;
this.condExList = condExList;
this.actionExList = actionExList;
this.body = body;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitForStmt(this);
}
}
#endregion
#region ForeachStmt
/// <summary>
/// Represents a foreach-loop statement.
/// </summary>
[Serializable]
public sealed class ForeachVar : AstNode
{
/// <summary>
/// Whether the variable is aliased.
/// </summary>
public bool Alias { get { return alias; } set { alias = value; } }
private bool alias;
/// <summary>
/// The variable itself. Can be <c>null</c> reference if <see cref="ListEx"/> is represented instead.
/// </summary>
public VariableUse Variable { get { return this.expr as VariableUse; } }
/// <summary>
/// PHP list expression. Can be <c>null</c> reference if <see cref="VariableUse"/> is represented instead.
/// </summary>
public ListEx List { get { return this.expr as ListEx; } }
/// <summary>
/// Inner expression representing <see cref="Variable"/> or <see cref="List"/>.
/// </summary>
internal Expression/*!*/Expression { get { return expr; } }
private readonly Expression/*!*/expr;
/// <summary>
/// Position of foreach variable.
/// </summary>
internal Text.Span Span { get { return expr.Span; } }
public ForeachVar(VariableUse variable, bool alias)
{
this.expr = variable;
this.alias = alias;
}
/// <summary>
/// Initializes instance of <see cref="ForeachVar"/> representing PHP list expression.
/// </summary>
/// <param name="list"></param>
public ForeachVar(ListEx/*!*/list)
{
Debug.Assert(list != null);
Debug.Assert(list.RValue == null);
this.expr = list;
this.alias = false;
}
}
/// <summary>
/// Represents a foreach statement.
/// </summary>
[Serializable]
public class ForeachStmt : Statement
{
private Expression/*!*/ enumeree;
/// <summary>Array to enumerate through</summary>
public Expression /*!*/Enumeree { get { return enumeree; } }
private ForeachVar keyVariable;
/// <summary>Variable to store key in (can be null)</summary>
public ForeachVar KeyVariable { get { return keyVariable; } }
private ForeachVar/*!*/ valueVariable;
/// <summary>Variable to store value in</summary>
public ForeachVar /*!*/ ValueVariable { get { return valueVariable; } }
private Statement/*!*/ body;
/// <summary>Body - statement in loop</summary>
public Statement/*!*/ Body { get { return body; } internal set { body = value; } }
public ForeachStmt(Text.Span span, Expression/*!*/ enumeree, ForeachVar key, ForeachVar/*!*/ value,
Statement/*!*/ body)
: base(span)
{
Debug.Assert(enumeree != null && value != null && body != null);
this.enumeree = enumeree;
this.keyVariable = key;
this.valueVariable = value;
this.body = body;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitForeachStmt(this);
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.DeriveBytesTests
{
public class PasswordDeriveBytesTests
{
// Note some tests were copied from Rfc2898DeriveBytes (and modified accordingly).
private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 };
private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 };
private const string TestPassword = "PasswordGoesHere";
private const string TestPasswordB = "FakePasswordsAreHard";
private const int DefaultIterationCount = 100;
[Fact]
public static void Ctor_NullPasswordBytes()
{
using (var pdb = new PasswordDeriveBytes((byte[])null, s_testSalt))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(s_testSalt, pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_NullPasswordString()
{
Assert.Throws<ArgumentNullException>(() => new PasswordDeriveBytes((string)null, s_testSalt));
}
[Fact]
public static void Ctor_NullSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, null))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(null, pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_EmptySalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, Array.Empty<byte>()))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(Array.Empty<byte>(), pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_DiminishedSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, new byte[7]))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(7, pdb.Salt.Length);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_TooFewIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 0));
}
[Fact]
public static void Ctor_NegativeIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue / 2));
}
[Fact]
public static void Ctor_DefaultIterations()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_IterationsRespected()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 1))
{
Assert.Equal(1, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_CspParameters()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, new CspParameters())) { }
}
[Fact]
public static void Ctor_CspParameters_Null()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, null)) { }
}
[Fact]
public static void Ctor_SaltCopied()
{
byte[] saltIn = (byte[])s_testSalt.Clone();
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, saltIn, "SHA1", DefaultIterationCount))
{
byte[] saltOut = deriveBytes.Salt;
Assert.NotSame(saltIn, saltOut);
Assert.Equal(saltIn, saltOut);
// Right now we know that at least one of the constructor and get_Salt made a copy, if it was
// only get_Salt then this next part would fail.
saltIn[0] = unchecked((byte)~saltIn[0]);
// Have to read the property again to prove it's detached.
Assert.NotEqual(saltIn, deriveBytes.Salt);
}
}
[Fact]
public static void GetSaltCopies()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", DefaultIterationCount))
{
first = deriveBytes.Salt;
second = deriveBytes.Salt;
}
Assert.NotSame(first, second);
Assert.Equal(first, second);
}
[Fact]
public static void SetSaltAfterGetBytes_Throws()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
Assert.Throws<CryptographicException>(() => deriveBytes.Salt = s_testSalt);
}
}
[Fact]
public static void SetSaltAfterGetBytes_Reset()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
deriveBytes.Reset();
deriveBytes.Salt = s_testSaltB;
Assert.Equal(s_testSaltB, deriveBytes.Salt);
}
}
[Fact]
public static void MinimumAcceptableInputs()
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, new byte[8], "SHA1", 1))
{
output = deriveBytes.GetBytes(1);
}
Assert.Equal(1, output.Length);
Assert.Equal(0xF8, output[0]);
}
[Fact]
public static void GetBytes_ZeroLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<ArgumentException>(() => deriveBytes.GetBytes(0));
}
}
[Fact]
public static void GetBytes_NegativeLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(-1));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue / 2));
}
}
[Fact]
public static void GetBytes_NotIdempotent()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
second = deriveBytes.GetBytes(32);
}
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_StableIfReset()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
deriveBytes.Reset();
second = deriveBytes.GetBytes(32);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_ExtraBytes()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// SHA1 default
Assert.Equal("SHA1", deriveBytes.HashName);
// Request double of SHA1 hash size
first = deriveBytes.GetBytes(40);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Make two passes over the hash
byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2);
// Since we requested 20 bytes there are no 'extra' bytes left over to cause the "_extraCount" bug
// in GetBytes(); that issue is tested in GetBytes_StreamLike_Bug_Compat.
// Request 20 'extra' bytes in one call
byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length);
Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length);
Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_Bug_Compat()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal("SHA1", deriveBytes.HashName);
// Request 20 bytes (SHA1 hash size) plus 12 extra bytes
first = deriveBytes.GetBytes(32);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Ask for half now (16 bytes)
byte[] firstHalf = deriveBytes.GetBytes(first.Length / 2);
// Ask for the other half now (16 bytes)
byte[] lastHalf = deriveBytes.GetBytes(first.Length - firstHalf.Length);
// lastHalf should contain the last 4 bytes from the SHA1 hash plus 12 extra bytes
// but due to the _extraCount bug it doesn't.
// Merge the two buffers into the second array
Buffer.BlockCopy(firstHalf, 0, second, 0, firstHalf.Length);
Buffer.BlockCopy(lastHalf, 0, second, firstHalf.Length, lastHalf.Length);
}
// Fails due to _extraCount bug (the bug is fixed in Rfc2898DeriveBytes)
Assert.NotEqual(first, second);
// However, the first 16 bytes will be equal because the _extraCount bug does
// not affect the first call, only the subsequent GetBytes() call.
byte[] first_firstHalf = new byte[first.Length / 2];
byte[] second_firstHalf = new byte[first.Length / 2];
Buffer.BlockCopy(first, 0, first_firstHalf, 0, first_firstHalf.Length);
Buffer.BlockCopy(second, 0, second_firstHalf, 0, second_firstHalf.Length);
Assert.Equal(first_firstHalf, second_firstHalf);
}
[Fact]
public static void GetBytes_Boundary()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Boundary case success
deriveBytes.GetBytes(1000 * 20);
// Boundary case failure
Assert.Throws<CryptographicException>(() => deriveBytes.GetBytes(1));
}
}
[Fact]
public static void GetBytes_KnownValues_MD5_32()
{
TestKnownValue_GetBytes(
HashAlgorithmName.MD5,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("F8D88E9DAFC828DA2400F5144271C2F630A1C061C654FC9DE2E7900E121461B9"));
}
[Fact]
public static void GetBytes_KnownValues_SHA256_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA256,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("3774A17468276057717A90C25B72915921D8F8C046F7868868DBB99BB4C4031CADE9E26BE77BEA39"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("12F2497EC3EB78B0EA32AABFD8B9515FBC800BEEB6316A4DDF4EA62518341488A116DA3BBC26C685"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_2()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount + 1,
ByteUtils.HexToByteArray("FB6199E4D9BB017D2F3AF6964F3299971607C6B984934A9E43140631957429160C33A6630EF12E31"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_3()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSaltB,
DefaultIterationCount,
ByteUtils.HexToByteArray("DCA4851AB3C9960CF387E64DE7A1B2E09616BEA6A4666AAFAC31F1670F23530E38BD4BF4D9248A08"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_4()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPasswordB,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("1DCA2A3405E93D9E3F7CD10653444F2FD93F5BE32C4B1BEDDF94D0D67461CBE86B5BDFEB32071E96"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_TripleDes()
{
byte[] key = TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"TripleDES",
192,
s_testSalt,
ByteUtils.HexToByteArray("97628A641949D99DCED35DB0ABCE20F21FF4DA9B46E00BCE"));
// Verify key is valid
using (var alg = new TripleDESCryptoServiceProvider())
{
alg.Key = key;
alg.IV = new byte[8];
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.CBC;
byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "9DC863445642B88AC46B3B107CB5A0ACC1596A176962EE8F".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_RC2()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA256,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("CF4A1CA60093E71D6B740DBB962B3C66"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.MD5,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("84F4B6854CDF896A86FB493B852B6E1F"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_RC2_NoSalt()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
null, // Salt is not used here so we should get same key value
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_DES()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"DES",
64,
s_testSalt,
ByteUtils.HexToByteArray("B0685D8C98F4854A"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_KeyLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 127, s_testSalt));
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 129, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_Algorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("BADALG", "SHA1", 128, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_HashAlgorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "BADALG", 128, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_IV()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null));
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[1]));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void CryptDeriveKey_Throws_Unix()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<PlatformNotSupportedException>(() => (deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null)));
}
}
private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected)
{
byte[] output;
byte[] iv = new byte[8];
using (var deriveBytes = new PasswordDeriveBytes(password, salt))
{
output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv);
}
Assert.Equal(expected, output);
// For these tests, the returned IV is always zero
Assert.Equal(new byte[8], iv);
return output;
}
private static void TestKnownValue_GetBytes(HashAlgorithmName hashName, string password, byte[] salt, int iterationCount, byte[] expected)
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(password, salt, hashName.Name, iterationCount))
{
output = deriveBytes.GetBytes(expected.Length);
}
Assert.Equal(expected, output);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/11/2009 2:34:48 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Globalization;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// Extent works like an envelope but is faster acting, has a minimum memory profile,
/// only works in 2D and has no events.
/// </summary>
[Serializable, TypeConverter(typeof(ExpandableObjectConverter))]
public class Extent : ICloneable, IExtent
{
/// <summary>
/// Creates a new instance of Extent. This introduces no error checking and assumes
/// that the user knows what they are doing when working with this.
/// </summary>
public Extent()
{
MinX = double.NaN; //changed by jany_ (2015-07-17) default extent is empty because if there is no content there is no extent
MaxX = double.NaN;
MinY = double.NaN;
MaxY = double.NaN;
}
/// <summary>
/// Creates a new extent from the specified ordinates
/// </summary>
/// <param name="xMin"></param>
/// <param name="yMin"></param>
/// <param name="xMax"></param>
/// <param name="yMax"></param>
public Extent(double xMin, double yMin, double xMax, double yMax)
{
MinX = xMin;
MinY = yMin;
MaxX = xMax;
MaxY = yMax;
}
/// <summary>
/// Given a long array of doubles, this builds an extent from a small part of that
/// xmin, ymin, xmax, ymax
/// </summary>
/// <param name="values"></param>
/// <param name="offset"></param>
public Extent(double[] values, int offset)
{
if (values.Length < 4 + offset)
throw new IndexOutOfRangeException(
"The length of the array of double values should be greater than or equal to 4 plus the value of the offset.");
MinX = values[0 + offset];
MinY = values[1 + offset];
MaxX = values[2 + offset];
MaxY = values[3 + offset];
}
/// <summary>
/// XMin, YMin, XMax, YMax order
/// </summary>
/// <param name="values"></param>
public Extent(double[] values)
{
if (values.Length < 4)
throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4.");
MinX = values[0];
MinY = values[1];
MaxX = values[2];
MaxY = values[3];
}
/// <summary>
/// Creates a new extent from the specified envelope
/// </summary>
/// <param name="env"></param>
public Extent(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
MinX = env.MinX;
MinY = env.MinY;
MaxX = env.MaxX;
MaxY = env.MaxY;
}
/// <summary>
/// Gets the Center of this extent.
/// </summary>
public Coordinate Center
{
get
{
double x = MinX + (MaxX - MinX) / 2;
double y = MinY + (MaxY - MinY) / 2;
return new Coordinate(x, y);
}
}
#region ICloneable Members
/// <summary>
/// Produces a clone, rather than using this same object.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
return new Extent(MinX, MinY, MaxX, MaxY);
}
#endregion
#region IExtent Members
/// <summary>
/// Gets or sets whether the M values are used. M values are considered optional,
/// and not mandatory. Unused could mean either bound is NaN for some reason, or
/// else that the bounds are invalid by the Min being less than the Max.
/// </summary>
public virtual bool HasM
{
get { return false; }
}
/// <summary>
/// Gets or sets whether the M values are used. M values are considered optional,
/// and not mandatory. Unused could mean either bound is NaN for some reason, or
/// else that the bounds are invalid by the Min being less than the Max.
/// </summary>
public virtual bool HasZ
{
get { return false; }
}
/// <summary>
/// Max X
/// </summary>
[Serialize("MaxX")]
public double MaxX { get; set; }
/// <summary>
/// Max Y
/// </summary>
[Serialize("MaxY")]
public double MaxY { get; set; }
/// <summary>
/// Min X
/// </summary>
[Serialize("MinX")]
public double MinX { get; set; }
/// <summary>
/// Min Y
/// </summary>
[Serialize("MinY")]
public double MinY { get; set; }
#endregion
#region IRectangle Members
/// <summary>
/// Gets MaxY - MinY. Setting this will update MinY, keeping MaxY the same. (Pinned at top left corner).
/// </summary>
public double Height
{
get { return MaxY - MinY; }
set { MinY = MaxY - value; }
}
/// <summary>
/// Gets MaxX - MinX. Setting this will update MaxX, keeping MinX the same. (Pinned at top left corner).
/// </summary>
public double Width
{
get { return MaxX - MinX; }
set { MaxX = MinX + value; }
}
/// <summary>
/// Gets MinX. Setting this will shift both MinX and MaxX, keeping the width the same.
/// </summary>
public double X
{
get { return MinX; }
set
{
double w = Width;
MinX = value;
Width = w;
}
}
/// <summary>
/// Gets MaxY. Setting this will shift both MinY and MaxY, keeping the height the same.
/// </summary>
public double Y
{
get { return MaxY; }
set
{
double h = Height;
MaxY = value;
Height = h;
}
}
#endregion
/// <summary>
/// Equality test
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Extent left, IExtent right)
{
if (((object)left) == null) return ((right) == null);
return left.Equals(right);
}
/// <summary>
/// Inequality test
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Extent left, IExtent right)
{
if (((object)left) == null) return ((right) != null);
return !left.Equals(right);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public virtual bool Contains(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (MinX > ext.MinX)
{
return false;
}
if (MaxX < ext.MaxX)
{
return false;
}
if (MinY > ext.MinY)
{
return false;
}
return !(MaxY < ext.MaxY);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="c">The coordinate to test.</param>
/// <returns>Boolean</returns>
public virtual bool Contains(Coordinate c)
{
if (Equals(c, null))
throw new ArgumentNullException("c");
if (MinX > c.X)
{
return false;
}
if (MaxX < c.X)
{
return false;
}
if (MinY > c.Y)
{
return false;
}
return !(MaxY < c.Y);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Contains(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (MinX > env.MinX)
{
return false;
}
if (MaxX < env.MaxX)
{
return false;
}
if (MinY > env.MinY)
{
return false;
}
return !(MaxY < env.MaxY);
}
/// <summary>
/// Copies the MinX, MaxX, MinY, MaxY values from extent.
/// </summary>
/// <param name="extent">Any IExtent implementation.</param>
public virtual void CopyFrom(IExtent extent)
{
if (Equals(extent, null))
throw new ArgumentNullException("extent");
MinX = extent.MinX;
MaxX = extent.MaxX;
MinY = extent.MinY;
MaxY = extent.MaxY;
}
/// <summary>
/// Allows equality testing for extents that is derived on the extent itself.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
// Check the identity case for reference equality
if (base.Equals(obj))
{
return true;
}
IExtent other = obj as IExtent;
if (other == null)
{
return false;
}
if (MinX != other.MinX)
{
return false;
}
if (MaxX != other.MaxX)
{
return false;
}
if (MinY != other.MinY)
{
return false;
}
if (MaxY != other.MaxY)
{
return false;
}
return true;
}
/// <summary>
/// Expand will adjust both the minimum and maximum by the specified sizeX and sizeY
/// </summary>
/// <param name="padX">The amount to expand left and right.</param>
/// <param name="padY">The amount to expand up and down.</param>
public void ExpandBy(double padX, double padY)
{
MinX -= padX;
MaxX += padX;
MinY -= padY;
MaxY += padY;
}
/// <summary>
/// This expand the extent by the specified padding on all bounds. So the width will
/// change by twice the padding for instance. To Expand only x and y, use
/// the overload with those values explicitly specified.
/// </summary>
/// <param name="padding">The double padding to expand the extent.</param>
public virtual void ExpandBy(double padding)
{
MinX -= padding;
MaxX += padding;
MinY -= padding;
MaxY += padding;
}
/// <summary>
/// Expands this extent to include the domain of the specified extent
/// </summary>
/// <param name="ext">The extent to expand to include</param>
public virtual void ExpandToInclude(IExtent ext)
{
if (ext == null) //Simplify, avoiding nested if
return;
if (double.IsNaN(MinX) || ext.MinX < MinX)
{
MinX = ext.MinX;
}
if (double.IsNaN(MinY) || ext.MinY < MinY)
{
MinY = ext.MinY;
}
if (double.IsNaN(MaxX) || ext.MaxX > MaxX)
{
MaxX = ext.MaxX;
}
if (double.IsNaN(MaxY) || ext.MaxY > MaxY)
{
MaxY = ext.MaxY;
}
}
/// <summary>
/// Expands this extent to include the domain of the specified point
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void ExpandToInclude(double x, double y)
{
if (double.IsNaN(MinX) || x < MinX)
{
MinX = x;
}
if (double.IsNaN(MinY) || y < MinY)
{
MinY = y;
}
if (double.IsNaN(MaxX) || x > MaxX)
{
MaxX = x;
}
if (double.IsNaN(MaxY) || y > MaxY)
{
MaxY = y;
}
}
/// <summary>
/// Spreads the values for the basic X, Y extents across the whole range of int.
/// Repetition will occur, but it should be rare.
/// </summary>
/// <returns>Integer</returns>
public override int GetHashCode()
{
// 215^4 ~ Int.MaxValue so the value will cover the range based mostly on first 2 sig figs.
int xmin = Convert.ToInt32(MinX * 430 / MinX - 215);
int xmax = Convert.ToInt32(MaxX * 430 / MaxX - 215);
int ymin = Convert.ToInt32(MinY * 430 / MinY - 215);
int ymax = Convert.ToInt32(MaxY * 430 / MaxY - 215);
return (xmin * xmax * ymin * ymax);
}
/// <summary>
/// Calculates the intersection of this extent and the other extent. A result
/// with a min greater than the max in either direction is considered invalid
/// and represents no intersection.
/// </summary>
/// <param name="other">The other extent to intersect with.</param>
public virtual Extent Intersection(Extent other)
{
if (Equals(other, null))
throw new ArgumentNullException("other");
Extent result = new Extent
{
MinX = (MinX > other.MinX) ? MinX : other.MinX,
MaxX = (MaxX < other.MaxX) ? MaxX : other.MaxX,
MinY = (MinY > other.MinY) ? MinY : other.MinY,
MaxY = (MaxY < other.MaxY) ? MaxY : other.MaxY
};
return result;
}
/// <summary>
/// Returns true if the coordinate exists anywhere within this envelope
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public virtual bool Intersects(Coordinate c)
{
if (Equals(c, null))
throw new ArgumentNullException("c");
if (double.IsNaN(c.X) || double.IsNaN(c.Y))
{
return false;
}
return c.X >= MinX && c.X <= MaxX && c.Y >= MinY && c.Y <= MaxY;
}
/// <summary>
/// Tests for intersection with the specified coordinate
/// </summary>
/// <param name="x">The double ordinate to test intersection with in the X direction</param>
/// <param name="y">The double ordinate to test intersection with in the Y direction</param>
/// <returns>True if a point with the specified x and y coordinates is within or on the border
/// of this extent object. NAN values will always return false.</returns>
public bool Intersects(double x, double y)
{
if (double.IsNaN(x) || double.IsNaN(y))
{
return false;
}
return x >= MinX && x <= MaxX && y >= MinY && y <= MaxY;
}
/// <summary>
/// Tests to see if the point is inside or on the boundary of this extent.
/// </summary>
/// <param name="vert"></param>
/// <returns></returns>
public bool Intersects(Vertex vert)
{
if (vert.X < MinX)
{
return false;
}
if (vert.X > MaxX)
{
return false;
}
if (vert.Y < MinY)
{
return false;
}
return !(vert.Y > MaxY);
}
/// <summary>
/// Tests for an intersection with the specified extent
/// </summary>
/// <param name="ext">The other extent</param>
/// <returns>Boolean, true if they overlap anywhere, or even touch</returns>
public virtual bool Intersects(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (ext.MaxX < MinX)
{
return false;
}
if (ext.MaxY < MinY)
{
return false;
}
if (ext.MinX > MaxX)
{
return false;
}
return !(ext.MinY > MaxY);
}
/// <summary>
/// Tests with the specified envelope for a collision
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Intersects(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (env.MaxX < MinX)
{
return false;
}
if (env.MaxY < MinY)
{
return false;
}
if (env.MinX > MaxX)
{
return false;
}
return !(env.MinY > MaxY);
}
/// <summary>
/// If this is undefined, it will have a min that is larger than the max, or else
/// any value is NaN. This only applies to the X and Z terms. Check HasM or HasZ higher dimensions.
/// </summary>
/// <returns>Boolean, true if the envelope has not had values set for it yet.</returns>
public bool IsEmpty()
{
if (double.IsNaN(MinX) || double.IsNaN(MaxX))
{
return true;
}
if (double.IsNaN(MinY) || double.IsNaN(MaxY))
{
return true;
}
return (MinX > MaxX || MinY > MaxY); // Simplified
}
/// <summary>
/// This allows parsing the X and Y values from a string version of the extent as:
/// 'X[-180|180], Y[-90|90]' Where minimum always precedes maximum. The correct
/// M or MZ version of extent will be returned if the string has those values.
/// </summary>
/// <param name="text">The string text to parse.</param>
/// <exception cref="ExtentParseException"/>
public static Extent Parse(string text)
{
Extent result;
string fail;
if (TryParse(text, out result, out fail)) return result;
var ep = new ExtentParseException(String.Format("Attempting to read an extent string failed while reading the {0} term.", fail))
{
Expression = text
};
throw ep;
}
/// <summary>
/// This reads the string and attempts to derive values from the text.
/// </summary>
public static bool TryParse(string text, out Extent result, out string nameFailed)
{
double xmin, xmax, ymin, ymax, mmin, mmax;
result = null;
if (text.Contains("Z"))
{
double zmin, zmax;
nameFailed = "Z";
ExtentMZ mz = new ExtentMZ();
if (TryExtract(text, "Z", out zmin, out zmax) == false) return false;
mz.MinZ = zmin;
mz.MaxZ = zmax;
nameFailed = "M";
if (TryExtract(text, "M", out mmin, out mmax) == false) return false;
mz.MinM = mmin;
mz.MaxM = mmax;
result = mz;
}
else if (text.Contains("M"))
{
nameFailed = "M";
ExtentM me = new ExtentM();
if (TryExtract(text, "M", out mmin, out mmax) == false) return false;
me.MinM = mmin;
me.MaxM = mmax;
result = me;
}
else
{
result = new Extent();
}
nameFailed = "X";
if (TryExtract(text, "X", out xmin, out xmax) == false) return false;
result.MinX = xmin;
result.MaxX = xmax;
nameFailed = "Y";
if (TryExtract(text, "Y", out ymin, out ymax) == false) return false;
result.MinY = ymin;
result.MaxY = ymax;
return true;
}
/// <summary>
/// This centers the X and Y aspect of the extent on the specified center location.
/// </summary>
public void SetCenter(double centerX, double centerY, double width, double height)
{
MinX = centerX - width / 2;
MaxX = centerX + width / 2;
MinY = centerY - height / 2;
MaxY = centerY + height / 2;
}
/// <summary>
/// This centers the X and Y aspect of the extent on the specified center location.
/// </summary>
/// <param name="center">The center coordinate to to set.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public void SetCenter(Coordinate center, double width, double height)
{
SetCenter(center.X, center.Y, width, height);
}
/// <summary>
/// This centers the extent on the specified coordinate, keeping the width and height the same.
/// </summary>
public void SetCenter(Coordinate center)
{
//prevents NullReferenceException when accessing center.X and center.Y
if (Equals(center, null))
throw new ArgumentNullException("center");
SetCenter(center.X, center.Y, Width, Height);
}
/// <summary>
/// Sets the values for xMin, xMax, yMin and yMax.
/// </summary>
/// <param name="minX">The double Minimum in the X direction.</param>
/// <param name="minY">The double Minimum in the Y direction.</param>
/// <param name="maxX">The double Maximum in the X direction.</param>
/// <param name="maxY">The double Maximum in the Y direction.</param>
public void SetValues(double minX, double minY, double maxX, double maxY)
{
MinX = minX;
MinY = minY;
MaxX = maxX;
MaxY = maxY;
}
/// <summary>
/// Creates a geometric envelope interface from this
/// </summary>
/// <returns></returns>
public Envelope ToEnvelope()
{
if (double.IsNaN(MinX)) return new Envelope();
return new Envelope(MinX, MaxX, MinY, MaxY);
}
/// <summary>
/// Creates a string that shows the extent.
/// </summary>
/// <returns>The string form of the extent.</returns>
public override string ToString()
{
return "X[" + MinX + "|" + MaxX + "], Y[" + MinY + "|" + MaxY + "]";
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public virtual bool Within(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (MinX < ext.MinX)
{
return false;
}
if (MaxX > ext.MaxX)
{
return false;
}
if (MinY < ext.MinY)
{
return false;
}
return !(MaxY > ext.MaxY);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Within(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (MinX < env.MinX)
{
return false;
}
if (MaxX > env.MaxX)
{
return false;
}
if (MinY < env.MinY)
{
return false;
}
return !(MaxY > env.MaxY);
}
/// <summary>
/// Attempts to extract the min and max from one element of text. The element should be
/// formatted like X[1.5, 2.7] using an invariant culture.
/// </summary>
/// <param name="entireText"></param>
/// <param name="name">The name of the dimension, like X.</param>
/// <param name="min">The minimum that gets assigned</param>
/// <param name="max">The maximum that gets assigned</param>
/// <returns>Boolean, true if the parse was successful.</returns>
private static bool TryExtract(string entireText, string name, out double min, out double max)
{
int i = entireText.IndexOf(name, StringComparison.Ordinal);
i += name.Length + 1;
int j = entireText.IndexOf(']', i);
string vals = entireText.Substring(i, j - i);
return TryParseExtremes(vals, out min, out max);
}
/// <summary>
/// This method converts the X and Y text into two doubles.
/// </summary>
private static bool TryParseExtremes(string numeric, out double min, out double max)
{
string[] res = numeric.Split('|');
max = double.NaN;
if (double.TryParse(res[0].Trim(), NumberStyles.Any,
CultureInfo.InvariantCulture, out min) == false) return false;
if (double.TryParse(res[1].Trim(), NumberStyles.Any,
CultureInfo.InvariantCulture, out max) == false) return false;
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The RegexReplacement class represents a substitution string for
// use when using regexs to search/replace, etc. It's logically
// a sequence intermixed (1) constant strings and (2) group numbers.
using System.Collections.Generic;
using System.IO;
namespace System.Text.RegularExpressions
{
internal sealed class RegexReplacement
{
// Constants for special insertion patterns
internal const int Specials = 4;
internal const int LeftPortion = -1;
internal const int RightPortion = -2;
internal const int LastGroup = -3;
internal const int WholeString = -4;
private readonly String _rep;
private readonly List<String> _strings; // table of string constants
private readonly List<Int32> _rules; // negative -> group #, positive -> string #
/// <summary>
/// Since RegexReplacement shares the same parser as Regex,
/// the constructor takes a RegexNode which is a concatenation
/// of constant strings and backreferences.
/// </summary>
internal RegexReplacement(String rep, RegexNode concat, Dictionary<Int32, Int32> _caps)
{
if (concat.Type() != RegexNode.Concatenate)
throw new ArgumentException(SR.ReplacementError);
StringBuilder sb = StringBuilderCache.Acquire();
List<String> strings = new List<String>();
List<Int32> rules = new List<Int32>();
for (int i = 0; i < concat.ChildCount(); i++)
{
RegexNode child = concat.Child(i);
switch (child.Type())
{
case RegexNode.Multi:
sb.Append(child._str);
break;
case RegexNode.One:
sb.Append(child._ch);
break;
case RegexNode.Ref:
if (sb.Length > 0)
{
rules.Add(strings.Count);
strings.Add(sb.ToString());
sb.Length = 0;
}
int slot = child._m;
if (_caps != null && slot >= 0)
slot = (int)_caps[slot];
rules.Add(-Specials - 1 - slot);
break;
default:
throw new ArgumentException(SR.ReplacementError);
}
}
if (sb.Length > 0)
{
rules.Add(strings.Count);
strings.Add(sb.ToString());
}
StringBuilderCache.Release(sb);
_rep = rep;
_strings = strings;
_rules = rules;
}
/// <summary>
/// Given a Match, emits into the StringBuilder the evaluated
/// substitution pattern.
/// </summary>
private void ReplacementImpl(StringBuilder sb, Match match)
{
for (int i = 0; i < _rules.Count; i++)
{
int r = _rules[i];
if (r >= 0) // string lookup
sb.Append(_strings[r]);
else if (r < -Specials) // group lookup
sb.Append(match.GroupToStringImpl(-Specials - 1 - r));
else
{
switch (-Specials - 1 - r)
{ // special insertion patterns
case LeftPortion:
sb.Append(match.GetLeftSubstring());
break;
case RightPortion:
sb.Append(match.GetRightSubstring());
break;
case LastGroup:
sb.Append(match.LastGroupToStringImpl());
break;
case WholeString:
sb.Append(match.GetOriginalString());
break;
}
}
}
}
/// <summary>
/// Given a Match, emits into the List<String> the evaluated
/// Right-to-Left substitution pattern.
/// </summary>
private void ReplacementImplRTL(List<String> al, Match match)
{
for (int i = _rules.Count - 1; i >= 0; i--)
{
int r = _rules[i];
if (r >= 0) // string lookup
al.Add(_strings[r]);
else if (r < -Specials) // group lookup
al.Add(match.GroupToStringImpl(-Specials - 1 - r));
else
{
switch (-Specials - 1 - r)
{ // special insertion patterns
case LeftPortion:
al.Add(match.GetLeftSubstring());
break;
case RightPortion:
al.Add(match.GetRightSubstring());
break;
case LastGroup:
al.Add(match.LastGroupToStringImpl());
break;
case WholeString:
al.Add(match.GetOriginalString());
break;
}
}
}
}
/// <summary>
/// The original pattern string
/// </summary>
internal String Pattern
{
get { return _rep; }
}
/// <summary>
/// Returns the replacement result for a single match
/// </summary>
internal String Replacement(Match match)
{
StringBuilder sb = StringBuilderCache.Acquire();
ReplacementImpl(sb, match);
return StringBuilderCache.GetStringAndRelease(sb);
}
// Three very similar algorithms appear below: replace (pattern),
// replace (evaluator), and split.
/// <summary>
/// Replaces all occurrences of the regex in the string with the
/// replacement pattern.
///
/// Note that the special case of no matches is handled on its own:
/// with no matches, the input string is returned unchanged.
/// The right-to-left case is split out because StringBuilder
/// doesn't handle right-to-left string building directly very well.
/// </summary>
internal String Replace(Regex regex, String input, int count, int startat)
{
if (count < -1)
throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
if (count == 0)
return input;
Match match = regex.Match(input, startat);
if (!match.Success)
{
return input;
}
else
{
StringBuilder sb = StringBuilderCache.Acquire();
if (!regex.RightToLeft)
{
int prevat = 0;
do
{
if (match.Index != prevat)
sb.Append(input, prevat, match.Index - prevat);
prevat = match.Index + match.Length;
ReplacementImpl(sb, match);
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat < input.Length)
sb.Append(input, prevat, input.Length - prevat);
}
else
{
List<String> al = new List<String>();
int prevat = input.Length;
do
{
if (match.Index + match.Length != prevat)
al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));
prevat = match.Index;
ReplacementImplRTL(al, match);
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat > 0)
sb.Append(input, 0, prevat);
for (int i = al.Count - 1; i >= 0; i--)
{
sb.Append(al[i]);
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
}
/// <summary>
/// Replaces all occurrences of the regex in the string with the
/// replacement evaluator.
///
/// Note that the special case of no matches is handled on its own:
/// with no matches, the input string is returned unchanged.
/// The right-to-left case is split out because StringBuilder
/// doesn't handle right-to-left string building directly very well.
/// </summary>
internal static String Replace(MatchEvaluator evaluator, Regex regex,
String input, int count, int startat)
{
if (evaluator == null)
throw new ArgumentNullException(nameof(evaluator));
if (count < -1)
throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
if (count == 0)
return input;
Match match = regex.Match(input, startat);
if (!match.Success)
{
return input;
}
else
{
StringBuilder sb = StringBuilderCache.Acquire();
if (!regex.RightToLeft)
{
int prevat = 0;
do
{
if (match.Index != prevat)
sb.Append(input, prevat, match.Index - prevat);
prevat = match.Index + match.Length;
sb.Append(evaluator(match));
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat < input.Length)
sb.Append(input, prevat, input.Length - prevat);
}
else
{
List<String> al = new List<String>();
int prevat = input.Length;
do
{
if (match.Index + match.Length != prevat)
al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));
prevat = match.Index;
al.Add(evaluator(match));
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat > 0)
sb.Append(input, 0, prevat);
for (int i = al.Count - 1; i >= 0; i--)
{
sb.Append(al[i]);
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
}
/// <summary>
/// Does a split. In the right-to-left case we reorder the
/// array to be forwards.
/// </summary>
internal static String[] Split(Regex regex, String input, int count, int startat)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
String[] result;
if (count == 1)
{
result = new String[1];
result[0] = input;
return result;
}
count -= 1;
Match match = regex.Match(input, startat);
if (!match.Success)
{
result = new String[1];
result[0] = input;
return result;
}
else
{
List<String> al = new List<String>();
if (!regex.RightToLeft)
{
int prevat = 0;
for (; ;)
{
al.Add(input.Substring(prevat, match.Index - prevat));
prevat = match.Index + match.Length;
// add all matched capture groups to the list.
for (int i = 1; i < match.Groups.Count; i++)
{
if (match.IsMatched(i))
al.Add(match.Groups[i].ToString());
}
if (--count == 0)
break;
match = match.NextMatch();
if (!match.Success)
break;
}
al.Add(input.Substring(prevat, input.Length - prevat));
}
else
{
int prevat = input.Length;
for (; ;)
{
al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length));
prevat = match.Index;
// add all matched capture groups to the list.
for (int i = 1; i < match.Groups.Count; i++)
{
if (match.IsMatched(i))
al.Add(match.Groups[i].ToString());
}
if (--count == 0)
break;
match = match.NextMatch();
if (!match.Success)
break;
}
al.Add(input.Substring(0, prevat));
al.Reverse(0, al.Count);
}
return al.ToArray();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Modeling.Shell;
using System.Runtime.InteropServices;
namespace nHydrate.DslPackage.Forms
{
[Guid("12121DCE-997E-41D2-B2DD-B7F558B10DAF")]
public class FindWindow : ToolWindow
{
private FindWindowControl _findControl;
private nHydrate.Dsl.nHydrateModel _model = null;
private DiagramDocView _diagram = null;
private ModelingDocData _docView = null;
private List<Guid> _loadedModels = new List<Guid>();
//creates the tool window
public FindWindow(global::System.IServiceProvider serviceProvider)
: base(serviceProvider)
{
_findControl = new FindWindowControl();
}
/// <summary>
/// Specifies a resource string that appears on the tool window title bar.
/// </summary>
public override string WindowTitle => "nHydrate Object View";
//puts a label on the tool window
public override System.Windows.Forms.IWin32Window Window => this._findControl;
protected override void OnDocumentWindowChanged(ModelingDocView oldView, ModelingDocView newView)
{
if (newView == null && oldView != null)
{
//The model is being unloaded
var m = oldView.DocData.RootElement as nHydrate.Dsl.nHydrateModel;
if (m == null) return;
_loadedModels.Remove(m.Id);
oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.nHydrateModel)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ModelChanged));
#region Entity
oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#region Field
oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#endregion
#endregion
#region View
oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#region Field
oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove(
oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#endregion
#endregion
return;
}
//When the old view is null this is the first time. Only load the first time
if (newView == null)
return;
//Reload model if necessary
_model = newView.DocData.RootElement as nHydrate.Dsl.nHydrateModel;
if (_model == null) return;
_diagram = ((Microsoft.VisualStudio.Modeling.Shell.SingleDiagramDocView)newView).CurrentDesigner.DocView;
_docView = newView.DocData;
//This model is already hooked
if (!_loadedModels.Contains(_model.Id))
{
_loadedModels.Add(_model.Id);
newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.nHydrateModel)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ModelChanged));
#region Entity
newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
newView.DocData.Store.EventManagerDirectory.ElementAdded.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#region Field
newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
newView.DocData.Store.EventManagerDirectory.ElementAdded.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#endregion
#endregion
#region View
newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
newView.DocData.Store.EventManagerDirectory.ElementAdded.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#region Field
newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged));
newView.DocData.Store.EventManagerDirectory.ElementAdded.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler));
newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add(
newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)),
new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler));
#endregion
#endregion
}
_findControl.SetupObjects(_model, _diagram, _docView);
base.OnDocumentWindowChanged(oldView, newView);
}
private void ModelChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e)
{
if (_model.IsLoading) return;
//Name changed so rebuild
if (e.DomainProperty.Name == "DiagramVisibility")
{
_findControl.SetupObjects(_model, _diagram, _docView);
}
}
private void ElementChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e)
{
if (_model.IsLoading) return;
//Name changed so rebuild
if (e.DomainProperty.Name == "Name")
{
_findControl.SetupObjects(_model, _diagram, _docView);
}
}
private void ElementAddHandler(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e)
{
if (_model.IsLoading) return;
_findControl.SetupObjects(_model, _diagram, _docView);
}
private void ElementDeleteHandler(object sender, Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs e)
{
if (_model.IsLoading) return;
_findControl.SetupObjects(_model, _diagram, _docView);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using uWebshop.Newtonsoft.Json.Utilities;
#if NET20
using uWebshop.Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace uWebshop.Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
internal ReadType _readType;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private readonly List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _tokenType; }
}
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
public virtual Type ValueType
{
get { return (_value != null) ? _value.GetType() : null; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] {_currentPosition});
return JsonPosition.BuildPath(positions);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
internal JsonPosition GetPosition(int depth)
{
if (depth < _stack.Count)
return _stack[depth];
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_stack = new List<JsonPosition>(4);
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
_hasExceededMaxDepth = false;
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract int? ReadAsInt32();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract string ReadAsString();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTime? ReadAsDateTime();
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
#endif
internal virtual bool ReadInternal()
{
throw new NotImplementedException();
}
#if !NET20
internal DateTimeOffset? ReadAsDateTimeOffsetInternal()
{
_readType = ReadType.ReadAsDateTimeOffset;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Date)
{
if (Value is DateTime)
SetToken(JsonToken.Date, new DateTimeOffset((DateTime) Value));
return (DateTimeOffset) Value;
}
if (t == JsonToken.Null)
return null;
DateTimeOffset dt;
if (t == JsonToken.String)
{
var s = (string) Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
#endif
internal byte[] ReadAsBytesInternal()
{
_readType = ReadType.ReadAsBytes;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (IsWrappedInTypeObject())
{
byte[] data = ReadAsBytes();
ReadInternal();
SetToken(JsonToken.Bytes, data);
return data;
}
// attempt to convert possible base 64 string to bytes
if (t == JsonToken.String)
{
var s = (string) Value;
byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s);
SetToken(JsonToken.Bytes, data);
return data;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.Bytes)
return (byte[]) Value;
if (t == JsonToken.StartArray)
{
var data = new List<byte>();
while (ReadInternal())
{
t = TokenType;
switch (t)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadAsDecimalInternal()
{
_readType = ReadType.ReadAsDecimal;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is decimal))
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal) Value;
}
if (t == JsonToken.Null)
return null;
decimal d;
if (t == JsonToken.String)
{
var s = (string) Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadAsInt32Internal()
{
_readType = ReadType.ReadAsInt32;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is int))
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture));
return (int) Value;
}
if (t == JsonToken.Null)
return null;
int i;
if (t == JsonToken.String)
{
var s = (string) Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal string ReadAsStringInternal()
{
_readType = ReadType.ReadAsString;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.String)
return (string) Value;
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
{
if (Value != null)
{
string s;
if (Value is IFormattable)
s = ((IFormattable) Value).ToString(null, Culture);
else
s = Value.ToString();
SetToken(JsonToken.String, s);
return s;
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal DateTime? ReadAsDateTimeInternal()
{
_readType = ReadType.ReadAsDateTime;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Date)
return (DateTime) Value;
if (TokenType == JsonToken.Null)
return null;
DateTime dt;
if (TokenType == JsonToken.String)
{
var s = (string) Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (TokenType == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
private bool IsWrappedInTypeObject()
{
_readType = ReadType.Read;
if (TokenType == JsonToken.StartObject)
{
if (!ReadInternal())
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == "$type")
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]"))
{
ReadInternal();
if (Value.ToString() == "$value")
{
return true;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
return false;
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string) value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
UpdateScopeWithFinishedValue();
break;
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
_currentState = State.Finished;
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.F1Help
{
public class F1HelpTests
{
private async Task TestAsync(string markup, string expectedText)
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(markup))
{
var caret = workspace.Documents.First().CursorPosition;
var service = new CSharpHelpContextService();
var actualText = await service.GetHelpTermAsync(workspace.CurrentSolution.Projects.First().Documents.First(), workspace.Documents.First().SelectedSpans.First(), CancellationToken.None);
Assert.Equal(expectedText, actualText);
}
}
private async Task Test_KeywordAsync(string markup, string expectedText)
{
await TestAsync(markup, expectedText + "_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestVoid()
{
await Test_KeywordAsync(@"
class C
{
vo[||]id foo() { }
}", "void");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestReturn()
{
await Test_KeywordAsync(@"
class C
{
void foo()
{
ret[||]urn;
}
}", "return");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPartialType()
{
await Test_KeywordAsync(@"
part[||]ial class C
{
partial void foo();
}", "partialtype");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPartialMethod()
{
await Test_KeywordAsync(@"
partial class C
{
par[||]tial void foo();
}", "partialmethod");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestWhereClause()
{
await Test_KeywordAsync(@"
using System.Linq;
class Program<T> where T : class {
void foo(string[] args)
{
var x = from a in args whe[||]re a.Length > 0 select a;
}
}", "whereclause");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestWhereConstraint()
{
await Test_KeywordAsync(@"
using System.Linq;
class Program<T> wh[||]ere T : class {
void foo(string[] args)
{
var x = from a in args where a.Length > 0 select a;
}
}", "whereconstraint");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestPreprocessor()
{
await TestAsync(@"
#regi[||]on
#endregion", "#region");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConstructor()
{
await TestAsync(@"
namespace N
{
class C
{
void foo()
{
var x = new [|C|]();
}
}
}", "N.C.#ctor");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericClass()
{
await TestAsync(@"
namespace N
{
class C<T>
{
void foo()
{
[|C|]<int> c;
}
}
}", "N.C`1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericMethod()
{
await TestAsync(@"
namespace N
{
class C<T>
{
void foo<T, U, V>(T t, U u, V v)
{
C<int> c;
c.f[|oo|](1, 1, 1);
}
}
}", "N.C`1.foo``3");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestOperator()
{
await TestAsync(@"
namespace N
{
class C
{
void foo()
{
var two = 1 [|+|] 1;
}
}", "+_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestVar()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var[||] x = 3;
}
}", "var_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestEquals()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x =[||] 3;
}
}", "=_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestFromIn()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x = from n i[||]n { 1} select n
}
}", "from_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestProperty()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
new UriBuilder().Fragm[||]ent;
}
}", "System.UriBuilder.Fragment");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestForeachIn()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (var x in[||] { 1} )
{
}
}
}", "in_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestRegionDescription()
{
await TestAsync(@"
class Program
{
static void Main(string[] args)
{
#region Begin MyR[||]egion for testing
#endregion End
}
}", "#region");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestGenericAngle()
{
await TestAsync(@"class Program
{
static void generic<T>(T t)
{
generic[||]<int>(0);
}
}", "Program.generic``1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLocalReferenceIsType()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int x;
x[||];
}
}", "System.Int32");
}
[WorkItem(864266)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConstantField()
{
await TestAsync(@"class Program
{
static void Main(string[] args)
{
var i = int.Ma[||]xValue;
}
}", "System.Int32.MaxValue");
}
[WorkItem(862420)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestParameter()
{
await TestAsync(@"class Class2
{
void M1(int par[||]ameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}
", "System.Int32");
}
[WorkItem(862420)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestArgumentType()
{
await TestAsync(@"class Class2
{
void M1(int pa[||]rameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}
", "System.Int32");
}
[WorkItem(862396)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestNoToken()
{
await TestAsync(@"class Program
{
static void Main(string[] args)
{
[||]
}
}", "");
}
[WorkItem(862328)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLiteral()
{
await TestAsync(@"class Program
{
static void Main(string[] args)
{
Main(new string[] { ""fo[||]o"" });
}
}", "System.String");
}
[WorkItem(862478)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestColonColon()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
global:[||]:System.Console.Write("");
}
}", "::_CSharpKeyword");
}
[WorkItem(864658)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestNullable()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int?[||] a = int.MaxValue;
a.Value.GetHashCode();
}
}", "System.Nullable`1");
}
[WorkItem(863517)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestAfterLastToken()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (char var in ""!!!"")$$[||]
{
}
}
}", "");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestConditional()
{
await TestAsync(@"class Program
{
static void Main(string[] args)
{
var x = true [|?|] true : false;
}
}", "?_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestLocalVar()
{
await TestAsync(@"class C
{
void M()
{
var a = 0;
int v[||]ar = 1;
}
}", "System.Int32");
}
[WorkItem(867574)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestFatArrow()
{
await TestAsync(@"class C
{
void M()
{
var a = new System.Action(() =[||]> { });
}
}", "=>_CSharpKeyword");
}
[WorkItem(867572)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestSubscription()
{
await TestAsync(@"class CCC
{
event System.Action e;
void M()
{
e +[||]= () => { };
}
}", "CCC.e.add");
}
[WorkItem(867554)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestComment()
{
await TestAsync(@"// some comm[||]ents here", "comments");
}
[WorkItem(867529)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestDynamic()
{
await TestAsync(@"class C
{
void M()
{
dyna[||]mic d = 0;
}
}", "dynamic_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public async Task TestRangeVariable()
{
await TestAsync(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var zzz = from y in args select [||]y;
}
}", "System.String");
}
}
}
| |
using System;
namespace csmatio.types
{
/// <summary>
/// A base class that represents a generic Matlab Array object
/// </summary>
/// <author>David Zier (david.zier@gmail.com)</author>
public class MLArray
{
/* Matlab array types (Classes) */
/// <summary>Unknown Class</summary>
public const int mxUNKNOWN_CLASS = 0;
/// <summary>Cell Array Class</summary>
public const int mxCELL_CLASS = 1;
/// <summary>Structure Class</summary>
public const int mxSTRUCT_CLASS = 2;
/// <summary>Object Class</summary>
public const int mxOBJECT_CLASS = 3;
/// <summary>Character Array Class</summary>
public const int mxCHAR_CLASS = 4;
/// <summary>Sparse Array Class</summary>
public const int mxSPARSE_CLASS = 5;
/// <summary>Double Precision Array Class</summary>
public const int mxDOUBLE_CLASS = 6;
/// <summary>Single Precision Array Class</summary>
public const int mxSINGLE_CLASS = 7;
/// <summary>8-bit, Signed Integer Class</summary>
public const int mxINT8_CLASS = 8;
/// <summary>8-bit, Unsigned Integer Class</summary>
public const int mxUINT8_CLASS = 9;
/// <summary>16-bit, Signed Integer Class</summary>
public const int mxINT16_CLASS = 10;
/// <summary>16-bit, Unsigned Integer Class</summary>
public const int mxUINT16_CLASS = 11;
/// <summary>32-bit, Signed Integer Class</summary>
public const int mxINT32_CLASS = 12;
/// <summary>32-bit, Unsigned Integer Class</summary>
public const int mxUINT32_CLASS = 13;
/// <summary>64-bit, Signed Integer Class</summary>
public const int mxINT64_CLASS = 14;
/// <summary>64-bit, Unsigned Integer Class</summary>
public const int mxUINT64_CLASS = 15;
/// <summary>Function Handle Class</summary>
public const int mxFUNCTION_CLASS = 16;
/// <summary>Opaque Class</summary>
public const int mxOPAQUE_CLASS = 17;
/* Matlab array flags */
/// <summary>Complex Flag</summary>
public const int mtFLAG_COMPLEX = 0x0800;
/// <summary>Global Flag</summary>
public const int mtFLAG_GLOBAL = 0x0400;
/// <summary>Logical Flag</summary>
public const int mtFLAG_LOGICAL = 0x0200;
/// <summary>Mask for Flag to determine Flag Type</summary>
public const int mtFLAG_TYPE = 0xFF;
/// <summary>
/// The array dimensions.
/// </summary>
protected int[] _dims;
/// <summary>
/// The name of the array, default name is '@'.
/// </summary>
protected string _name;
/// <summary>
/// Any <c>mtFLAG</c> type of attributes.
/// </summary>
protected int _attributes;
/// <summary>
/// The <c>mxCLASS</c> MATLAB Array Types (Classes).
/// </summary>
protected int _type;
/// <summary>
/// Construct an MLArray object
/// </summary>
/// <param name="name">The name of the MLArray object.</param>
/// <param name="dims">A dimensions array for the object.</param>
/// <param name="type">The Matlab Array Type</param>
/// <param name="attributes">Attribute parameters for the array.</param>
public MLArray( string name, int[] dims, int type, int attributes )
{
_dims = new int[dims.Length];
Array.Copy( dims, 0, _dims, 0, dims.Length );
if( name != null && !name.Equals("") )
_name = name;
else
_name = "@"; // Default name
_type = type;
_attributes = attributes;
}
/// <summary>Gets the name of the array.</summary>
public string Name{ get{ return _name; } }
/// <summary>Gets the flags for this array.</summary>
public virtual int Flags
{
get{ return (int)((uint)(_type & mtFLAG_TYPE) | (uint)(_attributes & 0xFFFFFF00)); }
}
/// <summary>
/// Converts the name string into a byte array and returns it.
/// </summary>
/// <returns>A byte array.</returns>
public byte[] GetNameToByteArray()
{
byte[] bs = new byte[ _name.Length ];
for( int i = 0; i < _name.Length; i++ )
bs[i] = (byte)_name[i];
return bs;
}
/// <summary>
/// Gets the arrays dimensions.
/// </summary>
public int[] Dimensions
{
get
{
int[] ai = null;
if( _dims != null )
{
ai = new int[_dims.Length];
Array.Copy( _dims, 0, ai, 0, _dims.Length );
}
return ai;
}
}
/// <summary>Get the M dimension.</summary>
public int M{ get{ return( (_dims != null) ? _dims[0] : 0 ); } }
/// <summary>Get the N dimension.</summary>
public int N
{
get
{
int i = 0;
if( _dims != null )
{
if( _dims.Length > 2 )
{
i = 1;
for( int j = 1; j < _dims.Length; j++ )
i *= _dims[j];
}
else
i = _dims[1];
}
return i;
}
}
/// <summary>
/// Get the N dimensions or the size of the dimensions array
/// </summary>
public int NDimensions{ get{ return( (_dims != null) ? _dims.Length : 0 ); } }
/// <summary>
/// Get the size of the array.
/// </summary>
public int Size{ get{ return M * N; } }
/// <summary>
/// Get the Matlab Array Type for this array
/// </summary>
public int Type{ get{ return _type; } }
/// <summary>
/// Is the array empty?
/// </summary>
public bool IsEmpty{ get{ return N == 0; } }
/// <summary>
/// Converts a Matlab Array Class type into a string representation.
/// </summary>
/// <param name="type">A Matlab Array Class type</param>
/// <returns>A string representation.</returns>
public static string TypeToString( int type )
{
switch( type )
{
case mxUNKNOWN_CLASS:
return "unknown";
case mxCELL_CLASS:
return "cell";
case mxSTRUCT_CLASS:
return "struct";
case mxCHAR_CLASS:
return "char";
case mxSPARSE_CLASS:
return "sparse";
case mxDOUBLE_CLASS:
return "double";
case mxSINGLE_CLASS:
return "single";
case mxINT8_CLASS:
return "int8";
case mxUINT8_CLASS:
return "uint8";
case mxINT16_CLASS:
return "int16";
case mxUINT16_CLASS:
return "uint16";
case mxINT32_CLASS:
return "int32";
case mxUINT32_CLASS:
return "uint32";
case mxINT64_CLASS:
return "int64";
case mxUINT64_CLASS:
return "uint64";
case mxFUNCTION_CLASS:
return "function_handle";
case mxOPAQUE_CLASS:
return "opaque";
case mxOBJECT_CLASS:
return "object";
default:
return "unknown";
}
}
/// <summary>Is Array a Cell Class Type?</summary>
public bool IsCell{ get{ return _type == mxCELL_CLASS; } }
/// <summary>Is Array a Char Class Type?</summary>
public bool IsChar{ get{ return _type == mxCHAR_CLASS; } }
/// <summary>Is Array a Complex Number?</summary>
public bool IsComplex{ get{ return (_attributes & mtFLAG_COMPLEX) != 0; } }
/// <summary>Is Array a Sparse Array Class Type?</summary>
public bool IsSparse{ get{ return _type == mxSPARSE_CLASS; } }
/// <summary>Is Array a Struct Type?</summary>
public bool IsStruct{ get{ return _type == mxSTRUCT_CLASS; } }
/// <summary>Is Array a Double Precision Type?</summary>
public bool IsDouble{ get{ return _type == mxDOUBLE_CLASS; } }
/// <summary>Is Array a Single Precision Type?</summary>
public bool IsSingle{ get{ return _type == mxSINGLE_CLASS; } }
/// <summary>Is Array a 8-bit Signed Integer Type?</summary>
public bool IsInt8{ get{ return _type == mxINT8_CLASS; } }
/// <summary>Is Array a 16-bit Signed Integer Type?</summary>
public bool IsInt16{ get{ return _type == mxINT16_CLASS; } }
/// <summary>Is Array a 32-bit Signed Integer Type?</summary>
public bool IsInt32{ get{ return _type == mxINT32_CLASS; } }
/// <summary>Is Array a 8-bit Unsigned Integer Type?</summary>
public bool IsUInt8{ get{ return _type == mxUINT8_CLASS; } }
/// <summary>Is Array a 16-bit Unsigned Integer Type?</summary>
public bool IsUInt16{ get{ return _type == mxUINT16_CLASS; } }
/// <summary>Is Array a 32-bit Unsigned Integer Type?</summary>
public bool IsUInt32{ get{ return _type == mxUINT32_CLASS; } }
/// <summary>Is Array a 64-bit Signed Integer Type?</summary>
public bool IsInt64{ get{ return _type == mxINT64_CLASS; } }
/// <summary>Is Array a 64-bit Unsigned Integer Type?</summary>
public bool IsUInt64{ get{ return _type == mxUINT64_CLASS; } }
/// <summary>Is Array an Object Type?</summary>
public bool IsObject{ get{ return _type == mxOBJECT_CLASS; } }
/// <summary>Is Array an Opaque Type?</summary>
public bool IsOpaque{ get{ return _type == mxOPAQUE_CLASS; } }
/// <summary>Is Array a logical value?</summary>
public bool IsLogical{ get{ return (_attributes & mtFLAG_LOGICAL) != 0; } }
/// <summary>Is Array a Function Object?</summary>
public bool IsFunctionObject{ get{ return _type == mxFUNCTION_CLASS; } }
/// <summary>Is Array an Unknown Type?</summary>
public bool IsUnknown{ get{ return _type == mxUNKNOWN_CLASS; } }
/// <summary>
/// Get the index into the byte array.
/// </summary>
/// <param name="m">The m index of an MxN array.</param>
/// <param name="n">The n index of an MxN array.</param>
/// <returns>An index into the byte array.</returns>
protected int GetIndex( int m, int n )
{
return m+n*M;
}
/// <summary>
/// A string representation for this MLArray object
/// </summary>
/// <returns>A string representation.</returns>
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if( _dims != null )
{
sb.Append("[");
if( _dims.Length > 3 )
{
sb.Append(_dims.Length + "D");
}
else
{
sb.Append(_dims[0] + "x" + _dims[1]);
if( _dims.Length == 3)
sb.Append( "x" + _dims[2] );
}
sb.Append( " " + TypeToString( _type ) + " array" );
if( IsSparse )
{
sb.Append(" (sparse");
if( IsComplex )
sb.Append(" complex");
sb.Append(")");
}
else if( IsComplex )
{
sb.Append(" (complex)");
}
sb.Append("]");
}
else
{
sb.Append("[invalid]");
}
return sb.ToString();
}
/// <summary>
/// Get a string representation for the content of the array.
/// </summary>
/// <returns>A string representation.</returns>
public virtual string ContentToString()
{
return "content cannot be displayed";
}
}
}
| |
using J2N.Threading.Atomic;
using Lucene.Net.Attributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using Console = Lucene.Net.Util.SystemConsole;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Replicator
{
/*
* 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.
*/
[TestFixture]
public class IndexReplicationClientTest : ReplicatorTestCase
{
private class IndexReadyCallback : IDisposable
{
private readonly Directory indexDir;
private DirectoryReader reader;
private long lastGeneration = -1;
public IndexReadyCallback(Directory indexDir)
{
this.indexDir = indexDir;
if (DirectoryReader.IndexExists(indexDir))
{
reader = DirectoryReader.Open(indexDir);
lastGeneration = reader.IndexCommit.Generation;
}
}
public bool? Call()
{
if (reader == null)
{
reader = DirectoryReader.Open(indexDir);
lastGeneration = reader.IndexCommit.Generation;
}
else
{
DirectoryReader newReader = DirectoryReader.OpenIfChanged(reader);
assertNotNull("should not have reached here if no changes were made to the index", newReader);
long newGeneration = newReader.IndexCommit.Generation;
assertTrue("expected newer generation; current=" + lastGeneration + " new=" + newGeneration, newGeneration > lastGeneration);
reader.Dispose();
reader = newReader;
lastGeneration = newGeneration;
TestUtil.CheckIndex(indexDir);
}
return null;
}
public void Dispose()
{
IOUtils.Dispose(reader);
}
}
private MockDirectoryWrapper publishDir, handlerDir;
private IReplicator replicator;
private ISourceDirectoryFactory sourceDirFactory;
private ReplicationClient client;
private IReplicationHandler handler;
private IndexWriter publishWriter;
private IndexReadyCallback callback;
private const string VERSION_ID = "version";
private void AssertHandlerRevision(int expectedId, Directory dir)
{
// loop as long as client is alive. test-framework will terminate us if
// there's a serious bug, e.g. client doesn't really update. otherwise,
// introducing timeouts is not good, can easily lead to false positives.
while (client.IsUpdateThreadAlive)
{
// give client a chance to update
Thread.Sleep(100);
try
{
DirectoryReader reader = DirectoryReader.Open(dir);
try
{
int handlerId = int.Parse(reader.IndexCommit.UserData[VERSION_ID], NumberStyles.HexNumber);
if (expectedId == handlerId)
{
return;
}
else if (Verbose)
{
Console.WriteLine("expectedID=" + expectedId + " actual=" + handlerId + " generation=" + reader.IndexCommit.Generation);
}
}
finally
{
reader.Dispose();
}
}
catch (Exception)
{
// we can hit IndexNotFoundException or e.g. EOFException (on
// segments_N) because it is being copied at the same time it is read by
// DirectoryReader.open().
}
}
}
private IRevision CreateRevision(int id)
{
publishWriter.AddDocument(new Document());
publishWriter.SetCommitData(new Dictionary<string, string>{
{ VERSION_ID, id.ToString("X") }
});
publishWriter.Commit();
return new IndexRevision(publishWriter);
}
public override void SetUp()
{
base.SetUp();
publishDir = NewMockDirectory();
handlerDir = NewMockDirectory();
sourceDirFactory = new PerSessionDirectoryFactory(CreateTempDir("replicationClientTest").FullName);
replicator = new LocalReplicator();
callback = new IndexReadyCallback(handlerDir);
handler = new IndexReplicationHandler(handlerDir, callback.Call);
client = new ReplicationClient(replicator, handler, sourceDirFactory);
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, null);
conf.IndexDeletionPolicy = new SnapshotDeletionPolicy(conf.IndexDeletionPolicy);
publishWriter = new IndexWriter(publishDir, conf);
}
public override void TearDown()
{
IOUtils.Dispose(client, callback, publishWriter, replicator, publishDir, handlerDir);
base.TearDown();
}
[Test]
public void TestNoUpdateThread()
{
assertNull("no version expected at start", handler.CurrentVersion);
// Callback validates the replicated ind
replicator.Publish(CreateRevision(1));
client.UpdateNow();
replicator.Publish(CreateRevision(2));
client.UpdateNow();
// Publish two revisions without update,
replicator.Publish(CreateRevision(3));
replicator.Publish(CreateRevision(4));
client.UpdateNow();
}
[Test]
public void TestUpdateThread()
{
client.StartUpdateThread(10, "index");
replicator.Publish(CreateRevision(1));
AssertHandlerRevision(1, handlerDir);
replicator.Publish(CreateRevision(2));
AssertHandlerRevision(2, handlerDir);
// Publish two revisions without update, handler should be upgraded to latest
replicator.Publish(CreateRevision(3));
replicator.Publish(CreateRevision(4));
AssertHandlerRevision(4, handlerDir);
}
[Test]
public void TestRestart()
{
replicator.Publish(CreateRevision(1));
client.UpdateNow();
replicator.Publish(CreateRevision(2));
client.UpdateNow();
client.StopUpdateThread();
client.Dispose();
client = new ReplicationClient(replicator, handler, sourceDirFactory);
// Publish two revisions without update, handler should be upgraded to latest
replicator.Publish(CreateRevision(3));
replicator.Publish(CreateRevision(4));
client.UpdateNow();
}
// This test verifies that the client and handler do not end up in a corrupt
// index if exceptions are thrown at any point during replication. Either when
// a client copies files from the server to the temporary space, or when the
// handler copies them to the index directory.
[Test]
[Deadlock]
public void TestConsistencyOnExceptions()
{
// so the handler's index isn't empty
replicator.Publish(CreateRevision(1));
client.UpdateNow();
client.Dispose();
callback.Dispose();
// Replicator violates write-once policy. It may be that the
// handler copies files to the index dir, then fails to copy a
// file and reverts the copy operation. On the next attempt, it
// will copy the same file again. There is nothing wrong with this
// in a real system, but it does violate write-once, and MDW
// doesn't like it. Disabling it means that we won't catch cases
// where the handler overwrites an existing index file, but
// there's nothing currently we can do about it, unless we don't
// use MDW.
handlerDir.PreventDoubleWrite = false;
// wrap sourceDirFactory to return a MockDirWrapper so we can simulate errors
ISourceDirectoryFactory @in = sourceDirFactory;
AtomicInt32 failures = new AtomicInt32(AtLeast(10));
// wrap sourceDirFactory to return a MockDirWrapper so we can simulate errors
sourceDirFactory = new SourceDirectoryFactoryAnonymousInnerClass(this, @in, failures);
handler = new IndexReplicationHandler(handlerDir, () =>
{
if (Random.NextDouble() < 0.2 && failures > 0)
throw new Exception("random exception from callback");
return null;
});
client = new ReplicationClientAnonymousInnerClass(this, replicator, handler, sourceDirFactory, failures);
client.StartUpdateThread(10, "index");
Directory baseHandlerDir = handlerDir.Delegate;
int numRevisions = AtLeast(20);
for (int i = 2; i < numRevisions; i++)
{
replicator.Publish(CreateRevision(i));
AssertHandlerRevision(i, baseHandlerDir);
}
// disable errors -- maybe randomness didn't exhaust all allowed failures,
// and we don't want e.g. CheckIndex to hit false errors.
handlerDir.MaxSizeInBytes = 0;
handlerDir.RandomIOExceptionRate = 0.0;
handlerDir.RandomIOExceptionRateOnOpen = 0.0;
}
private class SourceDirectoryFactoryAnonymousInnerClass : ISourceDirectoryFactory
{
private long clientMaxSize = 100, handlerMaxSize = 100;
private double clientExRate = 1.0, handlerExRate = 1.0;
private readonly IndexReplicationClientTest test;
private readonly ISourceDirectoryFactory @in;
private readonly AtomicInt32 failures;
public SourceDirectoryFactoryAnonymousInnerClass(IndexReplicationClientTest test, ISourceDirectoryFactory @in, AtomicInt32 failures)
{
this.test = test;
this.@in = @in;
this.failures = failures;
}
public void CleanupSession(string sessionId)
{
@in.CleanupSession(sessionId);
}
public Directory GetDirectory(string sessionId, string source)
{
Directory dir = @in.GetDirectory(sessionId, source);
if (Random.nextBoolean() && failures > 0)
{ // client should fail, return wrapped dir
MockDirectoryWrapper mdw = new MockDirectoryWrapper(Random, dir);
mdw.RandomIOExceptionRateOnOpen = clientExRate;
mdw.MaxSizeInBytes = clientMaxSize;
mdw.RandomIOExceptionRate = clientExRate;
mdw.CheckIndexOnDispose = false;
clientMaxSize *= 2;
clientExRate /= 2;
return mdw;
}
if (failures > 0 && Random.nextBoolean())
{ // handler should fail
test.handlerDir.MaxSizeInBytes = handlerMaxSize;
test.handlerDir.RandomIOExceptionRateOnOpen = handlerExRate;
test.handlerDir.RandomIOExceptionRate = handlerExRate;
handlerMaxSize *= 2;
handlerExRate /= 2;
}
else
{
// disable errors
test.handlerDir.MaxSizeInBytes = 0;
test.handlerDir.RandomIOExceptionRate = 0;
test.handlerDir.RandomIOExceptionRateOnOpen = 0.0;
}
return dir;
}
}
private class ReplicationClientAnonymousInnerClass : ReplicationClient
{
private readonly IndexReplicationClientTest test;
private readonly AtomicInt32 failures;
public ReplicationClientAnonymousInnerClass(IndexReplicationClientTest test, IReplicator replicator, IReplicationHandler handler, ISourceDirectoryFactory factory, AtomicInt32 failures)
: base(replicator, handler, factory)
{
this.test = test;
this.failures = failures;
}
protected override void HandleUpdateException(Exception exception)
{
if (exception is IOException)
{
if (Verbose)
{
Console.WriteLine("hit exception during update: " + exception);
}
try
{
// test that the index can be read and also some basic statistics
DirectoryReader reader = DirectoryReader.Open(test.handlerDir.Delegate);
try
{
int numDocs = reader.NumDocs;
int version = int.Parse(reader.IndexCommit.UserData[VERSION_ID], NumberStyles.HexNumber);
assertEquals(numDocs, version);
}
finally
{
reader.Dispose();
}
// verify index consistency
TestUtil.CheckIndex(test.handlerDir.Delegate);
}
finally
{
// count-down number of failures
failures.DecrementAndGet();
if (Debugging.AssertsEnabled) Debugging.Assert(failures >= 0, () => "handler failed too many times: " + failures);
if (Verbose)
{
if (failures == 0)
{
Console.WriteLine("no more failures expected");
}
else
{
Console.WriteLine("num failures left: " + failures);
}
}
}
}
else
{
throw exception;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The MatchCollection lists the successful matches that
// result when searching a string for a regular expression.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Text.RegularExpressions
{
/*
* This collection returns a sequence of successful match results, either
* from GetMatchCollection() or GetExecuteCollection(). It stops when the
* first failure is encountered (it does not return the failed match).
*/
/// <summary>
/// Represents the set of names appearing as capturing group
/// names in a regular expression.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(CollectionDebuggerProxy<Match>))]
public class MatchCollection : IList<Match>, IReadOnlyList<Match>, IList
{
private readonly Regex _regex;
private readonly List<Match> _matches;
private bool _done;
private readonly string _input;
private readonly int _beginning;
private readonly int _length;
private int _startat;
private int _prevlen;
internal MatchCollection(Regex regex, string input, int beginning, int length, int startat)
{
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
_regex = regex;
_input = input;
_beginning = beginning;
_length = length;
_startat = startat;
_prevlen = -1;
_matches = new List<Match>();
_done = false;
}
public bool IsReadOnly => true;
/// <summary>
/// Returns the number of captures.
/// </summary>
public int Count
{
get
{
EnsureInitialized();
return _matches.Count;
}
}
/// <summary>
/// Returns the ith Match in the collection.
/// </summary>
public virtual Match this[int i]
{
get
{
if (i < 0)
throw new ArgumentOutOfRangeException(nameof(i));
Match match = GetMatch(i);
if (match == null)
throw new ArgumentOutOfRangeException(nameof(i));
return match;
}
}
/// <summary>
/// Provides an enumerator in the same order as Item[i].
/// </summary>
public IEnumerator GetEnumerator() => new Enumerator(this);
IEnumerator<Match> IEnumerable<Match>.GetEnumerator() => new Enumerator(this);
private Match GetMatch(int i)
{
Debug.Assert(i >= 0, "i cannot be negative.");
if (_matches.Count > i)
return _matches[i];
if (_done)
return null;
Match match;
do
{
match = _regex.Run(false, _prevlen, _input, _beginning, _length, _startat);
if (!match.Success)
{
_done = true;
return null;
}
_matches.Add(match);
_prevlen = match.Length;
_startat = match._textpos;
} while (_matches.Count <= i);
return match;
}
private void EnsureInitialized()
{
if (!_done)
{
GetMatch(int.MaxValue);
}
}
public bool IsSynchronized => false;
public object SyncRoot => this;
public void CopyTo(Array array, int arrayIndex)
{
EnsureInitialized();
((ICollection)_matches).CopyTo(array, arrayIndex);
}
public void CopyTo(Match[] array, int arrayIndex)
{
EnsureInitialized();
_matches.CopyTo(array, arrayIndex);
}
int IList<Match>.IndexOf(Match item)
{
EnsureInitialized();
return _matches.IndexOf(item);
}
void IList<Match>.Insert(int index, Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList<Match>.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
Match IList<Match>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
void ICollection<Match>.Add(Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<Match>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<Match>.Contains(Match item)
{
EnsureInitialized();
return _matches.Contains(item);
}
bool ICollection<Match>.Remove(Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
int IList.Add(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.Contains(object value) =>
value is Match && ((ICollection<Match>)this).Contains((Match)value);
int IList.IndexOf(object value) =>
value is Match ? ((IList<Match>)this).IndexOf((Match)value) : -1;
void IList.Insert(int index, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.IsFixedSize => true;
void IList.Remove(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
private sealed class Enumerator : IEnumerator<Match>
{
private readonly MatchCollection _collection;
private int _index;
internal Enumerator(MatchCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
if (_index == -2)
return false;
_index++;
Match match = _collection.GetMatch(_index);
if (match == null)
{
_index = -2;
return false;
}
return true;
}
public Match Current
{
get
{
if (_index < 0)
throw new InvalidOperationException(SR.EnumNotStarted);
return _collection.GetMatch(_index);
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose() { }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using static Orleans.Runtime.MembershipService.SiloHealthMonitor;
namespace Orleans.Runtime.MembershipService
{
/// <summary>
/// Responsible for ensuring that this silo monitors other silos in the cluster.
/// </summary>
internal class ClusterHealthMonitor : IHealthCheckParticipant, ILifecycleParticipant<ISiloLifecycle>, ClusterHealthMonitor.ITestAccessor
{
private readonly CancellationTokenSource shutdownCancellation = new CancellationTokenSource();
private readonly ILocalSiloDetails localSiloDetails;
private readonly IServiceProvider serviceProvider;
private readonly MembershipTableManager membershipService;
private readonly ILogger<ClusterHealthMonitor> log;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly IOptionsMonitor<ClusterMembershipOptions> clusterMembershipOptions;
private ImmutableDictionary<SiloAddress, SiloHealthMonitor> monitoredSilos = ImmutableDictionary<SiloAddress, SiloHealthMonitor>.Empty;
private MembershipVersion observedMembershipVersion;
private Func<SiloAddress, SiloHealthMonitor> createMonitor;
private Func<SiloHealthMonitor, ProbeResult, Task> onProbeResult;
/// <summary>
/// Exposes private members of <see cref="ClusterHealthMonitor"/> for test purposes.
/// </summary>
internal interface ITestAccessor
{
ImmutableDictionary<SiloAddress, SiloHealthMonitor> MonitoredSilos { get; set; }
Func<SiloAddress, SiloHealthMonitor> CreateMonitor { get; set; }
MembershipVersion ObservedVersion { get; }
Func<SiloHealthMonitor, ProbeResult, Task> OnProbeResult { get; set; }
}
public ClusterHealthMonitor(
ILocalSiloDetails localSiloDetails,
MembershipTableManager membershipService,
ILogger<ClusterHealthMonitor> log,
IOptionsMonitor<ClusterMembershipOptions> clusterMembershipOptions,
IFatalErrorHandler fatalErrorHandler,
IServiceProvider serviceProvider)
{
this.localSiloDetails = localSiloDetails;
this.serviceProvider = serviceProvider;
this.membershipService = membershipService;
this.log = log;
this.fatalErrorHandler = fatalErrorHandler;
this.clusterMembershipOptions = clusterMembershipOptions;
this.onProbeResult = this.OnProbeResultInternal;
Func<SiloHealthMonitor, ProbeResult, Task> onProbeResultFunc = (siloHealthMonitor, probeResult) => this.onProbeResult(siloHealthMonitor, probeResult);
this.createMonitor = silo => ActivatorUtilities.CreateInstance<SiloHealthMonitor>(serviceProvider, silo, onProbeResultFunc);
}
ImmutableDictionary<SiloAddress, SiloHealthMonitor> ITestAccessor.MonitoredSilos { get => this.monitoredSilos; set => this.monitoredSilos = value; }
Func<SiloAddress, SiloHealthMonitor> ITestAccessor.CreateMonitor { get => this.createMonitor; set => this.createMonitor = value; }
MembershipVersion ITestAccessor.ObservedVersion => this.observedMembershipVersion;
Func<SiloHealthMonitor, ProbeResult, Task> ITestAccessor.OnProbeResult { get => this.onProbeResult; set => this.onProbeResult = value; }
/// <summary>
/// Gets the collection of monitored silos.
/// </summary>
public ImmutableDictionary<SiloAddress, SiloHealthMonitor> SiloMonitors => this.monitoredSilos;
private async Task ProcessMembershipUpdates()
{
try
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting to process membership updates");
await foreach (var tableSnapshot in this.membershipService.MembershipTableUpdates.WithCancellation(this.shutdownCancellation.Token))
{
var newMonitoredSilos = this.UpdateMonitoredSilos(tableSnapshot, this.monitoredSilos, DateTime.UtcNow);
foreach (var pair in this.monitoredSilos)
{
if (!newMonitoredSilos.ContainsKey(pair.Key))
{
var cancellation = new CancellationTokenSource(this.clusterMembershipOptions.CurrentValue.ProbeTimeout).Token;
await pair.Value.StopAsync(cancellation);
}
}
this.monitoredSilos = newMonitoredSilos;
this.observedMembershipVersion = tableSnapshot.Version;
}
}
catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception))
{
this.fatalErrorHandler.OnFatalException(this, nameof(ProcessMembershipUpdates), exception);
}
finally
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopped processing membership updates");
}
}
[Pure]
private ImmutableDictionary<SiloAddress, SiloHealthMonitor> UpdateMonitoredSilos(
MembershipTableSnapshot membership,
ImmutableDictionary<SiloAddress, SiloHealthMonitor> monitoredSilos,
DateTime now)
{
// If I am still not fully functional, I should not be probing others.
if (!membership.Entries.TryGetValue(this.localSiloDetails.SiloAddress, out var self) || !IsFunctionalForMembership(self.Status))
{
return ImmutableDictionary<SiloAddress, SiloHealthMonitor>.Empty;
}
// keep watching shutting-down silos as well, so we can properly ensure they are dead.
var tmpList = new List<SiloAddress>();
foreach (var member in membership.Entries)
{
if (IsFunctionalForMembership(member.Value.Status))
{
tmpList.Add(member.Key);
}
}
tmpList.Sort((x, y) => x.GetConsistentHashCode().CompareTo(y.GetConsistentHashCode()));
int myIndex = tmpList.FindIndex(el => el.Equals(self.SiloAddress));
if (myIndex < 0)
{
// this should not happen ...
var error = string.Format("This silo {0} status {1} is not in its own local silo list! This is a bug!", self.SiloAddress.ToLongString(), self.Status);
log.Error(ErrorCode.Runtime_Error_100305, error);
throw new OrleansMissingMembershipEntryException(error);
}
// Go over every node excluding me,
// Find up to NumProbedSilos silos after me, which are not suspected by anyone and add them to the probedSilos,
// In addition, every suspected silo you encounter on the way, add it to the probedSilos.
var silosToWatch = new List<SiloAddress>();
var additionalSilos = new List<SiloAddress>();
for (int i = 0; i < tmpList.Count - 1 && silosToWatch.Count < this.clusterMembershipOptions.CurrentValue.NumProbedSilos; i++)
{
var candidate = tmpList[(myIndex + i + 1) % tmpList.Count];
var candidateEntry = membership.Entries[candidate];
if (candidate.IsSameLogicalSilo(this.localSiloDetails.SiloAddress)) continue;
bool isSuspected = candidateEntry.GetFreshVotes(now, this.clusterMembershipOptions.CurrentValue.DeathVoteExpirationTimeout).Count > 0;
if (isSuspected)
{
additionalSilos.Add(candidate);
}
else
{
silosToWatch.Add(candidate);
}
}
// Take new watched silos, but leave the probe counters for the old ones.
var newProbedSilos = ImmutableDictionary.CreateBuilder<SiloAddress, SiloHealthMonitor>();
foreach (var silo in silosToWatch.Union(additionalSilos))
{
SiloHealthMonitor monitor;
if (!monitoredSilos.TryGetValue(silo, out monitor))
{
monitor = this.createMonitor(silo);
monitor.Start();
}
newProbedSilos[silo] = monitor;
}
var result = newProbedSilos.ToImmutable();
if (!AreTheSame(monitoredSilos, result))
{
log.Info(ErrorCode.MembershipWatchList, "Will watch (actively ping) {0} silos: {1}",
newProbedSilos.Count, Utils.EnumerableToString(newProbedSilos.Keys, silo => silo.ToLongString()));
}
return result;
static bool AreTheSame<T>(ImmutableDictionary<SiloAddress, T> first, ImmutableDictionary<SiloAddress, T> second)
{
return first.Count == second.Count && first.Count == first.Keys.Intersect(second.Keys).Count();
}
static bool IsFunctionalForMembership(SiloStatus status)
{
return status == SiloStatus.Active || status == SiloStatus.ShuttingDown || status == SiloStatus.Stopping;
}
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
var tasks = new List<Task>();
lifecycle.Subscribe(nameof(ClusterHealthMonitor), ServiceLifecycleStage.Active, OnActiveStart, OnActiveStop);
Task OnActiveStart(CancellationToken ct)
{
tasks.Add(Task.Run(() => this.ProcessMembershipUpdates()));
return Task.CompletedTask;
}
async Task OnActiveStop(CancellationToken ct)
{
this.shutdownCancellation.Cancel(throwOnFirstException: false);
foreach (var monitor in this.monitoredSilos.Values)
{
tasks.Add(monitor.StopAsync(ct));
}
this.monitoredSilos = ImmutableDictionary<SiloAddress, SiloHealthMonitor>.Empty;
// Allow some minimum time for graceful shutdown.
var shutdownGracePeriod = Task.WhenAll(Task.Delay(ClusterMembershipOptions.ClusteringShutdownGracePeriod), ct.WhenCancelled());
await Task.WhenAny(shutdownGracePeriod, Task.WhenAll(tasks));
}
}
/// <summary>
/// Performs the default action when a new probe result is created.
/// </summary>
private async Task OnProbeResultInternal(SiloHealthMonitor monitor, ProbeResult probeResult)
{
// Do not act on probe results if shutdown is in progress.
if (this.shutdownCancellation.IsCancellationRequested)
{
return;
}
if (probeResult.IsDirectProbe)
{
if (probeResult.Status == ProbeResultStatus.Failed && probeResult.FailedProbeCount >= this.clusterMembershipOptions.CurrentValue.NumMissedProbesLimit)
{
await this.membershipService.TryToSuspectOrKill(monitor.SiloAddress).ConfigureAwait(false);
}
}
else if (probeResult.Status == ProbeResultStatus.Failed)
{
if (this.clusterMembershipOptions.CurrentValue.NumVotesForDeathDeclaration <= 2)
{
// Since both this silo and another silo were unable to probe the target silo, we declare it dead.
await this.membershipService.TryKill(monitor.SiloAddress).ConfigureAwait(false);
}
else
{
await this.membershipService.TryToSuspectOrKill(monitor.SiloAddress).ConfigureAwait(false);
}
}
}
bool IHealthCheckable.CheckHealth(DateTime lastCheckTime, out string reason)
{
var ok = true;
reason = default;
foreach (var monitor in this.monitoredSilos.Values)
{
ok &= monitor.CheckHealth(lastCheckTime, out var monitorReason);
if (!string.IsNullOrWhiteSpace(monitorReason))
{
var siloReason = $"Monitor for {monitor.SiloAddress} is degraded with: {monitorReason}.";
if (string.IsNullOrWhiteSpace(reason))
{
reason = siloReason;
}
else
{
reason = reason + " " + siloReason;
}
}
}
return ok;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.