context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//Code written by Pirouz Nourian, researcher at TU Delft 3D geoinformation in 2014, based on the algorithm described by Paul Bourke; released under a Creative Commons license. http://creativecommons.org/licenses/by/4.0/
//http://paulbourke.net/geometry/polygonise/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rhino;
using Rhino.Geometry;
namespace MarchingTetrahedrons_CSharp
{
public class Class1
{
public Mesh Field_to_IsoSurface(double ts, List<Point3d> p, List<double> m, int x, int y, int z)
{
List<double[]> GMs = null;
List<Box> GBoxes = Grid_to_Boxes(Plane.WorldXY, p, m, x, y, z, ref GMs);
//Print(GBoxes.count)
List<Tetrahedron> Tetrahedra = new List<Tetrahedron>();
for (int k = 0; k <= GBoxes.Count - 1; k++)
{
Tetrahedra.AddRange(BoxToTetrahedra(GBoxes[k], GMs[k].ToArray(), ts));
}
Mesh IsoSurface = new Mesh();
foreach (Tetrahedron TH in Tetrahedra)
{
string BSC = TH.BinaryStatus;
if (BSC.Equals("0000") | BSC.Equals("1111"))
{
}
else
{
IsoSurface.Append(MeshATetrahderon(TH, ts));
}
}
IsoSurface.UnifyNormals();
IsoSurface.MakeDeformable();
//IsoSurface.Weld(Math.PI)
return IsoSurface;
}
public class Tetrahedron
{
private int[] indices = new int[4];
private Point3d[] vertexPoints = new Point3d[4];
private Point3d[] BoxVertices = new Point3d[4];
private double[] Measures = new double[4];
private string Status = null;
public Tetrahedron(Box ABox, int[] Vertex_Indices, double[] BoxMeasures, double isoValue)
{
if (BoxMeasures.Length != 8)
return;
if (Vertex_Indices.Length != 4)
return;
BoxVertices = ABox.GetCorners();
if (BoxVertices.Length != 8)
return;
indices = Vertex_Indices;
for (int i = 0; i <= 3; i++)
{
vertexPoints[i] = BoxVertices[Vertex_Indices[i]];
Measures[i] = BoxMeasures[Vertex_Indices[i]];
if (Measures[i] > isoValue)
{
Status = "1" + Status;
}
else
{
Status = "0" + Status;
}
}
}
public double[] VertexMeasures
{
get { return Measures; }
set { Measures = value; }
}
public Point3d[] Vertices
{
get { return this.vertexPoints; }
}
public string Description
{
get { return string.Join(",", indices); }
}
public string BinaryStatus
{
get { return Status; }
}
public Mesh toMesh()
{
Mesh TetraMesh = new Mesh();
TetraMesh.Vertices.AddVertices(this.vertexPoints);
TetraMesh.Faces.AddFace(new MeshFace(0, 2, 1));TetraMesh.Faces.AddFace(new MeshFace(1, 2, 3));
TetraMesh.Faces.AddFace(new MeshFace(0, 1, 3));TetraMesh.Faces.AddFace(new MeshFace(0, 3, 2));
return TetraMesh;
}
}
public List<Tetrahedron> BoxToTetrahedra(Box ABox, double[] Measures, double iso)
{
if (Measures.Length != 8)
return null;
List<Tetrahedron> tetrahedra = new List<Tetrahedron>();
tetrahedra.Add(new Tetrahedron(ABox, new int[] { 0, 2, 3, 7 }, Measures, iso));tetrahedra.Add(new Tetrahedron(ABox, new int[] { 0, 2, 6, 7 }, Measures, iso));
tetrahedra.Add(new Tetrahedron(ABox, new int[] { 0, 4, 6, 7 }, Measures, iso));tetrahedra.Add(new Tetrahedron(ABox, new int[] { 0, 6, 1, 2 }, Measures, iso));
tetrahedra.Add(new Tetrahedron(ABox, new int[] { 0, 6, 1, 4 }, Measures, iso));tetrahedra.Add(new Tetrahedron(ABox, new int[] { 5, 6, 1, 4 }, Measures, iso));
return tetrahedra;
}
public List<Box> Grid_to_Boxes(Plane BasePlane, List<Point3d> GridPoints, List<double> GridMeasures, int XCount, int YCount, int ZCount, ref List<double[]> BoxMs)
{
if (GridPoints.Count != GridMeasures.Count)
return null;
List<Box> GBoxes = new List<Box>();
List<double[]> GMs = new List<double[]>();
int i = 0;
int j = 0;
int k = 0;
for (k = 0; k <= ZCount - 2; k++)
{
for (j = 0; j <= YCount - 2; j++)
{
for (i = 0; i <= XCount - 2; i++)
{
string code = (k + j + i).ToString();
//print(code)
List<Point3d> points = new List<Point3d>();
double[] GMeasures = new double[8];
int n0 = 0;int n1 = 0;int n2 = 0;int n3 = 0;int n4 = 0;int n5 = 0;int n6 = 0;int n7 = 0;
n0 = i + XCount * j + XCount * YCount * k;
n1 = n0 + 1;
n2 = n0 + XCount;
n3 = n1 + XCount;
n4 = n0 + XCount * YCount;
n5 = n4 + 1;
n6 = n4 + XCount;
n7 = n6 + 1;
points.Add(GridPoints[n0]);points.Add(GridPoints[n1]);points.Add(GridPoints[n2]);points.Add(GridPoints[n3]);
points.Add(GridPoints[n4]);points.Add(GridPoints[n5]);points.Add(GridPoints[n6]);points.Add(GridPoints[n7]);
Box GB = new Box(BasePlane, points);
GMeasures = new double[]
{
GridMeasures[n0],GridMeasures[n1],GridMeasures[n3],GridMeasures[n2],GridMeasures[n4],GridMeasures[n5],GridMeasures[n7],GridMeasures[n6]
};
//the order does not seem reasonable but it is. This is because of the way the box is formed out of vertices
GMs.Add(GMeasures);
GBoxes.Add(GB);
}
}
}
BoxMs = GMs;
return GBoxes;
}
public Mesh MeshATetrahderon(Tetrahedron TH, double ts)
{
if (TH.VertexMeasures.Length != 4)
return null;
object BSC = TH.BinaryStatus;
Mesh resMesh = new Mesh();
Mesh IsoMesh = new Mesh();
List<Point3d> Vertices = new List<Point3d>();
MeshFace Face = default(MeshFace);
if (BSC.Equals("0000") | BSC.Equals("1111"))
{
return null;
}
else if (BSC.Equals("0001") | BSC.Equals("1110"))
{
Vertices.Add(InterPoint(0, 1, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(0, 2, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(0, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(0, 1, 2);
}
else if (BSC.Equals("0010") | BSC.Equals("1101"))
{
Vertices.Add(InterPoint(1, 0, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(1, 2, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(1, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(2, 1, 0);
}
else if (BSC.Equals("0100") | BSC.Equals("1011"))
{
Vertices.Add(InterPoint(2, 0, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 1, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(2, 1, 0);
}
else if (BSC.Equals("1000") | BSC.Equals("0111"))
{
Vertices.Add(InterPoint(3, 0, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(3, 1, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(3, 2, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(2, 1, 0);
}
else if (BSC.Equals("0011") | BSC.Equals("1100"))
{
Vertices.Add(InterPoint(0, 2, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(0, 3, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(1, 2, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(1, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(0, 2, 3, 1);
}
else if (BSC.Equals("0101") | BSC.Equals("1010"))
{
Vertices.Add(InterPoint(0, 1, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(0, 3, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 1, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(0, 2, 3, 1);
}
else if (BSC.Equals("0110") | BSC.Equals("1001"))
{
Vertices.Add(InterPoint(1, 0, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(1, 3, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 0, ts, TH.Vertices, TH.VertexMeasures));
Vertices.Add(InterPoint(2, 3, ts, TH.Vertices, TH.VertexMeasures));
Face = new MeshFace(0, 2, 3, 1);
}
resMesh.Vertices.AddVertices(Vertices);
resMesh.Faces.AddFace(Face);
return resMesh;
}
public Point3d InterPoint(int p1, int p2, double iso, Point3d[] P, double[] M)
{
Point3d IntP = default(Point3d);IntP = P[p1] + ((P[p2] - P[p1]) * ((iso - M[p1]) / (M[p2] - M[p1])));
return IntP;
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ChainTests
{
[Fact]
public static void BuildChain()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
// Halfway between microsoftDotCom's NotBefore and NotAfter
// This isn't a boundary condition test.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Chain built validly");
// The chain should have 3 members
Assert.Equal(3, chain.ChainElements.Count);
// These are the three specific members.
Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
}
}
/// <summary>
/// Tests that when a certificate chain has a root certification which is not trusted by the trust provider,
/// Build returns false and a ChainStatus returns UntrustedRoot
/// </summary>
[Fact]
[OuterLoop]
public static void BuildChainExtraStoreUntrustedRoot()
{
using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword))
{
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.AddRange(collection);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);
bool valid = chain.Build(testCert);
Assert.False(valid);
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
}
}
public static IEnumerable<object[]> VerifyExpressionData()
{
// The test will be using the chain for TestData.MicrosoftDotComSslCertBytes
// The leaf cert (microsoft.com) is valid from 2014-10-15 00:00:00Z to 2016-10-15 23:59:59Z
DateTime[] validTimes =
{
// The NotBefore value
new DateTime(2014, 10, 15, 0, 0, 0, DateTimeKind.Utc),
// One second before the NotAfter value
new DateTime(2016, 10, 15, 23, 59, 58, DateTimeKind.Utc),
};
// The NotAfter value as a boundary condition differs on Windows and OpenSSL.
// Windows considers it valid (<= NotAfter).
// OpenSSL considers it invalid (< NotAfter), with a comment along the lines of
// "it'll be invalid in a millisecond, why bother with the <="
// So that boundary condition is not being tested.
DateTime[] invalidTimes =
{
// One second before the NotBefore time
new DateTime(2014, 10, 14, 23, 59, 59, DateTimeKind.Utc),
// One second after the NotAfter time
new DateTime(2016, 10, 16, 0, 0, 0, DateTimeKind.Utc),
};
List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3);
// Build (date, result, kind) tuples. The kind is used to help describe the test case.
// The DateTime format that xunit uses does show a difference in the DateTime itself, but
// having the Kind be a separate parameter just helps.
foreach (DateTime utcTime in validTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, true, utcTime.Kind });
testCases.Add(new object[] { local, true, local.Kind });
testCases.Add(new object[] { unspecified, true, unspecified.Kind });
}
foreach (DateTime utcTime in invalidTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, false, utcTime.Kind });
testCases.Add(new object[] { local, false, local.Kind });
testCases.Add(new object[] { unspecified, false, unspecified.Kind });
}
return testCases;
}
[Theory]
[MemberData(nameof(VerifyExpressionData))]
public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind)
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// Ignore anything except NotTimeValid
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = verificationTime;
bool builtSuccessfully = chain.Build(microsoftDotCom);
Assert.Equal(shouldBeValid, builtSuccessfully);
// If we failed to build the chain, ensure that NotTimeValid is one of the reasons.
if (!shouldBeValid)
{
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
}
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_Match()
{
using (var msCer = new X509Certificate2(TestData.MsCertificate))
using (X509Chain chain = new X509Chain())
{
// Code Signing
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2);
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(msCer);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (X509Chain chain = new X509Chain())
{
// Gibberish. (Code Signing + ".1")
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_Match()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (X509Chain chain = new X509Chain())
{
// Code Signing
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(cert);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (X509Chain chain = new X509Chain())
{
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[Fact]
public static void SafeX509ChainHandle_InvalidHandle_IsInvalid()
{
Assert.True(SafeX509ChainHandle.InvalidHandle.IsInvalid);
}
[Fact]
public static void SafeX509ChainHandle_InvalidHandle_StaticObject()
{
SafeX509ChainHandle firstCall = SafeX509ChainHandle.InvalidHandle;
SafeX509ChainHandle secondCall = SafeX509ChainHandle.InvalidHandle;
Assert.Same(firstCall, secondCall);
}
[Fact]
[OuterLoop( /* May require using the network, to download CRLs and intermediates */)]
public static void VerifyWithRevocation()
{
using (var cert = new X509Certificate2(Path.Combine("TestData", "MS.cer")))
using (var onlineChain = new X509Chain())
using (var offlineChain = new X509Chain())
{
onlineChain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
onlineChain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
onlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
onlineChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
bool valid = onlineChain.Build(cert);
Assert.True(valid, "Online Chain Built Validly");
// Since the network was enabled, we should get the whole chain.
Assert.Equal(3, onlineChain.ChainElements.Count);
Assert.Equal(0, onlineChain.ChainElements[0].ChainElementStatus.Length);
Assert.Equal(0, onlineChain.ChainElements[1].ChainElementStatus.Length);
// The root CA is not expected to be installed on everyone's machines,
// so allow for it to report UntrustedRoot, but nothing else..
X509ChainStatus[] rootElementStatus = onlineChain.ChainElements[2].ChainElementStatus;
if (rootElementStatus.Length != 0)
{
Assert.Equal(1, rootElementStatus.Length);
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, rootElementStatus[0].Status);
}
// Now that everything is cached, try again in Offline mode.
offlineChain.ChainPolicy.VerificationFlags = onlineChain.ChainPolicy.VerificationFlags;
offlineChain.ChainPolicy.VerificationTime = onlineChain.ChainPolicy.VerificationTime;
offlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
offlineChain.ChainPolicy.RevocationFlag = onlineChain.ChainPolicy.RevocationFlag;
valid = offlineChain.Build(cert);
Assert.True(valid, "Offline Chain Built Validly");
// Everything should look just like the online chain:
Assert.Equal(onlineChain.ChainElements.Count, offlineChain.ChainElements.Count);
for (int i = 0; i < offlineChain.ChainElements.Count; i++)
{
X509ChainElement onlineElement = onlineChain.ChainElements[i];
X509ChainElement offlineElement = offlineChain.ChainElements[i];
Assert.Equal(onlineElement.ChainElementStatus, offlineElement.ChainElementStatus);
Assert.Equal(onlineElement.Certificate, offlineElement.Certificate);
}
}
}
}
}
| |
namespace BlogRunnerGui
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnSelectNone = new System.Windows.Forms.Button();
this.btnSelectAll = new System.Windows.Forms.Button();
this.listProviders = new System.Windows.Forms.CheckedListBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.btnRun = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.chkVerbose = new System.Windows.Forms.CheckBox();
this.fileOutput = new BlogRunnerGui.FileInput();
this.fileConfig = new BlogRunnerGui.FileInput();
this.fileBlogProviders = new BlogRunnerGui.FileInput();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.btnSelectNone);
this.groupBox1.Controls.Add(this.btnSelectAll);
this.groupBox1.Controls.Add(this.listProviders);
this.groupBox1.Location = new System.Drawing.Point(12, 139);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(439, 179);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Providers";
//
// btnSelectNone
//
this.btnSelectNone.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnSelectNone.Location = new System.Drawing.Point(87, 149);
this.btnSelectNone.Name = "btnSelectNone";
this.btnSelectNone.Size = new System.Drawing.Size(75, 23);
this.btnSelectNone.TabIndex = 2;
this.btnSelectNone.Text = "Select &None";
this.btnSelectNone.UseVisualStyleBackColor = true;
this.btnSelectNone.Click += new System.EventHandler(this.btnSelectNone_Click);
//
// btnSelectAll
//
this.btnSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnSelectAll.Location = new System.Drawing.Point(6, 149);
this.btnSelectAll.Name = "btnSelectAll";
this.btnSelectAll.Size = new System.Drawing.Size(75, 23);
this.btnSelectAll.TabIndex = 1;
this.btnSelectAll.Text = "Select &All";
this.btnSelectAll.UseVisualStyleBackColor = true;
this.btnSelectAll.Click += new System.EventHandler(this.btnSelectAll_Click);
//
// listProviders
//
this.listProviders.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listProviders.CheckOnClick = true;
this.listProviders.FormattingEnabled = true;
this.listProviders.Location = new System.Drawing.Point(6, 19);
this.listProviders.Name = "listProviders";
this.listProviders.Size = new System.Drawing.Size(427, 124);
this.listProviders.TabIndex = 0;
this.listProviders.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.listProviders_ItemCheck);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 326);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(77, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Command Line";
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(12, 342);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(439, 67);
this.textBox1.TabIndex = 5;
//
// btnRun
//
this.btnRun.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnRun.Location = new System.Drawing.Point(295, 441);
this.btnRun.Name = "btnRun";
this.btnRun.Size = new System.Drawing.Size(75, 23);
this.btnRun.TabIndex = 8;
this.btnRun.Text = "&Run";
this.btnRun.UseVisualStyleBackColor = true;
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(376, 441);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 23);
this.btnClose.TabIndex = 9;
this.btnClose.Text = "Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// chkVerbose
//
this.chkVerbose.AutoSize = true;
this.chkVerbose.Location = new System.Drawing.Point(12, 445);
this.chkVerbose.Name = "chkVerbose";
this.chkVerbose.Size = new System.Drawing.Size(137, 17);
this.chkVerbose.TabIndex = 7;
this.chkVerbose.Text = "Enable &verbose logging";
this.chkVerbose.UseVisualStyleBackColor = true;
this.chkVerbose.CheckedChanged += new System.EventHandler(this.chkVerbose_CheckedChanged);
//
// fileOutput
//
this.fileOutput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileOutput.DialogStyle = BlogRunnerGui.DialogStyle.Save;
this.fileOutput.Location = new System.Drawing.Point(12, 97);
this.fileOutput.Name = "fileOutput";
this.fileOutput.Path = "";
this.fileOutput.Size = new System.Drawing.Size(439, 36);
this.fileOutput.TabIndex = 2;
this.fileOutput.Text = "&Output file path (optional)";
this.fileOutput.PathChanged += new System.EventHandler(this.fileOutput_PathChanged);
//
// fileConfig
//
this.fileConfig.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileConfig.DialogStyle = BlogRunnerGui.DialogStyle.Open;
this.fileConfig.Location = new System.Drawing.Point(12, 55);
this.fileConfig.Name = "fileConfig";
this.fileConfig.Path = "";
this.fileConfig.Size = new System.Drawing.Size(439, 36);
this.fileConfig.TabIndex = 1;
this.fileConfig.Text = "Path to &Config.xml";
this.fileConfig.PathChanged += new System.EventHandler(this.fileConfig_PathChanged);
//
// fileBlogProviders
//
this.fileBlogProviders.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileBlogProviders.DialogStyle = BlogRunnerGui.DialogStyle.Open;
this.fileBlogProviders.Location = new System.Drawing.Point(12, 12);
this.fileBlogProviders.Name = "fileBlogProviders";
this.fileBlogProviders.Path = "";
this.fileBlogProviders.Size = new System.Drawing.Size(439, 37);
this.fileBlogProviders.TabIndex = 0;
this.fileBlogProviders.Text = "Path to Blog&Providers.xml";
this.fileBlogProviders.PathChanged += new System.EventHandler(this.fileBlogProviders_PathChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(463, 476);
this.Controls.Add(this.chkVerbose);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnRun);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.fileOutput);
this.Controls.Add(this.fileConfig);
this.Controls.Add(this.fileBlogProviders);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "BlogRunner";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private FileInput fileBlogProviders;
private FileInput fileConfig;
private FileInput fileOutput;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnSelectNone;
private System.Windows.Forms.Button btnSelectAll;
private System.Windows.Forms.CheckedListBox listProviders;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.CheckBox chkVerbose;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace _safe_project_name_.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Timers;
using Spring.Threading.Collections.Generic;
using Spring.Threading.Future;
namespace Spring.Threading.Execution
{
/// <summary>
/// A <see cref="ThreadPoolExecutor"/> that can additionally schedule
/// commands to run after a given delay, or to execute
/// periodically. This class is preferable to <see cref="Timer"/>
/// when multiple worker threads are needed, or when the additional
/// flexibility or capabilities of <see cref="ThreadPoolExecutor"/> (which
/// this class extends) are required.
/// </summary>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
public class ScheduledThreadPoolExecutor : ThreadPoolExecutor, IScheduledExecutorService
{
/// <summary>
/// Creates a new ScheduledThreadPoolExecutor with the given core
/// pool size.
/// </summary>
/// <param name="corePoolSize">the number of threads to keep in the pool.</param>
/// <exception cref="ArgumentException">if corePoolSize is less than 0</exception>
public ScheduledThreadPoolExecutor( int corePoolSize ) : base(corePoolSize, Int32.MaxValue, new TimeSpan(0), new DelayQueue<IRunnable>())
{
}
/// <summary>
/// Creates a new ScheduledThreadPoolExecutor with the given core
/// pool size and using the specified <see cref="IThreadFactory"/>
/// </summary>
/// <param name="corePoolSize"></param>
/// <param name="threadFactory"></param>
public ScheduledThreadPoolExecutor(int corePoolSize, IThreadFactory threadFactory): base(corePoolSize, Int32.MaxValue, new TimeSpan(0), new DelayQueue<IRunnable>(), threadFactory )
{
}
/// <summary>
/// Returns <see lang="true"/> if this executor has been shut down.
/// </summary>
/// <returns>
/// Returns <see lang="true"/> if this executor has been shut down.
/// </returns>
public override bool IsShutdown
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Returns <see lang="true"/> if all tasks have completed following shut down.
/// </summary>
/// <remarks>
/// Note that this will never return <see lang="true"/> unless
/// either <see cref="Spring.Threading.Execution.IExecutorService.Shutdown()"/> or
/// <see cref="Spring.Threading.Execution.IExecutorService.ShutdownNow()"/> was called first.
/// </remarks>
/// <returns> <see lang="true"/> if all tasks have completed following shut down
/// </returns>
public override bool IsTerminated
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Initiates an orderly shutdown in which previously submitted
/// tasks are executed, but no new tasks will be
/// accepted. Invocation has no additional effect if already shut
/// down.
/// </summary>
public override void Shutdown()
{
throw new NotImplementedException();
}
/// <summary>
/// Attempts to stop all actively executing tasks, halts the
/// processing of waiting tasks, and returns a list of the tasks that were
/// awaiting execution.
/// </summary>
/// <remarks>
/// There are no guarantees beyond best-effort attempts to stop
/// processing actively executing tasks. For example, typical
/// implementations will cancel via <see cref="System.Threading.Thread.Interrupt()"/>, so if any
/// tasks mask or fail to respond to interrupts, they may never terminate.
/// </remarks>
/// <returns> list of tasks that never commenced execution</returns>
public override IList<IRunnable> ShutdownNow()
{
throw new NotImplementedException();
}
/// <summary>
/// Blocks until all tasks have completed execution after a shutdown
/// request, or the timeout occurs, or the current thread is
/// interrupted, whichever happens first.
/// </summary>
/// <param name="timeSpan">the time span to wait.
/// </param>
/// <returns> <see lang="true"/> if this executor terminated and <see lang="false"/>
/// if the timeout elapsed before termination
/// </returns>
public override bool AwaitTermination( TimeSpan timeSpan )
{
throw new NotImplementedException();
}
/// <summary>
/// Submits a value-returning task for execution and returns a
/// Future representing the pending results of the task. The
/// <see cref="IRunnable"/> method will return the task's result upon
/// <b>successful</b> completion.
/// </summary>
/// <remarks>
/// If you would like to immediately block waiting
/// for a task, you can use constructions of the form
/// <code>
/// result = exec.Submit(aCallable).GetResult();
/// </code>
/// <p/>
/// Note: The <see cref="ICallable{T}"/> class includes a set of methods
/// that can convert some other common closure-like objects,
/// for example, <see cref="IFuture{T}"/> to
/// <see cref="RejectedExecutionException"/> form so they can be submitted.
/// </remarks>
/// <param name="task">the task to submit</param>
/// <returns> a <see cref="IFuture{T}.GetResult()"/> representing pending completion of the task</returns>
/// <exception cref="Executors">if the task cannot be accepted for execution.</exception>
/// <exception cref="System.ArgumentNullException">if the command is null</exception>
public override IFuture<T> Submit<T>(ICallable<T> task )
{
throw new NotImplementedException();
}
/// <summary>
/// Submits a <see cref="RejectedExecutionException"/> task for execution and returns a
/// <see cref="IFuture{T}"/>
/// representing that task. The <see cref="IRunnable"/> method will
/// return the given result upon successful completion.
/// </summary>
/// <param name="task">the task to submit</param>
/// <param name="result">the result to return</param>
/// <returns> a <see cref="ArgumentNullException"/> representing pending completion of the task</returns>
/// <exception cref="IFuture{T}.GetResult()">if the task cannot be accepted for execution.</exception>
/// <exception cref="IFuture{T}">if the command is null</exception>
public override IFuture<T> Submit<T>( IRunnable task, T result )
{
throw new NotImplementedException();
}
/// <summary> Submits a Runnable task for execution and returns a Future
/// representing that task. The Future's <see cref="RejectedExecutionException"/> method will
/// return <see lang="null"/> upon successful completion.
/// </summary>
/// <param name="task">the task to submit
/// </param>
/// <returns> a Future representing pending completion of the task
/// </returns>
/// <exception cref="ArgumentNullException">if the task cannot be accepted for execution.</exception>
/// <exception cref="System.ArgumentNullException">if the command is null</exception>
public override IFuture<object> Submit( IRunnable task )
{
throw new NotImplementedException();
}
/// <summary>
/// Executes the given tasks, returning a list of <see cref="RejectedExecutionException"/>s holding
/// their status and results when all complete.
/// </summary>
/// <remarks>
/// <see cref="ArgumentNullException"/>
/// is <see lang="true"/> for each element of the returned list.
/// Note that a <b>completed</b> task could have
/// terminated either normally or by throwing an exception.
/// The results of this method are undefined if the given
/// collection is modified while this operation is in progress.
/// </remarks>
/// <param name="tasks">the collection of tasks</param>
/// <returns> A list of Futures representing the tasks, in the same
/// sequential order as produced by the iterator for the given task
/// list, each of which has completed.
/// </returns>
/// <exception cref="ICancellable.IsDone">if the task cannot be accepted for execution.</exception>
/// <exception cref="IFuture{T}">if the command is null</exception>
public override IList<IFuture<T>> InvokeAll<T>(IEnumerable<ICallable<T>> tasks )
{
throw new NotImplementedException();
}
/// <summary>
/// Executes the given tasks, returning a list of <see cref="ArgumentNullException"/>s holding
/// their status and results when all complete or the <paramref name="durationToWait"/> expires, whichever happens first.
/// </summary>
/// <remarks>
/// <see cref="RejectedExecutionException"/>
/// is <see lang="true"/> for each element of the returned list.
/// Note that a <b>completed</b> task could have
/// terminated either normally or by throwing an exception.
/// The results of this method are undefined if the given
/// collection is modified while this operation is in progress.
/// </remarks>
/// <param name="tasks">the collection of tasks</param>
/// <param name="durationToWait">the time span to wait.</param>
/// <returns> A list of Futures representing the tasks, in the same
/// sequential order as produced by the iterator for the given
/// task list. If the operation did not time out, each task will
/// have completed. If it did time out, some of these tasks will
/// not have completed.
/// </returns>
/// <exception cref="ICancellable.IsDone">if the task cannot be accepted for execution.</exception>
/// <exception cref="IFuture{T}">if the command is null</exception>
public override IList<IFuture<T>> InvokeAll<T>( IEnumerable<ICallable<T>> tasks, TimeSpan durationToWait )
{
throw new NotImplementedException();
}
/// <summary>
/// Executes the given tasks, returning the result
/// of one that has completed successfully (i.e., without throwing
/// an exception), if any do.
/// </summary>
/// <remarks>
/// Upon normal or exceptional return, tasks that have not completed are cancelled.
/// The results of this method are undefined if the given
/// collection is modified while this operation is in progress.
/// </remarks>
/// <param name="tasks">the collection of tasks</param>
/// <returns> The result returned by one of the tasks.</returns>
/// <exception cref="ArgumentNullException">if the task cannot be accepted for execution.</exception>
/// <exception cref="RejectedExecutionException">if the command is null</exception>
public override T InvokeAny<T>( IEnumerable<ICallable<T>> tasks )
{
throw new NotImplementedException();
}
/// <summary>
/// Creates and executes a one-shot action that becomes enabled
/// after the given delay.
/// </summary>
/// <param name="command">the task to execute.</param>
/// <param name="delay">the <see cref="IScheduledFuture{T}"/> from now to delay execution.</param>
/// <returns>
/// a <see cref="TimeSpan"/> representing pending completion of the task,
/// and whose <see cref="IFuture{T}.GetResult()"/> method will return <see lang="null"/>
/// upon completion.
/// </returns>
public IScheduledFuture<object> Schedule( IRunnable command, TimeSpan delay )
{
throw new NotImplementedException();
}
/// <summary>
/// Creates and executes a <see cref="IScheduledFuture{T}"/> that becomes enabled after the
/// given delay.
/// </summary>
/// <param name="callable">the function to execute.</param>
/// <param name="delay">the <see cref="IScheduledFuture{T}"/> from now to delay execution.</param>
/// <returns> a <see cref="TimeSpan"/> that can be used to extract result or cancel.
/// </returns>
public IScheduledFuture<T> Schedule<T>(ICallable<T> callable, TimeSpan delay )
{
throw new NotImplementedException();
}
/// <summary>
/// Creates and executes a periodic action that becomes enabled first
/// after the given initial <paramref name="initialDelay"/>, and subsequently with the given
/// <paramref name="period"/>
/// </summary>
/// <remarks>
/// That is executions will commence after
/// <paramref name="initialDelay"/>, the <paramref name="initialDelay"/> + <paramref name="period"/>, then
/// <paramref name="initialDelay"/> + 2 * <paramref name="period"/>, and so on.
/// <p/>
///
/// If any execution of the task
/// encounters an exception, subsequent executions are suppressed.
/// Otherwise, the task will only terminate via cancellation or
/// termination of the executor. If any execution of this task
/// takes longer than its period, then subsequent executions
/// may start late, but will <b>NOT</b> concurrently execute.
/// </remarks>
/// <param name="command">the task to execute.</param>
/// <param name="initialDelay">the time to delay first execution.</param>
/// <param name="period">the period between successive executions.</param>
/// <returns> a <see cref="IFuture{T}"/> representing pending completion of the task,
/// and whose <see cref="IFuture{T}.GetResult()"/> method will throw an exception upon
/// cancellation.
/// </returns>
public IScheduledFuture<object> ScheduleAtFixedRate( IRunnable command, TimeSpan initialDelay, TimeSpan period )
{
throw new NotImplementedException();
}
/// <summary>
/// Creates and executes a periodic action that becomes enabled first
/// after the given initial delay, and subsequently with the
/// given delay between the termination of one execution and the
/// commencement of the next.
/// </summary>
/// <remarks>
/// If any execution of the task
/// encounters an exception, subsequent executions are suppressed.
/// Otherwise, the task will only terminate via cancellation or
/// termination of the executor.
/// </remarks>
/// <param name="command">the task to execute.</param>
/// <param name="initialDelay">the time to delay first execution.</param>
/// <param name="delay">the delay between the termination of one execution and the commencement of the next.</param>
/// <returns> a <see cref="IFuture{T}.GetResult()"/> representing pending completion of the task,
/// and whose <see cref="IFuture{T}"/> method will throw an exception upon
/// cancellation.
/// </returns>
public IScheduledFuture<object> ScheduleWithFixedDelay( IRunnable command, TimeSpan initialDelay, TimeSpan delay )
{
throw new NotImplementedException();
}
/// <summary> Executes the given tasks, returning the result
/// of one that has completed successfully (i.e., without throwing
/// an exception), if any do before the given timeout elapses.
/// </summary>
/// <remarks>
/// Upon normal or exceptional return, tasks that have not
/// completed are cancelled.
/// The results of this method are undefined if the given
/// collection is modified while this operation is in progress.
/// </remarks>
/// <param name="tasks">the collection of tasks</param>
/// <param name="durationToWait">the time span to wait.</param>
/// <returns> The result returned by one of the tasks.
/// </returns>
/// <exception cref="Spring.Threading.Execution.RejectedExecutionException">if the task cannot be accepted for execution.</exception>
/// <exception cref="System.ArgumentNullException">if the command is null</exception>
public override T InvokeAny<T>( IEnumerable<ICallable<T>> tasks, TimeSpan durationToWait )
{
throw new NotImplementedException();
}
/// <summary>
/// Executes the given command at some time in the future.
/// </summary>
/// <remarks>
/// The command may execute in a new thread, in a pooled thread, or in the calling
/// thread, at the discretion of the <see cref="ArgumentNullException"/> implementation.
/// </remarks>
/// <param name="command">the runnable task</param>
/// <exception cref="IExecutor">if the task cannot be accepted for execution.</exception>
/// <exception cref="RejectedExecutionException">if the command is null</exception>
public override void Execute( IRunnable command )
{
throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
// Enables instruction counting and displaying stats at process exit.
// #define STATS
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Interpreter {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
[DebuggerTypeProxy(typeof(InstructionArray.DebugView))]
public struct InstructionArray {
internal readonly int MaxStackDepth;
internal readonly int MaxContinuationDepth;
internal readonly Instruction[] Instructions;
internal readonly object[] Objects;
internal readonly RuntimeLabel[] Labels;
// list of (instruction index, cookie) sorted by instruction index:
internal readonly List<KeyValuePair<int, object>> DebugCookies;
internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions,
object[] objects, RuntimeLabel[] labels, List<KeyValuePair<int, object>> debugCookies) {
MaxStackDepth = maxStackDepth;
MaxContinuationDepth = maxContinuationDepth;
Instructions = instructions;
DebugCookies = debugCookies;
Objects = objects;
Labels = labels;
}
internal int Length => Instructions.Length;
#region Debug View
internal sealed class DebugView {
private readonly InstructionArray _array;
public DebugView(InstructionArray array) {
_array = array;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionList.DebugView.InstructionView[]/*!*/ A0 {
get {
return InstructionList.DebugView.GetInstructionViews(
_array.Instructions,
_array.Objects,
(index) => _array.Labels[index].Index,
_array.DebugCookies
);
}
}
}
#endregion
}
[DebuggerTypeProxy(typeof(InstructionList.DebugView))]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public sealed class InstructionList {
private readonly List<Instruction> _instructions = new List<Instruction>();
private List<object> _objects;
private int _currentStackDepth;
private int _maxStackDepth;
private int _currentContinuationsDepth;
private int _maxContinuationDepth;
private int _runtimeLabelCount;
private List<BranchLabel> _labels;
// list of (instruction index, cookie) sorted by instruction index:
private List<KeyValuePair<int, object>> _debugCookies = null;
#region Debug View
internal sealed class DebugView {
private readonly InstructionList _list;
public DebugView(InstructionList list) {
_list = list;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionView[]/*!*/ A0 {
get {
return GetInstructionViews(
_list._instructions,
_list._objects,
(index) => _list._labels[index].TargetIndex,
_list._debugCookies
);
}
}
internal static InstructionView[] GetInstructionViews(IList<Instruction> instructions, IList<object> objects,
Func<int, int> labelIndexer, IList<KeyValuePair<int, object>> debugCookies) {
var result = new List<InstructionView>();
int stackDepth = 0;
int continuationsDepth = 0;
using (var cookieEnumerator = (debugCookies ?? EmptyArray<KeyValuePair<int, object>>.Instance).GetEnumerator()) {
var hasCookie = cookieEnumerator.MoveNext();
for (int i = 0; i < instructions.Count; i++) {
object cookie = null;
while (hasCookie && cookieEnumerator.Current.Key == i) {
cookie = cookieEnumerator.Current.Value;
hasCookie = cookieEnumerator.MoveNext();
}
int stackDiff = instructions[i].StackBalance;
int contDiff = instructions[i].ContinuationsBalance;
string name = instructions[i].ToDebugString(i, cookie, labelIndexer, objects);
result.Add(new InstructionView(instructions[i], name, i, stackDepth, continuationsDepth));
stackDepth += stackDiff;
continuationsDepth += contDiff;
}
}
return result.ToArray();
}
[DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")]
internal struct InstructionView {
private readonly int _index;
private readonly int _stackDepth;
private readonly int _continuationsDepth;
private readonly string _name;
private readonly Instruction _instruction;
internal string GetName() {
return _index.ToString() +
(_continuationsDepth == 0 ? "" : " C(" + _continuationsDepth.ToString() + ")") +
(_stackDepth == 0 ? "" : " S(" + _stackDepth.ToString() + ")");
}
internal string GetValue() {
return _name;
}
internal string GetDisplayType() {
return _instruction.ContinuationsBalance.ToString() + "/" + _instruction.StackBalance.ToString();
}
public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth) {
_instruction = instruction;
_name = name;
_index = index;
_stackDepth = stackDepth;
_continuationsDepth = continuationsDepth;
}
}
}
#endregion
#region Core Emit Ops
public void Emit(Instruction instruction) {
_instructions.Add(instruction);
UpdateStackDepth(instruction);
}
private void UpdateStackDepth(Instruction instruction) {
Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 &&
instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0);
_currentStackDepth -= instruction.ConsumedStack;
Debug.Assert(_currentStackDepth >= 0);
_currentStackDepth += instruction.ProducedStack;
if (_currentStackDepth > _maxStackDepth) {
_maxStackDepth = _currentStackDepth;
}
_currentContinuationsDepth -= instruction.ConsumedContinuations;
Debug.Assert(_currentContinuationsDepth >= 0);
_currentContinuationsDepth += instruction.ProducedContinuations;
if (_currentContinuationsDepth > _maxContinuationDepth) {
_maxContinuationDepth = _currentContinuationsDepth;
}
}
/// <summary>
/// Attaches a cookie to the last emitted instruction.
/// </summary>
[Conditional("DEBUG")]
public void SetDebugCookie(object cookie) {
#if DEBUG
if (_debugCookies == null) {
_debugCookies = new List<KeyValuePair<int, object>>();
}
Debug.Assert(Count > 0);
_debugCookies.Add(new KeyValuePair<int, object>(Count - 1, cookie));
#endif
}
public int Count => _instructions.Count;
public int CurrentStackDepth => _currentStackDepth;
public int CurrentContinuationsDepth => _currentContinuationsDepth;
public int MaxStackDepth => _maxStackDepth;
internal Instruction GetInstruction(int index) {
return _instructions[index];
}
#if STATS
private static Dictionary<string, int> _executedInstructions = new Dictionary<string, int>();
private static Dictionary<string, Dictionary<object, bool>> _instances = new Dictionary<string, Dictionary<object, bool>>();
static InstructionList() {
AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) => {
PerfTrack.DumpHistogram(_executedInstructions);
Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, (sum, value) => sum + value));
Console.WriteLine("-----");
var referenced = new Dictionary<string, int>();
int total = 0;
foreach (var entry in _instances) {
referenced[entry.Key] = entry.Value.Count;
total += entry.Value.Count;
}
PerfTrack.DumpHistogram(referenced);
Console.WriteLine("-- Total referenced: {0}", total);
Console.WriteLine("-----");
});
}
#endif
public InstructionArray ToArray() {
#if STATS
lock (_executedInstructions) {
_instructions.ForEach((instr) => {
int value = 0;
var name = instr.GetType().Name;
_executedInstructions.TryGetValue(name, out value);
_executedInstructions[name] = value + 1;
Dictionary<object, bool> dict;
if (!_instances.TryGetValue(name, out dict)) {
_instances[name] = dict = new Dictionary<object, bool>();
}
dict[instr] = true;
});
}
#endif
return new InstructionArray(
_maxStackDepth,
_maxContinuationDepth,
_instructions.ToArray(),
_objects?.ToArray(),
BuildRuntimeLabels(),
_debugCookies
);
}
#endregion
#region Stack Operations
private const int PushIntMinCachedValue = -100;
private const int PushIntMaxCachedValue = 100;
private const int CachedObjectCount = 256;
private static Instruction _null;
private static Instruction _true;
private static Instruction _false;
private static Instruction[] _ints;
private static Instruction[] _loadObjectCached;
public void EmitLoad(object value) {
EmitLoad(value, null);
}
public void EmitLoad(bool value) {
if (value) {
Emit(_true ?? (_true = new LoadObjectInstruction(ScriptingRuntimeHelpers.True)));
} else {
Emit(_false ?? (_false = new LoadObjectInstruction(ScriptingRuntimeHelpers.False)));
}
}
public void EmitLoad(object value, Type type) {
if (value == null) {
Emit(_null ?? (_null = new LoadObjectInstruction(null)));
return;
}
if (type == null || type.IsValueType) {
if (value is bool b) {
EmitLoad(b);
return;
}
if (value is int i) {
if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) {
if (_ints == null) {
_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
}
i -= PushIntMinCachedValue;
Emit(_ints[i] ?? (_ints[i] = new LoadObjectInstruction(value)));
return;
}
}
}
if (_objects == null) {
_objects = new List<object>();
if (_loadObjectCached == null) {
_loadObjectCached = new Instruction[CachedObjectCount];
}
}
if (_objects.Count < _loadObjectCached.Length) {
uint index = (uint)_objects.Count;
_objects.Add(value);
Emit(_loadObjectCached[index] ?? (_loadObjectCached[index] = new LoadCachedObjectInstruction(index)));
} else {
Emit(new LoadObjectInstruction(value));
}
}
public void EmitDup() {
Emit(DupInstruction.Instance);
}
public void EmitPop() {
Emit(PopInstruction.Instance);
}
#endregion
#region Locals
internal void SwitchToBoxed(int index, int instructionIndex) {
if (_instructions[instructionIndex] is IBoxableInstruction instruction) {
var newInstruction = instruction.BoxIfIndexMatches(index);
if (newInstruction != null) {
_instructions[instructionIndex] = newInstruction;
}
}
}
private const int LocalInstrCacheSize = 64;
private static Instruction[] _loadLocal;
private static Instruction[] _loadLocalBoxed;
private static Instruction[] _loadLocalFromClosure;
private static Instruction[] _loadLocalFromClosureBoxed;
private static Instruction[] _assignLocal;
private static Instruction[] _storeLocal;
private static Instruction[] _assignLocalBoxed;
private static Instruction[] _storeLocalBoxed;
private static Instruction[] _assignLocalToClosure;
private static Instruction[] _initReference;
private static Instruction[] _initImmutableRefBox;
private static Instruction[] _parameterBox;
private static Instruction[] _parameter;
public void EmitLoadLocal(int index) {
if (_loadLocal == null) {
_loadLocal = new Instruction[LocalInstrCacheSize];
}
if (index < _loadLocal.Length) {
Emit(_loadLocal[index] ?? (_loadLocal[index] = new LoadLocalInstruction(index)));
} else {
Emit(new LoadLocalInstruction(index));
}
}
public void EmitLoadLocalBoxed(int index) {
Emit(LoadLocalBoxed(index));
}
internal static Instruction LoadLocalBoxed(int index) {
if (_loadLocalBoxed == null) {
_loadLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < _loadLocalBoxed.Length) {
return _loadLocalBoxed[index] ?? (_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index));
}
return new LoadLocalBoxedInstruction(index);
}
public void EmitLoadLocalFromClosure(int index) {
if (_loadLocalFromClosure == null) {
_loadLocalFromClosure = new Instruction[LocalInstrCacheSize];
}
if (index < _loadLocalFromClosure.Length) {
Emit(_loadLocalFromClosure[index] ?? (_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index)));
} else {
Emit(new LoadLocalFromClosureInstruction(index));
}
}
public void EmitLoadLocalFromClosureBoxed(int index) {
if (_loadLocalFromClosureBoxed == null) {
_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < _loadLocalFromClosureBoxed.Length) {
Emit(_loadLocalFromClosureBoxed[index] ?? (_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index)));
} else {
Emit(new LoadLocalFromClosureBoxedInstruction(index));
}
}
public void EmitAssignLocal(int index) {
if (_assignLocal == null) {
_assignLocal = new Instruction[LocalInstrCacheSize];
}
if (index < _assignLocal.Length) {
Emit(_assignLocal[index] ?? (_assignLocal[index] = new AssignLocalInstruction(index)));
} else {
Emit(new AssignLocalInstruction(index));
}
}
public void EmitStoreLocal(int index) {
if (_storeLocal == null) {
_storeLocal = new Instruction[LocalInstrCacheSize];
}
if (index < _storeLocal.Length) {
Emit(_storeLocal[index] ?? (_storeLocal[index] = new StoreLocalInstruction(index)));
} else {
Emit(new StoreLocalInstruction(index));
}
}
public void EmitAssignLocalBoxed(int index) {
Emit(AssignLocalBoxed(index));
}
internal static Instruction AssignLocalBoxed(int index) {
if (_assignLocalBoxed == null) {
_assignLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < _assignLocalBoxed.Length) {
return _assignLocalBoxed[index] ?? (_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index));
}
return new AssignLocalBoxedInstruction(index);
}
public void EmitStoreLocalBoxed(int index) {
Emit(StoreLocalBoxed(index));
}
internal static Instruction StoreLocalBoxed(int index) {
if (_storeLocalBoxed == null) {
_storeLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < _storeLocalBoxed.Length) {
return _storeLocalBoxed[index] ?? (_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index));
}
return new StoreLocalBoxedInstruction(index);
}
public void EmitAssignLocalToClosure(int index) {
if (_assignLocalToClosure == null) {
_assignLocalToClosure = new Instruction[LocalInstrCacheSize];
}
if (index < _assignLocalToClosure.Length) {
Emit(_assignLocalToClosure[index] ?? (_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index)));
} else {
Emit(new AssignLocalToClosureInstruction(index));
}
}
public void EmitStoreLocalToClosure(int index) {
EmitAssignLocalToClosure(index);
EmitPop();
}
public void EmitInitializeLocal(int index, Type type) {
object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type);
if (value != null) {
Emit(new InitializeLocalInstruction.ImmutableValue(index, value));
} else if (type.IsValueType) {
Emit(new InitializeLocalInstruction.MutableValue(index, type));
} else {
Emit(InitReference(index));
}
}
internal void EmitInitializeParameter(int index) {
Emit(Parameter(index));
}
internal static Instruction Parameter(int index) {
if (_parameter == null) {
_parameter = new Instruction[LocalInstrCacheSize];
}
if (index < _parameter.Length) {
return _parameter[index] ?? (_parameter[index] = new InitializeLocalInstruction.Parameter(index));
}
return new InitializeLocalInstruction.Parameter(index);
}
internal static Instruction ParameterBox(int index) {
if (_parameterBox == null) {
_parameterBox = new Instruction[LocalInstrCacheSize];
}
if (index < _parameterBox.Length) {
return _parameterBox[index] ?? (_parameterBox[index] = new InitializeLocalInstruction.ParameterBox(index));
}
return new InitializeLocalInstruction.ParameterBox(index);
}
internal static Instruction InitReference(int index) {
if (_initReference == null) {
_initReference = new Instruction[LocalInstrCacheSize];
}
if (index < _initReference.Length) {
return _initReference[index] ?? (_initReference[index] = new InitializeLocalInstruction.Reference(index));
}
return new InitializeLocalInstruction.Reference(index);
}
internal static Instruction InitImmutableRefBox(int index) {
if (_initImmutableRefBox == null) {
_initImmutableRefBox = new Instruction[LocalInstrCacheSize];
}
if (index < _initImmutableRefBox.Length) {
return _initImmutableRefBox[index] ?? (_initImmutableRefBox[index] = new InitializeLocalInstruction.ImmutableBox(index, null));
}
return new InitializeLocalInstruction.ImmutableBox(index, null);
}
public void EmitNewRuntimeVariables(int count) {
Emit(new RuntimeVariablesInstruction(count));
}
#endregion
#region Array Operations
public void EmitGetArrayItem(Type arrayType) {
Type elementType = arrayType.GetElementType();
if (elementType.IsClass || elementType.IsInterface) {
Emit(InstructionFactory<object>.Factory.GetArrayItem());
} else {
Emit(InstructionFactory.GetFactory(elementType).GetArrayItem());
}
}
public void EmitSetArrayItem(Type arrayType) {
Type elementType = arrayType.GetElementType();
if (elementType.IsClass || elementType.IsInterface) {
Emit(InstructionFactory<object>.Factory.SetArrayItem());
} else {
Emit(InstructionFactory.GetFactory(elementType).SetArrayItem());
}
}
public void EmitNewArray(Type elementType) {
Emit(InstructionFactory.GetFactory(elementType).NewArray());
}
public void EmitNewArrayBounds(Type elementType, int rank) {
Emit(new NewArrayBoundsInstruction(elementType, rank));
}
public void EmitNewArrayInit(Type elementType, int elementCount) {
Emit(InstructionFactory.GetFactory(elementType).NewArrayInit(elementCount));
}
#endregion
#region Arithmetic Operations
public void EmitAdd(Type type, bool @checked) {
if (@checked) {
Emit(AddOvfInstruction.Create(type));
} else {
Emit(AddInstruction.Create(type));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitSub(Type type, bool @checked) {
throw new NotSupportedException();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitMul(Type type, bool @checked) {
throw new NotSupportedException();
}
public void EmitDiv(Type type) {
Emit(DivInstruction.Create(type));
}
#endregion
#region Comparisons
public void EmitEqual(Type type) {
Emit(EqualInstruction.Create(type));
}
public void EmitNotEqual(Type type) {
Emit(NotEqualInstruction.Create(type));
}
public void EmitLessThan(Type type) {
Emit(LessThanInstruction.Create(type));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitLessThanOrEqual(Type type) {
throw new NotSupportedException();
}
public void EmitGreaterThan(Type type) {
Emit(GreaterThanInstruction.Create(type));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitGreaterThanOrEqual(Type type) {
throw new NotSupportedException();
}
#endregion
#region Conversions
public void EmitNumericConvertChecked(TypeCode from, TypeCode to) {
Emit(new NumericConvertInstruction.Checked(from, to));
}
public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to) {
Emit(new NumericConvertInstruction.Unchecked(from, to));
}
#endregion
#region Boolean Operators
public void EmitNot() {
Emit(NotInstruction.Instance);
}
#endregion
#region Types
public void EmitDefaultValue(Type type) {
Emit(InstructionFactory.GetFactory(type).DefaultValue());
}
public void EmitNew(ConstructorInfo constructorInfo) {
Emit(new NewInstruction(constructorInfo));
}
internal void EmitCreateDelegate(LightDelegateCreator creator) {
Emit(new CreateDelegateInstruction(creator));
}
public void EmitTypeEquals() {
Emit(TypeEqualsInstruction.Instance);
}
public void EmitTypeIs(Type type) {
Emit(InstructionFactory.GetFactory(type).TypeIs());
}
public void EmitTypeAs(Type type) {
Emit(InstructionFactory.GetFactory(type).TypeAs());
}
#endregion
#region Fields and Methods
private static readonly Dictionary<FieldInfo, Instruction> _loadFields = new Dictionary<FieldInfo, Instruction>();
public void EmitLoadField(FieldInfo field) {
Emit(GetLoadField(field));
}
private Instruction GetLoadField(FieldInfo field) {
lock (_loadFields) {
if (_loadFields.TryGetValue(field, out Instruction instruction))
return instruction;
if (field.IsStatic) {
instruction = new LoadStaticFieldInstruction(field);
} else {
instruction = new LoadFieldInstruction(field);
}
_loadFields.Add(field, instruction);
return instruction;
}
}
public void EmitStoreField(FieldInfo field) {
if (field.IsStatic) {
Emit(new StoreStaticFieldInstruction(field));
} else {
Emit(new StoreFieldInstruction(field));
}
}
#endregion
#region Dynamic
public void EmitDynamic(Type type, CallSiteBinder binder) {
Emit(CreateDynamicInstruction(type, binder));
}
#region Generated Dynamic InstructionList Factory
// *** BEGIN GENERATED CODE ***
// generated by function: gen_instructionlist_factory from: generate_dynamic_instructions.py
public void EmitDynamic<T0, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(CallSiteBinder binder) {
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>.Factory(binder));
}
// *** END GENERATED CODE ***
#endregion
private static Dictionary<Type, Func<CallSiteBinder, Instruction>> _factories =
new Dictionary<Type, Func<CallSiteBinder, Instruction>>();
/// <exception cref="SecurityException">Instruction can't be created due to insufficient privileges.</exception>
internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder) {
Func<CallSiteBinder, Instruction> factory;
lock (_factories) {
if (!_factories.TryGetValue(delegateType, out factory)) {
if (delegateType.GetMethod("Invoke").ReturnType == typeof(void)) {
// TODO: We should generally support void returning binders but the only
// ones that exist are delete index/member who's perf isn't that critical.
return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder), true);
}
Type instructionType = DynamicInstructionN.GetDynamicInstructionType(delegateType);
if (instructionType == null) {
return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder));
}
factory = (Func<CallSiteBinder, Instruction>)instructionType.GetMethod("Factory").CreateDelegate(typeof(Func<CallSiteBinder, Instruction>));
_factories[delegateType] = factory;
}
}
return factory(binder);
}
#endregion
#region Control Flow
private static readonly RuntimeLabel[] EmptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) };
private RuntimeLabel[] BuildRuntimeLabels() {
if (_runtimeLabelCount == 0) {
return EmptyRuntimeLabels;
}
var result = new RuntimeLabel[_runtimeLabelCount + 1];
foreach (BranchLabel label in _labels) {
if (label.HasRuntimeLabel) {
result[label.LabelIndex] = label.ToRuntimeLabel();
}
}
// "return and rethrow" label:
result[result.Length - 1] = new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0);
return result;
}
public BranchLabel MakeLabel() {
if (_labels == null) {
_labels = new List<BranchLabel>();
}
var label = new BranchLabel();
_labels.Add(label);
return label;
}
internal void FixupBranch(int branchIndex, int offset) {
_instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset);
}
private int EnsureLabelIndex(BranchLabel label) {
if (label.HasRuntimeLabel) {
return label.LabelIndex;
}
label.LabelIndex = _runtimeLabelCount;
_runtimeLabelCount++;
return label.LabelIndex;
}
public int MarkRuntimeLabel() {
BranchLabel handlerLabel = MakeLabel();
MarkLabel(handlerLabel);
return EnsureLabelIndex(handlerLabel);
}
public void MarkLabel(BranchLabel label) {
label.Mark(this);
}
public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue) {
Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue));
}
private void EmitBranch(OffsetInstruction instruction, BranchLabel label) {
Emit(instruction);
label.AddBranch(this, Count - 1);
}
public void EmitBranch(BranchLabel label) {
EmitBranch(new BranchInstruction(), label);
}
public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue) {
EmitBranch(new BranchInstruction(hasResult, hasValue), label);
}
public void EmitCoalescingBranch(BranchLabel leftNotNull) {
EmitBranch(new CoalescingBranchInstruction(), leftNotNull);
}
public void EmitBranchTrue(BranchLabel elseLabel) {
EmitBranch(new BranchTrueInstruction(), elseLabel);
}
public void EmitBranchFalse(BranchLabel elseLabel) {
EmitBranch(new BranchFalseInstruction(), elseLabel);
}
public void EmitThrow() {
Emit(ThrowInstruction.Throw);
}
public void EmitThrowVoid() {
Emit(ThrowInstruction.VoidThrow);
}
public void EmitRethrow() {
Emit(ThrowInstruction.Rethrow);
}
public void EmitRethrowVoid() {
Emit(ThrowInstruction.VoidRethrow);
}
public void EmitEnterTryFinally(BranchLabel finallyStartLabel) {
Emit(EnterTryFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel)));
}
public void EmitEnterFinally() {
Emit(EnterFinallyInstruction.Instance);
}
public void EmitLeaveFinally() {
Emit(LeaveFinallyInstruction.Instance);
}
public void EmitLeaveFault(bool hasValue) {
Emit(hasValue ? LeaveFaultInstruction.NonVoid : LeaveFaultInstruction.Void);
}
public void EmitEnterExceptionHandlerNonVoid() {
Emit(EnterExceptionHandlerInstruction.NonVoid);
}
public void EmitEnterExceptionHandlerVoid() {
Emit(EnterExceptionHandlerInstruction.Void);
}
public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel) {
Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue));
}
public void EmitSwitch(Dictionary<int, int> cases) {
Emit(new SwitchInstruction(cases));
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Writes log messages to the database using an ADO.NET provider.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/Database_target">Documentation on NLog Wiki</seealso>
/// <example>
/// <para>
/// The configuration is dependent on the database type, because
/// there are differnet methods of specifying connection string, SQL
/// command and command parameters.
/// </para>
/// <para>MS SQL Server using System.Data.SqlClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" />
/// <para>Oracle using System.Data.OracleClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" />
/// <para>Oracle using System.Data.OleDBClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" />
/// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para>
/// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" />
/// </example>
[Target("Database")]
public sealed class DatabaseTarget : Target, IInstallable
{
private static Assembly systemDataAssembly = typeof(IDbConnection).Assembly;
private IDbConnection activeConnection = null;
private string activeConnectionString;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
public DatabaseTarget()
{
this.Parameters = new List<DatabaseParameterInfo>();
this.InstallDdlCommands = new List<DatabaseCommandInfo>();
this.UninstallDdlCommands = new List<DatabaseCommandInfo>();
this.DBProvider = "sqlserver";
this.DBHost = ".";
#if !NET_CF
this.ConnectionStringsSettings = ConfigurationManager.ConnectionStrings;
#endif
}
/// <summary>
/// Gets or sets the name of the database provider.
/// </summary>
/// <remarks>
/// <para>
/// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are:
/// </para>
/// <ul>
/// <li><c>System.Data.SqlClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li>
/// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="http://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li>
/// <li><c>System.Data.OracleClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li>
/// <li><c>Oracle.DataAccess.Client</c> - <see href="http://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li>
/// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li>
/// <li><c>Npgsql</c> - <see href="http://npgsql.projects.postgresql.org/">Npgsql driver for PostgreSQL</see></li>
/// <li><c>MySql.Data.MySqlClient</c> - <see href="http://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li>
/// </ul>
/// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para>
/// <para>
/// Alternatively the parameter value can be be a fully qualified name of the provider
/// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens:
/// </para>
/// <ul>
/// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li>
/// <li><c>oledb</c> - OLEDB Data Provider</li>
/// <li><c>odbc</c> - ODBC Data Provider</li>
/// </ul>
/// </remarks>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
[DefaultValue("sqlserver")]
public string DBProvider { get; set; }
#if !NET_CF
/// <summary>
/// Gets or sets the name of the connection string (as specified in <see href="http://msdn.microsoft.com/en-us/library/bf7sd233.aspx"><connectionStrings> configuration section</see>.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public string ConnectionStringName { get; set; }
#endif
/// <summary>
/// Gets or sets the connection string. When provided, it overrides the values
/// specified in DBHost, DBUserName, DBPassword, DBDatabase.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout ConnectionString { get; set; }
/// <summary>
/// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used.
/// </summary>
/// <docgen category='Installation Options' order='10' />
public Layout InstallConnectionString { get; set; }
/// <summary>
/// Gets the installation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "install-command")]
public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; }
/// <summary>
/// Gets the uninstallation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")]
public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the
/// database connection open between the log events.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(true)]
public bool KeepConnection { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use database transactions.
/// Some data providers require this.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(false)]
public bool UseTransactions { get; set; }
/// <summary>
/// Gets or sets the database host name. If the ConnectionString is not provided
/// this value will be used to construct the "Server=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBHost { get; set; }
/// <summary>
/// Gets or sets the database user name. If the ConnectionString is not provided
/// this value will be used to construct the "User ID=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBUserName { get; set; }
/// <summary>
/// Gets or sets the database password. If the ConnectionString is not provided
/// this value will be used to construct the "Password=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBPassword { get; set; }
/// <summary>
/// Gets or sets the database name. If the ConnectionString is not provided
/// this value will be used to construct the "Database=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBDatabase { get; set; }
/// <summary>
/// Gets or sets the text of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// Typically this is a SQL INSERT statement or a stored procedure call.
/// It should use the database-specific parameters (marked as <c>@parameter</c>
/// for SQL server or <c>:parameter</c> for Oracle, other data providers
/// have their own notation) and not the layout renderers,
/// because the latter is prone to SQL injection attacks.
/// The layout renderers should be specified as <parameter /> elements instead.
/// </remarks>
/// <docgen category='SQL Statement' order='10' />
[RequiredParameter]
public Layout CommandText { get; set; }
/// <summary>
/// Gets the collection of parameters. Each parameter contains a mapping
/// between NLog layout and a database named or positional parameter.
/// </summary>
/// <docgen category='SQL Statement' order='11' />
[ArrayParameter(typeof(DatabaseParameterInfo), "parameter")]
public IList<DatabaseParameterInfo> Parameters { get; private set; }
#if !NET_CF
internal DbProviderFactory ProviderFactory { get; set; }
// this is so we can mock the connection string without creating sub-processes
internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; }
#endif
internal Type ConnectionType { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
this.RunInstallCommands(installationContext, this.InstallDdlCommands);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
this.RunInstallCommands(installationContext, this.UninstallDdlCommands);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return null;
}
internal IDbConnection OpenConnection(string connectionString)
{
IDbConnection connection;
#if !NET_CF
if (this.ProviderFactory != null)
{
connection = this.ProviderFactory.CreateConnection();
}
else
#endif
{
connection = (IDbConnection)Activator.CreateInstance(this.ConnectionType);
}
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "connectionStrings", Justification = "Name of the config file section.")]
protected override void InitializeTarget()
{
base.InitializeTarget();
bool foundProvider = false;
#if !NET_CF
if (!string.IsNullOrEmpty(this.ConnectionStringName))
{
// read connection string and provider factory from the configuration file
var cs = this.ConnectionStringsSettings[this.ConnectionStringName];
if (cs == null)
{
throw new NLogConfigurationException("Connection string '" + this.ConnectionStringName + "' is not declared in <connectionStrings /> section.");
}
this.ConnectionString = SimpleLayout.Escape(cs.ConnectionString);
this.ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName);
foundProvider = true;
}
if (!foundProvider)
{
foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
{
if ((string)row["InvariantName"] == this.DBProvider)
{
this.ProviderFactory = DbProviderFactories.GetFactory(this.DBProvider);
foundProvider = true;
}
}
}
#endif
if (!foundProvider)
{
switch (this.DBProvider.ToUpper(CultureInfo.InvariantCulture))
{
case "SQLSERVER":
case "MSSQL":
case "MICROSOFT":
case "MSDE":
this.ConnectionType = systemDataAssembly.GetType("System.Data.SqlClient.SqlConnection", true);
break;
case "OLEDB":
this.ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true);
break;
case "ODBC":
this.ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true);
break;
default:
this.ConnectionType = Type.GetType(this.DBProvider, true);
break;
}
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
this.CloseConnection();
}
/// <summary>
/// Writes the specified logging event to the database. It creates
/// a new database command, prepares parameters for it by calculating
/// layouts and executes the command.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
try
{
this.WriteEventToDatabase(logEvent);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when writing to database {0}", exception);
this.CloseConnection();
throw;
}
finally
{
if (!this.KeepConnection)
{
this.CloseConnection();
}
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
var buckets = SortHelpers.BucketSort(logEvents, c => this.BuildConnectionString(c.LogEvent));
try
{
foreach (var kvp in buckets)
{
foreach (AsyncLogEventInfo ev in kvp.Value)
{
try
{
this.WriteEventToDatabase(ev.LogEvent);
ev.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of exception, close the connection and report it
InternalLogger.Error("Error when writing to database {0}", exception);
this.CloseConnection();
ev.Continuation(exception);
}
}
}
}
finally
{
if (!this.KeepConnection)
{
this.CloseConnection();
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void WriteEventToDatabase(LogEventInfo logEvent)
{
this.EnsureConnectionOpen(this.BuildConnectionString(logEvent));
IDbCommand command = this.activeConnection.CreateCommand();
command.CommandText = this.CommandText.Render(logEvent);
InternalLogger.Trace("Executing {0}: {1}", command.CommandType, command.CommandText);
foreach (DatabaseParameterInfo par in this.Parameters)
{
IDbDataParameter p = command.CreateParameter();
p.Direction = ParameterDirection.Input;
if (par.Name != null)
{
p.ParameterName = par.Name;
}
if (par.Size != 0)
{
p.Size = par.Size;
}
if (par.Precision != 0)
{
p.Precision = par.Precision;
}
if (par.Scale != 0)
{
p.Scale = par.Scale;
}
string stringValue = par.Layout.Render(logEvent);
p.Value = stringValue;
command.Parameters.Add(p);
InternalLogger.Trace(" Parameter: '{0}' = '{1}' ({2})", p.ParameterName, p.Value, p.DbType);
}
int result = command.ExecuteNonQuery();
InternalLogger.Trace("Finished execution, result = {0}", result);
}
private string BuildConnectionString(LogEventInfo logEvent)
{
if (this.ConnectionString != null)
{
return this.ConnectionString.Render(logEvent);
}
var sb = new StringBuilder();
sb.Append("Server=");
sb.Append(this.DBHost.Render(logEvent));
sb.Append(";");
if (this.DBUserName == null)
{
sb.Append("Trusted_Connection=SSPI;");
}
else
{
sb.Append("User id=");
sb.Append(this.DBUserName.Render(logEvent));
sb.Append(";Password=");
sb.Append(this.DBPassword.Render(logEvent));
sb.Append(";");
}
if (this.DBDatabase != null)
{
sb.Append("Database=");
sb.Append(this.DBDatabase.Render(logEvent));
}
return sb.ToString();
}
private void EnsureConnectionOpen(string connectionString)
{
if (this.activeConnection != null)
{
if (this.activeConnectionString != connectionString)
{
this.CloseConnection();
}
}
if (this.activeConnection != null)
{
return;
}
this.activeConnection = this.OpenConnection(connectionString);
this.activeConnectionString = connectionString;
}
private void CloseConnection()
{
if (this.activeConnection != null)
{
this.activeConnection.Close();
this.activeConnection = null;
this.activeConnectionString = null;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands)
{
// create log event that will be used to render all layouts
LogEventInfo logEvent = installationContext.CreateLogEvent();
try
{
foreach (var commandInfo in commands)
{
string cs;
if (commandInfo.ConnectionString != null)
{
// if there is connection string specified on the command info, use it
cs = commandInfo.ConnectionString.Render(logEvent);
}
else if (this.InstallConnectionString != null)
{
// next, try InstallConnectionString
cs = this.InstallConnectionString.Render(logEvent);
}
else
{
// if it's not defined, fall back to regular connection string
cs = this.BuildConnectionString(logEvent);
}
this.EnsureConnectionOpen(cs);
var command = this.activeConnection.CreateCommand();
command.CommandType = commandInfo.CommandType;
command.CommandText = commandInfo.Text.Render(logEvent);
try
{
installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText);
command.ExecuteNonQuery();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures)
{
installationContext.Warning(exception.Message);
}
else
{
installationContext.Error(exception.Message);
throw;
}
}
}
}
finally
{
this.CloseConnection();
}
}
}
}
#endif
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Users.Data;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Framework.Helpers
{
/// <summary>
/// Lists the possible types of data sources for the MDF system
/// </summary>
public enum DataSourceType
{
/// <summary>The current module</summary>
This,
/// <summary>All modules in the portal</summary>
All,
/// <summary>The specified list of modules (for the portal)</summary>
List
}
/// <summary>
/// MDFHelper file by Jakob Hansen.
/// MDF = Module Data Filter
/// This class Represents all settings used by the MDF settings system
/// </summary>
public class MDFSettings
{
#region Public Fields
/// <summary>
///
/// </summary>
public const string NameApplyMDF = "MDF_APPLY_MDF";
/// <summary>
///
/// </summary>
public const string NameDataSource = "MDF_DATA_SOURCE";
/// <summary>
///
/// </summary>
public const string NameMaxHits = "MDF_MAX_HITS";
/// <summary>
///
/// </summary>
public const string NameModuleList = "MDF_MODULE_LIST";
/// <summary>
///
/// </summary>
public const string NameAllNotInList = "MDF_ALL_NOT_IN_LIST";
/// <summary>
///
/// </summary>
public const string NameSortField = "MDF_SORT_FIELD";
/// <summary>
///
/// </summary>
public const string NameSortDirection= "MDF_SORT_DIRECTION";
/// <summary>
///
/// </summary>
public const string NameSearchString = "MDF_SEARCH_STRING";
/// <summary>
///
/// </summary>
public const string NameSearchField = "MDF_SEARCH_FIELD";
/// <summary>
///
/// </summary>
public const string NameMobileOnly = "MDF_MOBILE_ONLY";
/// <summary>
///
/// </summary>
public const bool DefaultValueApplyMDF = false;
/// <summary>
///
/// </summary>
public const DataSourceType DefaultValueDataSource = DataSourceType.This;
/// <summary>
///
/// </summary>
public const int DefaultValueMaxHits = 20;
/// <summary>
///
/// </summary>
public const string DefaultValueModuleList = "";
/// <summary>
///
/// </summary>
public const bool DefaultValueAllNotInList = false;
/// <summary>
///
/// </summary>
public const string DefaultValueSortField = "";
/// <summary>
///
/// </summary>
public const string DefaultValueSortDirection = "ASC";
/// <summary>
///
/// </summary>
public const string DefaultValueSearchString = "";
/// <summary>
///
/// </summary>
public const string DefaultValueSearchField = "";
/// <summary>
///
/// </summary>
public const bool DefaultValueMobileOnly = false;
#endregion
#region Private fields
bool _applyMDF = DefaultValueApplyMDF;
DataSourceType _dataSource = DefaultValueDataSource;
int _maxHits = DefaultValueMaxHits;
string _moduleList = DefaultValueModuleList; //Module ID. Can be a list: "23,45,56"
bool _allNotInList = DefaultValueAllNotInList;
string _sortField = DefaultValueSortField;
string _sortDirection = DefaultValueSortDirection;
string _searchString = DefaultValueSearchString;
string _searchField = DefaultValueSearchField;
bool _mobileOnly = DefaultValueMobileOnly;
bool _supportsWorkflow = false;
WorkFlowVersion _workflowVersion = WorkFlowVersion.Production;
string _itemTableName = "";
string _titleFieldName = "";
string _selectFieldList = "";
string _searchFieldList = "";
int _portalID = -1;
int _userID = -1;
#endregion
#region Public Properties
/// <summary>
/// Controls if the MDF system should be used.
/// Default value: false
/// </summary>
/// <value><c>true</c> if [apply MDF]; otherwise, <c>false</c>.</value>
public bool ApplyMDF
{
get {return _applyMDF;}
set {_applyMDF = value;}
}
/// <summary>
/// Controls the data displyed in the module
/// Default value: DataSourceType.This;
/// </summary>
/// <value>The data source.</value>
public DataSourceType DataSource
{
get {return _dataSource;}
set {_dataSource = value;}
}
/// <summary>
/// Represents the number of items returned by the service.
/// Value 0 means no hit limit (all found items are displayed).
/// Default value: 20
/// </summary>
/// <value>The max hits.</value>
public int MaxHits
{
get {return _maxHits;}
set {_maxHits = value;}
}
/// <summary>
/// Comma separated list of module ID's. e.g.: 1234,234,5454.
/// Only data for these ID's are listed. (see also AllNotInList!)
/// Default value: string.Empty
/// </summary>
/// <value>The module list.</value>
public string ModuleList
{
get {return _moduleList;}
set {_moduleList = value;}
}
/// <summary>
/// If DataSource is All or List this can exclude modules listed in ModuleList
/// Default value: false
/// </summary>
/// <value><c>true</c> if [all not in list]; otherwise, <c>false</c>.</value>
public bool AllNotInList
{
get {return _allNotInList;}
set {_allNotInList = value;}
}
/// <summary>
/// Sort list on this field
/// Valid values: You must set this in the module constructor.
/// Must be a existing field in the module core item table.
/// </summary>
/// <value>The sort field.</value>
public string SortField
{
get {return _sortField;}
set {_sortField = value;}
}
/// <summary>
/// Sort Ascending or Descending
/// Valid values: ASC;DESC
/// Default value: ASC
/// </summary>
/// <value>The sort direction.</value>
public string SortDirection
{
get {return _sortDirection;}
set {_sortDirection = value;}
}
/// <summary>
/// Search string. An empty string means no search (same as off).
/// Default value: string.Empty
/// </summary>
/// <value>The search string.</value>
public string SearchString
{
get {return _searchString;}
set {_searchString = value;}
}
/// <summary>
/// Set this if only a single field should be searched e.g.: "Title"
/// Default value: string.Empty
/// </summary>
/// <value>The search field.</value>
public string SearchField
{
get {return _searchField;}
set {_searchField = value;}
}
/// <summary>
/// Default value: false
/// </summary>
/// <value><c>true</c> if [supports workflow]; otherwise, <c>false</c>.</value>
public bool SupportsWorkflow
{
get {return _supportsWorkflow;}
set {_supportsWorkflow = value;}
}
/// <summary>
/// Default value: Production
/// </summary>
/// <value>The workflow version.</value>
public WorkFlowVersion WorkflowVersion
{
get {return _workflowVersion;}
set {_workflowVersion = value;}
}
/// <summary>
/// The name of the modules core item table e.g. "rb_Links" for module Links
/// Default value: string.Empty
/// </summary>
/// <value>The name of the item table.</value>
public string ItemTableName
{
get {return _itemTableName;}
set {_itemTableName = value;}
}
/// <summary>
/// The name of the field in the item table that is considered the item title. Typical value is "Title"
/// Default value: string.Empty
/// </summary>
/// <value>The name of the title field.</value>
public string TitleFieldName
{
get {return _titleFieldName;}
set {_titleFieldName = value;}
}
/// <summary>
/// The list of fields in the SQL select, separated with comma.
/// NOTE: must be prefixed with itm., e.g.: "itm.ItemID,itm.CreatedByUser,itm.CreatedDate,itm.Title"
/// Default value: string.Empty
/// </summary>
/// <value>The select field list.</value>
public string SelectFieldList
{
get {return _selectFieldList;}
set {_selectFieldList = value;}
}
/// <summary>
/// Fields to search - must be of nvarchar or ntext type.
/// NOTE: must be seperated with semicolon, e.g.: "Title;Url;MobileUrl;Description;CreatedByUser"
/// Default value: string.Empty
/// </summary>
/// <value>The search field list.</value>
public string SearchFieldList
{
get {return _searchFieldList;}
set {_searchFieldList = value;}
}
/// <summary>
/// When true only data for mobile devices are displyed
/// Default value: false
/// </summary>
/// <value><c>true</c> if [mobile only]; otherwise, <c>false</c>.</value>
public bool MobileOnly
{
get {return _mobileOnly;}
set {_mobileOnly = value;}
}
/// <summary>
/// The portal id
/// Default value: -1
/// </summary>
/// <value>The portal ID.</value>
public int PortalID
{
get {return _portalID;}
set {_portalID = value;}
}
/// <summary>
/// When the value of UserID is 0 the user has not signed in (it's a guest!)
/// Default value: -1
/// </summary>
/// <value>The user ID.</value>
public int UserID
{
get {return _userID;}
set {_userID = value;}
}
#endregion
#region Public Methods
/// <summary>
/// Fills all MDF settings. Returns true if no problems reading and
/// parsing all MDF settings.
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <param name="itemTableName">Name of the item table.</param>
/// <param name="titleFieldName">Name of the title field.</param>
/// <param name="selectFieldList">The select field list.</param>
/// <param name="searchFieldList">The search field list.</param>
/// <returns></returns>
public bool Populate(PortalModuleControl pmc, string itemTableName, string titleFieldName, string selectFieldList, string searchFieldList)
{
bool PopulateDone;
try
{
_applyMDF = bool.Parse(pmc.Settings[NameApplyMDF].ToString());
string ds = pmc.Settings[NameDataSource].ToString();
if (ds == DataSourceType.This.ToString())
_dataSource = DataSourceType.This;
else if (ds == DataSourceType.All.ToString())
_dataSource = DataSourceType.All;
else if (ds == DataSourceType.List.ToString())
_dataSource = DataSourceType.List;
_maxHits = int.Parse(pmc.Settings[NameMaxHits].ToString());
_moduleList = pmc.Settings[NameModuleList].ToString();
_allNotInList = bool.Parse(pmc.Settings[NameAllNotInList].ToString());
_sortField = pmc.Settings[NameSortField].ToString();
_sortDirection = pmc.Settings[NameSortDirection].ToString();
_searchString = pmc.Settings[NameSearchString].ToString();
_searchField = pmc.Settings[NameSearchField].ToString();
_mobileOnly = bool.Parse(pmc.Settings[NameMobileOnly].ToString());
if (_dataSource == DataSourceType.This)
_moduleList = pmc.ModuleID.ToString();
if (_moduleList == "" && _dataSource == DataSourceType.List)
{
// Create data to lazy user that forgot to enter data in field Module List
_moduleList = pmc.ModuleID.ToString();
}
if (pmc.SupportsWorkflow)
{
_supportsWorkflow = pmc.SupportsWorkflow;
_workflowVersion = pmc.Version;
}
_itemTableName = itemTableName;
_titleFieldName = titleFieldName;
_selectFieldList = selectFieldList;
_searchFieldList = searchFieldList;
_portalID = pmc.PortalID;
UsersDB u = new UsersDB();
SqlDataReader dr = u.GetSingleUser(PortalSettings.CurrentUser.Identity.Email);
if (dr.Read())
_userID = Int32.Parse(dr["UserID"].ToString());
PopulateDone = true;
}
catch (Exception)
{
PopulateDone = false;
}
return PopulateDone;
}
/// <summary>
/// Initializes a new instance of the MDFSetting object with default settings.
/// </summary>
public MDFSettings()
{
//Nada code!
}
/// <summary>
/// Initializes a new instance of the MDFSetting object with real settings
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <param name="itemTableName">Name of the item table.</param>
/// <param name="titleFieldName">Name of the title field.</param>
/// <param name="selectFieldList">The select field list.</param>
/// <param name="searchFieldList">The search field list.</param>
public MDFSettings(PortalModuleControl pmc, string itemTableName, string titleFieldName, string selectFieldList, string searchFieldList)
{
Populate(pmc, itemTableName, titleFieldName, selectFieldList, searchFieldList);
}
/// <summary>
/// Retuns true if the module is using MDF.
/// </summary>
/// <param name="pmc">The PMC.</param>
/// <returns>
/// <c>true</c> if [is MDF applied] [the specified PMC]; otherwise, <c>false</c>.
/// </returns>
static public bool IsMDFApplied(PortalModuleControl pmc)
{
return bool.Parse(pmc.Settings[NameApplyMDF].ToString());
}
/// <summary>
/// Max apply mdf
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeApplyMDF(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 1;
si.Value = defaultValue.ToString();
si.EnglishName = "Apply MDF";
si.Description = "Controls if the MDF system is activated or not";
return si;
}
/// <summary>
/// Make data source
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeDataSource(DataSourceType defaultValue)
{
SettingItem si = new SettingItem(
new ListDataType(DataSourceType.This.ToString() + ";" + DataSourceType.All.ToString() + ";" + DataSourceType.List.ToString()));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 2;
si.Required = true;
si.Value = defaultValue.ToString();
si.EnglishName = "DataSource";
si.Description = "Controls where data displyed in the module is comming from. " +
"'This' is the current module, 'All' is all modules in the current portal " +
"and with 'List' you must specify a list of module id's, e.g.: 20242,10243";
return si;
}
/// <summary>
/// Makes the max hits.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeMaxHits(int defaultValue)
{
SettingItem si = new SettingItem(new IntegerDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 3;
si.Required = true;
si.Value = defaultValue.ToString();
si.MinValue = 0;
si.MaxValue = int.MaxValue;
si.EnglishName = "Max Hits";
si.Description = "Represents the number of items returned by MDF. Value 0 means no hit limit (all found items are displayed)";
return si;
}
/// <summary>
/// Makes the module list.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeModuleList(string defaultValue)
{
SettingItem si = new SettingItem(new StringDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 4;
si.Required = false;
si.Value = defaultValue;
si.EnglishName = "Module List";
si.Description = "Comma separated list of module ID's. e.g.: 20242,10243. Only data for these ID's are listed. (see also AllNotInList!)";
return si;
}
/// <summary>
/// Makes all not in list.
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeAllNotInList(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 5;
si.Value = defaultValue.ToString();
si.EnglishName = "All Not In List";
si.Description = "If DataSource is 'All' or 'List' this can exclude modules listed in Module List";
return si;
}
/// <summary>
/// Makes the sort field list.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="fieldList">The field list.</param>
/// <returns></returns>
static public SettingItem MakeSortFieldList(string defaultValue, string fieldList)
{
SettingItem si = new SettingItem(new ListDataType(fieldList));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 6;
si.Required = true;
si.Value = defaultValue;
si.EnglishName = "Sort Field";
si.Description = "A list of all fields from the core item table you want to sort on";
return si;
}
/// <summary>
/// Makes the sort direction.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeSortDirection(string defaultValue)
{
SettingItem si = new SettingItem(new ListDataType("ASC;DESC"));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 7;
si.Required = true;
si.Value = defaultValue;
si.EnglishName = "Sort Direction";
si.Description = "Sort Ascending or Descending";
return si;
}
/// <summary>
/// Makes the search string.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
static public SettingItem MakeSearchString(string defaultValue)
{
SettingItem si = new SettingItem(new StringDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 8;
si.Required = false;
si.Value = defaultValue;
si.EnglishName = "Search string";
si.Description = "An empty string means no search (same as off)";
return si;
}
/// <summary>
/// Makes the search field list.
/// </summary>
/// <param name="fieldList">The field list.</param>
/// <returns></returns>
static public SettingItem MakeSearchFieldList(string fieldList)
{
SettingItem si = new SettingItem(new ListDataType("All;" + fieldList));
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 9;
si.Required = true;
si.Value = "All";
si.EnglishName = "Search field";
si.Description = "Search all fields or a single named field in the item record. " +
"The list of possible search fields are different for different modules";
return si;
}
/// <summary>
/// Makes the mobile only.
/// </summary>
/// <param name="defaultValue">if set to <c>true</c> [default value].</param>
/// <returns></returns>
static public SettingItem MakeMobileOnly(bool defaultValue)
{
SettingItem si = new SettingItem(new BooleanDataType());
si.Group = SettingItemGroup.MDF_SETTINGS;
si.Order = 10;
si.Value = defaultValue.ToString();
si.EnglishName = "Mobile Only";
si.Description = "When true only data for mobile devices are displyed";
return si;
}
/// <summary>
/// Gets the SQL select.
/// </summary>
/// <returns></returns>
public string GetSqlSelect()
{
StringBuilder select = new StringBuilder("", 1000);
select.Append(" SELECT");
if (MaxHits > 0)
select.Append(" TOP " + MaxHits);
select.Append(" ");
select.Append(SelectFieldList);
if (SupportsWorkflow && WorkflowVersion == WorkFlowVersion.Staging)
select.Append(" FROM " + ItemTableName + "_st itm");
else
select.Append(" FROM " + ItemTableName + " itm");
if (DataSource == DataSourceType.This)
{
// Note that there at this point are only one single moduleid in ModuleList!
select.Append(" WHERE itm.ModuleID = " + ModuleList + "");
}
else
{
select.Append(", rb_Modules mod, rb_ModuleDefinitions modDef");
if (_userID > -1)
select.Append(", rb_Roles, rb_UserRoles");
if (DataSource == DataSourceType.List)
if (AllNotInList)
select.Append(" WHERE itm.ModuleID NOT IN (" + ModuleList + ")");
else
select.Append(" WHERE itm.ModuleID IN (" + ModuleList + ")");
else
if (AllNotInList)
select.Append(" WHERE itm.ModuleID NOT IN (" + ModuleList + ")");
else
select.Append(" WHERE 1=1");
if (MobileOnly)
select.Append(" AND Mod.ShowMobile=1");
select.Append(" AND itm.ModuleID = mod.ModuleID");
select.Append(" AND mod.ModuleDefID = modDef.ModuleDefID");
select.Append(" AND modDef.PortalID = " + PortalID.ToString());
if (_userID > -1)
{
select.Append(" AND rb_UserRoles.UserID = " + _userID.ToString());
select.Append(" AND rb_UserRoles.RoleID = rb_Roles.RoleID");
select.Append(" AND rb_Roles.PortalID = " + _portalID.ToString());
select.Append(" AND ((mod.AuthorizedViewRoles LIKE '%All Users%') OR (mod.AuthorizedViewRoles LIKE '%'+rb_Roles.RoleName+'%'))");
}
else
{
select.Append(" AND (mod.AuthorizedViewRoles LIKE '%All Users%')");
}
}
// Why this? Because some Rb modules inserts a record containing null value fields! :o(
select.Append(" AND itm." + TitleFieldName + " IS NOT NULL");
if (SearchString != "")
{
select.Append(" AND (");
if (SearchField == "All")
{
string[] arrField = _searchFieldList.Split(';');
bool firstField = true;
foreach (string field in arrField)
{
if (firstField)
firstField = false;
else
select.Append(" OR ");
select.Append("itm." + field + " like '%" + SearchString + "%'");
}
}
else
{
select.Append("itm." + SearchField + " like '%" + SearchString + "%'");
}
select.Append(")");
}
select.Append(" ORDER BY itm." + SortField + " " + SortDirection);
return select.ToString();
}
/// <summary>
/// Get the item list data as a SqlDataReader
/// </summary>
/// <returns></returns>
public SqlDataReader GetDataReader()
{
string sqlSelect = GetSqlSelect();
return DBHelper.GetDataReader(sqlSelect);
}
/// <summary>
/// Get the item list data as a DataSet
/// </summary>
/// <returns></returns>
public DataSet GetDataSet()
{
string sqlSelect = GetSqlSelect();
return DBHelper.GetDataSet(sqlSelect);
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnPromocione class.
/// </summary>
[Serializable]
public partial class PnPromocioneCollection : ActiveList<PnPromocione, PnPromocioneCollection>
{
public PnPromocioneCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnPromocioneCollection</returns>
public PnPromocioneCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnPromocione 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 PN_promociones table.
/// </summary>
[Serializable]
public partial class PnPromocione : ActiveRecord<PnPromocione>, IActiveRecord
{
#region .ctors and Default Settings
public PnPromocione()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnPromocione(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnPromocione(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnPromocione(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_promociones", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema);
colvarIdLegajo.ColumnName = "id_legajo";
colvarIdLegajo.DataType = DbType.Int32;
colvarIdLegajo.MaxLength = 0;
colvarIdLegajo.AutoIncrement = true;
colvarIdLegajo.IsNullable = false;
colvarIdLegajo.IsPrimaryKey = true;
colvarIdLegajo.IsForeignKey = false;
colvarIdLegajo.IsReadOnly = false;
colvarIdLegajo.DefaultSetting = @"";
colvarIdLegajo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLegajo);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarIdCategoria = new TableSchema.TableColumn(schema);
colvarIdCategoria.ColumnName = "id_categoria";
colvarIdCategoria.DataType = DbType.Int16;
colvarIdCategoria.MaxLength = 0;
colvarIdCategoria.AutoIncrement = false;
colvarIdCategoria.IsNullable = false;
colvarIdCategoria.IsPrimaryKey = false;
colvarIdCategoria.IsForeignKey = false;
colvarIdCategoria.IsReadOnly = false;
colvarIdCategoria.DefaultSetting = @"";
colvarIdCategoria.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdCategoria);
TableSchema.TableColumn colvarComentario = new TableSchema.TableColumn(schema);
colvarComentario.ColumnName = "comentario";
colvarComentario.DataType = DbType.AnsiString;
colvarComentario.MaxLength = -1;
colvarComentario.AutoIncrement = false;
colvarComentario.IsNullable = true;
colvarComentario.IsPrimaryKey = false;
colvarComentario.IsForeignKey = false;
colvarComentario.IsReadOnly = false;
colvarComentario.DefaultSetting = @"";
colvarComentario.ForeignKeyTableName = "";
schema.Columns.Add(colvarComentario);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_promociones",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLegajo")]
[Bindable(true)]
public int IdLegajo
{
get { return GetColumnValue<int>(Columns.IdLegajo); }
set { SetColumnValue(Columns.IdLegajo, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("IdCategoria")]
[Bindable(true)]
public short IdCategoria
{
get { return GetColumnValue<short>(Columns.IdCategoria); }
set { SetColumnValue(Columns.IdCategoria, value); }
}
[XmlAttribute("Comentario")]
[Bindable(true)]
public string Comentario
{
get { return GetColumnValue<string>(Columns.Comentario); }
set { SetColumnValue(Columns.Comentario, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(DateTime varFecha,short varIdCategoria,string varComentario)
{
PnPromocione item = new PnPromocione();
item.Fecha = varFecha;
item.IdCategoria = varIdCategoria;
item.Comentario = varComentario;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLegajo,DateTime varFecha,short varIdCategoria,string varComentario)
{
PnPromocione item = new PnPromocione();
item.IdLegajo = varIdLegajo;
item.Fecha = varFecha;
item.IdCategoria = varIdCategoria;
item.Comentario = varComentario;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLegajoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdCategoriaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ComentarioColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLegajo = @"id_legajo";
public static string Fecha = @"fecha";
public static string IdCategoria = @"id_categoria";
public static string Comentario = @"comentario";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
#region License
/*
* Copyright 2014 Weswit Srl
*
* 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 License
using System;
using System.Collections;
using Lightstreamer.Interfaces.Metadata;
namespace Lightstreamer.Adapters.Metadata {
/// <summary>
/// <para>Simple full implementation of a Metadata Adapter, made available
/// in Lightstreamer SDK.</para>
/// <para>The class handles Item List specifications, a special case of Item Group name
/// formed by simply concatenating the names of the Items contained in a List
/// in a space separated way. Similarly, the class
/// handles Field List specifications, a special case of Field Schema name
/// formed by concatenating the names of the contained Fields.</para>
/// <para>The resource levels are assigned the same for all Items and Users,
/// according with values that can be supplied together with adapter
/// configuration.</para>
/// <para>The return of the GetAllowedMaxBandwidth method can be supplied in a
/// "max_bandwidth" parameter; the return of the GetAllowedMaxItemFrequency
/// method can be supplied in a "max_frequency" parameter; the return of the
/// GetAllowedBufferSize method can be supplied in a "buffer_size" parameter;
/// the return of the GetDistinctSnapshotLength method can be supplied
/// in a "distinct_snapshot_length" tag. All resource limits not supplied
/// are granted as unlimited but for distinct_snapshot_length, which defaults
/// as 10.</para>
/// <para>There are no access restrictions, but an optional User name check is
/// performed if a comma separated list of User names is supplied in an
/// "allowed_users" parameter.</para>
/// </summary>
public class LiteralBasedProvider : MetadataProviderAdapter {
private string [] _allowedUsers;
private double _maxBandwidth;
private double _maxFrequency;
private int _bufferSize;
private int _distinctSnapshotLength;
/// <summary>
/// Void constructor required by the Remote Server.
/// </summary>
public LiteralBasedProvider() {}
/// <summary>
/// Reads configuration settings for user and resource constraints.
/// If some setting is missing, the corresponding constraint is not set.
/// </summary>
/// <param name="parameters">Can contain the configuration settings.</param>
/// <param name="configFile">Not used.</param>
/// <exception cref="MetadataProviderException">
/// never thrown in this case.
/// </exception>
public override void Init(IDictionary parameters, string configFile) {
if (parameters == null) {
parameters = new Hashtable();
}
string users = (string) parameters["allowed_users"];
if (users != null) {
_allowedUsers = MySplit(users, ",");
}
string mb = (string) parameters["max_bandwidth"];
if (mb != null) {
_maxBandwidth = Double.Parse(mb);
}
string mf = (string) parameters["max_frequency"];
if (mf != null) {
_maxFrequency = Double.Parse(mf);
}
string bs = (string) parameters["buffer_size"];
if (bs != null) {
_bufferSize = Int32.Parse(bs);
}
string dsl = (String) parameters["distinct_snapshot_length"];
if (dsl != null) {
_distinctSnapshotLength = Int32.Parse(dsl);
} else {
_distinctSnapshotLength = 10;
}
}
/// <summary>
/// Resolves an Item List Specification supplied in a Request. The names of the Items
/// in the List are returned.
/// Item List Specifications are expected to be formed by simply concatenating the names
/// of the contained Items, in a space separated way.
/// </summary>
/// <param name="user">A User name. Not used.</param>
/// <param name="sessionID">A Session ID. Not used.</param>
/// <param name="itemList">An Item List Specification.</param>
/// <returns>An array with the names of the Items in the List.</returns>
/// <exception cref="ItemsException">
/// never thrown in this case.
/// </exception>
public override string [] GetItems(string user, string sessionID, string itemList) {
return MySplit(itemList, " ");
}
/// <summary>
/// Resolves a Field List specification supplied in a Request. The names of the Fields
/// in the List are returned.
/// Field List specifications are expected to be formed by simply concatenating the names
/// of the contained Fields, in a space separated way.
/// </summary>
/// <param name="user">A User name. Not used.</param>
/// <param name="sessionID">A Session ID. Not used.</param>
/// <param name="itemList">The specification of the Item List whose Items the Field List
/// is to be applied to. Not used.</param>
/// <param name="fieldList">A Field List specification.</param>
/// <returns>An array with the names of the Fields in the List.</returns>
/// <exception cref="SchemaException">
/// never thrown in this case.
/// </exception>
public override string [] GetSchema(string user, string sessionID, string itemList, string fieldList) {
return MySplit(fieldList, " ");
}
/// <summary>
/// Checks if a user is enabled to make Requests to the related Data
/// Providers.
/// The check is deferred to a simpler 2-arguments version of the
/// method, where the httpHeader argument is discarded.
/// Note that, for authentication purposes, only the user and password
/// arguments should be consulted.
/// </summary>
/// <param name="user">A User name.</param>
/// <param name="password">An optional password. Not used.</param>
/// <param name="httpHeaders">An IDictionary-type value object that
/// contains a name-value pair for each header found in the HTTP
/// request that originated the call. Not used.</param>
/// <exception cref="AccessException">
/// in case a list of User names has been configured
/// and the supplied name does not belong to the list.
/// </exception>
public override void NotifyUser(string user, string password, IDictionary httpHeaders) {
NotifyUser(user, password);
}
/// <summary>
/// Checks if a user is enabled to make Requests to the related Data
/// Providers.
/// If a list of User names has been configured, this list is checked.
/// Otherwise, any User name is allowed. No password check is performed.
/// </summary>
/// <param name="user">A User name.</param>
/// <param name="password">An optional password. Not used.</param>
/// <exception cref="AccessException">
/// in case a list of User names has been configured
/// and the supplied name does not belong to the list.
/// </exception>
public override void NotifyUser(string user, string password)
{
if (!CheckUser(user))
{
throw new AccessException("Unauthorized user");
}
}
/// <summary>
/// Returns the bandwidth level to be allowed to a User for a push Session.
/// </summary>
/// <param name="user">A User name. Not used.</param>
/// <returns>The bandwidth, in Kbit/sec, as supplied in the Metadata
/// Adapter configuration.</returns>
public override double GetAllowedMaxBandwidth(string user) {
return _maxBandwidth;
}
/// <summary>
/// Returns the ItemUpdate frequency to be allowed to a User for a specific
/// Item.
/// </summary>
/// <param name="user">A User name. Not used.</param>
/// <param name="item">An Item Name. Not used.</param>
/// <returns>The allowed Update frequency, in Updates/sec, as supplied
/// in the Metadata Adapter configuration.</returns>
public override double GetAllowedMaxItemFrequency(string user, string item) {
return _maxFrequency;
}
/// <summary>
/// Returns the size of the buffer internally used to enqueue subsequent
/// ItemUpdates for the same Item.
/// </summary>
/// <param name="user">A User name. Not used.</param>
/// <param name="item">An Item Name. Not used.</param>
/// <returns>The allowed buffer size, as supplied in the Metadata Adapter
/// configuration.</returns>
public override int GetAllowedBufferSize(string user, string item) {
return _bufferSize;
}
/// <summary>
/// Returns the maximum allowed length for a Snapshot of any Item that
/// has been requested with publishing Mode DISTINCT.
/// </summary>
/// <param name="item">An Item Name. Not used.</param>
/// <returns>The maximum allowed length for the Snapshot, as supplied
/// in the Metadata Adapter configuration. In case no value has been
/// supplied, a default value of 10 events is returned, which is thought
/// to be enough to satisfy typical Client requests.</returns>
public override int GetDistinctSnapshotLength(string item) {
return _distinctSnapshotLength;
}
// ////////////////////////////////////////////////////////////////////////
// Internal methods
private bool CheckUser(string user) {
if ((_allowedUsers == null) || (_allowedUsers.Length == 0)) {
return true;
}
if (user == null) {
return false;
}
for (int i = 0; i < _allowedUsers.Length; i++) {
if (_allowedUsers[i] == null) {
continue;
}
if (_allowedUsers[i].Equals(user)) {
return true;
}
}
return false;
}
private string [] MySplit(string arg, string separators) {
return arg.Split(separators.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
}
}
| |
// Copyright (C) 2011, 2012 Zeno Gantner
//
// This file is part of MyMediaLite.
//
// MyMediaLite is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// MyMediaLite is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MyMediaLite. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using MyMediaLite.Data;
using MyMediaLite.DataType;
using MyMediaLite.IO;
namespace MyMediaLite.RatingPrediction
{
/// <summary>Bi-polar frequency-weighted Slope-One rating prediction</summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>
/// Daniel Lemire, Anna Maclachlan:
/// Slope One Predictors for Online Rating-Based Collaborative Filtering.
/// SIAM Data Mining (SDM 2005).
/// http://www.daniel-lemire.com/fr/abstracts/SDM2005.html
/// </description></item>
/// </list>
///
/// This recommender does NOT support incremental updates. They would be easy to implement, though.
/// </remarks>
public class BiPolarSlopeOne : RatingPredictor
{
private SkewSymmetricSparseMatrix diff_matrix_like;
private SymmetricSparseMatrix<int> freq_matrix_like;
private SkewSymmetricSparseMatrix diff_matrix_dislike;
private SymmetricSparseMatrix<int> freq_matrix_dislike;
private float global_average;
private IList<float> user_average;
///
public override bool CanPredict(int user_id, int item_id)
{
if (user_id > MaxUserID || item_id > MaxItemID)
return false;
foreach (int index in ratings.ByUser[user_id])
{
if (freq_matrix_like[item_id, ratings.Items[index]] != 0)
return true;
if (freq_matrix_dislike[item_id, ratings.Items[index]] != 0)
return true;
}
return false;
}
///
public override float Predict(int user_id, int item_id)
{
if (item_id > MaxItemID || user_id > MaxUserID)
return global_average;
double prediction = 0.0;
int frequencies = 0;
foreach (int index in ratings.ByUser[user_id])
{
if (ratings[index] > user_average[user_id])
{
int f = freq_matrix_like[item_id, ratings.Items[index]];
if (f != 0)
{
prediction += ( diff_matrix_like[item_id, ratings.Items[index]] + ratings[index] ) * f;
frequencies += f;
}
}
else
{
int f = freq_matrix_dislike[item_id, ratings.Items[index]];
if (f != 0)
{
prediction += ( diff_matrix_dislike[item_id, ratings.Items[index]] + ratings[index] ) * f;
frequencies += f;
}
}
}
if (frequencies == 0)
return global_average;
float result = (float) (prediction / frequencies);
if (result > MaxRating)
return MaxRating;
if (result < MinRating)
return MinRating;
return result;
}
///
public override void Train()
{
InitModel();
// default value if no prediction can be made
global_average = ratings.Average;
// compute difference sums and frequencies
foreach (int user_id in ratings.AllUsers)
{
float user_avg = 0;
foreach (int index in ratings.ByUser[user_id])
user_avg += ratings[index];
user_avg /= ratings.ByUser[user_id].Count;
// store for later use
user_average[user_id] = user_avg;
foreach (int index in ratings.ByUser[user_id])
foreach (int index2 in ratings.ByUser[user_id])
if (ratings[index] > user_avg && ratings[index2] > user_avg)
{
freq_matrix_like[ratings.Items[index], ratings.Items[index2]] += 1;
diff_matrix_like[ratings.Items[index], ratings.Items[index2]] += (float) (ratings[index] - ratings[index2]);
}
else if (ratings[index] < user_avg && ratings[index2] < user_avg)
{
freq_matrix_dislike[ratings.Items[index], ratings.Items[index2]] += 1;
diff_matrix_dislike[ratings.Items[index], ratings.Items[index2]] += (float) (ratings[index] - ratings[index2]);
}
}
// compute average differences
foreach (var pair in freq_matrix_like.NonEmptyEntryIDs)
{
int i = pair.Item1;
int j = pair.Item2;
if (i < j)
diff_matrix_like[i, j] /= freq_matrix_like[i, j];
}
foreach (var pair in freq_matrix_dislike.NonEmptyEntryIDs)
{
int i = pair.Item1;
int j = pair.Item2;
if (i < j)
diff_matrix_dislike[i, j] /= freq_matrix_dislike[i, j];
}
}
///
void InitModel()
{
// create data structure
diff_matrix_like = new SkewSymmetricSparseMatrix(MaxItemID + 1);
freq_matrix_like = new SymmetricSparseMatrix<int>(MaxItemID + 1);
diff_matrix_dislike = new SkewSymmetricSparseMatrix(MaxItemID + 1);
freq_matrix_dislike = new SymmetricSparseMatrix<int>(MaxItemID + 1);
user_average = new float[MaxUserID + 1];
}
///
public override void LoadModel(string file)
{
InitModel();
using ( StreamReader reader = Model.GetReader(file, this.GetType()) )
{
var global_average = float.Parse(reader.ReadLine(), CultureInfo.InvariantCulture);
var diff_matrix_like = (SkewSymmetricSparseMatrix) reader.ReadMatrix(this.diff_matrix_like);
var freq_matrix_like = (SymmetricSparseMatrix<int>) reader.ReadMatrix(this.freq_matrix_like);
var diff_matrix_dislike = (SkewSymmetricSparseMatrix) reader.ReadMatrix(this.diff_matrix_dislike);
var freq_matrix_dislike = (SymmetricSparseMatrix<int>) reader.ReadMatrix(this.freq_matrix_dislike);
var user_average = reader.ReadVector();
// assign new model
this.global_average = global_average;
this.diff_matrix_like = diff_matrix_like;
this.freq_matrix_like = freq_matrix_like;
this.diff_matrix_dislike = diff_matrix_dislike;
this.freq_matrix_dislike = freq_matrix_dislike;
this.user_average = user_average;
}
}
///
public override void SaveModel(string file)
{
using ( StreamWriter writer = Model.GetWriter(file, this.GetType(), "2.99") )
{
writer.WriteLine(global_average.ToString(CultureInfo.InvariantCulture));
writer.WriteSparseMatrix(diff_matrix_like);
writer.WriteSparseMatrix(freq_matrix_like);
writer.WriteSparseMatrix(diff_matrix_dislike);
writer.WriteSparseMatrix(freq_matrix_dislike);
writer.WriteVector(user_average);
}
}
}
}
| |
namespace SIL.Windows.Forms.ImageToolbox.ImageGallery
{
partial class ImageGalleryControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
private bool disposed = false;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposed)
return;
disposed = true;
if (disposing)
{
if (_thumbnailViewer != null)
_thumbnailViewer.Closing(); //this guy was working away in the background
if (_messageLabel != null)
_messageLabel.SizeChanged -= MessageLabelSizeChanged;
if (components != null)
components.Dispose();
if (_thumbnailViewer != null)
{
_thumbnailViewer.Dispose();
_thumbnailViewer = null;
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this._searchButton = new System.Windows.Forms.Button();
this._searchResultStats = new System.Windows.Forms.Label();
this._labelSearch = new System.Windows.Forms.Label();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this._searchLanguageMenu = new System.Windows.Forms.ToolStripDropDownButton();
this._downloadInstallerLink = new SIL.Windows.Forms.Widgets.BetterLinkLabel();
this._messageLabel = new SIL.Windows.Forms.Widgets.BetterLabel();
this._searchTermsBox = new SIL.Windows.Forms.Widgets.TextInputBox();
this._thumbnailViewer = new ThumbnailViewer();
this._localizationHelper = new SIL.Windows.Forms.i18n.LocalizationHelper(this.components);
this._collectionToolStrip = new System.Windows.Forms.ToolStrip();
this._collectionDropDown = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this._localizationHelper)).BeginInit();
this._collectionToolStrip.SuspendLayout();
this.SuspendLayout();
//
// _searchButton
//
this._searchButton.Font = new System.Drawing.Font("Segoe UI", 9F);
this._searchButton.Image = global::SIL.Windows.Forms.Properties.Resources.search18x18;
this._searchButton.Location = new System.Drawing.Point(175, 35);
this._searchButton.Name = "_searchButton";
this._searchButton.Size = new System.Drawing.Size(48, 28);
this._searchButton.TabIndex = 1;
this._searchButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this._searchButton.UseVisualStyleBackColor = true;
this._searchButton.Click += new System.EventHandler(this._searchButton_Click);
//
// _searchResultStats
//
this._searchResultStats.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
this._searchResultStats.Font = new System.Drawing.Font("Segoe UI", 10F);
this._searchResultStats.Location = new System.Drawing.Point(9, 70);
this._searchResultStats.Name = "_searchResultStats";
this._searchResultStats.Size = new System.Drawing.Size(375, 22);
this._searchResultStats.TabIndex = 12;
this._searchResultStats.Text = "~Search Result Stats";
//
// _labelSearch
//
this._labelSearch.AutoSize = true;
this._labelSearch.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._labelSearch.Location = new System.Drawing.Point(8, 8);
this._labelSearch.Name = "_labelSearch";
this._labelSearch.Size = new System.Drawing.Size(120, 20);
this._labelSearch.TabIndex = 14;
this._labelSearch.Text = "Image Galleries";
//
// toolStrip1
//
this.toolStrip1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.toolStrip1.AutoSize = false;
this.toolStrip1.BackColor = System.Drawing.Color.Transparent;
this.toolStrip1.CanOverflow = false;
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this._searchLanguageMenu});
this.toolStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow;
this.toolStrip1.Location = new System.Drawing.Point(228, 35);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(200, 28);
this.toolStrip1.TabIndex = 15;
this.toolStrip1.Text = "toolStrip1";
//
// _searchLanguageMenu
//
this._searchLanguageMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this._searchLanguageMenu.ImageTransparentColor = System.Drawing.Color.Magenta;
this._searchLanguageMenu.Name = "_searchLanguageMenu";
this._searchLanguageMenu.Size = new System.Drawing.Size(107, 19);
this._searchLanguageMenu.Text = "Language Name";
this._searchLanguageMenu.Visible = false;
//
// _downloadInstallerLink
//
this._downloadInstallerLink.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._downloadInstallerLink.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._downloadInstallerLink.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Underline);
this._downloadInstallerLink.ForeColor = System.Drawing.Color.Blue;
this._downloadInstallerLink.IsTextSelectable = true;
this._downloadInstallerLink.Location = new System.Drawing.Point(24, 269);
this._downloadInstallerLink.Multiline = true;
this._downloadInstallerLink.Name = "_downloadInstallerLink";
this._downloadInstallerLink.ReadOnly = true;
this._downloadInstallerLink.Size = new System.Drawing.Size(470, 17);
this._downloadInstallerLink.TabIndex = 11;
this._downloadInstallerLink.TabStop = false;
this._downloadInstallerLink.Text = "Download Art Of Reading Installer";
this._downloadInstallerLink.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this._downloadInstallerLink.URL = "https://bloomlibrary.org/artofreading";
this._downloadInstallerLink.Visible = false;
//
// _messageLabel
//
this._messageLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._messageLabel.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._messageLabel.Enabled = false;
this._messageLabel.Font = new System.Drawing.Font("Segoe UI", 9F);
this._messageLabel.ForeColor = System.Drawing.Color.Gray;
this._messageLabel.IsTextSelectable = false;
this._messageLabel.Location = new System.Drawing.Point(24, 124);
this._messageLabel.Multiline = true;
this._messageLabel.Name = "_messageLabel";
this._messageLabel.ReadOnly = true;
this._messageLabel.Size = new System.Drawing.Size(470, 17);
this._messageLabel.TabIndex = 10;
this._messageLabel.TabStop = false;
this._messageLabel.Text = "~No matching images";
this._messageLabel.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// _searchTermsBox
//
this._searchTermsBox.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._searchTermsBox.Location = new System.Drawing.Point(12, 35);
this._searchTermsBox.Name = "_searchTermsBox";
this._searchTermsBox.Size = new System.Drawing.Size(157, 28);
this._searchTermsBox.TabIndex = 0;
this._searchTermsBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this._searchTermsBox_KeyDown);
//
// _thumbnailViewer
//
this._thumbnailViewer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._thumbnailViewer.CaptionMethod = null;
this._thumbnailViewer.Location = new System.Drawing.Point(12, 95);
this._thumbnailViewer.Name = "_thumbnailViewer";
this._thumbnailViewer.Size = new System.Drawing.Size(494, 228);
this._thumbnailViewer.TabIndex = 2;
this._thumbnailViewer.ThumbBorderColor = System.Drawing.Color.Wheat;
this._thumbnailViewer.ThumbNailSize = 95;
this._thumbnailViewer.DoubleClick += new System.EventHandler(this._thumbnailViewer_DoubleClick);
//
// _localizationHelper
//
this._localizationHelper.Parent = this;
//
// _collectionToolStrip
//
this._collectionToolStrip.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._collectionToolStrip.AutoSize = false;
this._collectionToolStrip.BackColor = System.Drawing.Color.Transparent;
this._collectionToolStrip.CanOverflow = false;
this._collectionToolStrip.Dock = System.Windows.Forms.DockStyle.None;
this._collectionToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this._collectionToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this._collectionDropDown});
this._collectionToolStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow;
this._collectionToolStrip.Location = new System.Drawing.Point(373, 35);
this._collectionToolStrip.Name = "_collectionToolStrip";
this._collectionToolStrip.Size = new System.Drawing.Size(133, 28);
this._collectionToolStrip.TabIndex = 18;
this._collectionToolStrip.Text = "_collectionToolStrip";
//
// _collectionDropDown
//
this._collectionDropDown.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this._collectionDropDown.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._collectionDropDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this._collectionDropDown.Name = "_collectionDropDown";
this._collectionDropDown.Size = new System.Drawing.Size(64, 19);
this._collectionDropDown.Text = "Galleries";
this._collectionDropDown.Visible = false;
//
// ArtOfReadingChooser
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this._labelSearch);
this.Controls.Add(this._collectionToolStrip);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this._searchResultStats);
this.Controls.Add(this._downloadInstallerLink);
this.Controls.Add(this._messageLabel);
this.Controls.Add(this._searchButton);
this.Controls.Add(this._searchTermsBox);
this.Controls.Add(this._thumbnailViewer);
this.Name = "ImageGalleryControl";
this.Size = new System.Drawing.Size(530, 325);
this.Load += new System.EventHandler(this.ArtOfReadingChooser_Load);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this._localizationHelper)).EndInit();
this._collectionToolStrip.ResumeLayout(false);
this._collectionToolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ImageGallery.ThumbnailViewer _thumbnailViewer;
private System.Windows.Forms.Button _searchButton;
private SIL.Windows.Forms.Widgets.TextInputBox _searchTermsBox;
private Widgets.BetterLabel _messageLabel;
private i18n.LocalizationHelper _localizationHelper;
private Widgets.BetterLinkLabel _downloadInstallerLink;
private System.Windows.Forms.Label _searchResultStats;
private System.Windows.Forms.Label _labelSearch;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripDropDownButton _searchLanguageMenu;
private System.Windows.Forms.ToolStrip _collectionToolStrip;
private System.Windows.Forms.ToolStripDropDownButton _collectionDropDown;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CmsEngine.Application.Attributes;
using CmsEngine.Application.EditModels;
using CmsEngine.Application.Extensions;
using CmsEngine.Application.Extensions.Mapper;
using CmsEngine.Application.ViewModels;
using CmsEngine.Application.ViewModels.DataTableViewModels;
using CmsEngine.Core;
using CmsEngine.Data;
using CmsEngine.Data.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
namespace CmsEngine.Application.Services
{
public class PageService : Service, IPageService
{
private readonly IUnitOfWork _unitOfWork;
public PageService(IUnitOfWork uow, IHttpContextAccessor hca, ILoggerFactory loggerFactory, IMemoryCache memoryCache)
: base(uow, hca, loggerFactory, memoryCache)
{
_unitOfWork = uow;
}
public async Task<ReturnValue> Delete(Guid id)
{
var item = await _unitOfWork.Pages.GetByIdAsync(id);
var returnValue = new ReturnValue($"Page '{item.Title}' deleted at {DateTime.Now.ToString("T")}.");
try
{
_unitOfWork.Pages.Delete(item);
await _unitOfWork.Save();
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
returnValue.SetErrorMessage("An error has occurred while deleting the page");
}
return returnValue;
}
public async Task<ReturnValue> DeleteRange(Guid[] ids)
{
var items = await _unitOfWork.Pages.GetByMultipleIdsAsync(ids);
var returnValue = new ReturnValue($"Pages deleted at {DateTime.Now.ToString("T")}.");
try
{
_unitOfWork.Pages.DeleteRange(items);
await _unitOfWork.Save();
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
returnValue.SetErrorMessage("An error has occurred while deleting the pages");
}
return returnValue;
}
public IEnumerable<Page> FilterForDataTable(string searchValue, IEnumerable<Page> items)
{
if (!string.IsNullOrWhiteSpace(searchValue))
{
var searchableProperties = typeof(PageTableViewModel).GetProperties().Where(p => Attribute.IsDefined(p, typeof(Searchable)));
items = items.Where(items.GetSearchExpression(searchValue, searchableProperties).Compile());
}
return items;
}
public async Task<IEnumerable<PageViewModel>> GetAllPublished()
{
logger.LogDebug("PageService > GetPagesByStatusReadOnly()");
var items = await _unitOfWork.Pages.GetByStatusOrderByDescending(DocumentStatus.Published);
logger.LogDebug("Pages loaded: {0}", items.Count());
return items.MapToViewModel();
}
public async Task<PageViewModel> GetBySlug(string slug)
{
logger.LogDebug($"PageService > GetBySlug({slug})");
var item = await _unitOfWork.Pages.GetBySlug(slug);
return item?.MapToViewModel();
}
public async Task<(IEnumerable<PageTableViewModel> Data, int RecordsTotal, int RecordsFiltered)> GetForDataTable(DataParameters parameters)
{
var items = await _unitOfWork.Pages.GetForDataTable();
int recordsTotal = items.Count();
if (!string.IsNullOrWhiteSpace(parameters.Search.Value))
{
items = FilterForDataTable(parameters.Search.Value, items);
}
items = OrderForDataTable(parameters.Order[0].Column, parameters.Order[0].Dir, items);
return (items.MapToTableViewModel(), recordsTotal, items.Count());
}
public IEnumerable<Page> OrderForDataTable(int column, string direction, IEnumerable<Page> items)
{
try
{
switch (column)
{
case 1:
items = direction == "asc" ? items.OrderBy(o => o.Title) : items.OrderByDescending(o => o.Title);
break;
case 2:
items = direction == "asc" ? items.OrderBy(o => o.Description) : items.OrderByDescending(o => o.Description);
break;
case 3:
items = direction == "asc" ? items.OrderBy(o => o.Slug) : items.OrderByDescending(o => o.Slug);
break;
//case 4:
// items = direction == "asc" ? items.OrderBy(o => o.Author.FullName) : items.OrderByDescending(o => o.Author.FullName);
// break;
case 5:
items = direction == "asc" ? items.OrderBy(o => o.PublishedOn) : items.OrderByDescending(o => o.PublishedOn);
break;
case 6:
items = direction == "asc" ? items.OrderBy(o => o.Status) : items.OrderByDescending(o => o.Status);
break;
default:
items = items.OrderByDescending(o => o.PublishedOn);
break;
}
}
catch
{
throw;
}
return items;
}
public async Task<ReturnValue> Save(PageEditModel pageEditModel)
{
logger.LogDebug("PageService > Save(PageEditModel: {0})", pageEditModel.ToString());
var returnValue = new ReturnValue($"Page '{pageEditModel.Title}' saved.");
try
{
if (pageEditModel.IsNew)
{
logger.LogDebug("New page");
var page = pageEditModel.MapToModel();
page.WebsiteId = Instance.Id;
await PrepareRelatedPropertiesAsync(page);
await unitOfWork.Pages.Insert(page);
}
else
{
logger.LogDebug("Update page");
var page = pageEditModel.MapToModel(await unitOfWork.Pages.GetForSavingById(pageEditModel.VanityId));
page.WebsiteId = Instance.Id;
_unitOfWork.Pages.RemoveRelatedItems(page);
await PrepareRelatedPropertiesAsync(page);
_unitOfWork.Pages.Update(page);
}
await _unitOfWork.Save();
logger.LogDebug("Page saved");
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
returnValue.SetErrorMessage("An error has occurred while saving the page");
}
return returnValue;
}
public PageEditModel SetupEditModel()
{
logger.LogDebug("PageService > SetupEditModel()");
return new PageEditModel();
}
public async Task<PageEditModel> SetupEditModel(Guid id)
{
logger.LogDebug("PageService > SetupPageEditModel(id: {0})", id);
var item = await _unitOfWork.Pages.GetByIdAsync(id);
logger.LogDebug("Page: {0}", item.ToString());
return item?.MapToEditModel();
}
private async Task PrepareRelatedPropertiesAsync(Page page)
{
var user = await GetCurrentUserAsync();
page.PageApplicationUsers.Clear();
page.PageApplicationUsers.Add(new PageApplicationUser
{
PageId = page.Id,
ApplicationUserId = user.Id
});
}
}
}
| |
//
// RecipePrintPageRenderer.cs
//
// Author: Jeffrey Stedfast <jeff@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 System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace RecipesAndPrinting
{
public class RecipePrintPageRenderer : UIPrintPageRenderer
{
const float RecipeInfoHeight = 150.0f;
const float TitleSize = 24.0f;
const float Padding = 10.0f;
static UIFont SystemFont = UIFont.SystemFontOfSize (UIFont.SystemFontSize);
Dictionary<UIPrintFormatter, Recipe> recipeFormatterMap = new Dictionary<UIPrintFormatter, Recipe> ();
NSRange pageRange;
Recipe[] recipes;
public RecipePrintPageRenderer (Recipe[] recipes)
{
this.HeaderHeight = 20.0f;
this.FooterHeight = 20.0f;
this.recipes = recipes;
}
// Calculate the content area based on the printableRect, that is, the area in which
// the printer can print content. a.k.a the imageable area of the paper.
RectangleF ContentArea {
get {
RectangleF r = PrintableRect;
r.Height -= HeaderHeight + FooterHeight;
r.Y += HeaderHeight;
return r;
}
}
public override void PrepareForDrawingPages (NSRange range)
{
base.PrepareForDrawingPages (range);
pageRange = range;
}
// This property must be overriden when doing custom drawing as we are.
// Since our custom drawing is really only for the borders and we are
// relying on a series of UIMarkupTextPrintFormatters to display the recipe
// content, UIKit can calculate the number of pages based on informtation
// provided by those formatters.
//
// Therefore, setup the formatters, and ask super to count the pages.
public override int NumberOfPages {
get {
PrintFormatters = new UIPrintFormatter [0];
SetupPrintFormatters ();
return base.NumberOfPages;
}
}
// Iterate through the recipes setting each of their html representations into
// a UIMarkupTextPrintFormatter and add that formatter to the printing job.
void SetupPrintFormatters ()
{
RectangleF contentArea = ContentArea;
float previousFormatterMaxY = contentArea.Top;
int page = 0;
foreach (Recipe recipe in recipes) {
string html = recipe.HtmlRepresentation;
UIMarkupTextPrintFormatter formatter = new UIMarkupTextPrintFormatter (html);
recipeFormatterMap.Add (formatter, recipe);
// Make room for the recipe info
UIEdgeInsets contentInsets = new UIEdgeInsets (0.0f, 0.0f, 0.0f, 0.0f);
contentInsets.Top = previousFormatterMaxY + RecipeInfoHeight;
if (contentInsets.Top > contentArea.Bottom) {
// Move to the next page
contentInsets.Top = contentArea.Top + RecipeInfoHeight;
page++;
}
formatter.ContentInsets = contentInsets;
// Add the formatter to the renderer at the specified page
AddPrintFormatter (formatter, page);
page = formatter.StartPage + formatter.PageCount - 1;
previousFormatterMaxY = formatter.RectangleForPage (page).Bottom;
}
}
// Custom UIPrintPageRenderer's may override this class to draw a custom print page header.
// To illustrate that, this class sets the date in the header.
public override void DrawHeaderForPage (int index, RectangleF headerRect)
{
NSDateFormatter dateFormatter = new NSDateFormatter ();
dateFormatter.DateFormat = "MMMM d, yyyy 'at' h:mm a";
NSString dateString = new NSString (dateFormatter.ToString (NSDate.Now));
dateFormatter.Dispose ();
dateString.DrawString (headerRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Right);
dateString.Dispose ();
}
public override void DrawFooterForPage (int index, RectangleF footerRect)
{
NSString footer = new NSString (string.Format ("Page {0} of {1}", index - pageRange.Location + 1, pageRange.Length));
footer.DrawString (footerRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Center);
footer.Dispose ();
}
// To intermix custom drawing with the drawing performed by an associated print formatter,
// this method is called for each print formatter associated with a given page.
//
// We do this to intermix/overlay our custom drawing onto the recipe presentation.
// We draw the upper portion of the recipe presentation by hand (image, title, desc),
// and the bottom portion is drawn via the UIMarkupTextPrintFormatter.
public override void DrawPrintFormatterForPage (UIPrintFormatter printFormatter, int page)
{
base.DrawPrintFormatterForPage (printFormatter, page);
// To keep our custom drawing in sync with the printFormatter, base our drawing
// on the formatters rect.
RectangleF rect = printFormatter.RectangleForPage (page);
// Use a bezier path to draw the borders.
// We may potentially choose not to draw either the top or bottom line
// of the border depending on whether our recipe extended from the previous
// page, or carries onto the subsequent page.
UIBezierPath border = new UIBezierPath ();
if (page == printFormatter.StartPage) {
// For border drawing, get the rect that includes the formatter area plus the header area.
// Move the formatter's rect up the size of the custom drawn recipe presentation
// and essentially grow the rect's height by this amount.
rect.Height += RecipeInfoHeight;
rect.Y -= RecipeInfoHeight;
border.MoveTo (rect.Location);
border.AddLineTo (new PointF (rect.Right, rect.Top));
Recipe recipe = recipeFormatterMap[printFormatter];
// Run custom code to draw upper portion of the recipe presentation (image, title, desc)
DrawRecipe (recipe, rect);
}
// Draw the left border
border.MoveTo (rect.Location);
border.AddLineTo (new PointF (rect.Left, rect.Bottom));
// Draw the right border
border.MoveTo (new PointF (rect.Right, rect.Top));
border.AddLineTo (new PointF (rect.Right, rect.Bottom));
if (page == printFormatter.StartPage + printFormatter.PageCount - 1)
border.AddLineTo (new PointF (rect.Left, rect.Bottom));
// Set the UIColor to be used by the current graphics context, and then stroke
// stroke the current path that is defined by the border bezier path.
UIColor.Black.SetColor ();
border.Stroke ();
}
// Custom code to draw upper portion of the recipe presentation (image, title, desc).
// The argument rect is the full size of the recipe presentation.
void DrawRecipe (Recipe recipe, RectangleF rect)
{
DrawRecipeImage (recipe.Image, rect);
DrawRecipeName (recipe.Name, rect);
DrawRecipeInfo (recipe.AggregatedInfo, rect);
}
void DrawRecipeImage (UIImage image, RectangleF rect)
{
// Create a new rect based on the size of the header area
RectangleF imageRect = RectangleF.Empty;
// Scale the image to fit in the infoRect
float maxImageDimension = RecipeInfoHeight - Padding * 2;
float largestImageDimension = Math.Max (image.Size.Width, image.Size.Height);
float scale = maxImageDimension / largestImageDimension;
imageRect.Size.Width = image.Size.Width * scale;
imageRect.Size.Height = image.Size.Height * scale;
// Place the image rect at the x,y defined by the argument rect
imageRect.Location = new PointF (rect.Left + Padding, rect.Top + Padding);
// Ask the image to draw in the image rect
image.Draw (imageRect);
}
// Custom drawing code to put the recipe name in the title section of the recipe presentation's header.
void DrawRecipeName (string name, RectangleF rect)
{
RectangleF nameRect = RectangleF.Empty;
nameRect.X = rect.Left + RecipeInfoHeight;
nameRect.Y = rect.Top + Padding;
nameRect.Width = rect.Width - RecipeInfoHeight;
nameRect.Height = RecipeInfoHeight;
using (UIFont font = UIFont.BoldSystemFontOfSize (TitleSize)) {
using (NSString str = new NSString (name)) {
str.DrawString (nameRect, font, UILineBreakMode.Clip, UITextAlignment.Left);
}
}
}
// Custom drawing code to put the recipe recipe description, and prep time
// in the title section of the recipe presentation's header.
void DrawRecipeInfo (string info, RectangleF rect)
{
RectangleF infoRect = RectangleF.Empty;
infoRect.X = rect.Left + RecipeInfoHeight;
infoRect.Y = rect.Top + TitleSize * 2;
infoRect.Width = rect.Width - RecipeInfoHeight;
infoRect.Height = RecipeInfoHeight - TitleSize * 2;
UIColor.DarkGray.SetColor ();
using (NSString str = new NSString (info)) {
str.DrawString (infoRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Left);
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Web;
using System.Web.Routing;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Caching;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Client.Runtime.Serialization;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client.Services.Messages;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
namespace Microsoft.Xrm.Portal.Web.Handlers
{
/// <summary>
/// Used to invalidate cache items based on the type of message (publish, create, update, or delete) and the entity type and id.
/// </summary>
/// <remarks>
/// Only the default or configured <see cref="OrganizationServiceCache"/>s will be invalidated.
/// </remarks>
public class CacheInvalidationHandler : IHttpHandler, IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new CacheInvalidationHandler();
}
public bool IsReusable
{
get { return true; }
}
public virtual void ProcessRequest(HttpContext context)
{
try
{
if (context.Request.ContentType == "application/json")
{
ProcessJsonRequest(context);
return;
}
var message = GetMessage(context);
if (string.Equals("Publish", message, StringComparison.InvariantCultureIgnoreCase)
|| string.Equals("PublishAll", message, StringComparison.InvariantCultureIgnoreCase))
{
foreach (var serviceCache in GetServiceCaches())
{
serviceCache.Remove(GetPluginMessage(CacheItemCategory.Metadata));
}
// get the default object cache
foreach (var cache in GetObjectCaches())
{
cache.Remove("xrm:dependency:metadata:*");
}
return;
}
if (string.Equals("InvalidateAll", message, StringComparison.InvariantCultureIgnoreCase))
{
foreach (var serviceCache in GetServiceCaches())
{
serviceCache.Remove(GetPluginMessage(CacheItemCategory.All));
}
// get the default object cache
foreach (var cache in GetObjectCaches())
{
cache.RemoveAll();
}
return;
}
var entity = GetEntityReference(context);
// get the default service cache
if (string.Equals("Create", message, StringComparison.InvariantCultureIgnoreCase)
|| string.Equals("Update", message, StringComparison.InvariantCultureIgnoreCase)
|| string.Equals("Delete", message, StringComparison.InvariantCultureIgnoreCase))
{
foreach (var serviceCache in GetServiceCaches())
{
serviceCache.Remove(entity);
}
return;
}
}
catch (Exception e)
{
Tracing.FrameworkError(GetType().Name, "ProcessRequest", "Cache invalidation failed. {0}", e.Message);
}
}
protected virtual void ProcessJsonRequest(HttpContext context)
{
// {
// "MessageName":"Update",
// "Target":{"LogicalName":"adx_webpageaccesscontrolrule","Id":"40b062c7-1aea-e011-b5b7-001d60c95b1e"}
// }
// {
// "MessageName":"Associate",
// "Target":{"LogicalName":"adx_webpageaccesscontrolrule","Id":"40b062c7-1aea-e011-b5b7-001d60c95b1e"},
// "Relationship":{"SchemaName":"adx_webpageaccesscontrolrule_webrole","PrimaryEntityRole":"0"},
// "RelatedEntities":[{"LogicalName":"adx_webrole","Id":"bf5420f9-de03-e111-a1a1-00155d03a708"}]
// }
var body = GetRequestBody(context);
if (!string.IsNullOrWhiteSpace(body))
{
var message = body.DeserializeByJson(typeof(OrganizationServiceCachePluginMessage), null) as OrganizationServiceCachePluginMessage;
ThrowOnNull(message, "The plug-in message is unspecified.");
Tracing.FrameworkInformation(GetType().Name, "ProcessRequest", body);
foreach (var serviceCache in GetServiceCaches())
{
serviceCache.Remove(message);
}
}
}
protected virtual IEnumerable<ObjectCache> GetObjectCaches()
{
var section = CrmConfigurationManager.GetCrmSection();
var elements = section.ObjectCache.Cast<ObjectCacheElement>().ToList();
if (!elements.Any())
{
yield return CrmConfigurationManager.CreateObjectCache();
}
else
{
// ignore service cache objects that are nested in a composite service cache
var ignored = (
from element in elements
let inner = element.Parameters["innerObjectCacheName"]
where !string.IsNullOrWhiteSpace(inner)
select inner).ToList();
foreach (var element in elements.Where(e => !ignored.Contains(e.Name)))
{
yield return CrmConfigurationManager.CreateObjectCache(element.Name);
}
}
}
protected virtual IEnumerable<IOrganizationServiceCache> GetServiceCaches()
{
var section = CrmConfigurationManager.GetCrmSection();
var elements = section.ServiceCache.Cast<OrganizationServiceCacheElement>().ToList();
if (!elements.Any())
{
yield return CrmConfigurationManager.CreateServiceCache(null, (string)null, true);
}
else
{
// ignore service cache objects that are nested in a composite service cache
var ignored = (
from element in elements
let inner = element.Parameters["innerServiceCacheName"]
where !string.IsNullOrWhiteSpace(inner)
select inner).ToList();
foreach (var element in elements.Where(e => !ignored.Contains(e.Name)))
{
var connectionId = GetConnectionId(element.Parameters);
yield return CrmConfigurationManager.CreateServiceCache(element.Name, connectionId, true);
}
}
}
private static string GetConnectionId(NameValueCollection config)
{
var contextName = GetContextName(config);
var connectionStringName = CrmConfigurationManager.GetConnectionStringNameFromContext(contextName, true);
var connection = new CrmConnection(connectionStringName);
return connection.GetConnectionId();
}
private static string GetContextName(NameValueCollection config)
{
var contextName = config["contextName"];
if (!string.IsNullOrWhiteSpace(contextName)) return contextName;
var portalName = config["portalName"];
var portalContextElement = PortalCrmConfigurationManager.GetPortalContextElement(portalName, true);
var configName = !string.IsNullOrWhiteSpace(portalContextElement.ContextName)
? portalContextElement.ContextName
: portalContextElement.Name;
return configName;
}
protected static EntityReference GetEntityReference(HttpContext context)
{
var entityName = context.Request["EntityName"];
var id = context.Request["ID"];
ThrowOnNullOrWhiteSpace(entityName, "'EntityName' must be defined as a query string parameter.");
ThrowOnNullOrWhiteSpace(id, "'ID' must be defined as a query string parameter.");
return new EntityReference(entityName, new Guid(id));
}
protected static string GetMessage(HttpContext context)
{
var message = context.Request["Message"];
ThrowOnNullOrWhiteSpace(message, "'Message' must be defined as a query string parameter.");
return message;
}
private static void ThrowOnNull(object obj, string message)
{
if (obj == null) throw new ArgumentException(message);
}
private static void ThrowOnNullOrWhiteSpace(string text, string message)
{
if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException(message);
}
private static string GetRequestBody(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
return reader.ReadToEnd();
}
}
private static OrganizationServiceCachePluginMessage GetPluginMessage(CacheItemCategory category)
{
return new OrganizationServiceCachePluginMessage { Category = category };
}
}
}
| |
namespace CS461_Access_Control
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.tsslStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.tsslReadPause = new System.Windows.Forms.ToolStripStatusLabel();
this.tsslClock = new System.Windows.Forms.ToolStripStatusLabel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tmrTimeout = new System.Windows.Forms.Timer(this.components);
this.tmrClock = new System.Windows.Forms.Timer(this.components);
this.picPhoto = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtName = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.txtID = new System.Windows.Forms.TextBox();
this.btnRead = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.txtTime = new System.Windows.Forms.TextBox();
this.txtCompany = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtLocation = new System.Windows.Forms.TextBox();
this.btnAccessLog = new System.Windows.Forms.Button();
this.label6 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picPhoto)).BeginInit();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslStatus,
this.tsslReadPause,
this.tsslClock});
this.statusStrip1.Location = new System.Drawing.Point(0, 503);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(789, 24);
this.statusStrip1.TabIndex = 0;
this.statusStrip1.Text = "statusStrip1";
//
// tsslStatus
//
this.tsslStatus.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tsslStatus.Name = "tsslStatus";
this.tsslStatus.Size = new System.Drawing.Size(668, 19);
this.tsslStatus.Spring = true;
this.tsslStatus.Text = "Ready...";
this.tsslStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.tsslStatus.Click += new System.EventHandler(this.tsslStatus_Click);
//
// tsslReadPause
//
this.tsslReadPause.BackColor = System.Drawing.Color.Red;
this.tsslReadPause.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tsslReadPause.Name = "tsslReadPause";
this.tsslReadPause.Size = new System.Drawing.Size(57, 19);
this.tsslReadPause.Text = "Pause";
//
// tsslClock
//
this.tsslClock.Name = "tsslClock";
this.tsslClock.Size = new System.Drawing.Size(49, 19);
this.tsslClock.Text = "00:00:00";
this.tsslClock.Click += new System.EventHandler(this.tsslClock_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.settingsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(789, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.settingsToolStripMenuItem.Text = "Settings";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// tmrTimeout
//
this.tmrTimeout.Interval = 5000;
this.tmrTimeout.Tick += new System.EventHandler(this.tmrTimeout_Tick);
//
// tmrClock
//
this.tmrClock.Interval = 30000;
this.tmrClock.Tick += new System.EventHandler(this.tmrClock_Tick);
//
// picPhoto
//
this.picPhoto.Location = new System.Drawing.Point(578, 63);
this.picPhoto.Name = "picPhoto";
this.picPhoto.Size = new System.Drawing.Size(164, 182);
this.picPhoto.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picPhoto.TabIndex = 5;
this.picPhoto.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(25, 122);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(107, 25);
this.label1.TabIndex = 6;
this.label1.Text = "Numero :";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(25, 192);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(74, 25);
this.label2.TabIndex = 7;
this.label2.Text = "Club :";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(25, 254);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(81, 25);
this.label3.TabIndex = 8;
this.label3.Text = "TagID:";
//
// txtName
//
this.txtName.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtName.Location = new System.Drawing.Point(30, 150);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(406, 31);
this.txtName.TabIndex = 9;
//
// txtTitle
//
this.txtTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTitle.Location = new System.Drawing.Point(30, 220);
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(406, 31);
this.txtTitle.TabIndex = 10;
//
// txtID
//
this.txtID.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtID.Location = new System.Drawing.Point(30, 282);
this.txtID.Name = "txtID";
this.txtID.Size = new System.Drawing.Size(406, 31);
this.txtID.TabIndex = 11;
//
// btnRead
//
this.btnRead.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnRead.Location = new System.Drawing.Point(679, 0);
this.btnRead.Name = "btnRead";
this.btnRead.Size = new System.Drawing.Size(110, 24);
this.btnRead.TabIndex = 2;
this.btnRead.Text = "Start";
this.btnRead.UseVisualStyleBackColor = true;
this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(293, 351);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(135, 25);
this.label4.TabIndex = 12;
this.label4.Text = "Access Time";
//
// txtTime
//
this.txtTime.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTime.Location = new System.Drawing.Point(434, 348);
this.txtTime.Name = "txtTime";
this.txtTime.Size = new System.Drawing.Size(265, 31);
this.txtTime.TabIndex = 13;
//
// txtCompany
//
this.txtCompany.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtCompany.Location = new System.Drawing.Point(30, 63);
this.txtCompany.Name = "txtCompany";
this.txtCompany.Size = new System.Drawing.Size(479, 44);
this.txtCompany.TabIndex = 14;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(293, 419);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(94, 25);
this.label5.TabIndex = 15;
this.label5.Text = "Location";
//
// txtLocation
//
this.txtLocation.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtLocation.Location = new System.Drawing.Point(434, 416);
this.txtLocation.Multiline = true;
this.txtLocation.Name = "txtLocation";
this.txtLocation.Size = new System.Drawing.Size(343, 79);
this.txtLocation.TabIndex = 16;
//
// btnAccessLog
//
this.btnAccessLog.Enabled = false;
this.btnAccessLog.Location = new System.Drawing.Point(705, 348);
this.btnAccessLog.Name = "btnAccessLog";
this.btnAccessLog.Size = new System.Drawing.Size(72, 31);
this.btnAccessLog.TabIndex = 17;
this.btnAccessLog.Text = "Access Log";
this.btnAccessLog.UseVisualStyleBackColor = true;
this.btnAccessLog.Click += new System.EventHandler(this.btnAccessLog_Click);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(25, 35);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(107, 25);
this.label6.TabIndex = 18;
this.label6.Text = "Nombre :";
//
// button1
//
this.button1.Location = new System.Drawing.Point(627, 275);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(92, 38);
this.button1.TabIndex = 19;
this.button1.Text = "Registro";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(789, 527);
this.Controls.Add(this.button1);
this.Controls.Add(this.label6);
this.Controls.Add(this.btnAccessLog);
this.Controls.Add(this.txtLocation);
this.Controls.Add(this.label5);
this.Controls.Add(this.txtCompany);
this.Controls.Add(this.txtTime);
this.Controls.Add(this.label4);
this.Controls.Add(this.btnRead);
this.Controls.Add(this.txtID);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.picPhoto);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "CS461 Access Control";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.Resize += new System.EventHandler(this.frmMain_Resize);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picPhoto)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripStatusLabel tsslStatus;
private System.Windows.Forms.ToolStripStatusLabel tsslClock;
private System.Windows.Forms.Timer tmrTimeout;
private System.Windows.Forms.Timer tmrClock;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel tsslReadPause;
private System.Windows.Forms.PictureBox picPhoto;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.TextBox txtTitle;
private System.Windows.Forms.TextBox txtID;
private System.Windows.Forms.Button btnRead;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtTime;
private System.Windows.Forms.TextBox txtCompany;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtLocation;
private System.Windows.Forms.Button btnAccessLog;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button button1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities.DynamicQuery;
using Signum.Entities.MachineLearning;
using Signum.Entities.UserAssets;
using Signum.Utilities;
using Signum.Utilities.Reflection;
namespace Signum.Engine.MachineLearning.TensorFlow
{
public interface ITensorFlowEncoding
{
string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token);
List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column);
object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options);
void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset); //Span<T>
}
public class NoneTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (!ReflectionTools.IsNumber(token.Token.Type) && token.Token.Type.UnNullify() != typeof(bool))
return PredictorMessage._0IsRequiredFor1.NiceToString(DefaultColumnEncodings.OneHot.NiceToString(), token.Token.NiceTypeName);
if (usage == PredictorColumnUsage.Output && (nn.PredictionType == PredictionType.Classification || nn.PredictionType == PredictionType.MultiClassification))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), nn.PredictionType.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
return new List<PredictorCodification> { new PredictorCodification(column) };
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var c = codifications.SingleEx();
inputValues[offset + c.Index] = Convert.ToSingle(value);
}
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var c = codifications.SingleEx();
return ReflectionTools.ChangeType(outputValues[c.Index], column.Token.Type);
}
}
public class OneHotTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (ReflectionTools.IsDecimalNumber(token.Token.Type))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
if (usage == PredictorColumnUsage.Output && (nn.PredictionType == PredictionType.Regression || nn.PredictionType == PredictionType.MultiRegression))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), nn.PredictionType.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
return rc.Values.Cast<object>().NotNull().Distinct().Select(v => new PredictorCodification(column) { IsValue = v }).ToList();
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var dic = GetCodificationDictionary(column, codifications);
if (value != null && dic.TryGetValue(value, out int index))
inputValues[offset + index] = 1;
}
public virtual Dictionary<object, int> GetCodificationDictionary(PredictorColumnBase column, List<PredictorCodification> codifications)
{
if (column.ColumnModel != null)
return (Dictionary<object, int>)column.ColumnModel;
column.ColumnModel = codifications.ToDictionary(a => a.IsValue!, a => a.Index);
return (Dictionary<object, int>)column.ColumnModel;
}
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var cods = options?.FilteredCodifications ?? codifications;
if (options?.AlternativeCount == null)
{
var max = float.MinValue;
PredictorCodification? best = null;
foreach (var c in cods)
{
if (max < outputValues[c.Index])
{
best = c;
max = outputValues[c.Index];
}
}
return best?.IsValue;
}
else
{
//Softmax
var sum = cods.Sum(cod => Math.Exp(outputValues[cod.Index]));
return cods.OrderByDescending(c => outputValues[c.Index]).Take(options.AlternativeCount.Value).Select(c => new AlternativePrediction(
probability: (float)(Math.Exp(outputValues[c.Index]) / sum),
value: c.IsValue
)).ToList();
}
}
}
public abstract class BaseNormalizeTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
if (!ReflectionTools.IsDecimalNumber(token.Token.Type) && !ReflectionTools.IsNumber(token.Token.Type))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
var values = rc.Values.Cast<object>().NotNull().Select(a => Convert.ToSingle(a)).ToList();
return new List<PredictorCodification>
{
new PredictorCodification(column)
{
Average = values.Count == 0 ? 0 : values.Average(),
StdDev = values.Count == 0 ? 1 : values.StdDev(),
Min = values.Count == 0 ? 0 : values.Min(),
Max = values.Count == 0 ? 1 : values.Max(),
}
};
}
public abstract float EncodeSingleValue(object? valueDefault, PredictorCodification c);
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
PredictorCodification c = codifications.SingleEx();
inputValues[offset + c.Index] = EncodeSingleValue(value, c);
}
public abstract object? DecodeSingleValue(float value, PredictorCodification c);
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
PredictorCodification cod = codifications.SingleEx();
float value = outputValues[cod.Index];
return DecodeSingleValue(value, cod);
}
}
public class NormalizeZScoreTFEncoding : BaseNormalizeTFEncoding
{
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
return (Convert.ToSingle(value) - c.Average!.Value) / c.StdDev!.Value;
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = c.Average! + (c.StdDev! * value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
public class NormalizeMinMaxTFEncoding : BaseNormalizeTFEncoding
{
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
return (Convert.ToSingle(value) - c.Min!.Value) / (c.Max!.Value - c.Min!.Value);
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = c.Min!.Value + ((c.Max!.Value - c.Min.Value) * value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
class NormalizeLogTFEncoding : BaseNormalizeTFEncoding
{
public float MinLog = -5;
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
var dValue = Convert.ToDouble(value);
return (dValue <= 0 ? MinLog : Math.Max(MinLog, (float)Math.Log(dValue)));
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = (float)Math.Exp((double)value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
public class SplitWordsTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (token.Token.Type != typeof(string))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
if (usage == PredictorColumnUsage.Output)
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), usage.NiceToString());
return null;
}
public virtual List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
var distinctStrings = rc.Values.Cast<string>().NotNull().Distinct();
var allWords = distinctStrings.SelectMany(str => SplitWords(str)).Distinct(StringComparer.CurrentCultureIgnoreCase).ToList();
return allWords.Select(v => new PredictorCodification(column) { IsValue = v }).ToList();
}
public char[] separators = new[] { '.', ',', ' ', '-', '(', ')', '/', '\\', ';', ':' };
public virtual string[] SplitWords(string str)
{
return str.SplitNoEmpty(separators);
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var words = SplitWords((string)value! ?? "");
var dic = GetCodificationDictionary(column, codifications);
foreach (var w in words)
{
if (dic.TryGetValue(w, out int index))
inputValues[index + offset] = 1;
}
}
public int MaxDecodedWords = 5;
public float MinDecodedWordValue = 0.1f;
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var bestCodifications = codifications
.Where(c => outputValues[c.Index] > MinDecodedWordValue)
.OrderByDescending(a => outputValues[a.Index])
.Take(MaxDecodedWords)
.ToList();
return bestCodifications.ToString(a => a.IsValue!.ToString(), ", ");
}
public virtual Dictionary<string, int> GetCodificationDictionary(PredictorColumnBase column, List<PredictorCodification> codifications)
{
if (column.ColumnModel != null)
return (Dictionary<string, int>)column.ColumnModel;
column.ColumnModel = codifications.ToDictionaryEx(a => (string)a.IsValue!, a => a.Index, StringComparer.CurrentCultureIgnoreCase);
return (Dictionary<string, int>)column.ColumnModel;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Express Route API provides programmatic access to the functionality
/// needed by the customer to set up Dedicated Circuits and Dedicated
/// Circuit Links. The Express Route Customer API is a REST API. All API
/// operations are performed over SSL and mutually authenticated using
/// X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class BorderGatewayProtocolPeeringOperationsExtensions
{
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// Border Gateway Protocol Peering
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginNew(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginNewAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// Border Gateway Protocol Peering
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginNewAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return operations.BeginNewAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service Key representing the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginRemove(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginRemoveAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service Key representing the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginRemoveAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.BeginRemoveAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing bgp peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginUpdate(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginUpdateAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing bgp peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginUpdateAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return operations.BeginUpdateAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Get Border Gateway Protocol Peering operation retrieves the bgp
/// peering for the dedicated circuit with the specified service key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The servicee key representing the dedicated circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static BorderGatewayProtocolPeeringGetResponse Get(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).GetAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Border Gateway Protocol Peering operation retrieves the bgp
/// peering for the dedicated circuit with the specified service key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The servicee key representing the dedicated circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static Task<BorderGatewayProtocolPeeringGetResponse> GetAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.GetAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// border gateway protocol peering associated with the dedicated
/// circuit specified by the service key provided.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Bgp Peering operation.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static BorderGatewayProtocolPeeringGetResponse New(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).NewAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// border gateway protocol peering associated with the dedicated
/// circuit specified by the service key provided.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Bgp Peering operation.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static Task<BorderGatewayProtocolPeeringGetResponse> NewAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return operations.NewAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service key associated with the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static ExpressRouteOperationStatusResponse Remove(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).RemoveAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service key associated with the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<ExpressRouteOperationStatusResponse> RemoveAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.RemoveAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing border gateway protocol peering or creates a new one if
/// one doesn't exist.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static BorderGatewayProtocolPeeringGetResponse Update(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).UpdateAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing border gateway protocol peering or creates a new one if
/// one doesn't exist.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static Task<BorderGatewayProtocolPeeringGetResponse> UpdateAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return operations.UpdateAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
}
}
| |
using System;
using RLToolkit.Logger;
namespace RLToolkit.Widgets
{
/// <summary>
/// Widget that allow the user to add multiple instances of controls as column
/// </summary>
[System.ComponentModel.ToolboxItem(true)]
public partial class DynamicColumn : Gtk.Bin
{
private int numberControls = 1;
private System.Type baseControl;
private object[] baseParam;
private Gtk.Widget[] arrayWidgets;
private int maxControls = 8;
#region signals
/// <summary>
/// Occurs when we add a new control to the Column
/// </summary>
public event EventHandler OnNewControl;
/// <summary>
/// Occurs when we remove a control from the column
/// </summary>
public event EventHandler OnRemControl;
/// <summary>
/// Occurs when the max or min control count has been achieved
/// </summary>
public event EventHandler CapControlReached;
#endregion
#region Constructors
/// <summary>
/// Constructor for a DynamicColumn empty (will use empty Gtk.Label as empty controls).
/// </summary>
public DynamicColumn ()
{
this.Log ().Debug ("Empty Constructor for the DynamicColumn");
this.Build ();
SetControlType (typeof(Gtk.Label), null);
}
/// <summary>
/// Constructor for a DynamicColumn with a supplied control type
/// </summary>
/// <param name="controlType">The Control type to spawn.</param>
public DynamicColumn (System.Type controlType)
{
this.Log ().Debug ("Constructor for the DynamicColumn using " + controlType.Name);
this.Build ();
SetControlType (controlType, null);
}
/// <summary>
/// Constructor for a DynamicColumn with a supplied control type and parameters
/// </summary>
/// <param name="controlType">The Control type to spawn.</param>
/// <param name="param">Parameter (optional).</param>
public DynamicColumn (System.Type controlType, object[] param)
{
this.Log ().Debug ("Constructor for the DynamicColumn using " + controlType.Name + " with params");
this.Build ();
SetControlType (controlType, param);
}
#endregion
#region public methods
/// <summary>
/// Set the type of control to use as child control that will spawn
/// </summary>
/// <param name="controlType">The Control type to spawn.</param>
/// <param name="param">Parameter (optional).</param>
public void SetControlType(System.Type controlType, object[] param)
{
this.Log().Debug("Setting type to: " + controlType.Name);
baseControl = controlType;
baseParam = param;
arrayWidgets = new Gtk.Widget[1];
Gtk.Widget newWidget = CreateCtrl ();
arrayWidgets [0] = newWidget;
RefreshControl ();
}
/// <summary>
/// Fetches the content of the control array.
/// </summary>
/// <returns>The control array.</returns>
public Gtk.Widget[] GetControlArray()
{
this.Log().Debug("Fetching the control array");
return arrayWidgets;
}
/// <summary>
/// Sets the control array.
/// </summary>
/// <param name="newArray">New array that will replace the old one</param>
public void SetControlArray(Gtk.Widget[] newArray)
{
this.Log().Debug("updating the control array");
arrayWidgets = newArray;
RefreshControl();
}
/// <summary>
/// Updates the max count on control the user can add. Note: will cut the current control list is the new maximum is too high.
/// </summary>
/// <param name="newCount">New count.</param>
public void UpdateMaxCount(int newCount)
{
this.Log().Debug("updating the Max count to " + newCount.ToString());
// find if we're over the new count
if (numberControls > newCount)
{
this.Log().Warn(string.Format("There is too many controls ({0}) to keep them all with the new count ({1}).", numberControls, newCount));
numberControls = newCount;
// update the array and max numbers
Gtk.Widget[] newArray = new Gtk.Widget[numberControls];
for (int i = 0; i<numberControls; i++) {
newArray [i] = arrayWidgets [i];
}
arrayWidgets = newArray;
RefreshControl();
}
// update the max
maxControls = newCount;
}
#endregion
#region Helper methods
private Gtk.Widget CreateCtrl()
{
this.Log().Debug("Creating a new control");
if (baseParam == null) {
return (Gtk.Widget)Activator.CreateInstance (baseControl);
} else {
return (Gtk.Widget)Activator.CreateInstance (baseControl, baseParam);
}
}
private void RefreshControl()
{
this.Log ().Debug ("Refreshing the controls");
// wipe everything
foreach (Gtk.Widget ch in columnBox.Children) {
columnBox.Remove (ch);
}
// add the widgets
int i = 0;
foreach (Gtk.Widget w in arrayWidgets) {
columnBox.Spacing = i;
columnBox.Add (w);
i++;
}
// refresh all
columnBox.ShowAll ();
}
#endregion
#region events
/// <summary>
/// Raises the button minus clicked event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
protected void OnBtnMinusClicked (object sender, EventArgs e)
{
this.Log ().Info ("Trying to remove a control");
if (numberControls > 1) {
Gtk.Widget[] newArray = new Gtk.Widget[numberControls-1];
for (int i = 0; i<numberControls-1; i++) {
newArray [i] = arrayWidgets [i];
}
arrayWidgets = newArray;
numberControls--;
if (OnRemControl != null)
{
OnRemControl(this, e);
}
RefreshControl ();
} else {
// i'm sorry dave but i cannot let you do this.
this.Log ().Warn ("Min number of control reached");
if (CapControlReached != null)
{
CapControlReached(this, e);
}
}
}
/// <summary>
/// Raises the button plus clicked event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
protected void OnBtnPlusClicked (object sender, EventArgs e)
{
this.Log ().Info ("Trying to add a control");
if (numberControls < maxControls) {
Gtk.Widget[] newArray = new Gtk.Widget[numberControls + 1];
for (int i = 0; i<numberControls; i++) {
newArray [i] = arrayWidgets [i];
}
numberControls++;
arrayWidgets = newArray;
Gtk.Widget newControl = CreateCtrl();
arrayWidgets [numberControls - 1] = newControl;
if (OnNewControl != null)
{
OnNewControl(this, e);
}
RefreshControl ();
} else {
// i'm sorry dave but i cannot let you do this.
this.Log ().Warn ("Max number of controls reached");
if (CapControlReached != null)
{
CapControlReached(this, e);
}
}
}
#endregion
}
}
| |
namespace Seobiseu {
partial class MainForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.lsvServices = new System.Windows.Forms.ListView();
this.lsvServices_colDisplayName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.mnxServices = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxServicesStart = new System.Windows.Forms.ToolStripMenuItem();
this.mnxServicesRestart = new System.Windows.Forms.ToolStripMenuItem();
this.mnxServicesStop = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.mnxServicesAdd = new System.Windows.Forms.ToolStripMenuItem();
this.mnxServicesRemove = new System.Windows.Forms.ToolStripMenuItem();
this.imlServiceStatus = new System.Windows.Forms.ImageList(this.components);
this.mnu = new System.Windows.Forms.ToolStrip();
this.mnuStart = new System.Windows.Forms.ToolStripButton();
this.mnuStop = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuAdd = new System.Windows.Forms.ToolStripButton();
this.mnuRemove = new System.Windows.Forms.ToolStripButton();
this.mnuApp = new System.Windows.Forms.ToolStripDropDownButton();
this.mnuAppOptions = new System.Windows.Forms.ToolStripMenuItem();
this.mnuApp0 = new System.Windows.Forms.ToolStripSeparator();
this.mnuAppFeedback = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAppAbout = new System.Windows.Forms.ToolStripMenuItem();
this.bwServicesUpdate = new System.ComponentModel.BackgroundWorker();
this.sta = new System.Windows.Forms.StatusStrip();
this.staStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.staServiceName = new System.Windows.Forms.ToolStripStatusLabel();
this.mnxServices.SuspendLayout();
this.mnu.SuspendLayout();
this.sta.SuspendLayout();
this.SuspendLayout();
//
// lsvServices
//
this.lsvServices.AllowDrop = true;
this.lsvServices.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lsvServices.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.lsvServices_colDisplayName});
this.lsvServices.ContextMenuStrip = this.mnxServices;
this.lsvServices.Dock = System.Windows.Forms.DockStyle.Fill;
this.lsvServices.FullRowSelect = true;
this.lsvServices.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.lsvServices.LabelWrap = false;
this.lsvServices.Location = new System.Drawing.Point(0, 27);
this.lsvServices.MultiSelect = false;
this.lsvServices.Name = "lsvServices";
this.lsvServices.Size = new System.Drawing.Size(482, 203);
this.lsvServices.SmallImageList = this.imlServiceStatus;
this.lsvServices.TabIndex = 0;
this.lsvServices.UseCompatibleStateImageBehavior = false;
this.lsvServices.View = System.Windows.Forms.View.Details;
this.lsvServices.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.lsvServices_ItemDrag);
this.lsvServices.SelectedIndexChanged += new System.EventHandler(this.lsvServices_SelectedIndexChanged);
this.lsvServices.DragDrop += new System.Windows.Forms.DragEventHandler(this.lsvServices_DragDrop);
this.lsvServices.DragEnter += new System.Windows.Forms.DragEventHandler(this.lsvServices_DragEnter);
this.lsvServices.MouseUp += new System.Windows.Forms.MouseEventHandler(this.lsvServices_MouseUp);
//
// lsvServices_colDisplayName
//
this.lsvServices_colDisplayName.Text = "Name";
this.lsvServices_colDisplayName.Width = 180;
//
// mnxServices
//
this.mnxServices.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxServices.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxServicesStart,
this.mnxServicesRestart,
this.mnxServicesStop,
this.toolStripMenuItem2,
this.mnxServicesAdd,
this.mnxServicesRemove});
this.mnxServices.Name = "mnxServices";
this.mnxServices.Size = new System.Drawing.Size(180, 140);
this.mnxServices.Opening += new System.ComponentModel.CancelEventHandler(this.mnxServices_Opening);
//
// mnxServicesStart
//
this.mnxServicesStart.Image = ((System.Drawing.Image)(resources.GetObject("mnxServicesStart.Image")));
this.mnxServicesStart.Name = "mnxServicesStart";
this.mnxServicesStart.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.mnxServicesStart.Size = new System.Drawing.Size(179, 26);
this.mnxServicesStart.Tag = "mnuStart";
this.mnxServicesStart.Text = "Start";
this.mnxServicesStart.Click += new System.EventHandler(this.mnxServicesStart_Click);
//
// mnxServicesRestart
//
this.mnxServicesRestart.Image = ((System.Drawing.Image)(resources.GetObject("mnxServicesRestart.Image")));
this.mnxServicesRestart.Name = "mnxServicesRestart";
this.mnxServicesRestart.Size = new System.Drawing.Size(179, 26);
this.mnxServicesRestart.Tag = "mnuRestart";
this.mnxServicesRestart.Text = "Restart";
this.mnxServicesRestart.Click += new System.EventHandler(this.mnxServicesRestart_Click);
//
// mnxServicesStop
//
this.mnxServicesStop.Image = ((System.Drawing.Image)(resources.GetObject("mnxServicesStop.Image")));
this.mnxServicesStop.Name = "mnxServicesStop";
this.mnxServicesStop.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F5)));
this.mnxServicesStop.Size = new System.Drawing.Size(179, 26);
this.mnxServicesStop.Tag = "mnuStop";
this.mnxServicesStop.Text = "Stop";
this.mnxServicesStop.Click += new System.EventHandler(this.mnxServicesStop_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(176, 6);
//
// mnxServicesAdd
//
this.mnxServicesAdd.Image = ((System.Drawing.Image)(resources.GetObject("mnxServicesAdd.Image")));
this.mnxServicesAdd.Name = "mnxServicesAdd";
this.mnxServicesAdd.ShortcutKeys = System.Windows.Forms.Keys.Insert;
this.mnxServicesAdd.Size = new System.Drawing.Size(179, 26);
this.mnxServicesAdd.Tag = "mnuAdd";
this.mnxServicesAdd.Text = "Add";
this.mnxServicesAdd.Click += new System.EventHandler(this.mnxServicesAdd_Click);
//
// mnxServicesRemove
//
this.mnxServicesRemove.Image = ((System.Drawing.Image)(resources.GetObject("mnxServicesRemove.Image")));
this.mnxServicesRemove.Name = "mnxServicesRemove";
this.mnxServicesRemove.ShortcutKeys = System.Windows.Forms.Keys.Delete;
this.mnxServicesRemove.Size = new System.Drawing.Size(179, 26);
this.mnxServicesRemove.Tag = "mnuRemove";
this.mnxServicesRemove.Text = "Remove";
this.mnxServicesRemove.Click += new System.EventHandler(this.mnxServicesRemove_Click);
//
// imlServiceStatus
//
this.imlServiceStatus.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imlServiceStatus.ImageSize = new System.Drawing.Size(16, 16);
this.imlServiceStatus.TransparentColor = System.Drawing.Color.Transparent;
//
// mnu
//
this.mnu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.mnu.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuStart,
this.mnuStop,
this.toolStripSeparator2,
this.mnuAdd,
this.mnuRemove,
this.mnuApp});
this.mnu.Location = new System.Drawing.Point(0, 0);
this.mnu.Name = "mnu";
this.mnu.Padding = new System.Windows.Forms.Padding(1, 0, 1, 0);
this.mnu.Size = new System.Drawing.Size(482, 27);
this.mnu.TabIndex = 1;
//
// mnuStart
//
this.mnuStart.Image = global::Seobiseu.Properties.Resources.mnuStart_16;
this.mnuStart.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuStart.Name = "mnuStart";
this.mnuStart.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.mnuStart.Size = new System.Drawing.Size(64, 24);
this.mnuStart.Text = "Start";
this.mnuStart.ToolTipText = "Start service (F5)";
this.mnuStart.Click += new System.EventHandler(this.mnuStart_Click);
//
// mnuStop
//
this.mnuStop.Image = global::Seobiseu.Properties.Resources.mnuStop_16;
this.mnuStop.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuStop.Name = "mnuStop";
this.mnuStop.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.mnuStop.Size = new System.Drawing.Size(64, 24);
this.mnuStop.Text = "Stop";
this.mnuStop.ToolTipText = "Stop service (Shift+F5)";
this.mnuStop.Click += new System.EventHandler(this.mnuStop_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 27);
//
// mnuAdd
//
this.mnuAdd.Image = global::Seobiseu.Properties.Resources.mnuAdd_16;
this.mnuAdd.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuAdd.Name = "mnuAdd";
this.mnuAdd.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.mnuAdd.Size = new System.Drawing.Size(61, 24);
this.mnuAdd.Text = "Add";
this.mnuAdd.ToolTipText = "Add service (Insert)";
this.mnuAdd.Click += new System.EventHandler(this.mnuAdd_Click);
//
// mnuRemove
//
this.mnuRemove.Image = global::Seobiseu.Properties.Resources.mnuRemove_16;
this.mnuRemove.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuRemove.Name = "mnuRemove";
this.mnuRemove.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.mnuRemove.Size = new System.Drawing.Size(87, 24);
this.mnuRemove.Text = "Remove";
this.mnuRemove.ToolTipText = "Remove service (Delete)";
this.mnuRemove.Click += new System.EventHandler(this.mnuRemove_Click);
//
// mnuApp
//
this.mnuApp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.mnuApp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuApp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuAppOptions,
this.mnuApp0,
this.mnuAppFeedback,
this.mnuAppAbout});
this.mnuApp.Image = global::Seobiseu.Properties.Resources.mnuApp_16;
this.mnuApp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuApp.Name = "mnuApp";
this.mnuApp.Size = new System.Drawing.Size(34, 24);
this.mnuApp.Text = "Application";
//
// mnuAppOptions
//
this.mnuAppOptions.Name = "mnuAppOptions";
this.mnuAppOptions.Size = new System.Drawing.Size(182, 26);
this.mnuAppOptions.Text = "&Options";
this.mnuAppOptions.Click += new System.EventHandler(this.mnuAppOptions_Click);
//
// mnuApp0
//
this.mnuApp0.Name = "mnuApp0";
this.mnuApp0.Size = new System.Drawing.Size(179, 6);
//
// mnuAppFeedback
//
this.mnuAppFeedback.Name = "mnuAppFeedback";
this.mnuAppFeedback.Size = new System.Drawing.Size(182, 26);
this.mnuAppFeedback.Text = "Send &feedback";
this.mnuAppFeedback.Click += new System.EventHandler(this.mnuAppFeedback_Click);
//
// mnuAppAbout
//
this.mnuAppAbout.Name = "mnuAppAbout";
this.mnuAppAbout.Size = new System.Drawing.Size(182, 26);
this.mnuAppAbout.Text = "&About";
this.mnuAppAbout.Click += new System.EventHandler(this.mnuAppAbout_Click);
//
// bwServicesUpdate
//
this.bwServicesUpdate.WorkerReportsProgress = true;
this.bwServicesUpdate.WorkerSupportsCancellation = true;
this.bwServicesUpdate.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwServicesUpdate_DoWork);
this.bwServicesUpdate.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bwServicesUpdate_ProgressChanged);
//
// sta
//
this.sta.ImageScalingSize = new System.Drawing.Size(20, 20);
this.sta.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.staStatus,
this.staServiceName});
this.sta.Location = new System.Drawing.Point(0, 230);
this.sta.Name = "sta";
this.sta.Size = new System.Drawing.Size(482, 25);
this.sta.TabIndex = 2;
this.sta.Text = "statusStrip1";
//
// staStatus
//
this.staStatus.Name = "staStatus";
this.staStatus.Size = new System.Drawing.Size(454, 20);
this.staStatus.Spring = true;
this.staStatus.Text = " ";
this.staStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// staServiceName
//
this.staServiceName.Name = "staServiceName";
this.staServiceName.Size = new System.Drawing.Size(13, 20);
this.staServiceName.Text = " ";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(482, 255);
this.Controls.Add(this.lsvServices);
this.Controls.Add(this.sta);
this.Controls.Add(this.mnu);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MinimumSize = new System.Drawing.Size(320, 200);
this.Name = "MainForm";
this.Text = "Seobiseu";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
this.Load += new System.EventHandler(this.Form_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
this.Resize += new System.EventHandler(this.Form_Resize);
this.mnxServices.ResumeLayout(false);
this.mnu.ResumeLayout(false);
this.mnu.PerformLayout();
this.sta.ResumeLayout(false);
this.sta.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView lsvServices;
private System.Windows.Forms.ColumnHeader lsvServices_colDisplayName;
private System.Windows.Forms.ToolStrip mnu;
private System.Windows.Forms.ToolStripButton mnuStart;
private System.Windows.Forms.ToolStripButton mnuStop;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton mnuAdd;
private System.Windows.Forms.ToolStripButton mnuRemove;
private System.Windows.Forms.ImageList imlServiceStatus;
private System.Windows.Forms.ContextMenuStrip mnxServices;
private System.Windows.Forms.ToolStripMenuItem mnxServicesStart;
private System.Windows.Forms.ToolStripMenuItem mnxServicesStop;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem mnxServicesAdd;
private System.Windows.Forms.ToolStripMenuItem mnxServicesRemove;
private System.ComponentModel.BackgroundWorker bwServicesUpdate;
private System.Windows.Forms.StatusStrip sta;
private System.Windows.Forms.ToolStripStatusLabel staStatus;
private System.Windows.Forms.ToolStripStatusLabel staServiceName;
private System.Windows.Forms.ToolStripMenuItem mnxServicesRestart;
private System.Windows.Forms.ToolStripDropDownButton mnuApp;
private System.Windows.Forms.ToolStripMenuItem mnuAppOptions;
private System.Windows.Forms.ToolStripSeparator mnuApp0;
private System.Windows.Forms.ToolStripMenuItem mnuAppFeedback;
private System.Windows.Forms.ToolStripMenuItem mnuAppAbout;
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using NUnit.Core.Extensibility;
namespace NUnit.Core
{
/// <summary>
/// CoreExtensions is a singleton class that groups together all
/// the extension points that are supported in the test domain.
/// It also provides access to the test builders and decorators
/// by other parts of the NUnit core.
/// </summary>
public class CoreExtensions : ExtensionHost, IService
{
#region Instance Fields
private IAddinRegistry addinRegistry;
private bool initialized;
private SuiteBuilderCollection suiteBuilders;
private TestCaseBuilderCollection testBuilders;
private TestDecoratorCollection testDecorators;
private EventListenerCollection listeners;
#endregion
#region CoreExtensions Singleton
private static CoreExtensions host;
public static CoreExtensions Host
{
get
{
if (host == null)
{
host = new CoreExtensions();
// host.InitializeService();
}
return host;
}
}
#endregion
#region Constructors
public CoreExtensions()
{
this.suiteBuilders = new SuiteBuilderCollection();
this.testBuilders = new TestCaseBuilderCollection();
this.testDecorators = new TestDecoratorCollection();
this.listeners = new EventListenerCollection();
this.extensions = new IExtensionPoint[]
{ suiteBuilders, testBuilders, testDecorators };
this.supportedTypes = ExtensionType.Core;
}
#endregion
#region
public bool Initialized
{
get { return initialized; }
}
/// <summary>
/// Our AddinRegistry may be set from outside or passed into the domain
/// </summary>
public IAddinRegistry AddinRegistry
{
get
{
if ( addinRegistry == null )
addinRegistry = AppDomain.CurrentDomain.GetData( "AddinRegistry" ) as IAddinRegistry;
return addinRegistry;
}
set { addinRegistry = value; }
}
public ISuiteBuilder SuiteBuilders
{
get { return suiteBuilders; }
}
public TestCaseBuilderCollection TestBuilders
{
get { return testBuilders; }
}
public ITestDecorator TestDecorators
{
get { return testDecorators; }
}
public FrameworkRegistry TestFrameworks
{
get { return frameworks; }
}
#endregion
#region Public Methods
public void InstallBuiltins()
{
//Trace.WriteLine( "Installing Builtins" );
// Define NUnit Framework
FrameworkRegistry.Register( "NUnit", "nunit.framework" );
// Install builtin SuiteBuilders - Note that the
// NUnitTestCaseBuilder is installed whenever
// an NUnitTestFixture is being populated and
// removed afterward.
Install( new Builders.NUnitTestFixtureBuilder() );
Install( new Builders.SetUpFixtureBuilder() );
}
public void InstallAddins()
{
//Trace.WriteLine( "Installing Addins" );
if( AddinRegistry != null )
{
foreach (Addin addin in AddinRegistry.Addins)
{
if ( (this.ExtensionTypes & addin.ExtensionType) != 0 )
{
try
{
Type type = Type.GetType(addin.TypeName);
if ( type == null )
AddinRegistry.SetStatus( addin.Name, AddinStatus.Error, "Could not locate type" );
else if ( !InstallAddin( type ) )
AddinRegistry.SetStatus( addin.Name, AddinStatus.Error, "Install returned false" );
else
AddinRegistry.SetStatus( addin.Name, AddinStatus.Loaded, null );
}
catch( Exception ex )
{
AddinRegistry.SetStatus( addin.Name, AddinStatus.Error, ex.Message );
}
}
}
}
}
public void InstallAdhocExtensions( Assembly assembly )
{
foreach ( Type type in assembly.GetExportedTypes() )
{
if ( type.GetCustomAttributes(typeof(NUnitAddinAttribute), false).Length == 1 )
InstallAddin( type );
}
}
#endregion
#region Helper Methods
private bool InstallAddin( Type type )
{
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
object obj = ctor.Invoke( new object[0] );
IAddin theAddin = (IAddin)obj;
return theAddin.Install(this);
}
#endregion
#region Type Safe Install Helpers
internal void Install( ISuiteBuilder builder )
{
suiteBuilders.Install( builder );
}
internal void Install( ITestCaseBuilder builder )
{
testBuilders.Install( builder );
}
internal void Install( ITestDecorator decorator )
{
testDecorators.Install( decorator );
}
internal void Install( EventListener listener )
{
listeners.Install( listener );
}
#endregion
#region IService Members
public void UnloadService()
{
// TODO: Add CoreExtensions.UnloadService implementation
}
public void InitializeService()
{
InstallBuiltins();
InstallAddins();
initialized = true;
}
#endregion
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Language.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Language.V1.Snippets
{
public class GeneratedLanguageServiceClientSnippets
{
public async Task AnalyzeSentimentAsync()
{
// Snippet: AnalyzeSentimentAsync(Document,CallSettings)
// Additional: AnalyzeSentimentAsync(Document,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document);
// End snippet
}
public void AnalyzeSentiment()
{
// Snippet: AnalyzeSentiment(Document,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document);
// End snippet
}
public async Task AnalyzeSentimentAsync_RequestObject()
{
// Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);
// End snippet
}
public void AnalyzeSentiment_RequestObject()
{
// Snippet: AnalyzeSentiment(AnalyzeSentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
// End snippet
}
public async Task AnalyzeEntitiesAsync()
{
// Snippet: AnalyzeEntitiesAsync(Document,EncodingType,CallSettings)
// Additional: AnalyzeEntitiesAsync(Document,EncodingType,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document, encodingType);
// End snippet
}
public void AnalyzeEntities()
{
// Snippet: AnalyzeEntities(Document,EncodingType,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document, encodingType);
// End snippet
}
public async Task AnalyzeEntitiesAsync_RequestObject()
{
// Snippet: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(request);
// End snippet
}
public void AnalyzeEntities_RequestObject()
{
// Snippet: AnalyzeEntities(AnalyzeEntitiesRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(request);
// End snippet
}
public async Task AnalyzeEntitySentimentAsync()
{
// Snippet: AnalyzeEntitySentimentAsync(Document,EncodingType,CallSettings)
// Additional: AnalyzeEntitySentimentAsync(Document,EncodingType,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document, encodingType);
// End snippet
}
public void AnalyzeEntitySentiment()
{
// Snippet: AnalyzeEntitySentiment(Document,EncodingType,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document, encodingType);
// End snippet
}
public async Task AnalyzeEntitySentimentAsync_RequestObject()
{
// Snippet: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(request);
// End snippet
}
public void AnalyzeEntitySentiment_RequestObject()
{
// Snippet: AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(request);
// End snippet
}
public async Task AnalyzeSyntaxAsync()
{
// Snippet: AnalyzeSyntaxAsync(Document,EncodingType,CallSettings)
// Additional: AnalyzeSyntaxAsync(Document,EncodingType,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document, encodingType);
// End snippet
}
public void AnalyzeSyntax()
{
// Snippet: AnalyzeSyntax(Document,EncodingType,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document, encodingType);
// End snippet
}
public async Task AnalyzeSyntaxAsync_RequestObject()
{
// Snippet: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(request);
// End snippet
}
public void AnalyzeSyntax_RequestObject()
{
// Snippet: AnalyzeSyntax(AnalyzeSyntaxRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
EncodingType = EncodingType.None,
};
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(request);
// End snippet
}
public async Task AnnotateTextAsync()
{
// Snippet: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType,CallSettings)
// Additional: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features, encodingType);
// End snippet
}
public void AnnotateText()
{
// Snippet: AnnotateText(Document,AnnotateTextRequest.Types.Features,EncodingType,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features, encodingType);
// End snippet
}
public async Task AnnotateTextAsync_RequestObject()
{
// Snippet: AnnotateTextAsync(AnnotateTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
EncodingType = EncodingType.None,
};
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(request);
// End snippet
}
public void AnnotateText_RequestObject()
{
// Snippet: AnnotateText(AnnotateTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
EncodingType = EncodingType.None,
};
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(request);
// End snippet
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Compute
{
/// <summary>
/// Operations for managing the virtual machine images in compute
/// management.
/// </summary>
internal partial class VirtualMachineImageOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineImageOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineImageOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualMachineImageOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a virtual machine image.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The get vm image operation response.
/// </returns>
public async Task<VirtualMachineImageGetResponse> GetAsync(VirtualMachineImageGetParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters != null)
{
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Offer == null)
{
throw new ArgumentNullException("parameters.Offer");
}
if (parameters.PublisherName == null)
{
throw new ArgumentNullException("parameters.PublisherName");
}
if (parameters.Skus == null)
{
throw new ArgumentNullException("parameters.Skus");
}
if (parameters.Version == null)
{
throw new ArgumentNullException("parameters.Version");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/locations/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Location);
}
url = url + "/publishers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.PublisherName);
}
url = url + "/artifacttypes/vmimage/offers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Offer);
}
url = url + "/skus/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Skus);
}
url = url + "/versions/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Version);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineImageGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineImageGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
VirtualMachineImage virtualMachineImageInstance = new VirtualMachineImage();
result.VirtualMachineImage = virtualMachineImageInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken planValue = propertiesValue["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
PurchasePlan planInstance = new PurchasePlan();
virtualMachineImageInstance.PurchasePlan = planInstance;
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
}
JToken osDiskImageValue = propertiesValue["osDiskImage"];
if (osDiskImageValue != null && osDiskImageValue.Type != JTokenType.Null)
{
OSDiskImage osDiskImageInstance = new OSDiskImage();
virtualMachineImageInstance.OSDiskImage = osDiskImageInstance;
JToken operatingSystemValue = osDiskImageValue["operatingSystem"];
if (operatingSystemValue != null && operatingSystemValue.Type != JTokenType.Null)
{
string operatingSystemInstance = ((string)operatingSystemValue);
osDiskImageInstance.OperatingSystem = operatingSystemInstance;
}
}
JToken dataDiskImagesArray = propertiesValue["dataDiskImages"];
if (dataDiskImagesArray != null && dataDiskImagesArray.Type != JTokenType.Null)
{
foreach (JToken dataDiskImagesValue in ((JArray)dataDiskImagesArray))
{
DataDiskImage dataDiskImageInstance = new DataDiskImage();
virtualMachineImageInstance.DataDiskImages.Add(dataDiskImageInstance);
JToken lunValue = dataDiskImagesValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskImageInstance.Lun = lunInstance;
}
}
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineImageInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
virtualMachineImageInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineImageInstance.Location = locationInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of virtual machine images.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A list of virtual machine image resource information.
/// </returns>
public async Task<VirtualMachineImageResourceList> ListAsync(VirtualMachineImageListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters != null)
{
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Offer == null)
{
throw new ArgumentNullException("parameters.Offer");
}
if (parameters.PublisherName == null)
{
throw new ArgumentNullException("parameters.PublisherName");
}
if (parameters.Skus == null)
{
throw new ArgumentNullException("parameters.Skus");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/locations/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Location);
}
url = url + "/publishers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.PublisherName);
}
url = url + "/artifacttypes/vmimage/offers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Offer);
}
url = url + "/skus/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Skus);
}
url = url + "/versions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (parameters != null && parameters.FilterExpression != null)
{
queryParameters.Add(parameters.FilterExpression);
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineImageResourceList result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineImageResourceList();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken resourcesArray = responseDoc;
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineImageResource virtualMachineImageResourceInstance = new VirtualMachineImageResource();
result.Resources.Add(virtualMachineImageResourceInstance);
JToken idValue = resourcesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineImageResourceInstance.Id = idInstance;
}
JToken nameValue = resourcesValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineImageResourceInstance.Name = nameInstance;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineImageResourceInstance.Location = locationInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of virtual machine image offers.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A list of virtual machine image resource information.
/// </returns>
public async Task<VirtualMachineImageResourceList> ListOffersAsync(VirtualMachineImageListOffersParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters != null)
{
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.PublisherName == null)
{
throw new ArgumentNullException("parameters.PublisherName");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListOffersAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/locations/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Location);
}
url = url + "/publishers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.PublisherName);
}
url = url + "/artifacttypes/vmimage/offers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineImageResourceList result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineImageResourceList();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken resourcesArray = responseDoc;
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineImageResource virtualMachineImageResourceInstance = new VirtualMachineImageResource();
result.Resources.Add(virtualMachineImageResourceInstance);
JToken idValue = resourcesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineImageResourceInstance.Id = idInstance;
}
JToken nameValue = resourcesValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineImageResourceInstance.Name = nameInstance;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineImageResourceInstance.Location = locationInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of virtual machine image publishers.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A list of virtual machine image resource information.
/// </returns>
public async Task<VirtualMachineImageResourceList> ListPublishersAsync(VirtualMachineImageListPublishersParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters != null)
{
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListPublishersAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/locations/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Location);
}
url = url + "/publishers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineImageResourceList result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineImageResourceList();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken resourcesArray = responseDoc;
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineImageResource virtualMachineImageResourceInstance = new VirtualMachineImageResource();
result.Resources.Add(virtualMachineImageResourceInstance);
JToken idValue = resourcesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineImageResourceInstance.Id = idInstance;
}
JToken nameValue = resourcesValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineImageResourceInstance.Name = nameInstance;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineImageResourceInstance.Location = locationInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of virtual machine image skus.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A list of virtual machine image resource information.
/// </returns>
public async Task<VirtualMachineImageResourceList> ListSkusAsync(VirtualMachineImageListSkusParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters != null)
{
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Offer == null)
{
throw new ArgumentNullException("parameters.Offer");
}
if (parameters.PublisherName == null)
{
throw new ArgumentNullException("parameters.PublisherName");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListSkusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/locations/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Location);
}
url = url + "/publishers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.PublisherName);
}
url = url + "/artifacttypes/vmimage/offers/";
if (parameters != null)
{
url = url + Uri.EscapeDataString(parameters.Offer);
}
url = url + "/skus";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineImageResourceList result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineImageResourceList();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken resourcesArray = responseDoc;
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineImageResource virtualMachineImageResourceInstance = new VirtualMachineImageResource();
result.Resources.Add(virtualMachineImageResourceInstance);
JToken idValue = resourcesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
virtualMachineImageResourceInstance.Id = idInstance;
}
JToken nameValue = resourcesValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineImageResourceInstance.Name = nameInstance;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineImageResourceInstance.Location = locationInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
namespace MiniUML.Model.ViewModels.Document
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using MiniUML.Framework;
using MiniUML.Framework.Command;
using MiniUML.Model.Events;
using MiniUML.Model.Model;
using MiniUML.Model.ViewModels.RubberBand;
using MiniUML.Model.ViewModels.Shapes;
using MiniUML.View.Views.RubberBand;
using MsgBox;
using MiniUML.Model.ViewModels.Interfaces;
public class CanvasViewModel : BaseViewModel, IShapeParent
{
#region fields
private bool _IsFocused;
private SelectedItems _SelectedItem;
private RelayCommand<object> _SelectCommand = null;
private RelayCommand<object> _DeleteCommand = null;
private RelayCommand<object> _CutCommand = null;
private RelayCommand<object> _CopyCommand = null;
private RelayCommand<object> _PasteCommand = null;
private ICanvasViewMouseHandler _ICanvasViewMouseHandler = null;
private RubberBandViewModel _RubberBand = null;
private readonly IMessageBoxService _MsgBox;
#endregion fields
#region constructor
/// <summary>
/// Class constructor
/// </summary>
/// <param name="documentViewModel"></param>
public CanvasViewModel(DocumentViewModel documentViewModel, IMessageBoxService msgBox)
: this()
{
_MsgBox = msgBox;
// Store a reference to the parent view model
// (necessary to implement begin and end operation around undo).
DocumentViewModel = documentViewModel;
_SelectedItem = new SelectedItems();
_IsFocused = false;
}
/// <summary>
/// Hidden parameterless constructor
/// </summary>
protected CanvasViewModel()
{
}
#endregion constructor
#region properties
/// <summary>
/// This property can be bound to a focus behaviour in a view
/// to transfer focus when the viewmodel deems this to be appropriate.
/// </summary>
public bool IsFocused
{
get
{
return _IsFocused;
}
set
{
if (_IsFocused != value)
{
_IsFocused = value;
NotifyPropertyChanged(() => this.IsFocused);
}
}
}
/// <summary>
/// Property to expose selected items collection.
/// </summary>
public SelectedItems SelectedItem
{
get
{
return _SelectedItem;
}
}
/// <summary>
/// Viewmodel to the document represented by this canvas.
/// </summary>
public DocumentViewModel DocumentViewModel { get; }
/// <summary>
/// Get canvas view model mouse handler which is used to draw
/// connections between items - using a class that is defined
/// outside of the actual canvas viewmodel class.
/// </summary>
public ICanvasViewMouseHandler CanvasViewMouseHandler
{
get
{
return _ICanvasViewMouseHandler;
}
private set
{
if (_ICanvasViewMouseHandler != value)
{
_ICanvasViewMouseHandler = value;
}
}
}
public RubberBandViewModel RubberBand
{
get
{
if (_RubberBand == null)
_RubberBand = new RubberBandViewModel();
return _RubberBand;
}
}
#region Commands
/// <summary>
/// Get a command that can be used to active the mouse select shape mode.
/// </summary>
public RelayCommand<object> SelectCommand
{
get
{
if (_SelectCommand == null)
_SelectCommand = new RelayCommand<object>(
(p) => this.OnSelectMode_Execute(),
(p) => this.OnSelectMode_CanExecute());
return _SelectCommand;
}
}
/// <summary>
/// Get a command that can be used to Delete a currently selected shape mode.
/// </summary>
public RelayCommand<object> DeleteCommand
{
get
{
if (_DeleteCommand == null)
_DeleteCommand = new RelayCommand<object>(
(p) => this.OnDeleteCommand_Executed(),
(p) => this.OnDeleteCutCopyCommand_CanExecute());
return _DeleteCommand;
}
}
/// <summary>
/// Get a command that can be used to Cut a currently selected shape into the windows clipboard.
/// </summary>
public RelayCommand<object> CutCommand
{
get
{
if (_CutCommand == null)
_CutCommand = new RelayCommand<object>(
(p) => this.OnCutCommand_Executed(),
(p) => this.OnDeleteCutCopyCommand_CanExecute());
return _CutCommand;
}
}
/// <summary>
/// Get a command that can be used to Copy a currently selected shape from the windows clipboard.
/// </summary>
public RelayCommand<object> CopyCommand
{
get
{
if (_CopyCommand == null)
_CopyCommand = new RelayCommand<object>(
(p) => this.OnCopyCommand_Executed(),
(p) => this.OnDeleteCutCopyCommand_CanExecute());
return _CopyCommand;
}
}
/// <summary>
/// Get a command that can be used to Paste a shape from the windows clipboard
/// into the collection of currently selected shapes on to the canvas.
/// </summary>
public RelayCommand<object> PasteCommand
{
get
{
if (_PasteCommand == null)
_PasteCommand = new RelayCommand<object>(
(p) => this.OnPasteCommand_Executed(),
(p) => this.OnPasteCommand_CanExecute());
return _PasteCommand;
}
}
#endregion
#endregion properties
#region methods
#region IShapeParent methods
/// <summary>
/// Removes the corresponding shape from the
/// collection of shapes displayed on the canvas.
/// </summary>
/// <param name="obj"></param>
void IShapeParent.Remove(ShapeViewModelBase shape)
{
this.DocumentViewModel.dm_DocumentDataModel.Remove(shape);
}
/// <summary>
/// Brings the shape into front of the canvas view
/// (moves shape on top of virtual Z-axis)
/// </summary>
/// <param name="obj"></param>
void IShapeParent.BringToFront(ShapeViewModelBase shape)
{
this.DocumentViewModel.dm_DocumentDataModel.BringToFront(shape);
}
/// <summary>
/// Brings the shape into the back of the canvas view
/// (moves shape to the bottom of virtual Z-axis)
/// </summary>
/// <param name="obj"></param>
void IShapeParent.SendToBack(ShapeViewModelBase shape)
{
this.DocumentViewModel.dm_DocumentDataModel.SendToBack(shape);
}
/// <summary>
/// The resize shape function resizes all currently selected
/// shapes in accordance to the delta contained in the supplied
/// <paramref name="e"/> parameter.
///
/// Method is based on resize method in
/// http://www.codeproject.com/Articles/23871/WPF-Diagram-Designer-Part-3
/// </summary>
/// <param name="e"></param>
void IShapeParent.ResizeSelectedShapes(DragDeltaThumbEvent e)
{
if (SelectedItem.Shapes.Count == 0)
return;
double minLeft = double.MaxValue;
double minTop = double.MaxValue;
double minDeltaHorizontal = double.MaxValue;
double minDeltaVertical = double.MaxValue;
double dragDeltaVertical, dragDeltaHorizontal;
// filter for those items that contain a height property and
// find the min of their min (Height, Width) properties
foreach (var item in this.SelectedItem.Shapes)
{
ShapeSizeViewModelBase shape = item as ShapeSizeViewModelBase;
if (shape == null) // filter for those items that have a height or width
continue;
minLeft = Math.Min(shape.Left, minLeft);
minTop = Math.Min(shape.Top, minTop);
minDeltaVertical = Math.Min(minDeltaVertical, shape.Height - shape.MinHeight);
minDeltaHorizontal = Math.Min(minDeltaHorizontal, shape.Width - shape.MinWidth);
}
// Resize currently selected items with regard to min height and width determined before
foreach (var item in this.SelectedItem.Shapes)
{
ShapeSizeViewModelBase shape = item as ShapeSizeViewModelBase;
if (shape == null) // filter for those items that have a height or width
continue;
switch (e.VerticalAlignment)
{
// Changing an element at its bottom changes the its height only
case VerticalAlignment.Bottom:
dragDeltaVertical = Math.Min(-e.VerticalChange, minDeltaVertical);
shape.Height = shape.Height - dragDeltaVertical;
break;
// Changing an element at its top changes the Y position and the height
case VerticalAlignment.Top:
dragDeltaVertical = Math.Min(Math.Max(-minTop, e.VerticalChange), minDeltaVertical);
shape.Top = shape.Top + dragDeltaVertical;
shape.Height = shape.Height - dragDeltaVertical;
break;
}
switch (e.HorizontalAlignment)
{
// Changing an element at its left side changes the x position and its width
case HorizontalAlignment.Left:
dragDeltaHorizontal = Math.Min(Math.Max(-minLeft, e.HorizontalChange), minDeltaHorizontal);
shape.Left = shape.Left + dragDeltaHorizontal;
shape.Width = shape.Width - dragDeltaHorizontal;
break;
// Changing an element at its right side changes the its width only
case HorizontalAlignment.Right:
dragDeltaHorizontal = Math.Min(-e.HorizontalChange, minDeltaHorizontal);
shape.Width = shape.Width - dragDeltaHorizontal;
break;
}
}
}
/// <summary>
/// Align all selected shapes (if any) to a given shape <paramref name="shape"/>.
/// The actual alignment operation performed is defined by the <paramref name="alignmentOption"/> parameter.
/// </summary>
/// <param name="shape"></param>
/// <param name="alignmentOption"></param>
void IShapeParent.AlignShapes(ShapeSizeViewModelBase shape, AlignShapes alignmentOption)
{
if (shape == null)
return;
double YShapeCenter = shape.Top + (shape.Height / 2);
double XShapeCenter = shape.Left + (shape.Width / 2);
double shapeRight = shape.Position.X + shape.Width;
foreach (var item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>())
{
if (shape == item) // Adjust shape to itself is a superflous operation
continue;
switch (alignmentOption)
{
case AlignShapes.Bottom:
item.MoveEndPosition(new Point(item.EndPosition.X, shape.EndPosition.Y));
break;
case AlignShapes.CenteredHorizontal:
item.MovePosition(new Point(item.Position.X, YShapeCenter - (item.Height / 2)));
break;
case AlignShapes.CenteredVertical:
item.MovePosition(new Point(XShapeCenter - (item.Width / 2), item.Position.Y));
break;
case AlignShapes.Left:
item.MovePosition(new Point(shape.Position.X, item.Position.Y));
break;
case AlignShapes.Right:
item.MovePosition(new Point(shapeRight - item.Width, item.Position.Y));
break;
case AlignShapes.Top:
item.MovePosition(new Point(item.Position.X, shape.Top));
break;
default:
throw new NotImplementedException(alignmentOption.ToString());
}
}
}
/// <summary>
/// Adjusts width, height, or both, of all selected shapes (if any)
/// such that they are sized equally to the given <paramref name="shape"/>.
/// </summary>
/// <param name="shape"></param>
/// <param name="option"></param>
void IShapeParent.AdjustShapesToSameSize(ShapeSizeViewModelBase shape, SameSize option)
{
switch (option)
{
case SameSize.SameWidth:
this.SameWidth(shape);
break;
case SameSize.SameHeight:
this.SameHeight(shape);
break;
case SameSize.SameWidthandHeight:
this.SameWidthandHeight(shape);
break;
default:
throw new NotImplementedException(option.ToString());
}
}
/// <summary>
/// Destribute all selected shapes (if any) over X or Y space evenly.
/// </summary>
/// <param name="shape"></param>
/// <param name="distribOption"></param>
void IShapeParent.DistributeShapes(Destribute distribOption)
{
switch (distribOption)
{
case Destribute.Horizontally:
this.DistributeHorizontal();
break;
case Destribute.Vertically:
this.DistributeVertical();
break;
default:
throw new NotImplementedException(distribOption.ToString());
}
}
#endregion IShapeParent methods
/// <summary>
/// Add a new shape in the data model to make it visible on the canvas.
/// </summary>
/// <param name="element"></param>
public void AddShape(ShapeViewModelBase element)
{
this.DocumentViewModel.dm_DocumentDataModel.AddShape(element);
}
#region Mouse handling (ICanvasViewMouseHandler)
/// <summary>
/// Method is executed when the canvas switches into the 'draw association'
/// mode when the user clicks a draw 'connection' button. The method is called
/// directly by the corresponding CommandModel that creates an association like shape.
///
/// The mouse handler supplied in <paramref name="value"/> is installed by this method
/// which includes cancelling a previously installed mouse handler (if any) and beginning
/// a new undo operation.
/// </summary>
/// <param name="value"></param>
public void BeginCanvasViewMouseHandler(ICanvasViewMouseHandler value)
{
if (this.CanvasViewMouseHandler == value) // no change
return;
if (this.CanvasViewMouseHandler != null)
this.CancelCanvasViewMouseHandler();
this.CanvasViewMouseHandler = value;
if (this.CanvasViewMouseHandler != null)
DocumentViewModel.dm_DocumentDataModel.BeginOperation("CanvasViewMouseHandler session");
}
/// <summary>
/// This method is called when the association drawing mode is cancelled
/// (either via explicit command [click on Select Mode button] or
/// because the source or target may be in-appropriate).
/// </summary>
public void CancelCanvasViewMouseHandler()
{
var handler = this.CanvasViewMouseHandler;
this.CanvasViewMouseHandler = null;
try
{
handler.OnCancelMouseHandler();
CreateRubberBandMouseHandler rbh = handler as CreateRubberBandMouseHandler;
// Make sure event completion handler is detached when mouse command handler is finished
//// if (rbh != null)
//// rbh.RubberBandSelection -= this.handle_RubberBandSelection;
}
finally
{
DocumentViewModel.dm_DocumentDataModel.EndOperation("CanvasViewMouseHandler session");
}
}
public void Handle_RubberBandSelection(RubberBandSelectionEventArgs e)
{
if (e != null)
{
if (e.Select == MouseSelection.CancelSelection)
return;
// Clear existing selection since multiselection with addition is not what we want
if (e.Select == MouseSelection.ReducedToNewSelection)
this.SelectedItem.Clear();
Rect rubberBand = new Rect(e.StartPoint, e.EndPoint);
foreach (var item in this.DocumentViewModel.dm_DocumentDataModel.DocRoot.OfType<ShapeSizeViewModelBase>())
{
Rect itemBounds = new Rect(item.Position, item.EndPosition);
bool contains = rubberBand.Contains(itemBounds);
if (contains == true)
{
this.SelectedItem.Add(item);
}
}
}
}
/// <summary>
/// This method is called when the draw association mode ends
/// successfully with a new connection drawn on the canvas.
/// </summary>
public void FinishCanvasViewMouseHandler()
{
this.CanvasViewMouseHandler = null;
DocumentViewModel.dm_DocumentDataModel.EndOperation("CanvasViewMouseHandler session");
}
/// <summary>
/// Destroy the current rubberband viewmodel to make way
/// for a new rubber band selection based on a new viewmodel and view.
/// </summary>
public void ResetRubberBand()
{
if (_RubberBand != null)
_RubberBand = null;
}
#endregion Mouse handling ICanvasViewMouseHandler
#region CommndImplementation
#region Selection mode command
/// <summary>
/// Determine whether canvas can switch to selection mode or not.
/// </summary>
/// <returns></returns>
private bool OnSelectMode_CanExecute()
{
return (this.CanvasViewMouseHandler != null);
}
/// <summary>
/// Implements the select mode command which switches the viewmodel into the
/// selection mode. The selection mode allows normal work with canvas elements
/// by clicking on them.
/// </summary>
private void OnSelectMode_Execute()
{
this.CancelCanvasViewMouseHandler();
}
#endregion Selection mode command
#region delete cut copy paste commands
/// <summary>
/// Determine whether a selected canvas element can be deleted, cut, or copied.
/// </summary>
/// <returns></returns>
private bool OnDeleteCutCopyCommand_CanExecute()
{
return (this.DocumentViewModel.dm_DocumentDataModel.State == DataModel.ModelState.Ready &&
_SelectedItem.Count > 0);
}
/// <summary>
/// Determine whether a Paste command can be executed or not.
/// </summary>
/// <returns></returns>
private bool OnPasteCommand_CanExecute()
{
return (this.DocumentViewModel.dm_DocumentDataModel.State == DataModel.ModelState.Ready && Clipboard.ContainsText());
}
/// <summary>
/// Delete a selected canvas element from the canvas.
/// </summary>
private void OnDeleteCommand_Executed()
{
try
{
DocumentViewModel.dm_DocumentDataModel.BeginOperation("DeleteCommandModel.OnExecute");
DocumentViewModel.dm_DocumentDataModel.DeleteElements(_SelectedItem.Shapes);
// Clear selection from selected elements in canvas viewmodel
_SelectedItem.Clear();
}
finally
{
DocumentViewModel.dm_DocumentDataModel.EndOperation("DeleteCommandModel.OnExecute");
}
}
/// <summary>
/// Cut currently selected shape(s) into the clipboard.
/// </summary>
private void OnCutCommand_Executed()
{
this.DocumentViewModel.dm_DocumentDataModel.BeginOperation("CutCommandModel.OnExecute");
string fragment = string.Empty;
if (this.SelectedItem.Count > 0)
fragment = this.DocumentViewModel.dm_DocumentDataModel.GetShapesAsXmlString(this.SelectedItem.Shapes);
this.DocumentViewModel.dm_DocumentDataModel.DeleteElements(_SelectedItem.Shapes);
_SelectedItem.Clear();
Clipboard.SetText(fragment);
this.DocumentViewModel.dm_DocumentDataModel.EndOperation("CutCommandModel.OnExecute");
}
/// <summary>
/// Copy currently selected shape(s) into the clipboard.
/// </summary>
private void OnCopyCommand_Executed()
{
string fragment = string.Empty;
if (this.SelectedItem.Count > 0)
fragment = this.DocumentViewModel.dm_DocumentDataModel.GetShapesAsXmlString(this.SelectedItem.Shapes);
Clipboard.SetText(fragment);
}
/// <summary>
/// Paste element from windows clipboard into current selection on to the canvas.
/// </summary>
private void OnPasteCommand_Executed()
{
try
{
string xmlDocument = Clipboard.GetText();
if (string.IsNullOrEmpty(xmlDocument) == true)
return;
// Look-up plugin model
string plugin = this.DocumentViewModel.dm_DocumentDataModel.PluginModelName;
PluginModelBase m = PluginManager.GetPluginModel(plugin);
// Look-up shape converter
UmlTypeToStringConverterBase conv = null;
conv = m.ShapeConverter;
List<ShapeViewModelBase> coll;
// Convert Xml document into a list of shapes and page definition
PageViewModelBase page = conv.ReadDocument(xmlDocument,
this.DocumentViewModel.vm_CanvasViewModel, out coll);
if (coll == null)
return;
if (coll.Count == 0)
return;
this.DocumentViewModel.dm_DocumentDataModel.BeginOperation("PasteCommandModel.OnExecute");
_SelectedItem.Clear();
foreach (var shape in coll)
{
this.DocumentViewModel.dm_DocumentDataModel.AddShape(shape);
_SelectedItem.Add(shape);
}
this.DocumentViewModel.dm_DocumentDataModel.EndOperation("PasteCommandModel.OnExecute");
}
catch
{
_MsgBox.Show(MiniUML.Framework.Local.Strings.STR_MSG_NoShapeInClipboard,
MiniUML.Framework.Local.Strings.STR_UnexpectedErrorCaption,
MsgBoxButtons.OK, MsgBoxImage.Warning);
}
}
#endregion delete command
#endregion CommndImplementation
#region private SameSize methods
private void SameWidth(ShapeSizeViewModelBase shape)
{
if (shape == null)
return;
foreach (var item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>())
{
if (shape == item) // Adjust shape to itself is a superflous operation
continue;
item.Width = shape.Width;
}
}
private void SameHeight(ShapeSizeViewModelBase shape)
{
if (shape == null)
return;
foreach (var item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>())
{
if (shape == item) // Adjust shape to itself is a superflous operation
continue;
item.Height = shape.Height;
}
}
private void SameWidthandHeight(ShapeSizeViewModelBase shape)
{
if (shape == null)
return;
foreach (var item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>())
{
if (shape == item) // Adjust shape to itself is a superflous operation
continue;
item.Width = shape.Width;
item.Height = shape.Height;
}
}
#endregion private SameSize methods
#region private Shape Distribution methods
/// <summary>
/// Destribute all selected shapes (if any) over X space evenly.
///
/// Method is based on:
/// http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part-4
///
/// DesignerCanvas.Commands.cs (DistributeHorizontal_Executed method)
/// </summary>
/// <param name="shape"></param>
private void DistributeHorizontal()
{
if (this.SelectedItem.Shapes.Count() <= 1)
return;
var selectedItems = from item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>()
let itemLeft = item.Left
orderby itemLeft
select item;
if (selectedItems.Count() > 1)
{
double left = Double.MaxValue;
double right = Double.MinValue;
double sumWidth = 0;
// Compute min(left), max(right), and sum(width) for all selected items
foreach (var item in selectedItems)
{
left = Math.Min(left, item.Left);
right = Math.Max(right, item.Left + item.Width);
sumWidth += item.Width;
}
double distance = Math.Max(0, (right - left - sumWidth) / (selectedItems.Count() - 1));
double offset = selectedItems.First().Left;
foreach (var item in selectedItems)
{
double delta = offset - item.Left;
item.Left = item.Left + delta;
offset = offset + item.Width + distance;
}
}
}
/// <summary>
/// Destribute all selected shapes (if any) over Y space evenly.
///
/// Method is based on:
/// http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part-4
///
/// DesignerCanvas.Commands.cs (DistributeVertical_Executed method)
/// </summary>
/// <param name="shape"></param>
private void DistributeVertical()
{
if (this.SelectedItem.Shapes.Count() <= 1)
return;
var selectedItems = from item in this.SelectedItem.Shapes.OfType<ShapeSizeViewModelBase>()
let itemTop = item.Top
orderby itemTop
select item;
if (selectedItems.Count() > 1)
{
double top = Double.MaxValue;
double bottom = Double.MinValue;
double sumHeight = 0;
// Compute min(top), max(bottom), and sum(Height) for all selected items
foreach (var item in selectedItems)
{
top = Math.Min(top, item.Top);
bottom = Math.Max(bottom, item.Top + item.Height);
sumHeight += item.Height;
}
double distance = Math.Max(0, (bottom - top - sumHeight) / (selectedItems.Count() - 1));
double offset = selectedItems.First().Top;
foreach (var item in selectedItems)
{
double delta = offset - item.Top;
item.Top = item.Top + delta;
offset = offset + item.Height + distance;
}
}
}
#endregion private Shape Distribution methods
#endregion methods
}
}
| |
using System;
namespace TechTest2014
{
#region Main Programm
class Program
{
public bool gameOver;
public bool restart;
public int score;
public int noOfEnemies; // decides how many enemies should be on the field
public PlayerShip playerShip;
public EnemyShip enemyShip1;
public EnemyShip enemyShip2;
public EnemyShip enemyShip3;
public EnemyShip enemyShip4;
public static void Main()
{
Start();
}
public static void Start(){
System.Console.WriteLine("Hello, World!");
CreatePlayerShip();
CreateEnemies();
RunGame();
}
private void RunGame()
{
// put player ship on map
playerShip.xPosition = 0;
playerShip.yPosition = 10;
// activate enemy ships at different intervals and move them down the screen
Random waitTime = new Random();
int seconds = waitTime.Next(3 * 1000, 11 * 1000);
// Continiously move the ships down after each sleep until they are at Y-coordinate 0 (outside the screen), then call OutOfBounds
enemyShip1.IsActivated = 1;
System.Threading.Thread.Sleep(seconds);
enemyShip2.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
// Hmm...I wonder if there is a way to change the Y position for all active ships so I dont have to do it per ship
System.Threading.Thread.Sleep(seconds);
enemyShip3.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
System.Threading.Thread.Sleep(seconds);
enemyShip4.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
enemyShip3.yPosition = enemyShip3.yPosition - enemyShip3.speed;
System.Threading.Thread.Sleep(seconds);
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
enemyShip3.yPosition = enemyShip3.yPosition - enemyShip3.speed;
enemyShip4.yPosition = enemyShip4.yPosition - enemyShip4.speed;
// check for every ship if out of bounds, then inactivate and reset
OutOfBounds(enemyShip1);
OutOfBounds(enemyShip2);
OutOfBounds(enemyShip3);
OutOfBounds(enemyShip4);
// How to continue to move the enemy ships all the time? Code above only moves enemy ships one step and we want the enemies to move all the time.
// Maybe a loop can be used in order to move the ships continously? MoveShip(enemyShip)?
//While (enemyShip1.IsActivated = 1 || enemyShip2.IsActivated = 1 || enemyShip3.IsActivated = 1 || enemyShip4.IsActivated = 1)
// {
// enemyShip1.yPosition = enemyShip1.yPosition - 10;
// enemyShip2.yPosition = enemyShip2.yPosition - 10;
// enemyShip3.yPosition = enemyShip3.yPosition - 10;
// enemyShip4.yPosition = enemyShip4.yPosition - 10;
// OutOfBounds(enemyShip1);
// OutOfBounds(enemyShip2);
// OutOfBounds(enemyShip3);
// OutOfBounds(enemyShip4);
}
public void OutOfBounds(EnemyShip enemyShip)
{
if (enemyShip.yPosition <= 0)
{
enemyShip.yPosition = 100;
enemyShip.IsActivated = 0;
}
}
private void CreatePlayerShip()
{
playerShip = new PlayerShip();
playerShip.health = 100;
playerShip.lifes = 3;
}
private void CreateEnemies()
{
// Hmmm...there must be a better way to create the enemy ships than creating them one by one. What if I want 10 enemies
enemyShip1 = new EnemyShip();
enemyShip2 = new EnemyShip();
enemyShip3 = new EnemyShip();
enemyShip4 = new EnemyShip();
// Hmm.. I wonder if there is a way to change this so I dont have to set the values for every ship
Random rnd = new Random();
rnd.Next(-100, 100);
enemyShip1.xPosition = int.Parse(rnd.ToString());
enemyShip1.yPosition = 100;
enemyShip1.IsActivated = 1;
}
}
#endregion
#region Player ship
class PlayerShip{
private int health;
private int lifes;
public int Health{
get{
return health;
}
set {
health = value;
}
}
public int Lifes{
get{
return lifes;
}
set{
lifes = value;
}
}
}
#endregion
#region Enemy Class
class EnemyShip{
public bool IsActivated;
public int xPosition;
public int yPosition;
}
#endregion
}
namespace TechTest2014
{
using System;
class Program
{
public bool gameOver;
public bool restart;
public int score;
public int noOfEnemies; // decides how many enemies should be on the field
public PlayerShip playerShip;
public EnemyShip enemyShip1;
public EnemyShip enemyShip2;
public EnemyShip enemyShip3;
public EnemyShip enemyShip4;
/// The purpose is to create the player ship, X enemies and then move the enemies toward the player
public static void Main(string[] args)
{
}
public void Start()
{
CreatePlayerShip();
CreateEnemies();
RunGame();
}
private void RunGame()
{
// put player ship on map
playerShip.xPosition = 0;
playerShip.yPosition = 10;
// activate enemy ships at different intervals and move them down the screen
Random waitTime = new Random();
int seconds = waitTime.Next(3 * 1000, 11 * 1000);
// Continiously move the ships down after each sleep until they are at Y-coordinate 0 (outside the screen), then call OutOfBounds
enemyShip1.IsActivated = 1;
System.Threading.Thread.Sleep(seconds);
enemyShip2.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
// Hmm...I wonder if there is a way to change the Y position for all active ships so I dont have to do it per ship
System.Threading.Thread.Sleep(seconds);
enemyShip3.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
System.Threading.Thread.Sleep(seconds);
enemyShip4.IsActivated = 1;
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
enemyShip3.yPosition = enemyShip3.yPosition - enemyShip3.speed;
System.Threading.Thread.Sleep(seconds);
enemyShip1.yPosition = enemyShip1.yPosition - enemyShip1.speed;
enemyShip2.yPosition = enemyShip2.yPosition - enemyShip2.speed;
enemyShip3.yPosition = enemyShip3.yPosition - enemyShip3.speed;
enemyShip4.yPosition = enemyShip4.yPosition - enemyShip4.speed;
// check for every ship if out of bounds, then inactivate and reset
OutOfBounds(enemyShip1);
OutOfBounds(enemyShip2);
OutOfBounds(enemyShip3);
OutOfBounds(enemyShip4);
// How to continue to move the enemy ships all the time? Code above only moves enemy ships one step and we want the enemies to move all the time.
// Maybe a loop can be used in order to move the ships continously? MoveShip(enemyShip)?
//While (enemyShip1.IsActivated = 1 || enemyShip2.IsActivated = 1 || enemyShip3.IsActivated = 1 || enemyShip4.IsActivated = 1)
// {
// enemyShip1.yPosition = enemyShip1.yPosition - 10;
// enemyShip2.yPosition = enemyShip2.yPosition - 10;
// enemyShip3.yPosition = enemyShip3.yPosition - 10;
// enemyShip4.yPosition = enemyShip4.yPosition - 10;
// OutOfBounds(enemyShip1);
// OutOfBounds(enemyShip2);
// OutOfBounds(enemyShip3);
// OutOfBounds(enemyShip4);
}
public void OutOfBounds(EnemyShip enemyShip)
{
if (enemyShip.yPosition <= 0)
{
enemyShip.yPosition = 100;
enemyShip.IsActivated = 0;
}
}
private void CreatePlayerShip()
{
playerShip = new PlayerShip();
playerShip.health = 100;
playerShip.lifes = 3;
}
private void CreateEnemies()
{
// Hmmm...there must be a better way to create the enemy ships than creating them one by one. What if I want 10 enemies
enemyShip1 = new EnemyShip();
enemyShip2 = new EnemyShip();
enemyShip3 = new EnemyShip();
enemyShip4 = new EnemyShip();
// Hmm.. I wonder if there is a way to change this so I dont have to set the values for every ship
Random rnd = new Random();
rnd.Next(-100, 100);
enemyShip1.xPosition = int.Parse(rnd.ToString());
enemyShip1.yPosition = 100;
enemyShip1.IsActivated = 1;
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software (typically granted by licensing Spine), you
* may not (a) modify, translate, adapt or otherwise create derivative works,
* improvements of the Software or develop new applications using the Software
* or (b) remove, delete, alter or obscure any trademarks or any copyright,
* trademark, patent or other intellectual property or proprietary rights
* notices on or in the Software, including any copy thereof. Redistributions
* in binary or source form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTARE 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.
*****************************************************************************/
/*****************************************************************************
* Automatic import and advanced preview added by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using System;
using System.Collections.Generic;
using UnityEditor;
#if !UNITY_4_3
using UnityEditor.AnimatedValues;
#endif
using UnityEngine;
using Spine;
[CustomEditor(typeof(SkeletonDataAsset))]
public class SkeletonDataAssetInspector : Editor {
private SerializedProperty atlasAsset, skeletonJSON, scale, fromAnimation, toAnimation, duration, defaultMix;
private bool showAnimationStateData = true;
#if UNITY_4_3
private bool m_showAnimationList = true;
#else
private AnimBool m_showAnimationList = new AnimBool(true);
#endif
private bool m_initialized = false;
private SkeletonDataAsset m_skeletonDataAsset;
private string m_skeletonDataAssetGUID;
void OnEnable () {
try {
atlasAsset = serializedObject.FindProperty("atlasAsset");
skeletonJSON = serializedObject.FindProperty("skeletonJSON");
scale = serializedObject.FindProperty("scale");
fromAnimation = serializedObject.FindProperty("fromAnimation");
toAnimation = serializedObject.FindProperty("toAnimation");
duration = serializedObject.FindProperty("duration");
defaultMix = serializedObject.FindProperty("defaultMix");
m_skeletonDataAsset = (SkeletonDataAsset)target;
m_skeletonDataAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_skeletonDataAsset));
EditorApplication.update += Update;
} catch {
}
}
void OnDestroy () {
m_initialized = false;
EditorApplication.update -= Update;
this.DestroyPreviewInstances();
if (this.m_previewUtility != null) {
this.m_previewUtility.Cleanup();
this.m_previewUtility = null;
}
}
override public void OnInspectorGUI () {
serializedObject.Update();
SkeletonDataAsset asset = (SkeletonDataAsset)target;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(atlasAsset);
EditorGUILayout.PropertyField(skeletonJSON);
EditorGUILayout.PropertyField(scale);
if (EditorGUI.EndChangeCheck()) {
if (m_previewUtility != null) {
m_previewUtility.Cleanup();
m_previewUtility = null;
}
}
SkeletonData skeletonData = asset.GetSkeletonData(asset.atlasAsset == null || asset.skeletonJSON == null);
if (skeletonData != null) {
showAnimationStateData = EditorGUILayout.Foldout(showAnimationStateData, "Animation State Data");
if (showAnimationStateData) {
EditorGUILayout.PropertyField(defaultMix);
// Animation names
String[] animations = new String[skeletonData.Animations.Count];
for (int i = 0; i < animations.Length; i++)
animations[i] = skeletonData.Animations[i].Name;
for (int i = 0; i < fromAnimation.arraySize; i++) {
SerializedProperty from = fromAnimation.GetArrayElementAtIndex(i);
SerializedProperty to = toAnimation.GetArrayElementAtIndex(i);
SerializedProperty durationProp = duration.GetArrayElementAtIndex(i);
EditorGUILayout.BeginHorizontal();
from.stringValue = animations[EditorGUILayout.Popup(Math.Max(Array.IndexOf(animations, from.stringValue), 0), animations)];
to.stringValue = animations[EditorGUILayout.Popup(Math.Max(Array.IndexOf(animations, to.stringValue), 0), animations)];
durationProp.floatValue = EditorGUILayout.FloatField(durationProp.floatValue);
if (GUILayout.Button("Delete")) {
duration.DeleteArrayElementAtIndex(i);
toAnimation.DeleteArrayElementAtIndex(i);
fromAnimation.DeleteArrayElementAtIndex(i);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
if (GUILayout.Button("Add Mix")) {
duration.arraySize++;
toAnimation.arraySize++;
fromAnimation.arraySize++;
}
EditorGUILayout.Space();
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button(new GUIContent("Setup Pose", SpineEditorUtilities.Icons.skeleton), GUILayout.Width(105), GUILayout.Height(18))) {
StopAnimation();
m_skeletonAnimation.skeleton.SetToSetupPose();
m_requireRefresh = true;
}
#if UNITY_4_3
m_showAnimationList = EditorGUILayout.Foldout(m_showAnimationList, new GUIContent("Animations", SpineEditorUtilities.Icons.animationRoot));
if(m_showAnimationList){
#else
m_showAnimationList.target = EditorGUILayout.Foldout(m_showAnimationList.target, new GUIContent("Animations", SpineEditorUtilities.Icons.animationRoot));
if (EditorGUILayout.BeginFadeGroup(m_showAnimationList.faded)) {
#endif
EditorGUILayout.LabelField("Name", "Duration");
foreach (Spine.Animation a in skeletonData.Animations) {
GUILayout.BeginHorizontal();
if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) {
if (m_skeletonAnimation.state.GetCurrent(0) != null && m_skeletonAnimation.state.GetCurrent(0).Animation == a) {
GUI.contentColor = Color.black;
if (GUILayout.Button("\u25BA", GUILayout.Width(24))) {
StopAnimation();
}
GUI.contentColor = Color.white;
} else {
if (GUILayout.Button("\u25BA", GUILayout.Width(24))) {
PlayAnimation(a.Name, true);
}
}
} else {
GUILayout.Label("?", GUILayout.Width(24));
}
EditorGUILayout.LabelField(new GUIContent(a.Name, SpineEditorUtilities.Icons.animation), new GUIContent(a.Duration.ToString("f3") + "s" + ("(" + (Mathf.RoundToInt(a.Duration * 30)) + ")").PadLeft(12, ' ')));
GUILayout.EndHorizontal();
}
}
#if !UNITY_4_3
EditorGUILayout.EndFadeGroup();
#endif
}
if (!Application.isPlaying) {
if (serializedObject.ApplyModifiedProperties() ||
(UnityEngine.Event.current.type == EventType.ValidateCommand && UnityEngine.Event.current.commandName == "UndoRedoPerformed")
) {
asset.Reset();
}
}
}
//preview window stuff
private PreviewRenderUtility m_previewUtility;
private GameObject m_previewInstance;
private Vector2 previewDir;
private SkeletonAnimation m_skeletonAnimation;
private SkeletonData m_skeletonData;
private static int sliderHash = "Slider".GetHashCode();
private float m_lastTime;
private bool m_playing;
private bool m_requireRefresh;
private Color m_originColor = new Color(0.3f, 0.3f, 0.3f, 1);
private void StopAnimation () {
m_skeletonAnimation.state.ClearTrack(0);
m_playing = false;
}
List<Spine.Event> m_animEvents = new List<Spine.Event>();
List<float> m_animEventFrames = new List<float>();
private void PlayAnimation (string animName, bool loop) {
m_animEvents.Clear();
m_animEventFrames.Clear();
m_skeletonAnimation.state.SetAnimation(0, animName, loop);
Spine.Animation a = m_skeletonAnimation.state.GetCurrent(0).Animation;
foreach (Timeline t in a.Timelines) {
if (t.GetType() == typeof(EventTimeline)) {
EventTimeline et = (EventTimeline)t;
for (int i = 0; i < et.Events.Length; i++) {
m_animEvents.Add(et.Events[i]);
m_animEventFrames.Add(et.Frames[i]);
}
}
}
m_playing = true;
}
private void InitPreview () {
if (this.m_previewUtility == null) {
this.m_lastTime = Time.realtimeSinceStartup;
this.m_previewUtility = new PreviewRenderUtility(true);
this.m_previewUtility.m_Camera.isOrthoGraphic = true;
this.m_previewUtility.m_Camera.orthographicSize = 1;
this.m_previewUtility.m_Camera.cullingMask = -2147483648;
this.CreatePreviewInstances();
}
}
private void CreatePreviewInstances () {
this.DestroyPreviewInstances();
if (this.m_previewInstance == null) {
string skinName = EditorPrefs.GetString(m_skeletonDataAssetGUID + "_lastSkin", "");
m_previewInstance = SpineEditorUtilities.SpawnAnimatedSkeleton((SkeletonDataAsset)target, skinName).gameObject;
m_previewInstance.hideFlags = HideFlags.HideAndDontSave;
m_previewInstance.layer = 0x1f;
m_skeletonAnimation = m_previewInstance.GetComponent<SkeletonAnimation>();
m_skeletonAnimation.initialSkinName = skinName;
m_skeletonAnimation.LateUpdate();
m_skeletonData = m_skeletonAnimation.skeletonDataAsset.GetSkeletonData(true);
m_previewInstance.renderer.enabled = false;
m_initialized = true;
AdjustCameraGoals(true);
}
}
private void DestroyPreviewInstances () {
if (this.m_previewInstance != null) {
DestroyImmediate(this.m_previewInstance);
m_previewInstance = null;
}
m_initialized = false;
}
public override bool HasPreviewGUI () {
//TODO: validate json data
return skeletonJSON.objectReferenceValue != null;
}
Texture m_previewTex = new Texture();
public override void OnInteractivePreviewGUI (Rect r, GUIStyle background) {
this.InitPreview();
if (UnityEngine.Event.current.type == EventType.Repaint) {
if (m_requireRefresh) {
this.m_previewUtility.BeginPreview(r, background);
this.DoRenderPreview(true);
this.m_previewTex = this.m_previewUtility.EndPreview();
m_requireRefresh = false;
}
if (this.m_previewTex != null)
GUI.DrawTexture(r, m_previewTex, ScaleMode.StretchToFill, false);
}
DrawSkinToolbar(r);
NormalizedTimeBar(r);
//TODO: implement panning
// this.previewDir = Drag2D(this.previewDir, r);
MouseScroll(r);
}
float m_orthoGoal = 1;
Vector3 m_posGoal = new Vector3(0, 0, -10);
double m_adjustFrameEndTime = 0;
private void AdjustCameraGoals (bool calculateMixTime) {
if (calculateMixTime) {
if (m_skeletonAnimation.state.GetCurrent(0) != null) {
m_adjustFrameEndTime = EditorApplication.timeSinceStartup + m_skeletonAnimation.state.GetCurrent(0).Mix;
}
}
GameObject go = this.m_previewInstance;
Bounds bounds = go.renderer.bounds;
m_orthoGoal = bounds.size.y;
m_posGoal = bounds.center + new Vector3(0, 0, -10);
}
private void AdjustCameraGoals () {
AdjustCameraGoals(false);
}
private void AdjustCamera () {
if (m_previewUtility == null)
return;
if (EditorApplication.timeSinceStartup < m_adjustFrameEndTime) {
AdjustCameraGoals();
}
float orthoSet = Mathf.Lerp(this.m_previewUtility.m_Camera.orthographicSize, m_orthoGoal, 0.1f);
this.m_previewUtility.m_Camera.orthographicSize = orthoSet;
float dist = Vector3.Distance(m_previewUtility.m_Camera.transform.position, m_posGoal);
if (dist > 60f * ((SkeletonDataAsset)target).scale) {
Vector3 pos = Vector3.Lerp(this.m_previewUtility.m_Camera.transform.position, m_posGoal, 0.1f);
pos.x = 0;
this.m_previewUtility.m_Camera.transform.position = pos;
this.m_previewUtility.m_Camera.transform.rotation = Quaternion.identity;
m_requireRefresh = true;
}
}
private void DoRenderPreview (bool drawHandles) {
GameObject go = this.m_previewInstance;
if (m_requireRefresh) {
go.renderer.enabled = true;
if (EditorApplication.isPlaying) {
//do nothing
} else {
m_skeletonAnimation.Update((Time.realtimeSinceStartup - m_lastTime));
}
m_lastTime = Time.realtimeSinceStartup;
if (!EditorApplication.isPlaying)
m_skeletonAnimation.LateUpdate();
if (drawHandles) {
Handles.SetCamera(m_previewUtility.m_Camera);
Handles.color = m_originColor;
Handles.DrawLine(new Vector3(-1000 * m_skeletonDataAsset.scale, 0, 0), new Vector3(1000 * m_skeletonDataAsset.scale, 0, 0));
Handles.DrawLine(new Vector3(0, 1000 * m_skeletonDataAsset.scale, 0), new Vector3(0, -1000 * m_skeletonDataAsset.scale, 0));
}
this.m_previewUtility.m_Camera.Render();
go.renderer.enabled = false;
}
}
void Update () {
AdjustCamera();
if (m_playing) {
m_requireRefresh = true;
Repaint();
} else if (m_requireRefresh) {
Repaint();
} else {
#if !UNITY_4_3
if (m_showAnimationList.isAnimating)
Repaint();
#endif
}
}
void DrawSkinToolbar (Rect r) {
if (m_skeletonAnimation == null)
return;
if (m_skeletonAnimation.skeleton != null) {
string label = (m_skeletonAnimation.skeleton != null && m_skeletonAnimation.skeleton.Skin != null) ? m_skeletonAnimation.skeleton.Skin.Name : "default";
Rect popRect = new Rect(r);
popRect.y += 32;
popRect.x += 4;
popRect.height = 24;
popRect.width = 40;
EditorGUI.DropShadowLabel(popRect, new GUIContent("Skin", SpineEditorUtilities.Icons.skinsRoot));
popRect.y += 11;
popRect.width = 150;
popRect.x += 44;
if (GUI.Button(popRect, label, EditorStyles.popup)) {
SelectSkinContext();
}
}
}
void SelectSkinContext () {
GenericMenu menu = new GenericMenu();
foreach (Skin s in m_skeletonData.Skins) {
menu.AddItem(new GUIContent(s.Name), this.m_skeletonAnimation.skeleton.Skin == s, SetSkin, (object)s);
}
menu.ShowAsContext();
}
void SetSkin (object o) {
Skin skin = (Skin)o;
m_skeletonAnimation.initialSkinName = skin.Name;
m_skeletonAnimation.Reset();
m_requireRefresh = true;
EditorPrefs.SetString(m_skeletonDataAssetGUID + "_lastSkin", skin.Name);
}
void NormalizedTimeBar (Rect r) {
Rect barRect = new Rect(r);
barRect.height = 32;
barRect.x += 4;
barRect.width -= 4;
GUI.Box(barRect, "");
Rect lineRect = new Rect(barRect);
float width = lineRect.width;
TrackEntry t = m_skeletonAnimation.state.GetCurrent(0);
if (t != null) {
int loopCount = (int)(t.Time / t.EndTime);
float currentTime = t.Time - (t.EndTime * loopCount);
float normalizedTime = currentTime / t.Animation.Duration;
lineRect.x = barRect.x + (width * normalizedTime) - 0.5f;
lineRect.width = 2;
GUI.color = Color.red;
GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
for (int i = 0; i < m_animEvents.Count; i++) {
//TODO: Tooltip
//Spine.Event spev = animEvents[i];
float fr = m_animEventFrames[i];
Rect evRect = new Rect(barRect);
evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (SpineEditorUtilities.Icons._event.width / 2), barRect.x, float.MaxValue);
evRect.width = SpineEditorUtilities.Icons._event.width;
evRect.height = SpineEditorUtilities.Icons._event.height;
evRect.y += SpineEditorUtilities.Icons._event.height;
GUI.DrawTexture(evRect, SpineEditorUtilities.Icons._event);
//TODO: Tooltip
/*
UnityEngine.Event ev = UnityEngine.Event.current;
if(ev.isMouse){
if(evRect.Contains(ev.mousePosition)){
Rect tooltipRect = new Rect(evRect);
tooltipRect.width = 500;
tooltipRect.y -= 4;
tooltipRect.x += 4;
GUI.Label(tooltipRect, spev.Data.Name);
}
}
*/
}
}
}
void MouseScroll (Rect position) {
UnityEngine.Event current = UnityEngine.Event.current;
int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive);
switch (current.GetTypeForControl(controlID)) {
case EventType.ScrollWheel:
if (position.Contains(current.mousePosition)) {
m_orthoGoal += current.delta.y * ((SkeletonDataAsset)target).scale * 10;
GUIUtility.hotControl = controlID;
current.Use();
}
break;
}
}
//TODO: Implement preview panning
/*
static Vector2 Drag2D(Vector2 scrollPosition, Rect position)
{
int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive);
UnityEngine.Event current = UnityEngine.Event.current;
switch (current.GetTypeForControl(controlID))
{
case EventType.MouseDown:
if (position.Contains(current.mousePosition) && (position.width > 50f))
{
GUIUtility.hotControl = controlID;
current.Use();
EditorGUIUtility.SetWantsMouseJumping(1);
}
return scrollPosition;
case EventType.MouseUp:
if (GUIUtility.hotControl == controlID)
{
GUIUtility.hotControl = 0;
}
EditorGUIUtility.SetWantsMouseJumping(0);
return scrollPosition;
case EventType.MouseMove:
return scrollPosition;
case EventType.MouseDrag:
if (GUIUtility.hotControl == controlID)
{
scrollPosition -= (Vector2) (((current.delta * (!current.shift ? ((float) 1) : ((float) 3))) / Mathf.Min(position.width, position.height)) * 140f);
scrollPosition.y = Mathf.Clamp(scrollPosition.y, -90f, 90f);
current.Use();
GUI.changed = true;
}
return scrollPosition;
}
return scrollPosition;
}
*/
public override GUIContent GetPreviewTitle () {
return new GUIContent("Preview");
}
public override void OnPreviewSettings () {
if (!m_initialized) {
GUILayout.HorizontalSlider(0, 0, 2, GUILayout.MaxWidth(64));
} else {
float speed = GUILayout.HorizontalSlider(m_skeletonAnimation.timeScale, 0, 2, GUILayout.MaxWidth(64));
//snap to nearest 0.25
float y = speed / 0.25f;
int q = Mathf.RoundToInt(y);
speed = q * 0.25f;
m_skeletonAnimation.timeScale = speed;
}
}
//TODO: Fix first-import error
//TODO: Update preview without thumbnail
public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) {
Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
this.InitPreview();
if (this.m_previewUtility.m_Camera == null)
return null;
m_requireRefresh = true;
this.DoRenderPreview(false);
AdjustCameraGoals(false);
this.m_previewUtility.m_Camera.orthographicSize = m_orthoGoal / 2;
this.m_previewUtility.m_Camera.transform.position = m_posGoal;
this.m_previewUtility.BeginStaticPreview(new Rect(0, 0, width, height));
this.DoRenderPreview(false);
//TODO: Figure out why this is throwing errors on first attempt
// if(m_previewUtility != null){
// Handles.SetCamera(this.m_previewUtility.m_Camera);
// Handles.BeginGUI();
// GUI.DrawTexture(new Rect(40,60,width,height), SpineEditorUtilities.Icons.spine, ScaleMode.StretchToFill);
// Handles.EndGUI();
// }
tex = this.m_previewUtility.EndStaticPreview();
return tex;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
using System.Linq.Expressions;
#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation.Language;
using System.Runtime.CompilerServices;
namespace System.Management.Automation.Interpreter
{
using AstUtils = System.Management.Automation.Interpreter.Utils;
using LoopFunc = Func<object[], StrongBox<object>[], InterpretedFrame, int>;
internal sealed class LoopCompiler : ExpressionVisitor
{
private struct LoopVariable
{
public ExpressionAccess Access;
// a variable that holds on the strong box for closure variables:
public ParameterExpression BoxStorage;
public LoopVariable(ExpressionAccess access, ParameterExpression box)
{
Access = access;
BoxStorage = box;
}
public override string ToString()
{
return Access.ToString() + " " + BoxStorage;
}
}
private readonly ParameterExpression _frameDataVar;
private readonly ParameterExpression _frameClosureVar;
private readonly ParameterExpression _frameVar;
private readonly LabelTarget _returnLabel;
// locals and closure variables defined outside the loop
private readonly Dictionary<ParameterExpression, LocalVariable> _outerVariables, _closureVariables;
private readonly PowerShellLoopExpression _loop;
private List<ParameterExpression> _temps;
// tracks variables that flow in and flow out for initialization and
private readonly Dictionary<ParameterExpression, LoopVariable> _loopVariables;
// variables which are defined and used within the loop
private HashSet<ParameterExpression> _loopLocals;
private readonly HybridReferenceDictionary<LabelTarget, BranchLabel> _labelMapping;
private readonly int _loopStartInstructionIndex;
private readonly int _loopEndInstructionIndex;
internal LoopCompiler(PowerShellLoopExpression loop,
HybridReferenceDictionary<LabelTarget, BranchLabel> labelMapping,
Dictionary<ParameterExpression, LocalVariable> locals,
Dictionary<ParameterExpression, LocalVariable> closureVariables,
int loopStartInstructionIndex,
int loopEndInstructionIndex)
{
_loop = loop;
_outerVariables = locals;
_closureVariables = closureVariables;
_frameDataVar = Expression.Parameter(typeof(object[]));
_frameClosureVar = Expression.Parameter(typeof(StrongBox<object>[]));
_frameVar = Expression.Parameter(typeof(InterpretedFrame));
_loopVariables = new Dictionary<ParameterExpression, LoopVariable>();
_returnLabel = Expression.Label(typeof(int));
_labelMapping = labelMapping;
_loopStartInstructionIndex = loopStartInstructionIndex;
_loopEndInstructionIndex = loopEndInstructionIndex;
}
internal LoopFunc CreateDelegate()
{
var loop = Visit(_loop);
var body = new List<Expression>();
var finallyClause = new List<Expression>();
foreach (var variable in _loopVariables)
{
LocalVariable local;
if (!_outerVariables.TryGetValue(variable.Key, out local))
{
local = _closureVariables[variable.Key];
}
Expression elemRef = local.LoadFromArray(_frameDataVar, _frameClosureVar);
if (local.InClosureOrBoxed)
{
var box = variable.Value.BoxStorage;
Debug.Assert(box != null);
body.Add(Expression.Assign(box, elemRef));
AddTemp(box);
}
else
{
// Always initialize the variable even if it is only written to.
// If a write-only variable is actually not assigned during execution of the loop we will still write some value back.
// This value must be the original value, which we assign at entry.
body.Add(Expression.Assign(variable.Key, AstUtils.Convert(elemRef, variable.Key.Type)));
if ((variable.Value.Access & ExpressionAccess.Write) != 0)
{
finallyClause.Add(Expression.Assign(elemRef, AstUtils.Box(variable.Key)));
}
AddTemp(variable.Key);
}
}
if (finallyClause.Count > 0)
{
body.Add(Expression.TryFinally(loop, Expression.Block(finallyClause)));
}
else
{
body.Add(loop);
}
body.Add(Expression.Label(_returnLabel, Expression.Constant(_loopEndInstructionIndex - _loopStartInstructionIndex)));
var lambda = Expression.Lambda<LoopFunc>(
_temps != null ? Expression.Block(_temps, body) : Expression.Block(body),
new[] { _frameDataVar, _frameClosureVar, _frameVar }
);
return lambda.Compile();
}
protected override Expression VisitExtension(Expression node)
{
// Reduce extensions before we visit them so that we operate on a plain DLR tree,
// where we know relationships among the nodes (which nodes represent write context etc.).
if (node.CanReduce)
{
return Visit(node.Reduce());
}
return base.VisitExtension(node);
}
#region Gotos
protected override Expression VisitGoto(GotoExpression node)
{
BranchLabel label;
var target = node.Target;
var value = Visit(node.Value);
// TODO: Is it possible for an inner reducible node of the loop to rely on nodes produced by reducing outer reducible nodes?
// Unknown label => must be within the loop:
if (!_labelMapping.TryGetValue(target, out label))
{
return node.Update(target, value);
}
// Known label within the loop:
if (label.TargetIndex >= _loopStartInstructionIndex && label.TargetIndex < _loopEndInstructionIndex)
{
return node.Update(target, value);
}
return Expression.Return(_returnLabel,
(value != null && value.Type != typeof(void)) ?
Expression.Call(_frameVar, InterpretedFrame.GotoMethod, Expression.Constant(label.LabelIndex), AstUtils.Box(value)) :
Expression.Call(_frameVar, InterpretedFrame.VoidGotoMethod, Expression.Constant(label.LabelIndex)),
node.Type
);
}
#endregion
#region Local Variables
// Gather all outer variables accessed in the loop.
// Determines which ones are read from and written to.
// We will consider a variable as "read" if it is read anywhere in the loop even though
// the first operation might actually always be "write". We could do better if we had CFG.
protected override Expression VisitBlock(BlockExpression node)
{
var variables = ((BlockExpression)node).Variables;
var prevLocals = EnterVariableScope(variables);
var res = base.VisitBlock(node);
ExitVariableScope(prevLocals);
return res;
}
private HashSet<ParameterExpression> EnterVariableScope(ICollection<ParameterExpression> variables)
{
if (_loopLocals == null)
{
_loopLocals = new HashSet<ParameterExpression>(variables);
return null;
}
var prevLocals = new HashSet<ParameterExpression>(_loopLocals);
_loopLocals.UnionWith(variables);
return prevLocals;
}
protected override CatchBlock VisitCatchBlock(CatchBlock node)
{
if (node.Variable != null)
{
var prevLocals = EnterVariableScope(new[] { node.Variable });
var res = base.VisitCatchBlock(node);
ExitVariableScope(prevLocals);
return res;
}
else
{
return base.VisitCatchBlock(node);
}
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
var prevLocals = EnterVariableScope(node.Parameters);
try
{
return base.VisitLambda<T>(node);
}
finally
{
ExitVariableScope(prevLocals);
}
}
private void ExitVariableScope(HashSet<ParameterExpression> prevLocals)
{
_loopLocals = prevLocals;
}
protected override Expression VisitBinary(BinaryExpression node)
{
// reduce compound assignments:
if (node.CanReduce)
{
return Visit(node.Reduce());
}
Debug.Assert(!node.NodeType.IsReadWriteAssignment());
var param = node.Left as ParameterExpression;
if (param != null && node.NodeType == ExpressionType.Assign)
{
var left = VisitVariable(param, ExpressionAccess.Write);
var right = Visit(node.Right);
// left parameter is a boxed variable:
if (left.Type != param.Type)
{
Debug.Assert(left.Type == typeof(object));
Expression rightVar;
if (right.NodeType != ExpressionType.Parameter)
{
// { left.Value = (object)(rightVar = right), rightVar }
rightVar = AddTemp(Expression.Parameter(right.Type));
right = Expression.Assign(rightVar, right);
}
else
{
// { left.Value = (object)right, right }
rightVar = right;
}
return Expression.Block(
node.Update(left, null, Expression.Convert(right, left.Type)),
rightVar
);
}
else
{
return node.Update(left, null, right);
}
}
else
{
return base.VisitBinary(node);
}
}
protected override Expression VisitUnary(UnaryExpression node)
{
// reduce inplace increment/decrement:
if (node.CanReduce)
{
return Visit(node.Reduce());
}
Debug.Assert(!node.NodeType.IsReadWriteAssignment());
return base.VisitUnary(node);
}
// TODO: if we supported ref/out parameter we would need to override
// MethodCallExpression, VisitDynamic and VisitNew
protected override Expression VisitParameter(ParameterExpression node)
{
return VisitVariable(node, ExpressionAccess.Read);
}
private Expression VisitVariable(ParameterExpression node, ExpressionAccess access)
{
ParameterExpression box;
LoopVariable existing;
LocalVariable loc;
if (_loopLocals.Contains(node))
{
// local to the loop - not propagated in or out
return node;
}
else if (_loopVariables.TryGetValue(node, out existing))
{
// existing outer variable that we are already tracking
box = existing.BoxStorage;
_loopVariables[node] = new LoopVariable(existing.Access | access, box);
}
else if (_outerVariables.TryGetValue(node, out loc) ||
(_closureVariables != null && _closureVariables.TryGetValue(node, out loc)))
{
// not tracking this variable yet, but defined in outer scope and seen for the 1st time
box = loc.InClosureOrBoxed ? Expression.Parameter(typeof(StrongBox<object>), node.Name) : null;
_loopVariables[node] = new LoopVariable(access, box);
}
else
{
// node is a variable defined in a nested lambda -> skip
return node;
}
if (box != null)
{
if ((access & ExpressionAccess.Write) != 0)
{
// compound assignments were reduced:
Debug.Assert((access & ExpressionAccess.Read) == 0);
// box.Value = (object)rhs
return LightCompiler.Unbox(box);
}
else
{
// (T)box.Value
return Expression.Convert(LightCompiler.Unbox(box), node.Type);
}
}
return node;
}
private ParameterExpression AddTemp(ParameterExpression variable)
{
if (_temps == null)
{
_temps = new List<ParameterExpression>();
}
_temps.Add(variable);
return variable;
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using Amazon.CloudFront.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.CloudFront.Model.Internal.MarshallTransformations
{
/// <summary>
/// Create Distribution Request Marshaller
/// </summary>
public class CreateDistributionRequestMarshaller : IMarshaller<IRequest, CreateDistributionRequest>
{
public IRequest Marshall(CreateDistributionRequest createDistributionRequest)
{
IRequest request = new DefaultRequest(createDistributionRequest, "AmazonCloudFront");
request.HttpMethod = "POST";
string uriResourcePath = "2013-08-26/distribution";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Namespaces = true;
if (createDistributionRequest != null)
{
DistributionConfig distributionConfigDistributionConfig = createDistributionRequest.DistributionConfig;
if (distributionConfigDistributionConfig != null)
{
xmlWriter.WriteStartElement("DistributionConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (distributionConfigDistributionConfig.IsSetCallerReference())
{
xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.CallerReference.ToString());
}
if (distributionConfigDistributionConfig != null)
{
Aliases aliasesAliases = distributionConfigDistributionConfig.Aliases;
if (aliasesAliases != null)
{
xmlWriter.WriteStartElement("Aliases", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (aliasesAliases.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", aliasesAliases.Quantity.ToString());
}
if (aliasesAliases != null)
{
List<string> aliasesAliasesitemsList = aliasesAliases.Items;
if (aliasesAliasesitemsList != null && aliasesAliasesitemsList.Count > 0)
{
int aliasesAliasesitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string aliasesAliasesitemsListValue in aliasesAliasesitemsList)
{
xmlWriter.WriteStartElement("CNAME", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(aliasesAliasesitemsListValue);
xmlWriter.WriteEndElement();
aliasesAliasesitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig.IsSetDefaultRootObject())
{
xmlWriter.WriteElementString("DefaultRootObject", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.DefaultRootObject.ToString());
}
if (distributionConfigDistributionConfig != null)
{
Origins originsOrigins = distributionConfigDistributionConfig.Origins;
if (originsOrigins != null)
{
xmlWriter.WriteStartElement("Origins", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (originsOrigins.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOrigins.Quantity.ToString());
}
if (originsOrigins != null)
{
List<Origin> originsOriginsitemsList = originsOrigins.Items;
if (originsOriginsitemsList != null && originsOriginsitemsList.Count > 0)
{
int originsOriginsitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (Origin originsOriginsitemsListValue in originsOriginsitemsList)
{
xmlWriter.WriteStartElement("Origin", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (originsOriginsitemsListValue.IsSetId())
{
xmlWriter.WriteElementString("Id", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOriginsitemsListValue.Id.ToString());
}
if (originsOriginsitemsListValue.IsSetDomainName())
{
xmlWriter.WriteElementString("DomainName", "http://cloudfront.amazonaws.com/doc/2013-08-26/", originsOriginsitemsListValue.DomainName.ToString());
}
if (originsOriginsitemsListValue != null)
{
S3OriginConfig s3OriginConfigS3OriginConfig = originsOriginsitemsListValue.S3OriginConfig;
if (s3OriginConfigS3OriginConfig != null)
{
xmlWriter.WriteStartElement("S3OriginConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (s3OriginConfigS3OriginConfig.IsSetOriginAccessIdentity())
{
xmlWriter.WriteElementString("OriginAccessIdentity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", s3OriginConfigS3OriginConfig.OriginAccessIdentity.ToString());
}
xmlWriter.WriteEndElement();
}
}
if (originsOriginsitemsListValue != null)
{
CustomOriginConfig customOriginConfigCustomOriginConfig = originsOriginsitemsListValue.CustomOriginConfig;
if (customOriginConfigCustomOriginConfig != null)
{
xmlWriter.WriteStartElement("CustomOriginConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (customOriginConfigCustomOriginConfig.IsSetHTTPPort())
{
xmlWriter.WriteElementString("HTTPPort", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.HTTPPort.ToString());
}
if (customOriginConfigCustomOriginConfig.IsSetHTTPSPort())
{
xmlWriter.WriteElementString("HTTPSPort", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.HTTPSPort.ToString());
}
if (customOriginConfigCustomOriginConfig.IsSetOriginProtocolPolicy())
{
xmlWriter.WriteElementString("OriginProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customOriginConfigCustomOriginConfig.OriginProtocolPolicy.ToString());
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
originsOriginsitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig != null)
{
DefaultCacheBehavior defaultCacheBehaviorDefaultCacheBehavior = distributionConfigDistributionConfig.DefaultCacheBehavior;
if (defaultCacheBehaviorDefaultCacheBehavior != null)
{
xmlWriter.WriteStartElement("DefaultCacheBehavior", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (defaultCacheBehaviorDefaultCacheBehavior.IsSetTargetOriginId())
{
xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.TargetOriginId.ToString());
}
if (defaultCacheBehaviorDefaultCacheBehavior != null)
{
ForwardedValues forwardedValuesForwardedValues = defaultCacheBehaviorDefaultCacheBehavior.ForwardedValues;
if (forwardedValuesForwardedValues != null)
{
xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (forwardedValuesForwardedValues.IsSetQueryString())
{
xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2013-08-26/", forwardedValuesForwardedValues.QueryString.ToString().ToLower());
}
if (forwardedValuesForwardedValues != null)
{
CookiePreference cookiePreferenceCookies = forwardedValuesForwardedValues.Cookies;
if (cookiePreferenceCookies != null)
{
xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cookiePreferenceCookies.IsSetForward())
{
xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookiePreferenceCookies.Forward.ToString());
}
if (cookiePreferenceCookies != null)
{
CookieNames cookieNamesWhitelistedNames = cookiePreferenceCookies.WhitelistedNames;
if (cookieNamesWhitelistedNames != null)
{
xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cookieNamesWhitelistedNames.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookieNamesWhitelistedNames.Quantity.ToString());
}
if (cookieNamesWhitelistedNames != null)
{
List<string> cookieNamesWhitelistedNamesitemsList = cookieNamesWhitelistedNames.Items;
if (cookieNamesWhitelistedNamesitemsList != null && cookieNamesWhitelistedNamesitemsList.Count > 0)
{
int cookieNamesWhitelistedNamesitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string cookieNamesWhitelistedNamesitemsListValue in cookieNamesWhitelistedNamesitemsList)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(cookieNamesWhitelistedNamesitemsListValue);
xmlWriter.WriteEndElement();
cookieNamesWhitelistedNamesitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (defaultCacheBehaviorDefaultCacheBehavior != null)
{
TrustedSigners trustedSignersTrustedSigners = defaultCacheBehaviorDefaultCacheBehavior.TrustedSigners;
if (trustedSignersTrustedSigners != null)
{
xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (trustedSignersTrustedSigners.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Enabled.ToString().ToLower());
}
if (trustedSignersTrustedSigners.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Quantity.ToString());
}
if (trustedSignersTrustedSigners != null)
{
List<string> trustedSignersTrustedSignersitemsList = trustedSignersTrustedSigners.Items;
if (trustedSignersTrustedSignersitemsList != null && trustedSignersTrustedSignersitemsList.Count > 0)
{
int trustedSignersTrustedSignersitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string trustedSignersTrustedSignersitemsListValue in trustedSignersTrustedSignersitemsList)
{
xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(trustedSignersTrustedSignersitemsListValue);
xmlWriter.WriteEndElement();
trustedSignersTrustedSignersitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (defaultCacheBehaviorDefaultCacheBehavior.IsSetViewerProtocolPolicy())
{
xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.ViewerProtocolPolicy.ToString());
}
if (defaultCacheBehaviorDefaultCacheBehavior.IsSetMinTTL())
{
xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", defaultCacheBehaviorDefaultCacheBehavior.MinTTL.ToString());
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig != null)
{
CacheBehaviors cacheBehaviorsCacheBehaviors = distributionConfigDistributionConfig.CacheBehaviors;
if (cacheBehaviorsCacheBehaviors != null)
{
xmlWriter.WriteStartElement("CacheBehaviors", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cacheBehaviorsCacheBehaviors.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviors.Quantity.ToString());
}
if (cacheBehaviorsCacheBehaviors != null)
{
List<CacheBehavior> cacheBehaviorsCacheBehaviorsitemsList = cacheBehaviorsCacheBehaviors.Items;
if (cacheBehaviorsCacheBehaviorsitemsList != null && cacheBehaviorsCacheBehaviorsitemsList.Count > 0)
{
int cacheBehaviorsCacheBehaviorsitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (CacheBehavior cacheBehaviorsCacheBehaviorsitemsListValue in cacheBehaviorsCacheBehaviorsitemsList)
{
xmlWriter.WriteStartElement("CacheBehavior", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetPathPattern())
{
xmlWriter.WriteElementString("PathPattern", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.PathPattern.ToString());
}
if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetTargetOriginId())
{
xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.TargetOriginId.ToString());
}
if (cacheBehaviorsCacheBehaviorsitemsListValue != null)
{
ForwardedValues forwardedValuesForwardedValues = cacheBehaviorsCacheBehaviorsitemsListValue.ForwardedValues;
if (forwardedValuesForwardedValues != null)
{
xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (forwardedValuesForwardedValues.IsSetQueryString())
{
xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2013-08-26/", forwardedValuesForwardedValues.QueryString.ToString().ToLower());
}
if (forwardedValuesForwardedValues != null)
{
CookiePreference cookiePreferenceCookies = forwardedValuesForwardedValues.Cookies;
if (cookiePreferenceCookies != null)
{
xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cookiePreferenceCookies.IsSetForward())
{
xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookiePreferenceCookies.Forward.ToString());
}
if (cookiePreferenceCookies != null)
{
CookieNames cookieNamesWhitelistedNames = cookiePreferenceCookies.WhitelistedNames;
if (cookieNamesWhitelistedNames != null)
{
xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (cookieNamesWhitelistedNames.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cookieNamesWhitelistedNames.Quantity.ToString());
}
if (cookieNamesWhitelistedNames != null)
{
List<string> cookieNamesWhitelistedNamesitemsList = cookieNamesWhitelistedNames.Items;
if (cookieNamesWhitelistedNamesitemsList != null && cookieNamesWhitelistedNamesitemsList.Count > 0)
{
int cookieNamesWhitelistedNamesitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string cookieNamesWhitelistedNamesitemsListValue in cookieNamesWhitelistedNamesitemsList)
{
xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(cookieNamesWhitelistedNamesitemsListValue);
xmlWriter.WriteEndElement();
cookieNamesWhitelistedNamesitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (cacheBehaviorsCacheBehaviorsitemsListValue != null)
{
TrustedSigners trustedSignersTrustedSigners = cacheBehaviorsCacheBehaviorsitemsListValue.TrustedSigners;
if (trustedSignersTrustedSigners != null)
{
xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (trustedSignersTrustedSigners.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Enabled.ToString().ToLower());
}
if (trustedSignersTrustedSigners.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Quantity.ToString());
}
if (trustedSignersTrustedSigners != null)
{
List<string> trustedSignersTrustedSignersitemsList = trustedSignersTrustedSigners.Items;
if (trustedSignersTrustedSignersitemsList != null && trustedSignersTrustedSignersitemsList.Count > 0)
{
int trustedSignersTrustedSignersitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string trustedSignersTrustedSignersitemsListValue in trustedSignersTrustedSignersitemsList)
{
xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(trustedSignersTrustedSignersitemsListValue);
xmlWriter.WriteEndElement();
trustedSignersTrustedSignersitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetViewerProtocolPolicy())
{
xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.ViewerProtocolPolicy.ToString());
}
if (cacheBehaviorsCacheBehaviorsitemsListValue.IsSetMinTTL())
{
xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", cacheBehaviorsCacheBehaviorsitemsListValue.MinTTL.ToString());
}
xmlWriter.WriteEndElement();
cacheBehaviorsCacheBehaviorsitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig != null)
{
CustomErrorResponses customErrorResponsesCustomErrorResponses = distributionConfigDistributionConfig.CustomErrorResponses;
if (customErrorResponsesCustomErrorResponses != null)
{
xmlWriter.WriteStartElement("CustomErrorResponses", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (customErrorResponsesCustomErrorResponses.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponses.Quantity.ToString());
}
if (customErrorResponsesCustomErrorResponses != null)
{
List<CustomErrorResponse> customErrorResponsesCustomErrorResponsesitemsList = customErrorResponsesCustomErrorResponses.Items;
if (customErrorResponsesCustomErrorResponsesitemsList != null && customErrorResponsesCustomErrorResponsesitemsList.Count > 0)
{
int customErrorResponsesCustomErrorResponsesitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (CustomErrorResponse customErrorResponsesCustomErrorResponsesitemsListValue in customErrorResponsesCustomErrorResponsesitemsList)
{
xmlWriter.WriteStartElement("CustomErrorResponse", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetErrorCode())
{
xmlWriter.WriteElementString("ErrorCode", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ErrorCode.ToString());
}
if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetResponsePagePath())
{
xmlWriter.WriteElementString("ResponsePagePath", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ResponsePagePath.ToString());
}
if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetResponseCode())
{
xmlWriter.WriteElementString("ResponseCode", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ResponseCode.ToString());
}
if (customErrorResponsesCustomErrorResponsesitemsListValue.IsSetErrorCachingMinTTL())
{
xmlWriter.WriteElementString("ErrorCachingMinTTL", "http://cloudfront.amazonaws.com/doc/2013-08-26/", customErrorResponsesCustomErrorResponsesitemsListValue.ErrorCachingMinTTL.ToString());
}
xmlWriter.WriteEndElement();
customErrorResponsesCustomErrorResponsesitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig.IsSetComment())
{
xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.Comment.ToString());
}
if (distributionConfigDistributionConfig != null)
{
LoggingConfig loggingConfigLogging = distributionConfigDistributionConfig.Logging;
if (loggingConfigLogging != null)
{
xmlWriter.WriteStartElement("Logging", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (loggingConfigLogging.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Enabled.ToString().ToLower());
}
if (loggingConfigLogging.IsSetIncludeCookies())
{
xmlWriter.WriteElementString("IncludeCookies", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.IncludeCookies.ToString().ToLower());
}
if (loggingConfigLogging.IsSetBucket())
{
xmlWriter.WriteElementString("Bucket", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Bucket.ToString());
}
if (loggingConfigLogging.IsSetPrefix())
{
xmlWriter.WriteElementString("Prefix", "http://cloudfront.amazonaws.com/doc/2013-08-26/", loggingConfigLogging.Prefix.ToString());
}
xmlWriter.WriteEndElement();
}
}
if (distributionConfigDistributionConfig.IsSetPriceClass())
{
xmlWriter.WriteElementString("PriceClass", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.PriceClass.ToString());
}
if (distributionConfigDistributionConfig.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", distributionConfigDistributionConfig.Enabled.ToString().ToLower());
}
if (distributionConfigDistributionConfig != null)
{
ViewerCertificate viewerCertificateViewerCertificate = distributionConfigDistributionConfig.ViewerCertificate;
if (viewerCertificateViewerCertificate != null)
{
xmlWriter.WriteStartElement("ViewerCertificate", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (viewerCertificateViewerCertificate.IsSetIAMCertificateId())
{
xmlWriter.WriteElementString("IAMCertificateId", "http://cloudfront.amazonaws.com/doc/2013-08-26/", viewerCertificateViewerCertificate.IAMCertificateId.ToString());
}
if (viewerCertificateViewerCertificate.IsSetCloudFrontDefaultCertificate())
{
xmlWriter.WriteElementString("CloudFrontDefaultCertificate", "http://cloudfront.amazonaws.com/doc/2013-08-26/", viewerCertificateViewerCertificate.CloudFrontDefaultCertificate.ToString().ToLower());
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
try
{
request.Content = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString());
request.Headers.Add("Content-Type", "application/xml");
}
catch (EncoderFallbackException e)
{
throw new AmazonServiceException("Unable to marshall request to XML", e);
}
return request;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
public static class SocketTaskExtensions
{
public static Task<Socket> AcceptAsync(this Socket socket)
{
return Task<Socket>.Factory.FromAsync(
(callback, state) => ((Socket)state).BeginAccept(callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndAccept(asyncResult),
state: socket);
}
public static Task<Socket> AcceptAsync(this Socket socket, Socket acceptSocket)
{
const int ReceiveSize = 0;
return Task<Socket>.Factory.FromAsync(
(socketForAccept, receiveSize, callback, state) => ((Socket)state).BeginAccept(socketForAccept, receiveSize, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndAccept(asyncResult),
acceptSocket,
ReceiveSize,
state: socket);
}
public static Task ConnectAsync(this Socket socket, EndPoint remoteEndPoint)
{
return Task.Factory.FromAsync(
(targetEndPoint, callback, state) => ((Socket)state).BeginConnect(targetEndPoint, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult),
remoteEndPoint,
state: socket);
}
public static Task ConnectAsync(this Socket socket, IPAddress address, int port)
{
return Task.Factory.FromAsync(
(targetAddress, targetPort, callback, state) => ((Socket)state).BeginConnect(targetAddress, targetPort, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult),
address,
port,
state: socket);
}
public static Task ConnectAsync(this Socket socket, IPAddress[] addresses, int port)
{
return Task.Factory.FromAsync(
(targetAddresses, targetPort, callback, state) => ((Socket)state).BeginConnect(targetAddresses, targetPort, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult),
addresses,
port,
state: socket);
}
public static Task ConnectAsync(this Socket socket, string host, int port)
{
return Task.Factory.FromAsync(
(targetHost, targetPort, callback, state) => ((Socket)state).BeginConnect(targetHost, targetPort, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult),
host,
port,
state: socket);
}
public static Task<int> ReceiveAsync(this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags)
{
return Task<int>.Factory.FromAsync(
(targetBuffer, flags, callback, state) => ((Socket)state).BeginReceive(
targetBuffer.Array,
targetBuffer.Offset,
targetBuffer.Count,
flags,
callback,
state),
asyncResult => ((Socket)asyncResult.AsyncState).EndReceive(asyncResult),
buffer,
socketFlags,
state: socket);
}
public static Task<int> ReceiveAsync(
this Socket socket,
IList<ArraySegment<byte>> buffers,
SocketFlags socketFlags)
{
return Task<int>.Factory.FromAsync(
(targetBuffers, flags, callback, state) => ((Socket)state).BeginReceive(targetBuffers, flags, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndReceive(asyncResult),
buffers,
socketFlags,
state: socket);
}
public static Task<SocketReceiveFromResult> ReceiveFromAsync(
this Socket socket,
ArraySegment<byte> buffer,
SocketFlags socketFlags,
EndPoint remoteEndPoint)
{
object[] packedArguments = new object[] { socket, remoteEndPoint };
return Task<SocketReceiveFromResult>.Factory.FromAsync(
(targetBuffer, flags, callback, state) =>
{
var arguments = (object[])state;
var s = (Socket)arguments[0];
var e = (EndPoint)arguments[1];
IAsyncResult result = s.BeginReceiveFrom(
targetBuffer.Array,
targetBuffer.Offset,
targetBuffer.Count,
flags,
ref e,
callback,
state);
arguments[1] = e;
return result;
},
asyncResult =>
{
var arguments = (object[])asyncResult.AsyncState;
var s = (Socket)arguments[0];
var e = (EndPoint)arguments[1];
int bytesReceived = s.EndReceiveFrom(asyncResult, ref e);
return new SocketReceiveFromResult()
{
ReceivedBytes = bytesReceived,
RemoteEndPoint = e
};
},
buffer,
socketFlags,
state: packedArguments);
}
public static Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(
this Socket socket,
ArraySegment<byte> buffer,
SocketFlags socketFlags,
EndPoint remoteEndPoint)
{
object[] packedArguments = new object[] { socket, socketFlags, remoteEndPoint };
return Task<SocketReceiveMessageFromResult>.Factory.FromAsync(
(targetBuffer, callback, state) =>
{
var arguments = (object[])state;
var s = (Socket)arguments[0];
var f = (SocketFlags)arguments[1];
var e = (EndPoint)arguments[2];
IAsyncResult result = s.BeginReceiveMessageFrom(
targetBuffer.Array,
targetBuffer.Offset,
targetBuffer.Count,
f,
ref e,
callback,
state);
arguments[2] = e;
return result;
},
asyncResult =>
{
var arguments = (object[])asyncResult.AsyncState;
var s = (Socket)arguments[0];
var f = (SocketFlags)arguments[1];
var e = (EndPoint)arguments[2];
IPPacketInformation ipPacket;
int bytesReceived = s.EndReceiveMessageFrom(
asyncResult,
ref f,
ref e,
out ipPacket);
return new SocketReceiveMessageFromResult()
{
PacketInformation = ipPacket,
ReceivedBytes = bytesReceived,
RemoteEndPoint = e,
SocketFlags = f
};
},
buffer,
state: packedArguments);
}
public static Task<int> SendAsync(this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags)
{
return Task<int>.Factory.FromAsync(
(targetBuffer, flags, callback, state) => ((Socket)state).BeginSend(
targetBuffer.Array,
targetBuffer.Offset,
targetBuffer.Count,
flags,
callback,
state),
asyncResult => ((Socket)asyncResult.AsyncState).EndSend(asyncResult),
buffer,
socketFlags,
state: socket);
}
public static Task<int> SendAsync(
this Socket socket,
IList<ArraySegment<byte>> buffers,
SocketFlags socketFlags)
{
return Task<int>.Factory.FromAsync(
(targetBuffers, flags, callback, state) => ((Socket)state).BeginSend(targetBuffers, flags, callback, state),
asyncResult => ((Socket)asyncResult.AsyncState).EndSend(asyncResult),
buffers,
socketFlags,
state: socket);
}
public static Task<int> SendToAsync(
this Socket socket,
ArraySegment<byte> buffer,
SocketFlags socketFlags,
EndPoint remoteEndPoint)
{
return Task<int>.Factory.FromAsync(
(targetBuffer, flags, endPoint, callback, state) => ((Socket)state).BeginSendTo(
targetBuffer.Array,
targetBuffer.Offset,
targetBuffer.Count,
flags,
endPoint,
callback,
state),
asyncResult => ((Socket)asyncResult.AsyncState).EndSendTo(asyncResult),
buffer,
socketFlags,
remoteEndPoint,
state: socket);
}
}
}
| |
/*
* 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 log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.RegionLoader.Filesystem;
using OpenSim.Framework.RegionLoader.Web;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace OpenSim.ApplicationPlugins.LoadRegions
{
public class LoadRegionsPlugin : IApplicationPlugin, IRegionCreator
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private NewRegionCreated m_newRegionCreatedHandler;
public event NewRegionCreated OnNewRegionCreated;
#region IApplicationPlugin Members
protected OpenSimBase m_openSim;
// TODO: required by IPlugin, but likely not at all right
private string m_name = "LoadRegionsPlugin";
private string m_version = "0.0";
public string Name
{
get { return m_name; }
}
public string Version
{
get { return m_version; }
}
public void Dispose()
{
}
public void Initialise()
{
m_log.Error("[LOAD REGIONS PLUGIN]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
public void Initialise(OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionCreator>(this);
}
public void PostInitialise()
{
//m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (m_openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from web");
regionLoader = new RegionLoaderWebServer();
}
regionLoader.SetIniConfigSource(m_openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
m_log.Info("[LOAD REGIONS PLUGIN]: Loading specific shared modules...");
//m_log.Info("[LOAD REGIONS PLUGIN]: DynamicTextureModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule());
//m_log.Info("[LOAD REGIONS PLUGIN]: LoadImageURLModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule());
//m_log.Info("[LOAD REGIONS PLUGIN]: XMLRPCModule...");
//m_openSim.ModuleLoader.LoadDefaultSharedModule(new XMLRPCModule());
// m_log.Info("[LOADREGIONSPLUGIN]: AssetTransactionModule...");
// m_openSim.ModuleLoader.LoadDefaultSharedModule(new AssetTransactionModule());
m_log.Info("[LOAD REGIONS PLUGIN]: Done.");
if (!CheckRegionsForSanity(regionsToLoad))
{
m_log.Error("[LOAD REGIONS PLUGIN]: Halting startup due to conflicts in region configurations");
Environment.Exit(1);
}
List<IScene> createdScenes = new List<IScene>();
for (int i = 0; i < regionsToLoad.Length; i++)
{
IScene scene;
m_log.Debug("[LOAD REGIONS PLUGIN]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() +
")");
bool changed = m_openSim.PopulateRegionEstateInfo(regionsToLoad[i]);
m_openSim.CreateRegion(regionsToLoad[i], true, out scene);
createdScenes.Add(scene);
if (changed)
regionsToLoad[i].EstateSettings.Save();
}
foreach (IScene scene in createdScenes)
{
scene.Start();
m_newRegionCreatedHandler = OnNewRegionCreated;
if (m_newRegionCreatedHandler != null)
{
m_newRegionCreatedHandler(scene);
}
}
}
#endregion IApplicationPlugin Members
/// <summary>
/// Check that region configuration information makes sense.
/// </summary>
/// <param name="regions"></param>
/// <returns>True if we're sane, false if we're insane</returns>
private bool CheckRegionsForSanity(RegionInfo[] regions)
{
if (regions.Length == 0)
return true;
foreach (RegionInfo region in regions)
{
if (region.RegionID == UUID.Zero)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Region {0} has invalid UUID {1}",
region.RegionName, region.RegionID);
return false;
}
}
for (int i = 0; i < regions.Length - 1; i++)
{
for (int j = i + 1; j < regions.Length; j++)
{
if (regions[i].RegionID == regions[j].RegionID)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same UUID {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionID);
return false;
}
else if (
regions[i].RegionLocX == regions[j].RegionLocX && regions[i].RegionLocY == regions[j].RegionLocY)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same grid location ({2}, {3})",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionLocX, regions[i].RegionLocY);
return false;
}
else if (regions[i].InternalEndPoint.Port == regions[j].InternalEndPoint.Port)
{
m_log.ErrorFormat(
"[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same internal IP port {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].InternalEndPoint.Port);
return false;
}
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
namespace NuGet
{
public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, IServiceBasedRepository, ICloneableRepository, ICultureAwareRepository, IOperationAwareRepository
{
private IDataServiceContext _context;
private readonly IHttpClient _httpClient;
private readonly PackageDownloader _packageDownloader;
private CultureInfo _culture;
private const string FindPackagesByIdSvcMethod = "FindPackagesById";
private const string SearchSvcMethod = "Search";
private const string GetUpdatesSvcMethod = "GetUpdates";
// Just forward calls to the package downloader
public event EventHandler<ProgressEventArgs> ProgressAvailable
{
add
{
_packageDownloader.ProgressAvailable += value;
}
remove
{
_packageDownloader.ProgressAvailable -= value;
}
}
public event EventHandler<WebRequestEventArgs> SendingRequest
{
add
{
_packageDownloader.SendingRequest += value;
_httpClient.SendingRequest += value;
}
remove
{
_packageDownloader.SendingRequest -= value;
_httpClient.SendingRequest -= value;
}
}
public PackageDownloader PackageDownloader
{
get { return _packageDownloader; }
}
public string CurrentOperation { get; private set; }
public DataServicePackageRepository(Uri serviceRoot)
: this(new HttpClient(serviceRoot))
{
}
public DataServicePackageRepository(IHttpClient client)
: this(client, new PackageDownloader())
{
}
public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
if (packageDownloader == null)
{
throw new ArgumentNullException("packageDownloader");
}
_httpClient = client;
_httpClient.AcceptCompression = true;
_packageDownloader = packageDownloader;
SendingRequest += (sender, e) =>
{
if (!String.IsNullOrEmpty(CurrentOperation))
{
e.Request.Headers[RepositoryOperationNames.OperationHeaderName] = CurrentOperation;
}
};
}
public CultureInfo Culture
{
get
{
if (_culture == null)
{
// TODO: Technically, if this is a remote server, we have to return the culture of the server
// instead of invariant culture. However, there is no trivial way to retrieve the server's culture,
// So temporarily use Invariant culture here.
_culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture;
}
return _culture;
}
}
public override string Source
{
get
{
return _httpClient.Uri.OriginalString;
}
}
public override bool SupportsPrereleasePackages
{
get
{
return Context.SupportsProperty("IsAbsoluteLatestVersion");
}
}
// Don't initialize the Context at the constructor time so that
// we don't make a web request if we are not going to actually use it
// since getting the Uri property of the RedirectedHttpClient will
// trigger that functionality.
internal IDataServiceContext Context
{
private get
{
if (_context == null)
{
_context = new DataServiceContextWrapper(_httpClient.Uri);
_context.SendingRequest += OnSendingRequest;
_context.ReadingEntity += OnReadingEntity;
_context.IgnoreMissingProperties = true;
}
return _context;
}
set
{
_context = value;
}
}
private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e)
{
var package = (DataServicePackage)e.Entity;
// REVIEW: This is the only way (I know) to download the package on demand
// GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage
package.Context = Context;
package.Downloader = _packageDownloader;
}
private void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
// Initialize the request
_httpClient.InitializeRequest(e.Request);
}
public override IQueryable<IPackage> GetPackages()
{
// REVIEW: Is it ok to assume that the package entity set is called packages?
return new SmartDataServiceQuery<DataServicePackage>(Context, Constants.PackageServiceEntitySetName);
}
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (!Context.SupportsServiceMethod(SearchSvcMethod))
{
// If there's no search method then we can't filter by target framework
return GetPackages().Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
}
// Convert the list of framework names into short names
var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name))
.Select(VersionUtility.GetShortFrameworkName);
// Create a '|' separated string of framework names
string targetFrameworkString = String.Join("|", shortFrameworkNames);
var searchParameters = new Dictionary<string, object> {
{ "searchTerm", "'" + UrlEncodeOdataParameter(searchTerm) + "'" },
{ "targetFramework", "'" + UrlEncodeOdataParameter(targetFrameworkString) + "'" },
};
if (SupportsPrereleasePackages)
{
searchParameters.Add("includePrerelease", ToString(allowPrereleaseVersions));
}
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(SearchSvcMethod, searchParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IEnumerable<IPackage> FindPackagesById(string packageId)
{
if (!Context.SupportsServiceMethod(FindPackagesByIdSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.FindPackagesByIdCore(this, packageId);
}
var serviceParameters = new Dictionary<string, object> {
{ "id", "'" + UrlEncodeOdataParameter(packageId) + "'" }
};
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackage> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks)
{
if (!Context.SupportsServiceMethod(GetUpdatesSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.GetUpdatesCore(this, packages, includePrerelease, includeAllVersions, targetFrameworks);
}
// Pipe all the things!
string ids = String.Join("|", packages.Select(p => p.Id));
string versions = String.Join("|", packages.Select(p => p.Version.ToString()));
string targetFrameworksValue = targetFrameworks.IsEmpty() ? "" : String.Join("|", targetFrameworks.Select(VersionUtility.GetShortFrameworkName));
var serviceParameters = new Dictionary<string, object> {
{ "packageIds", "'" + ids + "'" },
{ "versions", "'" + versions + "'" },
{ "includePrerelease", ToString(includePrerelease) },
{ "includeAllVersions", ToString(includeAllVersions) },
{ "targetFrameworks", "'" + UrlEncodeOdataParameter(targetFrameworksValue) + "'" },
};
var query = Context.CreateQuery<DataServicePackage>(GetUpdatesSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IPackageRepository Clone()
{
return new DataServicePackageRepository(_httpClient, _packageDownloader);
}
public IDisposable StartOperation(string operation)
{
string oldOperation = CurrentOperation;
CurrentOperation = operation;
return new DisposableAction(() =>
{
CurrentOperation = oldOperation;
});
}
private static string UrlEncodeOdataParameter(string value)
{
if (!String.IsNullOrEmpty(value))
{
// OData requires that a single quote MUST be escaped as 2 single quotes.
// In .NET 4.5, Uri.EscapeDataString() escapes single quote as %27. Thus we must replace %27 with 2 single quotes.
// In .NET 4.0, Uri.EscapeDataString() doesn't escape single quote. Thus we must replace it with 2 single quotes.
return Uri.EscapeDataString(value).Replace("'", "''").Replace("%27", "''");
}
return value;
}
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")]
private static string ToString(bool value)
{
return value.ToString().ToLowerInvariant();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.Cci.Comparers;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
// writeInline => [ , , ] vs []\n[]\n
public void WriteAttributes(IEnumerable<ISecurityAttribute> securityAttributes, bool writeInline = false, string prefix = "")
{
if (!securityAttributes.SelectMany(s => s.Attributes).Any(IncludeAttribute))
return;
securityAttributes = securityAttributes.OrderBy(s => s.Action.ToString(), StringComparer.OrdinalIgnoreCase);
bool first = true;
WriteSymbol("[");
foreach (ISecurityAttribute securityAttribute in securityAttributes)
{
foreach (ICustomAttribute attribute in securityAttribute.Attributes)
{
if (!first)
{
if (writeInline)
{
WriteSymbol(",", addSpace: true);
}
else
{
WriteSymbol("]");
_writer.WriteLine();
WriteSymbol("[");
}
}
WriteAttribute(attribute, prefix, securityAttribute.Action);
first = false;
}
}
WriteSymbol("]");
if (!writeInline)
_writer.WriteLine();
}
private static FakeCustomAttribute s_methodImpl = new FakeCustomAttribute("System.Runtime.CompilerServices", "MethodImpl");
private static FakeCustomAttribute s_dllImport = new FakeCustomAttribute("System.Runtime.InteropServices", "DllImport");
private void WriteMethodPseudoCustomAttributes(IMethodDefinition method)
{
// Decided not to put more information (parameters) here as that would have introduced a lot of noise.
if (method.IsPlatformInvoke)
{
if (IncludeAttribute(s_dllImport))
{
string typeName = _forCompilation ? s_dllImport.FullTypeName : s_dllImport.TypeName;
WriteFakeAttribute(typeName, writeInline: true, parameters: "\"" + method.PlatformInvokeData.ImportModule.Name.Value + "\"");
}
}
var ops = CreateMethodImplOptions(method);
if (ops != default(System.Runtime.CompilerServices.MethodImplOptions))
{
if (IncludeAttribute(s_methodImpl))
{
string typeName = _forCompilation ? s_methodImpl.FullTypeName : s_methodImpl.TypeName;
string enumValue = _forCompilation ? string.Join("|", ops.ToString().Split('|').Select(x => "System.Runtime.CompilerServices.MethodImplOptions." + x)) : ops.ToString();
WriteFakeAttribute(typeName, writeInline: true, parameters: enumValue);
}
}
}
private System.Runtime.CompilerServices.MethodImplOptions CreateMethodImplOptions(IMethodDefinition method)
{
// Some options are not exposed in portable contracts. PortingHelpers.cs exposes the missing constants.
System.Runtime.CompilerServices.MethodImplOptions options = default(System.Runtime.CompilerServices.MethodImplOptions);
if (method.IsUnmanaged)
options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Unmanaged;
if (method.IsForwardReference)
options |= System.Runtime.CompilerServices.MethodImplOptionsEx.ForwardRef;
if (method.PreserveSignature)
options |= System.Runtime.CompilerServices.MethodImplOptions.PreserveSig;
if (method.IsRuntimeInternal)
options |= System.Runtime.CompilerServices.MethodImplOptionsEx.InternalCall;
if (method.IsSynchronized)
options |= System.Runtime.CompilerServices.MethodImplOptionsEx.Synchronized;
if (method.IsNeverInlined)
options |= System.Runtime.CompilerServices.MethodImplOptions.NoInlining;
if (method.IsAggressivelyInlined)
options |= System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining;
if (method.IsNeverOptimized)
options |= System.Runtime.CompilerServices.MethodImplOptions.NoOptimization;
return options;
}
public void WriteAttributes(IEnumerable<ICustomAttribute> attributes, bool writeInline = false, string prefix = null)
{
attributes = attributes.Where(IncludeAttribute);
if (!attributes.Any())
return;
attributes = attributes.OrderBy(a => a, new AttributeComparer(_filter, _forCompilation));
bool first = true;
WriteSymbol("[");
foreach (ICustomAttribute attribute in attributes)
{
if (!first)
{
if (writeInline)
{
WriteSymbol(",", addSpace: true);
}
else
{
WriteSymbol("]");
_writer.WriteLine();
WriteSymbol("[");
}
}
WriteAttribute(attribute, prefix);
first = false;
}
WriteSymbol("]");
if (!writeInline)
_writer.WriteLine();
}
public void WriteAttribute(ICustomAttribute attribute, string prefix = null, SecurityAction action = SecurityAction.ActionNil)
{
if (!string.IsNullOrEmpty(prefix))
{
Write(prefix);
WriteSymbol(":");
}
WriteTypeName(attribute.Constructor.ContainingType, noSpace: true); // Should we strip Attribute from name?
if (attribute.NumberOfNamedArguments > 0 || attribute.Arguments.Any() || action != SecurityAction.ActionNil)
{
WriteSymbol("(");
bool first = true;
if (action != SecurityAction.ActionNil)
{
Write("System.Security.Permissions.SecurityAction." + action.ToString());
first = false;
}
foreach (IMetadataExpression arg in attribute.Arguments)
{
if (!first) WriteSymbol(",", true);
WriteMetadataExpression(arg);
first = false;
}
foreach (IMetadataNamedArgument namedArg in attribute.NamedArguments)
{
if (!first) WriteSymbol(",", true);
WriteIdentifier(namedArg.ArgumentName);
WriteSymbol("=");
WriteMetadataExpression(namedArg.ArgumentValue);
first = false;
}
WriteSymbol(")");
}
}
private void WriteFakeAttribute(string typeName, params string[] parameters)
{
WriteFakeAttribute(typeName, false, parameters);
}
private void WriteFakeAttribute(string typeName, bool writeInline, params string[] parameters)
{
// These fake attributes are really only useful for the compilers
if (!_forCompilation && !_includeFakeAttributes)
return;
if (_forCompilationIncludeGlobalprefix)
typeName = "global::" + typeName;
WriteSymbol("[");
_writer.WriteTypeName(typeName);
if (parameters.Length > 0)
{
WriteSymbol("(");
_writer.WriteList(parameters, p =>
{
if (_forCompilationIncludeGlobalprefix)
p = "global::" + p;
Write(p);
});
WriteSymbol(")");
}
WriteSymbol("]");
if (!writeInline)
_writer.WriteLine();
}
private void WriteMetadataExpression(IMetadataExpression expression)
{
IMetadataConstant constant = expression as IMetadataConstant;
if (constant != null)
{
WriteMetadataConstant(constant);
return;
}
IMetadataCreateArray array = expression as IMetadataCreateArray;
if (array != null)
{
WriteMetadataArray(array);
return;
}
IMetadataTypeOf type = expression as IMetadataTypeOf;
if (type != null)
{
WriteKeyword("typeof", noSpace: true);
WriteSymbol("(");
WriteTypeName(type.TypeToGet, noSpace: true);
WriteSymbol(")");
return;
}
throw new NotSupportedException("IMetadataExpression type not supported");
}
private void WriteMetadataConstant(IMetadataConstant constant, ITypeReference constantType = null)
{
object value = constant.Value;
ITypeReference type = (constantType == null ? constant.Type : constantType);
if (value == null)
{
if (type.IsValueType)
{
// Write default(T) for value types
WriteDefaultOf(type);
}
else
{
WriteKeyword("null", noSpace: true);
}
}
else if (type.ResolvedType.IsEnum)
{
//TODO: Do a better job translating the Enum value.
WriteSymbol("(");
WriteTypeName(type, noSpace: true);
WriteSymbol(")");
WriteSymbol("("); // Wrap value in parens to avoid issues with negative values
Write(value.ToString());
WriteSymbol(")");
}
else if (value is string)
{
Write(QuoteString((string)value));
}
else if (value is char)
{
Write(String.Format("'{0}'", EscapeChar((char)value, false)));
}
else if (value is double)
{
double val = (double)value;
if (double.IsNegativeInfinity(val))
Write("-1.0 / 0.0");
else if (double.IsPositiveInfinity(val))
Write("1.0 / 0.0");
else if (double.IsNaN(val))
Write("0.0 / 0.0");
else
Write(((double)value).ToString("R", CultureInfo.InvariantCulture));
}
else if (value is float)
{
float val = (float)value;
if (float.IsNegativeInfinity(val))
Write("-1.0f / 0.0f");
else if (float.IsPositiveInfinity(val))
Write("1.0f / 0.0f");
else if (float.IsNaN(val))
Write("0.0f / 0.0f");
else
Write(((float)value).ToString("R", CultureInfo.InvariantCulture) + "f");
}
else if (value is bool)
{
if ((bool)value)
WriteKeyword("true", noSpace: true);
else
WriteKeyword("false", noSpace: true);
}
else if (value is int)
{
// int is the default and most used constant value so lets
// special case int to avoid a bunch of useless casts.
Write(value.ToString());
}
else
{
// Explicitly cast the value so that we avoid any signed/unsigned resolution issues
WriteSymbol("(");
WriteTypeName(type, noSpace: true);
WriteSymbol(")");
Write(value.ToString());
}
// Might need to add support for other types...
}
private void WriteMetadataArray(IMetadataCreateArray array)
{
bool first = true;
WriteKeyword("new");
WriteTypeName(array.Type, noSpace: true);
WriteSymbol("{", addSpace: true);
foreach (IMetadataExpression expr in array.Initializers)
{
if (first) { first = false; } else { WriteSymbol(",", true); }
WriteMetadataExpression(expr);
}
WriteSymbol("}");
}
private static string QuoteString(string str)
{
StringBuilder sb = new StringBuilder(str.Length + 4);
sb.Append("\"");
foreach (char ch in str)
{
sb.Append(EscapeChar(ch, true));
}
sb.Append("\"");
return sb.ToString();
}
private static string EscapeChar(char c, bool inString)
{
switch (c)
{
case '\r': return @"\r";
case '\n': return @"\n";
case '\f': return @"\f";
case '\t': return @"\t";
case '\v': return @"\v";
case '\0': return @"\0";
case '\a': return @"\a";
case '\b': return @"\b";
case '\\': return @"\\";
case '\'': return inString ? "'" : @"\'";
case '"': return inString ? "\\\"" : "\"";
}
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
if (cat == UnicodeCategory.Control ||
cat == UnicodeCategory.LineSeparator ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.Surrogate ||
cat == UnicodeCategory.PrivateUse ||
cat == UnicodeCategory.OtherNotAssigned)
return String.Format("\\u{0:X4}", (int)c);
return c.ToString();
}
private static bool ExcludeSpecialAttribute(ICustomAttribute c)
{
string typeName = c.FullName();
switch (typeName)
{
case "System.Runtime.CompilerServices.FixedBufferAttribute": return true;
case "System.ParamArrayAttribute": return true;
case "System.Reflection.DefaultMemberAttribute": return true;
case "System.Reflection.AssemblyKeyFileAttribute": return true;
case "System.Reflection.AssemblyDelaySignAttribute": return true;
case "System.Runtime.CompilerServices.ExtensionAttribute": return true;
case "System.Runtime.CompilerServices.DynamicAttribute": return true;
}
return false;
}
private static bool IsDynamic(IEnumerable<ICustomAttribute> attributes)
{
foreach (var attribute in attributes)
{
if (attribute.Type.AreEquivalent("System.Runtime.CompilerServices.DynamicAttribute"))
return true;
}
return false;
}
private bool IncludeAttribute(ICustomAttribute attribute)
{
if (ExcludeSpecialAttribute(attribute))
return false;
return _filter.Include(attribute);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
#nullable enable
namespace Telegram.Bot.Tests.Integ.Framework
{
public class UpdateReceiver
{
readonly ITelegramBotClient _botClient;
public List<string> AllowedUsernames { get; }
public UpdateReceiver(ITelegramBotClient botClient, IEnumerable<string>? allowedUsernames)
{
_botClient = botClient;
AllowedUsernames = allowedUsernames?.ToList() ?? new();
}
public async Task DiscardNewUpdatesAsync(CancellationToken cancellationToken = default)
{
CancellationTokenSource? cts = default;
try
{
if (cancellationToken == default)
{
cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
cancellationToken = cts.Token;
}
int offset = -1;
while (!cancellationToken.IsCancellationRequested)
{
var updates = await _botClient.GetUpdatesAsync(
offset,
allowedUpdates: Array.Empty<UpdateType>(),
cancellationToken: cancellationToken
);
if (updates.Length == 0) break;
offset = updates[^1].Id + 1;
}
}
finally
{
cts?.Dispose();
}
}
public async Task<Update[]> GetUpdatesAsync(
Func<Update, bool>? predicate = default,
int offset = 0,
CancellationToken cancellationToken = default,
params UpdateType[] updateTypes)
{
CancellationTokenSource? cts = default;
predicate ??= PassthroughPredicate;
try
{
if (cancellationToken == default)
{
cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
cancellationToken = cts.Token;
}
Update[] matchingUpdates = Array.Empty<Update>();
while (!cancellationToken.IsCancellationRequested)
{
Update[] updates = await GetOnlyAllowedUpdatesAsync(
offset: offset,
types: updateTypes,
cancellationToken: cancellationToken
);
matchingUpdates = updates
.Where(u => updateTypes.Contains(u.Type) && predicate(u))
.ToArray();
if (matchingUpdates.Length > 0) { break; }
offset = updates.LastOrDefault()?.Id + 1 ?? 0;
await Task.Delay(TimeSpan.FromSeconds(1.5), cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
return matchingUpdates;
}
finally
{
cts?.Dispose();
}
static bool PassthroughPredicate(Update _) => true;
}
public async Task<Update> GetCallbackQueryUpdateAsync(
int? messageId = default,
string? data = default,
bool discardNewUpdates = true,
CancellationToken cancellationToken = default)
{
if (discardNewUpdates) { await DiscardNewUpdatesAsync(cancellationToken); }
var updates = await GetUpdatesAsync(
predicate: u => (messageId == default || u.CallbackQuery?.Message?.MessageId == messageId) &&
(data == default || u.CallbackQuery?.Data == data),
updateTypes: new [] { UpdateType.CallbackQuery },
cancellationToken: cancellationToken
);
if (discardNewUpdates) { await DiscardNewUpdatesAsync(cancellationToken); }
var update = updates.First();
return update;
}
public async Task<Update> GetInlineQueryUpdateAsync(
bool discardNewUpdates = true,
CancellationToken cancellationToken = default)
{
if (discardNewUpdates) { await DiscardNewUpdatesAsync(cancellationToken); }
var updates = await GetUpdatesAsync(
updateTypes: new [] { UpdateType.InlineQuery },
cancellationToken: cancellationToken
);
if (discardNewUpdates) { await DiscardNewUpdatesAsync(cancellationToken); }
var update = updates.First();
return update;
}
/// <summary>
/// Receive the chosen inline query result and the message that was sent to chat. Use this method only after
/// bot answers to an inline query.
/// </summary>
/// <param name="chatId">Id of the chat where the message from inline query is excepted</param>
/// <param name="messageType">Type of message for chosen inline query e.g. Text message for article results</param>
/// <param name="cancellationToken"></param>
/// <returns>Message update generated for chosen result, and the update for chosen inline query result</returns>
public async Task<(Update MessageUpdate, Update ChosenResultUpdate)> GetInlineQueryResultUpdates(
long chatId,
MessageType messageType,
CancellationToken cancellationToken = default)
{
Update? messageUpdate = default;
Update? chosenResultUpdate = default;
while (ShouldContinue(cancellationToken, (messageUpdate, chosenResultUpdate)))
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
var updates = await GetUpdatesAsync(
predicate: u => (u.Message is { Chat: { Id: var id }, Type: var type } && id == chatId && type == messageType) ||
(u.ChosenInlineResult is not null),
cancellationToken: cancellationToken,
updateTypes: new[] { UpdateType.Message, UpdateType.ChosenInlineResult }
);
messageUpdate = updates.SingleOrDefault(u => u.Message?.Type == messageType);
chosenResultUpdate = updates.SingleOrDefault(u => u.Type == UpdateType.ChosenInlineResult);
}
cancellationToken.ThrowIfCancellationRequested();
return (messageUpdate!, chosenResultUpdate!);
static bool ShouldContinue(CancellationToken cancellationToken, (Update? update1, Update? update2) updates) =>
!cancellationToken.IsCancellationRequested && updates is not ({}, {});
}
async Task<Update[]> GetOnlyAllowedUpdatesAsync(
int offset,
CancellationToken cancellationToken,
params UpdateType[] types)
{
var updates = await _botClient.GetUpdatesAsync(
offset: offset,
timeout: 120,
allowedUpdates: types,
cancellationToken: cancellationToken
);
return updates.Where(IsAllowed).ToArray();
}
bool IsAllowed(Update update)
{
if (AllowedUsernames.All(string.IsNullOrWhiteSpace)) { return true; }
return update.Type switch
{
UpdateType.Message
or UpdateType.InlineQuery
or UpdateType.CallbackQuery
or UpdateType.PreCheckoutQuery
or UpdateType.ShippingQuery
or UpdateType.ChosenInlineResult
or UpdateType.PollAnswer
or UpdateType.ChatMember
or UpdateType.MyChatMember =>
AllowedUsernames.Contains(
update.GetUser()?.Username,
StringComparer.OrdinalIgnoreCase
),
UpdateType.Poll => true,
UpdateType.EditedMessage or UpdateType.ChannelPost or UpdateType.EditedChannelPost => false,
_ => throw new ArgumentOutOfRangeException(
paramName: nameof(update.Type),
actualValue: update.Type,
message: $"Unsupported update type {update.Type}"
),
};
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Internal;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Internal
{
internal class ProcessEx : IDisposable
{
private static readonly TimeSpan DefaultProcessTimeout = TimeSpan.FromMinutes(15);
private static readonly string NUGET_PACKAGES = GetNugetPackagesRestorePath();
private readonly ITestOutputHelper _output;
private readonly Process _process;
private readonly StringBuilder _stderrCapture;
private readonly StringBuilder _stdoutCapture;
private readonly object _pipeCaptureLock = new object();
private readonly object _testOutputLock = new object();
private BlockingCollection<string> _stdoutLines;
private readonly TaskCompletionSource<int> _exited;
private readonly CancellationTokenSource _stdoutLinesCancellationSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));
private readonly CancellationTokenSource _processTimeoutCts;
private bool _disposed;
public ProcessEx(ITestOutputHelper output, Process proc, TimeSpan timeout)
{
_output = output;
_stdoutCapture = new StringBuilder();
_stderrCapture = new StringBuilder();
_stdoutLines = new BlockingCollection<string>();
_exited = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_process = proc;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += OnOutputData;
proc.ErrorDataReceived += OnErrorData;
proc.Exited += OnProcessExited;
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
// We greedily create a timeout exception message even though a timeout is unlikely to happen for two reasons:
// 1. To make it less likely for Process getters to throw exceptions like "System.InvalidOperationException: Process has exited, ..."
// 2. To ensure if/when exceptions are thrown from Process getters, these exceptions can easily be observed.
var timeoutExMessage = $"Process proc {proc.ProcessName} {proc.StartInfo.Arguments} timed out after {timeout}.";
_processTimeoutCts = new CancellationTokenSource(timeout);
_processTimeoutCts.Token.Register(() =>
{
_exited.TrySetException(new TimeoutException(timeoutExMessage));
});
}
public Process Process => _process;
public Task Exited => _exited.Task;
public bool HasExited => _process.HasExited;
public string Error
{
get
{
lock (_pipeCaptureLock)
{
return _stderrCapture.ToString();
}
}
}
public string Output
{
get
{
lock (_pipeCaptureLock)
{
return _stdoutCapture.ToString();
}
}
}
public IEnumerable<string> OutputLinesAsEnumerable => _stdoutLines.GetConsumingEnumerable(_stdoutLinesCancellationSource.Token);
public int ExitCode => _process.ExitCode;
public object Id => _process.Id;
public static ProcessEx Run(ITestOutputHelper output, string workingDirectory, string command, string args = null, IDictionary<string, string> envVars = null, TimeSpan? timeout = default)
{
var startInfo = new ProcessStartInfo(command, args)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = workingDirectory
};
if (envVars != null)
{
foreach (var envVar in envVars)
{
startInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
}
}
startInfo.EnvironmentVariables["NUGET_PACKAGES"] = NUGET_PACKAGES;
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("helix")))
{
startInfo.EnvironmentVariables["NUGET_FALLBACK_PACKAGES"] = Environment.GetEnvironmentVariable("NUGET_FALLBACK_PACKAGES");
}
output.WriteLine($"==> {startInfo.FileName} {startInfo.Arguments} [{startInfo.WorkingDirectory}]");
var proc = Process.Start(startInfo);
return new ProcessEx(output, proc, timeout ?? DefaultProcessTimeout);
}
private void OnErrorData(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
}
lock (_pipeCaptureLock)
{
_stderrCapture.AppendLine(e.Data);
}
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine("[ERROR] " + e.Data);
}
}
}
private void OnOutputData(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
}
lock (_pipeCaptureLock)
{
_stdoutCapture.AppendLine(e.Data);
}
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine(e.Data);
}
}
if (_stdoutLines != null)
{
_stdoutLines.Add(e.Data);
}
}
private void OnProcessExited(object sender, EventArgs e)
{
lock (_testOutputLock)
{
if (!_disposed)
{
_output.WriteLine("Process exited.");
}
}
_process.WaitForExit();
_stdoutLines.CompleteAdding();
_stdoutLines = null;
_exited.TrySetResult(_process.ExitCode);
}
internal string GetFormattedOutput()
{
if (!_process.HasExited)
{
throw new InvalidOperationException($"Process {_process.ProcessName} with pid: {_process.Id} has not finished running.");
}
return $"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}";
}
public void WaitForExit(bool assertSuccess, TimeSpan? timeSpan = null)
{
if(!timeSpan.HasValue)
{
timeSpan = TimeSpan.FromSeconds(600);
}
var exited = Exited.Wait(timeSpan.Value);
if (!exited)
{
lock (_testOutputLock)
{
_output.WriteLine($"The process didn't exit within the allotted time ({timeSpan.Value.TotalSeconds} seconds).");
}
_process.Dispose();
}
else if (assertSuccess && _process.ExitCode != 0)
{
throw new Exception($"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}");
}
}
private static string GetNugetPackagesRestorePath() => (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NUGET_RESTORE")))
? typeof(ProcessEx).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attribute => attribute.Key == "TestPackageRestorePath")
?.Value
: Environment.GetEnvironmentVariable("NUGET_RESTORE");
public void Dispose()
{
_processTimeoutCts.Dispose();
lock (_testOutputLock)
{
_disposed = true;
}
if (_process != null && !_process.HasExited)
{
_process.KillTree();
}
if (_process != null)
{
_process.CancelOutputRead();
_process.CancelErrorRead();
_process.ErrorDataReceived -= OnErrorData;
_process.OutputDataReceived -= OnOutputData;
_process.Exited -= OnProcessExited;
_process.Dispose();
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kodestruct.Analysis.BeamForces.PinnedFixed
{
public class ConcentratedLoadAtAnyPoint : ISingleLoadCaseBeam, ISingleLoadCaseDeflectionBeam
{
const string CASE = "C3A_2";
BeamPinnedFixed beam;
double L, P, a, b, R1,R2;
bool ReactionsWereCalculated;
public ConcentratedLoadAtAnyPoint(BeamPinnedFixed beam, double P, double a)
{
this.beam = beam;
L = beam.Length;
this.P = P;
this.a = a;
this.b = L - a;
ReactionsWereCalculated = false;
}
public double Moment(double X)
{
beam.EvaluateX(X);
if (ReactionsWereCalculated==false)
{
CalculateReactions();
}
double M;
double R1 = V1;
if (X<=a)
{
M = R1 * X;
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1,
new Dictionary<string, double>()
{
{"R1",R1},
{"X",X }
}, CASE, beam);
}
else
{
M = R1 * X - P * (X - a);
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1,
new Dictionary<string, double>()
{
{"R1",R1 },
{"X",X },
{"P",P },
{"P",P},
{"a",a }
}, CASE, beam);
}
return M;
}
public ForceDataPoint MomentMax()
{
if (ReactionsWereCalculated == false)
{
CalculateReactions();
}
double X, M;
if (M1>=M2)
{
M = M1;
X = a;
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1,
new Dictionary<string, double>()
{
{"R1",R1 },
{"X",X },
{"P",P},
{"a",a }
}, CASE, beam, true);
}
else
{
M = M2;
X = L;
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 2,
new Dictionary<string, double>()
{
{"L",L },
{"X",X },
{"P",P},
{"a",a },
{"b",b }
}, CASE, beam, true);
}
return new ForceDataPoint(X, M);
}
public ForceDataPoint MomentMin()
{
if (ReactionsWereCalculated == false)
{
CalculateReactions();
}
if (ReactionsWereCalculated == false)
{
CalculateReactions();
}
double X, M;
if (M1 <= M2)
{
M = M1;
X = a;
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1,
new Dictionary<string, double>()
{
{"R1",R1 },
{"X",X },
{"P",P},
{"a",a }
}, CASE, beam, false, true);
}
else
{
M = M2;
X = L;
BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 2,
new Dictionary<string, double>()
{
{"L",L },
{"X",X },
{"P",P},
{"a",a },
{"b",b }
}, CASE, beam, false, true);
}
return new ForceDataPoint(X, M);
}
public double Shear(double X)
{
beam.EvaluateX(X);
double V1A = Math.Abs(V1);
double V2A = Math.Abs(V2);
Dictionary<string, double> valDic = new Dictionary<string, double>()
{ {"L",L },
{"X",X},
{"P",P},
{"a",a },
{"b",b }
};
if (X<a)
{
BeamEntryFactory.CreateEntry("Vx", V1A, BeamTemplateType.Vx, 1,
valDic, CASE, beam);
return V1A;
}
else if (X>a)
{
BeamEntryFactory.CreateEntry("Vx", V1A, BeamTemplateType.Vx, 2,
valDic, CASE, beam);
return V2A;
}
else //right at the point of load
{
if (V1A>V2A)
{
BeamEntryFactory.CreateEntry("Vx", V1A, BeamTemplateType.Vx, 1,
valDic, CASE, beam);
return V1A;
}
else
{
BeamEntryFactory.CreateEntry("Vx", V2A, BeamTemplateType.Vx, 2,
valDic, CASE, beam);
return V2A;
}
}
}
public ForceDataPoint ShearMax()
{
double V1A = Math.Abs(V1);
double V2A = Math.Abs(V2);
double X;
Dictionary<string, double> valDic = new Dictionary<string, double>()
{ {"L",L },
{"P",P},
{"a",a },
{"b",b }
};
if (V1A > V2A)
{
valDic.Add("X", a);
BeamEntryFactory.CreateEntry("Vx", V1A, BeamTemplateType.Vmax, 1,
valDic, CASE, beam, true);
X = a;
return new ForceDataPoint(X, V1A);
}
else
{
X = L;
valDic.Add("X", L);
BeamEntryFactory.CreateEntry("Vx", V1A, BeamTemplateType.Vmax, 2,
valDic, CASE, beam, true);
return new ForceDataPoint(X,V2A);
}
}
double V1
{
get
{
double V = P * b * b / (2.0 * Math.Pow(L, 3)) * (a + 2.0 * L);
return V;
}
}
double V2
{
get
{
double V = P*a/(2.0*Math.Pow(L,3))*(3.0*L*L-a*a);
return V;
}
}
double M1
{
get
{
double M = R1 * a;
return M;
}
}
double M2
{
get
{
double M = -(P*a*b)/(2.0*L*L)*(a+L);
return M;
}
}
void CalculateReactions()
{
// double V = P * b * b / (2.0 * Math.Pow(L, 3)) * (a + 2.0 * L);
// double V = P*a/(2.0*Math.Pow(L,3))*(3.0*L*L-a*a);
Dictionary<string, double> valDic = new Dictionary<string, double>()
{ {"L",L },
{"P",P},
{"a",a },
{"b",b }
};
double R1 = V1;
BeamEntryFactory.CreateEntry("R1", R1, BeamTemplateType.R, 1,
valDic, CASE, beam);
double R2 = V2;
BeamEntryFactory.CreateEntry("R2", R2, BeamTemplateType.R, 2,
valDic, CASE, beam);
ReactionsWereCalculated = true;
}
public double MaximumDeflection()
{
double E = beam.ModulusOfElasticity;
double I = beam.MomentOfInertia;
double delta_Maximum = ((P * a * Math.Pow((Math.Pow(L, 2) - Math.Pow(a, 2)), 3.0)) / (3.0 * E *I * Math.Pow((3 * Math.Pow(L, 2) - Math.Pow(a, 2)), 2)));
return delta_Maximum;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/reservation_associated_parties.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 HOLMS.Types.Booking {
/// <summary>Holder for reflection information generated from booking/reservation_associated_parties.proto</summary>
public static partial class ReservationAssociatedPartiesReflection {
#region Descriptor
/// <summary>File descriptor for booking/reservation_associated_parties.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationAssociatedPartiesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cixib29raW5nL3Jlc2VydmF0aW9uX2Fzc29jaWF0ZWRfcGFydGllcy5wcm90",
"bxITaG9sbXMudHlwZXMuYm9va2luZxouYm9va2luZy9pbmRpY2F0b3JzL3Jl",
"c2VydmF0aW9uX2luZGljYXRvci5wcm90bxogY3JtL2d1ZXN0cy9ndWVzdF9p",
"bmRpY2F0b3IucHJvdG8aNWJvb2tpbmcvcmVzZXJ2YXRpb25zL3Jlc2VydmF0",
"aW9uX2NvbnRhY3RfcGVyc29uLnByb3RvIsACChxSZXNlcnZhdGlvbkFzc29j",
"aWF0ZWRQYXJ0aWVzEj0KDXByaW1hcnlfZ3Vlc3QYASABKAsyJi5ob2xtcy50",
"eXBlcy5jcm0uZ3Vlc3RzLkd1ZXN0SW5kaWNhdG9yEkEKEWFkZGl0aW9uYWxf",
"Z3Vlc3RzGAIgAygLMiYuaG9sbXMudHlwZXMuY3JtLmd1ZXN0cy5HdWVzdElu",
"ZGljYXRvchJTCg9jb250YWN0X3BlcnNvbnMYAyADKAsyOi5ob2xtcy50eXBl",
"cy5ib29raW5nLnJlc2VydmF0aW9ucy5SZXNlcnZhdGlvbkNvbnRhY3RQZXJz",
"b24SSQoLcmVzZXJ2YXRpb24YBCABKAsyNC5ob2xtcy50eXBlcy5ib29raW5n",
"LmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3JCFqoCE0hPTE1TLlR5",
"cGVzLkJvb2tpbmdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationContactPersonReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.ReservationAssociatedParties), global::HOLMS.Types.Booking.ReservationAssociatedParties.Parser, new[]{ "PrimaryGuest", "AdditionalGuests", "ContactPersons", "Reservation" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationAssociatedParties : pb::IMessage<ReservationAssociatedParties> {
private static readonly pb::MessageParser<ReservationAssociatedParties> _parser = new pb::MessageParser<ReservationAssociatedParties>(() => new ReservationAssociatedParties());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationAssociatedParties> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.ReservationAssociatedPartiesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAssociatedParties() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAssociatedParties(ReservationAssociatedParties other) : this() {
PrimaryGuest = other.primaryGuest_ != null ? other.PrimaryGuest.Clone() : null;
additionalGuests_ = other.additionalGuests_.Clone();
contactPersons_ = other.contactPersons_.Clone();
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationAssociatedParties Clone() {
return new ReservationAssociatedParties(this);
}
/// <summary>Field number for the "primary_guest" field.</summary>
public const int PrimaryGuestFieldNumber = 1;
private global::HOLMS.Types.CRM.Guests.GuestIndicator primaryGuest_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.CRM.Guests.GuestIndicator PrimaryGuest {
get { return primaryGuest_; }
set {
primaryGuest_ = value;
}
}
/// <summary>Field number for the "additional_guests" field.</summary>
public const int AdditionalGuestsFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.CRM.Guests.GuestIndicator> _repeated_additionalGuests_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.CRM.Guests.GuestIndicator.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.GuestIndicator> additionalGuests_ = new pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.GuestIndicator>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.CRM.Guests.GuestIndicator> AdditionalGuests {
get { return additionalGuests_; }
}
/// <summary>Field number for the "contact_persons" field.</summary>
public const int ContactPersonsFieldNumber = 3;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> _repeated_contactPersons_codec
= pb::FieldCodec.ForMessage(26, global::HOLMS.Types.Booking.Reservations.ReservationContactPerson.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> contactPersons_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> ContactPersons {
get { return contactPersons_; }
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 4;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationAssociatedParties);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationAssociatedParties other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(PrimaryGuest, other.PrimaryGuest)) return false;
if(!additionalGuests_.Equals(other.additionalGuests_)) return false;
if(!contactPersons_.Equals(other.contactPersons_)) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (primaryGuest_ != null) hash ^= PrimaryGuest.GetHashCode();
hash ^= additionalGuests_.GetHashCode();
hash ^= contactPersons_.GetHashCode();
if (reservation_ != null) hash ^= Reservation.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 (primaryGuest_ != null) {
output.WriteRawTag(10);
output.WriteMessage(PrimaryGuest);
}
additionalGuests_.WriteTo(output, _repeated_additionalGuests_codec);
contactPersons_.WriteTo(output, _repeated_contactPersons_codec);
if (reservation_ != null) {
output.WriteRawTag(34);
output.WriteMessage(Reservation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (primaryGuest_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PrimaryGuest);
}
size += additionalGuests_.CalculateSize(_repeated_additionalGuests_codec);
size += contactPersons_.CalculateSize(_repeated_contactPersons_codec);
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationAssociatedParties other) {
if (other == null) {
return;
}
if (other.primaryGuest_ != null) {
if (primaryGuest_ == null) {
primaryGuest_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
PrimaryGuest.MergeFrom(other.PrimaryGuest);
}
additionalGuests_.Add(other.additionalGuests_);
contactPersons_.Add(other.contactPersons_);
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
}
[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: {
if (primaryGuest_ == null) {
primaryGuest_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
input.ReadMessage(primaryGuest_);
break;
}
case 18: {
additionalGuests_.AddEntriesFrom(input, _repeated_additionalGuests_codec);
break;
}
case 26: {
contactPersons_.AddEntriesFrom(input, _repeated_contactPersons_codec);
break;
}
case 34: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLRange : XLRangeBase, IXLRange
{
#region Constructor
public XLRange(XLRangeParameters xlRangeParameters)
: base(xlRangeParameters.RangeAddress)
{
RangeParameters = new XLRangeParameters(xlRangeParameters.RangeAddress, xlRangeParameters.DefaultStyle);
if (!xlRangeParameters.IgnoreEvents)
{
SubscribeToShiftedRows((range, rowShifted) => this.WorksheetRangeShiftedRows(range, rowShifted));
SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted));
//xlRangeParameters.IgnoreEvents = true;
}
SetStyle(xlRangeParameters.DefaultStyle);
}
#endregion Constructor
public XLRangeParameters RangeParameters { get; private set; }
#region IXLRange Members
IXLRangeRow IXLRange.Row(Int32 row)
{
return Row(row);
}
IXLRangeColumn IXLRange.Column(Int32 columnNumber)
{
return Column(columnNumber);
}
IXLRangeColumn IXLRange.Column(String columnLetter)
{
return Column(columnLetter);
}
public virtual IXLRangeColumns Columns(Func<IXLRangeColumn, Boolean> predicate = null)
{
var retVal = new XLRangeColumns();
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate == null || predicate(column))
retVal.Add(column);
else
column.Dispose();
}
return retVal;
}
public virtual IXLRangeColumns Columns(Int32 firstColumn, Int32 lastColumn)
{
var retVal = new XLRangeColumns();
for (int co = firstColumn; co <= lastColumn; co++)
retVal.Add(Column(co));
return retVal;
}
public virtual IXLRangeColumns Columns(String firstColumn, String lastColumn)
{
return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn),
XLHelper.GetColumnNumberFromLetter(lastColumn));
}
public virtual IXLRangeColumns Columns(String columns)
{
var retVal = new XLRangeColumns();
var columnPairs = columns.Split(',');
foreach (string tPair in columnPairs.Select(pair => pair.Trim()))
{
String firstColumn;
String lastColumn;
if (tPair.Contains(':') || tPair.Contains('-'))
{
string[] columnRange = XLHelper.SplitRange(tPair);
firstColumn = columnRange[0];
lastColumn = columnRange[1];
}
else
{
firstColumn = tPair;
lastColumn = tPair;
}
Int32 tmp;
if (Int32.TryParse(firstColumn, out tmp))
{
foreach (IXLRangeColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn)))
retVal.Add(col);
}
else
{
foreach (IXLRangeColumn col in Columns(firstColumn, lastColumn))
retVal.Add(col);
}
}
return retVal;
}
IXLCell IXLRange.Cell(int row, int column)
{
return Cell(row, column);
}
IXLCell IXLRange.Cell(string cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLCell IXLRange.Cell(int row, string column)
{
return Cell(row, column);
}
IXLCell IXLRange.Cell(IXLAddress cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLRange IXLRange.Range(IXLRangeAddress rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLRange.Range(string rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLRange.Range(IXLCell firstCell, IXLCell lastCell)
{
return Range(firstCell, lastCell);
}
IXLRange IXLRange.Range(string firstCellAddress, string lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLRange.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLRange.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn)
{
return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn);
}
public IXLRangeRows Rows(Func<IXLRangeRow, Boolean> predicate = null)
{
var retVal = new XLRangeRows();
Int32 rowCount = RowCount();
for (Int32 r = 1; r <= rowCount; r++)
{
var row = Row(r);
if (predicate == null || predicate(row))
retVal.Add(Row(r));
else
row.Dispose();
}
return retVal;
}
public IXLRangeRows Rows(Int32 firstRow, Int32 lastRow)
{
var retVal = new XLRangeRows();
for (int ro = firstRow; ro <= lastRow; ro++)
retVal.Add(Row(ro));
return retVal;
}
public IXLRangeRows Rows(String rows)
{
var retVal = new XLRangeRows();
var rowPairs = rows.Split(',');
foreach (string tPair in rowPairs.Select(pair => pair.Trim()))
{
String firstRow;
String lastRow;
if (tPair.Contains(':') || tPair.Contains('-'))
{
string[] rowRange = XLHelper.SplitRange(tPair);
firstRow = rowRange[0];
lastRow = rowRange[1];
}
else
{
firstRow = tPair;
lastRow = tPair;
}
foreach (IXLRangeRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)))
retVal.Add(row);
}
return retVal;
}
public void Transpose(XLTransposeOptions transposeOption)
{
int rowCount = RowCount();
int columnCount = ColumnCount();
int squareSide = rowCount > columnCount ? rowCount : columnCount;
var firstCell = FirstCell();
MoveOrClearForTranspose(transposeOption, rowCount, columnCount);
TransposeMerged(squareSide);
TransposeRange(squareSide);
RangeAddress.LastAddress = new XLAddress(Worksheet,
firstCell.Address.RowNumber + columnCount - 1,
firstCell.Address.ColumnNumber + rowCount - 1,
RangeAddress.LastAddress.FixedRow,
RangeAddress.LastAddress.FixedColumn);
if (rowCount > columnCount)
{
var rng = Worksheet.Range(
RangeAddress.LastAddress.RowNumber + 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber + (rowCount - columnCount),
RangeAddress.LastAddress.ColumnNumber);
rng.Delete(XLShiftDeletedCells.ShiftCellsUp);
}
else if (columnCount > rowCount)
{
var rng = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + 1,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + (columnCount - rowCount));
rng.Delete(XLShiftDeletedCells.ShiftCellsLeft);
}
foreach (IXLCell c in Range(1, 1, columnCount, rowCount).Cells())
{
var border = new XLBorder(this, c.Style.Border);
c.Style.Border.TopBorder = border.LeftBorder;
c.Style.Border.TopBorderColor = border.LeftBorderColor;
c.Style.Border.LeftBorder = border.TopBorder;
c.Style.Border.LeftBorderColor = border.TopBorderColor;
c.Style.Border.RightBorder = border.BottomBorder;
c.Style.Border.RightBorderColor = border.BottomBorderColor;
c.Style.Border.BottomBorder = border.RightBorder;
c.Style.Border.BottomBorderColor = border.RightBorderColor;
}
}
public IXLTable AsTable()
{
return new XLTable(this, false);
}
public IXLTable AsTable(String name)
{
return new XLTable(this, name, false);
}
IXLTable IXLRange.CreateTable()
{
return CreateTable();
}
public XLTable CreateTable()
{
return new XLTable(this, true, true);
}
IXLTable IXLRange.CreateTable(String name)
{
return CreateTable(name);
}
public XLTable CreateTable(String name)
{
return new XLTable(this, name, true, true);
}
public IXLTable CreateTable(String name, Boolean setAutofilter)
{
return new XLTable(this, name, true, setAutofilter);
}
public new IXLRange CopyTo(IXLCell target)
{
base.CopyTo(target);
Int32 lastRowNumber = target.Address.RowNumber + RowCount() - 1;
if (lastRowNumber > XLHelper.MaxRowNumber)
lastRowNumber = XLHelper.MaxRowNumber;
Int32 lastColumnNumber = target.Address.ColumnNumber + ColumnCount() - 1;
if (lastColumnNumber > XLHelper.MaxColumnNumber)
lastColumnNumber = XLHelper.MaxColumnNumber;
return target.Worksheet.Range(target.Address.RowNumber,
target.Address.ColumnNumber,
lastRowNumber,
lastColumnNumber);
}
public new IXLRange CopyTo(IXLRangeBase target)
{
base.CopyTo(target);
Int32 lastRowNumber = target.RangeAddress.FirstAddress.RowNumber + RowCount() - 1;
if (lastRowNumber > XLHelper.MaxRowNumber)
lastRowNumber = XLHelper.MaxRowNumber;
Int32 lastColumnNumber = target.RangeAddress.FirstAddress.ColumnNumber + ColumnCount() - 1;
if (lastColumnNumber > XLHelper.MaxColumnNumber)
lastColumnNumber = XLHelper.MaxColumnNumber;
return target.Worksheet.Range(target.RangeAddress.FirstAddress.RowNumber,
target.RangeAddress.FirstAddress.ColumnNumber,
lastRowNumber,
lastColumnNumber);
}
public IXLRange SetDataType(XLDataType dataType)
{
DataType = dataType;
return this;
}
public new IXLRange Sort()
{
return base.Sort().AsRange();
}
public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange();
}
public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange();
}
public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.SortLeftToRight(sortOrder, matchCase, ignoreBlanks).AsRange();
}
#endregion IXLRange Members
private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted)
{
ShiftColumns(RangeAddress, range, columnsShifted);
}
private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted)
{
ShiftRows(RangeAddress, range, rowsShifted);
}
IXLRangeColumn IXLRange.FirstColumn(Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumn(predicate);
}
public XLRangeColumn FirstColumn(Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
return Column(1);
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate(column)) return column;
column.Dispose();
}
return null;
}
IXLRangeColumn IXLRange.LastColumn(Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumn(predicate);
}
public XLRangeColumn LastColumn(Func<IXLRangeColumn, Boolean> predicate = null)
{
Int32 columnCount = ColumnCount();
if (predicate == null)
return Column(columnCount);
for (Int32 c = columnCount; c >= 1; c--)
{
var column = Column(c);
if (predicate(column)) return column;
column.Dispose();
}
return null;
}
IXLRangeColumn IXLRange.FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumnUsed(false, predicate);
}
public XLRangeColumn FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return FirstColumnUsed(false, predicate);
}
IXLRangeColumn IXLRange.FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumnUsed(includeFormats, predicate);
}
public XLRangeColumn FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 firstColumnUsed = Worksheet.Internals.CellsCollection.FirstColumnUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return firstColumnUsed == 0 ? null : Column(firstColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1);
}
Int32 columnCount = ColumnCount();
for (Int32 co = 1; co <= columnCount; co++)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && predicate(column))
return column;
column.Dispose();
}
return null;
}
IXLRangeColumn IXLRange.LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumnUsed(false, predicate);
}
public XLRangeColumn LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return LastColumnUsed(false, predicate);
}
IXLRangeColumn IXLRange.LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumnUsed(includeFormats, predicate);
}
public XLRangeColumn LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 lastColumnUsed = Worksheet.Internals.CellsCollection.LastColumnUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return lastColumnUsed == 0 ? null : Column(lastColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1);
}
Int32 columnCount = ColumnCount();
for (Int32 co = columnCount; co >= 1; co--)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && predicate(column))
return column;
column.Dispose();
}
return null;
}
IXLRangeRow IXLRange.FirstRow(Func<IXLRangeRow, Boolean> predicate)
{
return FirstRow(predicate);
}
public XLRangeRow FirstRow(Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
return Row(1);
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (predicate(row)) return row;
row.Dispose();
}
return null;
}
IXLRangeRow IXLRange.LastRow(Func<IXLRangeRow, Boolean> predicate)
{
return LastRow(predicate);
}
public XLRangeRow LastRow(Func<IXLRangeRow, Boolean> predicate = null)
{
Int32 rowCount = RowCount();
if (predicate == null)
return Row(rowCount);
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = Row(ro);
if (predicate(row)) return row;
row.Dispose();
}
return null;
}
IXLRangeRow IXLRange.FirstRowUsed(Func<IXLRangeRow, Boolean> predicate)
{
return FirstRowUsed(false, predicate);
}
public XLRangeRow FirstRowUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return FirstRowUsed(false, predicate);
}
IXLRangeRow IXLRange.FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return FirstRowUsed(includeFormats, predicate);
}
public XLRangeRow FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 rowFromCells = Worksheet.Internals.CellsCollection.FirstRowUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
//Int32 rowFromRows = Worksheet.Internals.RowsCollection.FirstRowUsed(includeFormats);
return rowFromCells == 0 ? null : Row(rowFromCells - RangeAddress.FirstAddress.RowNumber + 1);
}
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
row.Dispose();
}
return null;
}
IXLRangeRow IXLRange.LastRowUsed(Func<IXLRangeRow, Boolean> predicate)
{
return LastRowUsed(false, predicate);
}
public XLRangeRow LastRowUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return LastRowUsed(false, predicate);
}
IXLRangeRow IXLRange.LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return LastRowUsed(includeFormats, predicate);
}
public XLRangeRow LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 lastRowUsed = Worksheet.Internals.CellsCollection.LastRowUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return lastRowUsed == 0 ? null : Row(lastRowUsed - RangeAddress.FirstAddress.RowNumber + 1);
}
Int32 rowCount = RowCount();
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
row.Dispose();
}
return null;
}
IXLRangeRows IXLRange.RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return RowsUsed(includeFormats, predicate);
}
public XLRangeRows RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
XLRangeRows rows = new XLRangeRows();
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row)))
rows.Add(row);
else
row.Dispose();
}
return rows;
}
IXLRangeRows IXLRange.RowsUsed(Func<IXLRangeRow, Boolean> predicate)
{
return RowsUsed(predicate);
}
public XLRangeRows RowsUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return RowsUsed(false, predicate);
}
IXLRangeColumns IXLRange.ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return ColumnsUsed(includeFormats, predicate);
}
public virtual XLRangeColumns ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
XLRangeColumns columns = new XLRangeColumns();
Int32 columnCount = ColumnCount();
for (Int32 co = 1; co <= columnCount; co++)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column)))
columns.Add(column);
else
column.Dispose();
}
return columns;
}
IXLRangeColumns IXLRange.ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return ColumnsUsed(predicate);
}
public virtual XLRangeColumns ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return ColumnsUsed(false, predicate);
}
public XLRangeRow Row(Int32 row)
{
if (row <= 0 || row > XLHelper.MaxRowNumber)
throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber));
var firstCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber + row - 1,
RangeAddress.FirstAddress.ColumnNumber,
false,
false);
var lastCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber + row - 1,
RangeAddress.LastAddress.ColumnNumber,
false,
false);
return new XLRangeRow(
new XLRangeParameters(new XLRangeAddress(firstCellAddress, lastCellAddress), Worksheet.Style), false);
}
public virtual XLRangeColumn Column(Int32 columnNumber)
{
if (columnNumber <= 0 || columnNumber > XLHelper.MaxColumnNumber)
throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}", XLHelper.MaxColumnNumber));
var firstCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1,
false,
false);
var lastCellAddress = new XLAddress(Worksheet,
RangeAddress.LastAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1,
false,
false);
return new XLRangeColumn(
new XLRangeParameters(new XLRangeAddress(firstCellAddress, lastCellAddress), Worksheet.Style), false);
}
public virtual XLRangeColumn Column(String columnLetter)
{
return Column(XLHelper.GetColumnNumberFromLetter(columnLetter));
}
private void TransposeRange(int squareSide)
{
var cellsToInsert = new Dictionary<XLSheetPoint, XLCell>();
var cellsToDelete = new List<XLSheetPoint>();
var rngToTranspose = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.RowNumber + squareSide - 1,
RangeAddress.FirstAddress.ColumnNumber + squareSide - 1);
Int32 roCount = rngToTranspose.RowCount();
Int32 coCount = rngToTranspose.ColumnCount();
for (Int32 ro = 1; ro <= roCount; ro++)
{
for (Int32 co = 1; co <= coCount; co++)
{
var oldCell = rngToTranspose.Cell(ro, co);
var newKey = rngToTranspose.Cell(co, ro).Address;
// new XLAddress(Worksheet, c.Address.ColumnNumber, c.Address.RowNumber);
var newCell = new XLCell(Worksheet, newKey, oldCell.GetStyleId());
newCell.CopyFrom(oldCell, true);
cellsToInsert.Add(new XLSheetPoint(newKey.RowNumber, newKey.ColumnNumber), newCell);
cellsToDelete.Add(new XLSheetPoint(oldCell.Address.RowNumber, oldCell.Address.ColumnNumber));
}
}
cellsToDelete.ForEach(c => Worksheet.Internals.CellsCollection.Remove(c));
cellsToInsert.ForEach(c => Worksheet.Internals.CellsCollection.Add(c.Key, c.Value));
}
private void TransposeMerged(Int32 squareSide)
{
var rngToTranspose = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.RowNumber + squareSide - 1,
RangeAddress.FirstAddress.ColumnNumber + squareSide - 1);
foreach (IXLRange merge in Worksheet.Internals.MergedRanges.Where(Contains))
{
merge.RangeAddress.LastAddress = rngToTranspose.Cell(merge.ColumnCount(), merge.RowCount()).Address;
}
}
private void MoveOrClearForTranspose(XLTransposeOptions transposeOption, int rowCount, int columnCount)
{
if (transposeOption == XLTransposeOptions.MoveCells)
{
if (rowCount > columnCount)
InsertColumnsAfter(false, rowCount - columnCount, false);
else if (columnCount > rowCount)
InsertRowsBelow(false, columnCount - rowCount, false);
}
else
{
if (rowCount > columnCount)
{
int toMove = rowCount - columnCount;
var rngToClear = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + 1,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + toMove);
rngToClear.Clear();
}
else if (columnCount > rowCount)
{
int toMove = columnCount - rowCount;
var rngToClear = Worksheet.Range(
RangeAddress.LastAddress.RowNumber + 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber + toMove,
RangeAddress.LastAddress.ColumnNumber);
rngToClear.Clear();
}
}
}
public override bool Equals(object obj)
{
var other = (XLRange)obj;
return RangeAddress.Equals(other.RangeAddress)
&& Worksheet.Equals(other.Worksheet);
}
public override int GetHashCode()
{
return RangeAddress.GetHashCode()
^ Worksheet.GetHashCode();
}
public new IXLRange Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats)
{
base.Clear(clearOptions);
return this;
}
public IXLRangeColumn FindColumn(Func<IXLRangeColumn, bool> predicate)
{
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate == null || predicate(column))
return column;
else
column.Dispose();
}
return null;
}
public IXLRangeRow FindRow(Func<IXLRangeRow, bool> predicate)
{
Int32 rowCount = RowCount();
for (Int32 r = 1; r <= rowCount; r++)
{
var row = Row(r);
if (predicate(row))
return row;
else
row.Dispose();
}
return null;
}
}
}
| |
// ReSharper disable InconsistentNaming
namespace Tester.CodeGenTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Providers;
public interface IGrainWithGenericMethods : IGrainWithGuidKey
{
Task<Type[]> GetTypesExplicit<T, U, V>();
Task<Type[]> GetTypesInferred<T, U, V>(T t, U u, V v);
Task<Type[]> GetTypesInferred<T, U>(T t, U u, int v);
Task<T> RoundTrip<T>(T val);
Task<int> RoundTrip(int val);
Task<T> Default<T>();
Task<string> Default();
Task<TGrain> Constraints<TGrain>(TGrain grain) where TGrain : IGrain;
Task SetValueOnObserver<T>(IGrainObserverWithGenericMethods observer, T value);
ValueTask<int> ValueTaskMethod(bool useCache);
}
public interface IGrainObserverWithGenericMethods : IGrainObserver
{
void SetValue<T>(T value);
}
public class GrainWithGenericMethods : Grain, IGrainWithGenericMethods
{
private object state;
public Task<Type[]> GetTypesExplicit<T, U, V>()
{
return Task.FromResult(new[] {typeof(T), typeof(U), typeof(V)});
}
public Task<Type[]> GetTypesInferred<T, U, V>(T t, U u, V v)
{
return Task.FromResult(new[] { typeof(T), typeof(U), typeof(V) });
}
public Task<Type[]> GetTypesInferred<T, U>(T t, U u, int v)
{
return Task.FromResult(new[] { typeof(T), typeof(U) });
}
public Task<T> RoundTrip<T>(T val)
{
return Task.FromResult(val);
}
public Task<int> RoundTrip(int val)
{
return Task.FromResult(-val);
}
public Task<T> Default<T>()
{
return Task.FromResult(default(T));
}
public Task<string> Default()
{
return Task.FromResult("default string");
}
public Task<TGrain> Constraints<TGrain>(TGrain grain) where TGrain : IGrain
{
return Task.FromResult(grain);
}
public void SetValue<T>(T value)
{
this.state = value;
}
public Task<T> GetValue<T>() => Task.FromResult((T) this.state);
public Task SetValueOnObserver<T>(IGrainObserverWithGenericMethods observer, T value)
{
observer.SetValue<T>(value);
return Task.FromResult(0);
}
public ValueTask<int> ValueTaskMethod(bool useCache)
{
if (useCache)
{
return new ValueTask<int>(1);
}
return new ValueTask<int>(Task.FromResult(2));
}
}
public interface IGenericGrainWithGenericMethods<T> : IGrainWithGuidKey
{
Task<T> Method(T value);
#pragma warning disable 693
Task<T> Method<T>(T value);
#pragma warning restore 693
}
public class GrainWithGenericMethods<T> : Grain, IGenericGrainWithGenericMethods<T>
{
public Task<T> Method(T value) => Task.FromResult(default(T));
#pragma warning disable 693
public Task<T> Method<T>(T value) => Task.FromResult(value);
#pragma warning restore 693
}
[StorageProvider(ProviderName = "MemoryStore")]
public class RuntimeGenericGrain : Grain<GenericGrainState<@event>>, IRuntimeCodeGenGrain<@event>
{
public Task<@event> SetState(@event value)
{
this.State.@event = value;
return Task.FromResult(this.State.@event);
}
public Task<@event> @static()
{
return Task.FromResult(this.State.@event);
}
}
public interface IRuntimeCodeGenGrain<T> : IGrainWithGuidKey
{
/// <summary>
/// Sets and returns the grain's state.
/// </summary>
/// <param name="value">The new state.</param>
/// <returns>The current state.</returns>
Task<T> SetState(T value);
/// <summary>
/// Tests that code generation correctly handles methods with reserved keyword identifiers.
/// </summary>
/// <returns>The current state's event.</returns>
Task<@event> @static();
}
[Serializable]
public class GenericGrainState<T>
{
public T @event { get; set; }
}
/// <summary>
/// A class designed to test that code generation correctly handles reserved keywords.
/// </summary>
public class @event : IEquatable<@event>
{
private static readonly IEqualityComparer<@event> EventComparerInstance = new EventEqualityComparer();
public enum @enum
{
@async,
@int,
}
/// <summary>
/// A public field.
/// </summary>
public Guid Id;
/// <summary>
/// A private field.
/// </summary>
private Guid privateId;
/// <summary>
/// A property with a reserved keyword type and identifier.
/// </summary>
public @event @public { get; set; }
/// <summary>
/// Gets or sets the enum.
/// </summary>
public @enum Enum { get; set; }
/// <summary>
/// A property with a reserved keyword generic type and identifier.
/// </summary>
public List<@event> @if { get; set; }
public static IEqualityComparer<@event> EventComparer
{
get
{
return EventComparerInstance;
}
}
/// <summary>
/// Gets or sets the private id.
/// </summary>
// ReSharper disable once ConvertToAutoProperty
public Guid PrivateId
{
get
{
return this.privateId;
}
set
{
this.privateId = value;
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((@event)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (this.@if != null ? this.@if.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (this.@public != null ? this.@public.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ this.privateId.GetHashCode();
hashCode = (hashCode * 397) ^ this.Id.GetHashCode();
return hashCode;
}
}
public bool Equals(@event other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.@if != other.@if)
{
if (this.@if != null && !this.@if.SequenceEqual(other.@if, EventComparer))
{
return false;
}
}
if (!Equals(this.@public, other.@public))
{
if (this.@public != null && !this.@public.Equals(other.@public))
{
return false;
}
}
return this.privateId.Equals(other.privateId) && this.Id.Equals(other.Id) && this.Enum == other.Enum;
}
private sealed class EventEqualityComparer : IEqualityComparer<@event>
{
public bool Equals(@event x, @event y)
{
return x.Equals(y);
}
public int GetHashCode(@event obj)
{
return obj.GetHashCode();
}
}
}
public class NestedGeneric<T>
{
public Nested Payload { get; set; }
public class Nested
{
public T Value { get; set; }
}
}
public class NestedConstructedGeneric
{
public Nested<int> Payload { get; set; }
public class Nested<T>
{
public T Value { get; set; }
}
}
public interface INestedGenericGrain : IGrainWithGuidKey
{
Task<int> Do(NestedGeneric<int> value);
Task<int> Do(NestedConstructedGeneric value);
}
/// <summary>
/// Tests that nested classes do not fail code generation.
/// </summary>
public class NestedGenericGrain : Grain, INestedGenericGrain
{
public Task<int> Do(NestedGeneric<int> value)
{
return Task.FromResult(value.Payload.Value);
}
public Task<int> Do(NestedConstructedGeneric value)
{
return Task.FromResult(value.Payload.Value);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the VwAspnetWebPartStateUser class.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStateUserCollection : ReadOnlyList<VwAspnetWebPartStateUser, VwAspnetWebPartStateUserCollection>
{
public VwAspnetWebPartStateUserCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vw_aspnet_WebPartState_User view.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStateUser : ReadOnlyRecord<VwAspnetWebPartStateUser>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("vw_aspnet_WebPartState_User", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarPathId = new TableSchema.TableColumn(schema);
colvarPathId.ColumnName = "PathId";
colvarPathId.DataType = DbType.Guid;
colvarPathId.MaxLength = 0;
colvarPathId.AutoIncrement = false;
colvarPathId.IsNullable = true;
colvarPathId.IsPrimaryKey = false;
colvarPathId.IsForeignKey = false;
colvarPathId.IsReadOnly = false;
schema.Columns.Add(colvarPathId);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = true;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarDataSize = new TableSchema.TableColumn(schema);
colvarDataSize.ColumnName = "DataSize";
colvarDataSize.DataType = DbType.Int32;
colvarDataSize.MaxLength = 0;
colvarDataSize.AutoIncrement = false;
colvarDataSize.IsNullable = true;
colvarDataSize.IsPrimaryKey = false;
colvarDataSize.IsForeignKey = false;
colvarDataSize.IsReadOnly = false;
schema.Columns.Add(colvarDataSize);
TableSchema.TableColumn colvarLastUpdatedDate = new TableSchema.TableColumn(schema);
colvarLastUpdatedDate.ColumnName = "LastUpdatedDate";
colvarLastUpdatedDate.DataType = DbType.DateTime;
colvarLastUpdatedDate.MaxLength = 0;
colvarLastUpdatedDate.AutoIncrement = false;
colvarLastUpdatedDate.IsNullable = false;
colvarLastUpdatedDate.IsPrimaryKey = false;
colvarLastUpdatedDate.IsForeignKey = false;
colvarLastUpdatedDate.IsReadOnly = false;
schema.Columns.Add(colvarLastUpdatedDate);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("vw_aspnet_WebPartState_User",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VwAspnetWebPartStateUser()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VwAspnetWebPartStateUser(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VwAspnetWebPartStateUser(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VwAspnetWebPartStateUser(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("PathId")]
[Bindable(true)]
public Guid? PathId
{
get
{
return GetColumnValue<Guid?>("PathId");
}
set
{
SetColumnValue("PathId", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid? UserId
{
get
{
return GetColumnValue<Guid?>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("DataSize")]
[Bindable(true)]
public int? DataSize
{
get
{
return GetColumnValue<int?>("DataSize");
}
set
{
SetColumnValue("DataSize", value);
}
}
[XmlAttribute("LastUpdatedDate")]
[Bindable(true)]
public DateTime LastUpdatedDate
{
get
{
return GetColumnValue<DateTime>("LastUpdatedDate");
}
set
{
SetColumnValue("LastUpdatedDate", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string PathId = @"PathId";
public static string UserId = @"UserId";
public static string DataSize = @"DataSize";
public static string LastUpdatedDate = @"LastUpdatedDate";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using Data.DbClient.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Data.DbClient
{
public partial class Database : IDisposable
{
#region Class Initialization
static Database()
{
var data = (string)AppDomain.CurrentDomain.GetData("DataDirectory");
var currentDirectory = data;
if (data == null)
{
currentDirectory = Directory.GetCurrentDirectory();
}
DataDirectory = currentDirectory;
var strs = new Dictionary<string, IDbFileHandler>(StringComparer.OrdinalIgnoreCase)
{
{".sdf", new SqlCeDbFileHandler()},
{".mdf", new SqlServerDbFileHandler()}
};
ConfigurationManager = new ConfigurationManagerWrapper(strs);
}
protected internal Database(Func<DbConnection> connectionFactory)
{
_connectionFactory = connectionFactory;
}
#endregion Class Initialization
#region Fields and Props
private static readonly IConfigurationManager ConfigurationManager;
private DbConnection _connection;
private readonly Func<DbConnection> _connectionFactory;
internal static string DataDirectory;
public DbConnection Connection => _connection ?? (_connection = _connectionFactory());
public static bool IsWebAssembly
{
get
{
var entry = Assembly.GetEntryAssembly();
return entry == null || Assembly.GetCallingAssembly().FullName.Contains(@"App_");
}
}
public static string AssemblyDirectoryPath => Path.GetDirectoryName(IsWebAssembly ? Assembly.GetCallingAssembly().Location : Assembly.GetEntryAssembly().Location);
#endregion Fields and Props
#region Helper Methods
private void EnsureConnectionOpen()
{
if (Connection.State == ConnectionState.Open) return;
Connection.Open();
OnConnectionOpened();
}
private async Task EnsureConnectionOpenAsync()
{
if (Connection.State == ConnectionState.Open) return;
await Connection.OpenAsync();
OnConnectionOpened();
}
private void EnsureConnectionIsClosed()
{
if (Connection.State == ConnectionState.Open || Connection.State == ConnectionState.Connecting) Connection.Close();
}
internal static string GetDefaultProviderName()
{
string str;
if (ConfigurationManager.AppSettings.TryGetValue("systemData:defaultProvider", out str)) return str;
str = IsWebAssembly ? "System.Data.SqlServerCe.4.0" : "System.Data.SqlServerCe.3.5";
return str;
}
public string GetConnectionProviderName()
{
var fullname = Connection.GetType().FullName;
var providerName = fullname.Substring(0, fullname.Length - (fullname.Length - fullname.LastIndexOf('.')));
if (providerName == "System.Data.SqlServerCe")
{
providerName = IsWebAssembly ? "System.Data.SqlServerCe.4.0" : "System.Data.SqlServerCe.3.5";
}
return providerName;
}
internal static IConnectionConfiguration GetConnectionConfiguration(string fileName, IDictionary<string, IDbFileHandler> handlers)
{
IDbFileHandler dbFileHandler = null;
var extension = Path.GetExtension(fileName);
if (extension != null && !handlers.TryGetValue(extension, out dbFileHandler))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, UnableToDetermineDatabase, fileName));
}
return dbFileHandler?.GetConnectionConfiguration(fileName);
}
public dynamic GetLastInsertId()
{
return QueryValue("SELECT @@Identity", args: new object[0]);
}
private static void AddParameters(DbCommand command, IEnumerable<object> args)
{
if (args == null) return;
var paramList = new List<DbParameter>();
var i = 0;
foreach (var o in args)
{
var isGeneric = o?.GetType().IsGenericType;
if (isGeneric.HasValue && isGeneric.Value)
{
var props = o?.GetType().GetProperties();
if (!props.Any()) continue;
foreach (var propertyInfo in props)
{
var nm = propertyInfo.Name;
var val = o?.GetType().GetProperty(nm)?.GetValue(o, null);
var dbParameter = command.CreateParameter();
dbParameter.ParameterName = nm;
if (val == null)
{
val = DBNull.Value;
}
dbParameter.Value = val;
paramList.Add(dbParameter);
}
}
else
{
var dbParameter = command.CreateParameter();
dbParameter.ParameterName = i.ToString(CultureInfo.InvariantCulture);
var value = o;
if (o == null)
{
value = DBNull.Value;
}
dbParameter.Value = value;
paramList.Add(dbParameter);
i++;
}
}
foreach (var p in paramList)
{
command.Parameters.Add(p);
}
//var dbParameters = args.Select((o, index) =>
//{
// var dbParameter = command.CreateParameter();
// dbParameter.ParameterName = index.ToString(CultureInfo.InvariantCulture);
// var value = o;
// if (o == null)
// {
// value = DBNull.Value;
// }
// dbParameter.Value = value;
// return dbParameter;
//});
//foreach (var dbParameter1 in dbParameters)
//{
// command.Parameters.Add(dbParameter1);
//}
}
public static IEnumerable<string> GetColumnNames(DbDataRecord record)
{
for (var i = 0; i < record.FieldCount; i++)
{
yield return record.GetName(i);
}
}
public static IEnumerable<string> GetColumnNames(DbDataReader reader)
{
for (var i = 0; i < reader.FieldCount; i++)
{
yield return reader.GetName(i);
}
}
public object DbNullToNull(object input)
{
return Convert.DBNull.Equals(input) ? null : input;
}
private static CommandType InferCommandType(string commandText)
{
if (!string.IsNullOrWhiteSpace(commandText) && commandText.Trim().ToCharArray().Count(c => c == ' ') < 2)
{
return CommandType.StoredProcedure;
}
else
{
return CommandType.Text;
}
}
#endregion Helper Methods
#region Open Methods
public static Database Open(string name)
{
if (!string.IsNullOrEmpty(name))
{
return OpenNamedConnection(name, ConfigurationManager);
}
throw new ArgumentException("name is NULL!");
}
private static Database OpenConnectionInternal(IConnectionConfiguration connectionConfig)
{
return OpenConnectionStringInternal(connectionConfig.ProviderFactory, connectionConfig.ConnectionString);
}
internal static Database OpenNamedConnection(string name, IConfigurationManager configurationManager)
{
var connection = configurationManager.GetConnection(name);
if (connection == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ConnectionStringNotFound, name));
}
return OpenConnectionInternal(connection);
}
#endregion Open Methods
#region OpenConnectionString Methods
public static Database OpenConnectionString(string connectionString)
{
return OpenConnectionString(connectionString, null);
}
public static Database OpenConnectionString(string connectionString, string providerName)
{
if (!string.IsNullOrEmpty(connectionString))
{
return OpenConnectionStringInternal(new DbProviderFactoryWrapper(providerName), connectionString);
}
throw new ArgumentException(@"connectionString is NULL!");
}
internal static Database OpenConnectionStringInternal(IDbProviderFactory providerFactory, string connectionString)
{
return new Database(() => providerFactory.CreateConnection(connectionString));
}
#endregion OpenConnectionString Methods
#region Open DbConnection Methods
public static Database OpenDbConnection(DbConnection connection)
{
//return new Database(() => connection.GetProviderFactory().CreateConnection(connection.ConnectionString));
return new Database(() => connection);
}
#endregion Open DbConnection Methods
#region Query Methods
#region Public Command Methods
#region Execute Methods
public int Execute(string commandText, int commandTimeout = 0, params object[] parameters)
{
if (string.IsNullOrEmpty(commandText)) throw new ArgumentException("commandText is NULL!");
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0) dbCommand.CommandTimeout = commandTimeout;
AddParameters(dbCommand, parameters);
int num;
using (dbCommand)
{
num = dbCommand.ExecuteNonQuery();
}
return num;
}
public static int ExecuteNonQuery(string connectionString, string providerName, string commandText, int commandTimeout = 0, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.Execute(commandText, commandTimeout, parameters);
}
}
public static int ExecuteNonQuery(DbConnection connection, string commandText, int commandTimeout = 0, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.Execute(commandText, commandTimeout, parameters);
}
}
#endregion Execute Methods
#region Query Methods
public IEnumerable<dynamic> Query(string commandText, int commandTimeout = 60, params object[] parameters)
{
if (!string.IsNullOrEmpty(commandText))
{
//return QueryInternalAsync(commandText, CancellationToken.None, commandTimeout, parameters).Result;
//return QueryInternal(commandText, commandTimeout, parameters).ToList<object>().AsReadOnly();
return QueryInternal(commandText, commandTimeout, parameters);
}
throw new ArgumentException("commandText is NULL!");
}
public static IEnumerable<dynamic> Query(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.Query(commandText, commandTimeout, parameters);
}
}
public static IEnumerable<dynamic> Query(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.Query(commandText, commandTimeout, parameters);
}
}
public IEnumerable<JObject> QueryToJObjects(string commandText, int commandTimeout = 60, params object[] parameters)
{
if (!string.IsNullOrEmpty(commandText))
{
return QueryInternalJObjectsAsync(commandText, CancellationToken.None, commandTimeout, parameters).Result;
//return QueryInternalJObjects(commandText, commandTimeout, parameters);
}
throw new ArgumentException("commandText is NULL!");
}
public static IEnumerable<JObject> QueryToJObjects(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryToJObjects(commandText, commandTimeout, parameters);
}
}
public static IEnumerable<JObject> QueryToJObjects(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryToJObjects(commandText, commandTimeout, parameters);
}
}
public IEnumerable<T> QueryTransformEach<T>(string commandText, Func<JObject, T> function, int commandTimeout = 60, params object[] parameters)
{
if (!string.IsNullOrEmpty(commandText))
{
return QueryInternalTransformToAsync(commandText, function, CancellationToken.None, commandTimeout, parameters).Result;
//return QueryInternalJObjects(commandText, commandTimeout, parameters);
}
throw new ArgumentException("commandText is NULL!");
}
public static IEnumerable<T> QueryTransformEach<T>(string connectionString, string providerName, string commandText, Func<JObject, T> function, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryTransformEach(commandText, function, commandTimeout, parameters);
}
}
public static IEnumerable<T> QueryTransformEach<T>(DbConnection connection, string commandText, Func<JObject, T> function, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryTransformEach(commandText, function, commandTimeout, parameters);
}
}
public Stream QueryToBson(string commandText, int commandTimeout = 60, params object[] parameters)
{
if (!string.IsNullOrEmpty(commandText))
{
return QueryInternalBsonAsync(commandText, CancellationToken.None, commandTimeout, parameters).Result;
//return QueryInternalJObjects(commandText, commandTimeout, parameters);
}
throw new ArgumentException("commandText is NULL!");
}
public static Stream QueryToBson(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryToBson(commandText, commandTimeout, parameters);
}
}
public static Stream QueryToBson(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryToBson(commandText, commandTimeout, parameters);
}
}
public Stream QueryToJsonStream(string commandText, int commandTimeout = 60, params object[] parameters)
{
if (!string.IsNullOrEmpty(commandText))
{
return QueryInternalJObjectWriterAsync(commandText, CancellationToken.None, commandTimeout, parameters).Result;
//return QueryInternalJObjects(commandText, commandTimeout, parameters);
}
throw new ArgumentException("commandText is NULL!");
}
public static Stream QueryToJsonStream(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryToJsonStream(commandText, commandTimeout, parameters);
}
}
public static Stream QueryToJsonStream(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryToJsonStream(commandText, commandTimeout, parameters);
}
}
public DataTable QueryToDataTable(string commandText, string tableName = null, int commandTimeout = 60, params object[] parameters)
{
if (string.IsNullOrEmpty(commandText)) throw new ArgumentException("commandText is NULL!");
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
var providerName = GetConnectionProviderName();
var da = DbProviderFactories.GetFactory(providerName).CreateDataAdapter();
// ReSharper disable once PossibleNullReferenceException
da.SelectCommand = dbCommand;
var dt = tableName == null ? new DataTable() : new DataTable(tableName);
da.Fill(dt);
return dt;
}
public static DataTable QueryToDataTable(string connectionString, string providerName, string commandText, string tableName = null, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryToDataTable(commandText, tableName, commandTimeout, parameters);
}
}
public static DataTable QueryToDataTable(DbConnection connection, string commandText, string tableName = null, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryToDataTable(commandText, tableName, commandTimeout, parameters);
}
}
public DataTable QueryAsDataTable(DbCommand dbCommand, string tableName = null, int commandTimeout = 60, params object[] parameters)
{
var dt = string.IsNullOrWhiteSpace(tableName) ? new DataTable() : new DataTable(tableName);
dt.Load(QueryToDataReader(dbCommand, commandTimeout, parameters));
return dt;
}
public static DataTable QueryToDataTable(DbCommand dbCommand, string tableName = null, int commandTimeout = 60, params object[] parameters)
{
//var dt = string.IsNullOrWhiteSpace(tableName) ? new DataTable() : new DataTable(tableName);
using (var db = OpenDbConnection(dbCommand.Connection))
{
return db.QueryAsDataTable(dbCommand, tableName, commandTimeout, parameters);
//dt.Load(db.QueryToDataReader(dbCommand, tableName, commandTimeout, parameters));
//return dt;
}
//_connection = dbCommand.Connection;
//EnsureConnectionOpen();
//dt.Load(dbCommand.ExecuteReader(CommandBehavior.CloseConnection));
//return dt;
}
/*
public static async Task<DataTable> GetDataAsync(string connectionString, string query)
{
DataTable resultTable = new DataTable();
try
{
ConnectionStringSettings connectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings[connectionString];
DbProviderFactory factory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionStringSettings.ConnectionString;
connection.Open();
DbCommand command = connection.CreateCommand();
command.CommandText = query;
command.CommandType = InferCommandType(commandText);
DbDataReader readers = command.ExecuteReader();
DataTable schemaTable = readers.GetSchemaTable();
foreach (DataRow dataRow in schemaTable.Rows)
{
DataColumn dataColumn = new DataColumn();
dataColumn.ColumnName = dataRow[0].ToString();
dataColumn.DataType = Type.GetType(dataRow["DataType"].ToString());
resultTable.Columns.Add(dataColumn);
}
readers.Close();
command.CommandTimeout = 30000;
using (DbDataReader reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
DataRow dataRow = resultTable.NewRow();
for (int i = 0; i < resultTable.Columns.Count; i++)
{
dataRow[i] = reader[i];
}
Console.WriteLine(string.Format("From thread {0}-and data-{1}", System.Threading.Thread.CurrentThread.ManagedThreadId, dataRow[0]));
resultTable.Rows.Add(dataRow);
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
return resultTable;
}
*/
#region Query To DataReader
public DbDataReader QueryToDataReader(string commandText, int commandTimeout = 60, params object[] parameters)
{
if (string.IsNullOrEmpty(commandText)) throw new ArgumentException("commandText is NULL!");
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
return dbCommand.ExecuteReader();
}
}
public async Task<DbDataReader> QueryToDataReaderAsync(string commandText, int commandTimeout = 60, params object[] parameters)
{
return await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, CancellationToken.None, commandTimeout, parameters);
}
public async Task<DbDataReader> QueryToDataReaderAsync(string commandText, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
return await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters);
}
public async Task<DbDataReader> QueryToDataReaderAsync(string commandText, CommandBehavior commandBehavior, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
if (string.IsNullOrEmpty(commandText)) throw new ArgumentException("commandText is NULL!");
//await EnsureConnectionOpenAsync();
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
return await dbCommand.ExecuteReaderAsync(commandBehavior, cancellationToken);
}
}
public DbDataReader QueryToDataReader(DbCommand dbCommand, int commandTimeout = 60, params object[] parameters)
{
_connection = dbCommand.Connection;
EnsureConnectionOpen();
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
return dbCommand.ExecuteReader();
}
}
public async Task<DbDataReader> QueryToDataReaderAsync(DbCommand dbCommand, int commandTimeout = 60, params object[] parameters)
{
return await QueryToDataReaderAsync(dbCommand, CommandBehavior.CloseConnection, CancellationToken.None, commandTimeout, parameters);
}
public async Task<DbDataReader> QueryToDataReaderAsync(DbCommand dbCommand, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
return await QueryToDataReaderAsync(dbCommand, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters);
}
public async Task<DbDataReader> QueryToDataReaderAsync(DbCommand dbCommand, CommandBehavior commandBehavior, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
_connection = dbCommand.Connection;
await EnsureConnectionOpenAsync();
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
return await dbCommand.ExecuteReaderAsync(commandBehavior, cancellationToken);
}
}
#endregion Query To DataReader
#endregion Query Methods
#region Single / Scalar Methods
public dynamic QuerySingle(string commandText, int commandTimeout = 0, params object[] args)
{
if (!string.IsNullOrEmpty(commandText))
{
return QueryInternal(commandText, commandTimeout, args).FirstOrDefault<object>();
}
throw new ArgumentException("commandText is NULL!");
}
public static dynamic QuerySingle(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QuerySingle(commandText, commandTimeout, parameters);
}
}
public static dynamic QuerySingle(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QuerySingle(commandText, commandTimeout, parameters);
}
}
public dynamic QueryValue(string commandText, int commandTimeout = 0, params object[] args)
{
if (string.IsNullOrEmpty(commandText)) throw new ArgumentException("commandText is NULL!");
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0) dbCommand.CommandTimeout = commandTimeout;
AddParameters(dbCommand, args);
object obj;
using (dbCommand)
{
obj = dbCommand.ExecuteScalar();
}
return obj;
}
public static dynamic QueryValue(string connectionString, string providerName, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenConnectionString(connectionString, providerName))
{
return db.QueryValue(commandText, commandTimeout, parameters);
}
}
public static dynamic QueryValue(DbConnection connection, string commandText, int commandTimeout = 60, params object[] parameters)
{
using (var db = OpenDbConnection(connection))
{
return db.QueryValue(commandText, commandTimeout, parameters);
}
}
#endregion Single / Scalar Methods
#endregion Public Command Methods
#region Private Query Methods
protected IEnumerable<dynamic> QueryInternal(string commandText, int commandTimeout = 60, params object[] parameters)
{
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
List<string> columnNames = null;
var fcnt = 0;
var dbDataReaders = dbCommand.ExecuteReader();
using (dbDataReaders)
{
foreach (DbDataRecord dbDataRecord in dbDataReaders)
{
if (columnNames == null)
{
fcnt = dbDataRecord.FieldCount;
columnNames = GetColumnNames(dbDataRecord).ToList();
}
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (var i = 0; i < fcnt; i++)
d.Add(columnNames[i], DbNullToNull(dbDataRecord[i]));
yield return e;
}
}
}
}
private async Task<List<dynamic>> QueryInternalAsync(string commandText, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
var rv = new List<dynamic>();
List<string> columnNames = null;
var fcnt = 0;
using (var dr = await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters))
{
while (await dr.ReadAsync(cancellationToken))
{
if (columnNames == null)
{
fcnt = dr.FieldCount;
columnNames = GetColumnNames(dr).ToList();
}
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (var i = 0; i < fcnt; i++)
{
d.Add(columnNames[i], DbNullToNull(await dr.GetFieldValueAsync<object>(i, cancellationToken)));
}
rv.Add(e);
}
}
return rv;
}
private IEnumerable<JObject> QueryInternalJObjects(string commandText, int commandTimeout = 60, params object[] parameters)
{
EnsureConnectionOpen();
var dbCommand = Connection.CreateCommand();
dbCommand.CommandText = commandText;
dbCommand.CommandType = InferCommandType(commandText);
if (commandTimeout > 0)
{
dbCommand.CommandTimeout = commandTimeout;
}
AddParameters(dbCommand, parameters);
using (dbCommand)
{
List<string> columnNames = null;
var fcnt = 0;
var dbDataReaders = dbCommand.ExecuteReader();
using (dbDataReaders)
{
foreach (DbDataRecord dbDataRecord in dbDataReaders)
{
if (columnNames == null)
{
fcnt = dbDataRecord.FieldCount;
columnNames = GetColumnNames(dbDataRecord).ToList();
}
dynamic e = new JObject();
var d = e as IDictionary<string, JToken>;
for (var i = 0; i < fcnt; i++)
d.Add(columnNames[i], JToken.FromObject(dbDataRecord[i]));
yield return e;
}
}
}
}
private async Task<List<JObject>> QueryInternalJObjectsAsync(string commandText, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
var rv = new List<JObject>();
List<string> columnNames = null;
var fcnt = 0;
using (var dr = await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters))
{
while (await dr.ReadAsync(cancellationToken))
{
if (columnNames == null)
{
fcnt = dr.FieldCount;
columnNames = GetColumnNames(dr).ToList();
}
dynamic e = new JObject();
var d = e as IDictionary<string, JToken>;
for (var i = 0; i < fcnt; i++)
{
d.Add(columnNames[i], JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken)));
}
rv.Add(e);
}
}
return rv;
}
private async Task<List<T>> QueryInternalTransformToAsync<T>(string commandText, Func<JObject, T> function, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
var rv = new List<T>();
List<string> columnNames = null;
var fcnt = 0;
using (var dr = await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters))
{
while (await dr.ReadAsync(cancellationToken))
{
if (columnNames == null)
{
fcnt = dr.FieldCount;
columnNames = GetColumnNames(dr).ToList();
}
dynamic e = new JObject();
var d = e as IDictionary<string, JToken>;
for (var i = 0; i < fcnt; i++)
{
d.Add(columnNames[i], JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken)));
}
rv.Add(function.Invoke(e));
}
}
return rv;
}
private async Task<Stream> QueryInternalJObjectWriterAsync(string commandText, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
var rv = new MemoryStream();
List<string> columnNames = null;
var fcnt = 0;
using (var dr = await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters))
{
using (var writer = new JsonTextWriter(new StreamWriter(rv)))
{
//var jobjectType = typeof(JObject);
//var serializer = JsonSerializer.CreateDefault();
writer.WriteStartArray();
while (await dr.ReadAsync(cancellationToken))
{
writer.WriteStartObject();
if (columnNames == null)
{
fcnt = dr.FieldCount;
columnNames = GetColumnNames(dr).ToList();
}
//dynamic e = new JObject();
//var d = e as IDictionary<string, JToken>;
for (var i = 0; i < fcnt; i++)
{
//d.Add(columnNames[i], JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken)));
//var token = JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken));
writer.WritePropertyName(columnNames[i]);
writer.WriteValue(await dr.GetFieldValueAsync<object>(i, cancellationToken));
}
//serializer.Serialize(writer, d, jobjectType);
writer.WriteEnd();
//writer.WriteValue(e);
//rv.Add(e);
}
writer.WriteEndArray();
//serializer.Serialize(writer, value, type);
}
if (rv.CanSeek) rv.Seek(0, SeekOrigin.Begin); // reset Stream to beginning.
}
return rv;
}
private async Task<Stream> QueryInternalBsonAsync(string commandText, CancellationToken cancellationToken, int commandTimeout = 60, params object[] parameters)
{
var rv = new MemoryStream();
List<string> columnNames = null;
var fcnt = 0;
using (var dr = await QueryToDataReaderAsync(commandText, CommandBehavior.CloseConnection, cancellationToken, commandTimeout, parameters))
{
using (var writer = new BsonWriter(rv))
{
//var jobjectType = typeof(JObject);
//var serializer = JsonSerializer.CreateDefault();
writer.WriteStartArray();
while (await dr.ReadAsync(cancellationToken))
{
writer.WriteStartObject();
if (columnNames == null)
{
fcnt = dr.FieldCount;
columnNames = GetColumnNames(dr).ToList();
}
dynamic e = new JObject();
//var d = e as IDictionary<string, JToken>;
for (var i = 0; i < fcnt; i++)
{
//d.Add(columnNames[i], JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken)));
//var token = JToken.FromObject(await dr.GetFieldValueAsync<object>(i, cancellationToken));
writer.WritePropertyName(columnNames[i]);
writer.WriteValue(await dr.GetFieldValueAsync<object>(i, cancellationToken));
}
//serializer.Serialize(writer, d, jobjectType);
writer.WriteEnd();
//writer.WriteValue(e);
//rv.Add(e);
}
writer.WriteEndArray();
writer.Flush();
//serializer.Serialize(writer, value, type);
}
if (rv.CanSeek) rv.Seek(0, SeekOrigin.Begin); // reset Stream to beginning.
}
return rv;
}
#endregion Private Query Methods
#endregion Query Methods
#region IDisposable Region
public void Close()
{
Dispose();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && _connection != null)
{
_connection.Close();
_connection = null;
}
}
#endregion IDisposable Region
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Concurrency;
using Orleans.Runtime.Configuration;
namespace Orleans
{
/// <summary>
/// Interface for Membership Table.
/// </summary>
public interface IMembershipTable
{
/// <summary>
/// Initializes the membership table, will be called before all other methods
/// </summary>
/// <param name="globalConfiguration">the give global configuration</param>
/// <param name="tryInitTableVersion">whether an attempt will be made to init the underlying table</param>
/// <param name="traceLogger">the logger used by the membership table</param>
Task InitializeMembershipTable(GlobalConfiguration globalConfiguration, bool tryInitTableVersion, TraceLogger traceLogger);
/// <summary>
/// Deletes all table entries of the given deploymentId
/// </summary>
Task DeleteMembershipTableEntries(string deploymentId);
/// <summary>
/// Atomically reads the Membership Table information about a given silo.
/// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the
/// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically.
/// </summary>
/// <param name="entry">The address of the silo whose membership information needs to be read.</param>
/// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and
/// TableVersion, read atomically.</returns>
Task<MembershipTableData> ReadRow(SiloAddress key);
/// <summary>
/// Atomically reads the full content of the Membership Table.
/// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the
/// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically.
/// </summary>
/// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and
/// TableVersion, all read atomically.</returns>
Task<MembershipTableData> ReadAll();
/// <summary>
/// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) New MembershipEntry will be added to the table.
/// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo already exist in the table
/// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be inserted.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the insert operation succeeded and false otherwise.</returns>
Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion);
/// <summary>
/// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry)
/// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo does not exist in the table
/// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag.
/// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be updated.</param>
/// <param name="etag">The etag for the given MembershipEntry.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the update operation succeeded and false otherwise.</returns>
Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion);
/// <summary>
/// Updates the IAmAlive part (column) of the MembershipEntry for this silo.
/// This operation should only update the IAmAlive collumn and not change other columns.
/// This operation is a "dirty write" or "in place update" and is performed without etag validation.
/// With regards to eTags update:
/// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write").
/// With regards to TableVersion:
/// this operation should not change the TableVersion of the table. It should leave it untouched.
/// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability.
/// </summary>
/// <param name="entry"></param>
/// <returns>Task representing the successful execution of this operation. </returns>
Task UpdateIAmAlive(MembershipEntry entry);
}
/// <summary>
/// Membership table interface for grain based implementation.
/// </summary>
[Unordered]
public interface IMembershipTableGrain : IGrainWithGuidKey, IMembershipTable
{
}
[Serializable]
[Immutable]
public class TableVersion
{
/// <summary>
/// The version part of this TableVersion. Monotonically increasing number.
/// </summary>
public int Version { get; private set; }
/// <summary>
/// The etag of this TableVersion, used for validation of table update operations.
/// </summary>
public string VersionEtag { get; private set; }
public TableVersion(int version, string eTag)
{
Version = version;
VersionEtag = eTag;
}
public TableVersion Next()
{
return new TableVersion(Version + 1, VersionEtag);
}
public override string ToString()
{
return string.Format("<{0}, {1}>", Version, VersionEtag);
}
}
[Serializable]
public class MembershipTableData
{
public IReadOnlyList<Tuple<MembershipEntry, string>> Members { get; private set; }
public TableVersion Version { get; private set; }
public MembershipTableData(List<Tuple<MembershipEntry, string>> list, TableVersion version)
{
// put deads at the end, just for logging.
list.Sort(
(x, y) =>
{
if (x.Item1.Status.Equals(SiloStatus.Dead)) return 1; // put Deads at the end
if (y.Item1.Status.Equals(SiloStatus.Dead)) return -1; // put Deads at the end
return String.Compare(x.Item1.InstanceName, y.Item1.InstanceName, StringComparison.Ordinal);
});
Members = list.AsReadOnly();
Version = version;
}
public MembershipTableData(Tuple<MembershipEntry, string> tuple, TableVersion version)
{
Members = (new List<Tuple<MembershipEntry, string>> { tuple }).AsReadOnly();
Version = version;
}
public MembershipTableData(TableVersion version)
{
Members = (new List<Tuple<MembershipEntry, string>>()).AsReadOnly();
Version = version;
}
public Tuple<MembershipEntry, string> Get(SiloAddress silo)
{
return Members.First(tuple => tuple.Item1.SiloAddress.Equals(silo));
}
public bool Contains(SiloAddress silo)
{
return Members.Any(tuple => tuple.Item1.SiloAddress.Equals(silo));
}
public override string ToString()
{
int active = Members.Count(e => e.Item1.Status == SiloStatus.Active);
int dead = Members.Count(e => e.Item1.Status == SiloStatus.Dead);
int created = Members.Count(e => e.Item1.Status == SiloStatus.Created);
int joining = Members.Count(e => e.Item1.Status == SiloStatus.Joining);
int shuttingDown = Members.Count(e => e.Item1.Status == SiloStatus.ShuttingDown);
int stopping = Members.Count(e => e.Item1.Status == SiloStatus.Stopping);
string otherCounts = String.Format("{0}{1}{2}{3}",
created > 0 ? (", " + created + " are Created") : "",
joining > 0 ? (", " + joining + " are Joining") : "",
shuttingDown > 0 ? (", " + shuttingDown + " are ShuttingDown") : "",
stopping > 0 ? (", " + stopping + " are Stopping") : "");
return string.Format("{0} silos, {1} are Active, {2} are Dead{3}, Version={4}. All silos: {5}",
Members.Count,
active,
dead,
otherCounts,
Version,
Utils.EnumerableToString(Members, tuple => tuple.Item1.ToFullString()));
}
// return a copy of the table removing all dead appereances of dead nodes, except for the last one.
public MembershipTableData SupressDuplicateDeads()
{
var dead = new Dictionary<string, Tuple<MembershipEntry, string>>();
// pick only latest Dead for each instance
foreach (var next in Members.Where(item => item.Item1.Status == SiloStatus.Dead))
{
var name = next.Item1.InstanceName;
Tuple<MembershipEntry, string> prev;
if (!dead.TryGetValue(name, out prev))
{
dead[name] = next;
}
else
{
// later dead.
if (next.Item1.SiloAddress.Generation.CompareTo(prev.Item1.SiloAddress.Generation) > 0)
dead[name] = next;
}
}
//now add back non-dead
List<Tuple<MembershipEntry, string>> all = dead.Values.ToList();
all.AddRange(Members.Where(item => item.Item1.Status != SiloStatus.Dead));
return new MembershipTableData(all, Version);
}
}
[Serializable]
public class MembershipEntry
{
public SiloAddress SiloAddress { get; set; }
public string HostName { get; set; }
public SiloStatus Status { get; set; }
public int ProxyPort { get; set; }
public string RoleName { get; set; } // Optional - only for Azure role
public string InstanceName { get; set; } // Optional - only for Azure role
public int UpdateZone { get; set; } // Optional - only for Azure role
public int FaultZone { get; set; } // Optional - only for Azure role
public DateTime StartTime { get; set; } // Time this silo was started. For diagnostics.
public DateTime IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics.
public List<Tuple<SiloAddress, DateTime>> SuspectTimes { get; set; }
private static readonly List<Tuple<SiloAddress, DateTime>> EmptyList = new List<Tuple<SiloAddress, DateTime>>(0);
public void AddSuspector(SiloAddress suspectingSilo, DateTime suspectingTime)
{
if (SuspectTimes == null)
SuspectTimes = new List<Tuple<SiloAddress, DateTime>>();
var suspector = new Tuple<SiloAddress, DateTime>(suspectingSilo, suspectingTime);
SuspectTimes.Add(suspector);
}
// partialUpdate arrivies via gossiping with other oracles. In such a case only take the status.
internal void Update(MembershipEntry updatedSiloEntry)
{
SiloAddress = updatedSiloEntry.SiloAddress;
Status = updatedSiloEntry.Status;
//---
HostName = updatedSiloEntry.HostName;
ProxyPort = updatedSiloEntry.ProxyPort;
RoleName = updatedSiloEntry.RoleName;
InstanceName = updatedSiloEntry.InstanceName;
UpdateZone = updatedSiloEntry.UpdateZone;
FaultZone = updatedSiloEntry.FaultZone;
SuspectTimes = updatedSiloEntry.SuspectTimes;
StartTime = updatedSiloEntry.StartTime;
IAmAliveTime = updatedSiloEntry.IAmAliveTime;
}
internal List<Tuple<SiloAddress, DateTime>> GetFreshVotes(TimeSpan expiration)
{
if (SuspectTimes == null)
return EmptyList;
DateTime now = DateTime.UtcNow;
return SuspectTimes.FindAll(voter =>
{
DateTime otherVoterTime = voter.Item2;
// If now is smaller than otherVoterTime, than assume the otherVoterTime is fresh.
// This could happen if clocks are not synchronized and the other voter clock is ahead of mine.
if (now < otherVoterTime)
return true;
return now.Subtract(otherVoterTime) < expiration;
});
}
internal void TryUpdateStartTime(DateTime startTime)
{
if (StartTime.Equals(default(DateTime)))
StartTime = startTime;
}
public override string ToString()
{
return string.Format("SiloAddress={0} InstanceName={1} Status={2}", SiloAddress.ToLongString(), InstanceName, Status);
}
internal string ToFullString(bool full = false)
{
if (!full)
return ToString();
List<SiloAddress> suspecters = SuspectTimes == null
? null
: SuspectTimes.Select(tuple => tuple.Item1).ToList();
List<DateTime> timestamps = SuspectTimes == null
? null
: SuspectTimes.Select(tuple => tuple.Item2).ToList();
return string.Format("[SiloAddress={0} InstanceName={1} Status={2} HostName={3} ProxyPort={4} " +
"RoleName={5} UpdateZone={6} FaultZone={7} StartTime = {8} IAmAliveTime = {9} {10} {11}]",
SiloAddress.ToLongString(),
InstanceName,
Status,
HostName,
ProxyPort,
RoleName,
UpdateZone,
FaultZone,
TraceLogger.PrintDate(StartTime),
TraceLogger.PrintDate(IAmAliveTime),
suspecters == null
? ""
: "Suspecters = " + Utils.EnumerableToString(suspecters, sa => sa.ToLongString()),
timestamps == null
? ""
: "SuspectTimes = " + Utils.EnumerableToString(timestamps, TraceLogger.PrintDate)
);
}
}
}
| |
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 dks3Api.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;
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Car repair, sales, or parts.
/// </summary>
public class AutomotiveBusiness_Core : TypeCore, ILocalBusiness
{
public AutomotiveBusiness_Core()
{
this._TypeId = 30;
this._Id = "AutomotiveBusiness";
this._Schema_Org_Url = "http://schema.org/AutomotiveBusiness";
string label = "";
GetLabel(out label, "AutomotiveBusiness", typeof(AutomotiveBusiness_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[]{23,24,25,26,27,28,110,160,167};
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
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 TopGearApi.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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Owin.Host.HttpListener;
using Microsoft.Owin.Logging;
using Topshelf;
using Topshelf.HostConfigurators;
using Topshelf.Logging;
using Topshelf.Runtime;
using TraceFactoryDelegate = System.Func<string, System.Func<
System.Diagnostics.TraceEventType,
int,
object,
System.Exception,
System.Func<object,System.Exception,string>,
bool
>
>;
namespace Tavis.Owin
{
public class OwinServiceHost : ServiceControl
{
public string ServiceDescription { get; set; }
public string ServiceDisplayName { get; set; }
public string ServiceName { get; set; }
private Uri _HostUrl;
private readonly Func<IDictionary<string, object>, Task> _appFunc;
private static readonly LogWriter _log = HostLogger.Get<OwinServiceHost>();
private IDisposable _server;
/// <summary>
/// Create an OwinServiceHost
/// </summary>
/// <param name="defaultUrl">Currently only one URI. Ideally multiple should be supported.</param>
/// <param name="appFunc"></param>
public OwinServiceHost(Uri defaultUrl, Func<IDictionary<string,object>, Task> appFunc )
{
_HostUrl = defaultUrl;
_appFunc = appFunc;
}
/// <summary>
/// Call this method to initialize and run the service
/// </summary>
/// <param name="extraConfig"></param>
/// <returns></returns>
public TopshelfExitCode Initialize(Action<HostConfigurator> extraConfig = null)
{
return HostFactory.Run(configurator =>
{
Configure(configurator);
if (extraConfig != null) extraConfig(configurator);
});
}
private void Configure(HostConfigurator x)
{
//HostLogger.UseLogger(new TraceHostLoggerConfigurator()); Do this outside the class
x.Service(settings => this);
x.BeforeInstall(BeforeInstall);
x.AfterUninstall(AfterUnInstall);
x.RunAsNetworkService(); // Ideally this should be configurable
// I'm debating whether to pick this up from attributes of the executing assembly, or be explicit about it.
if (ServiceDescription != null) x.SetDescription(ServiceDescription);
if (ServiceDisplayName != null) x.SetDisplayName(ServiceDisplayName);
x.SetServiceName(ServiceName);
}
bool ServiceControl.Start(HostControl hostControl)
{
LoadConfig();
_log.Info("Creating HTTP listener at " + _HostUrl.AbsoluteUri);
_server = CreateHttpListenerServer(new List<Uri>() { _HostUrl }, _appFunc, TopShelfKatanaLoggerAdapter.CreateOwinDelegate(_log));
return _server != null;
}
bool ServiceControl.Stop(HostControl hostControl)
{
_server.Dispose();
_server = null;
return true;
}
private void BeforeInstall()
{
Console.Write("Enter host URL [{0}]:",_HostUrl);
var uri = AskForUri();
if (uri != null)
{
_HostUrl = uri;
StoreConfig();
}
AddUrlAcl(_HostUrl);
}
private void AfterUnInstall()
{
LoadConfig();
DeleteAcl(_HostUrl);
}
private void AddUrlAcl(Uri uri)
{
_log.Info("Adding Url ACL for Network Service for " + uri.AbsoluteUri);
var process = Process.Start(Environment.ExpandEnvironmentVariables("%SystemRoot%\\System32\\netsh.exe"),
String.Format("http add urlacl url={0} user=\"NT AUTHORITY\\NetworkService\"", uri.OriginalString));
process.WaitForExit();
_log.Debug("Completed with exit code " + process.ExitCode);
}
private void StoreConfig()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var host = config.AppSettings.Settings["Host"];
if (host != null)
{
host.Value = _HostUrl.AbsoluteUri;
}
else
{
config.AppSettings.Settings.Add("Host",_HostUrl.AbsoluteUri);
}
_log.Info("Saving selected URL to configuration file");
config.Save(ConfigurationSaveMode.Modified);
}
private void LoadConfig()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var hostUrl = config.AppSettings.Settings["Host"];
if (hostUrl != null) _HostUrl = new Uri(hostUrl.Value); // Override default URL if one is stored
}
private Uri AskForUri()
{
Uri newUri = null;
bool tryAgain = false;
do
{
var inputUrl = Console.ReadLine();
if (Uri.IsWellFormedUriString(inputUrl, UriKind.Absolute))
{
inputUrl += inputUrl.EndsWith("/") ? "" : "/";
newUri = new Uri(inputUrl);
}
else
{
if (!String.IsNullOrWhiteSpace(inputUrl))
{
tryAgain = true;
}
}
} while (tryAgain);
return newUri;
}
private void DeleteAcl(Uri uri)
{
_log.Info("Deleting Url ACL for Network Service for " + uri.AbsoluteUri);
var process = Process.Start(Environment.ExpandEnvironmentVariables("%SystemRoot%\\System32\\netsh.exe"), String.Format("http delete urlacl url={0}", uri.AbsoluteUri));
process.WaitForExit();
_log.Debug("Completed with exit code " + process.ExitCode);
}
public static IDisposable CreateHttpListenerServer(List<Uri> baseAddresses, Func<IDictionary<string, object>, Task> appFunc, TraceFactoryDelegate loggerFunc)
{
var props = new Dictionary<string, object>();
var addresses = baseAddresses.Select(baseAddress => new Dictionary<string, object>()
{
{"host", baseAddress.Host},
{"port", baseAddress.Port.ToString()},
{"scheme", baseAddress.Scheme},
{"path", baseAddress.AbsolutePath}
}).Cast<IDictionary<string, object>>().ToList();
props["host.Addresses"] = addresses;
props["server.LoggerFactory"] = loggerFunc;
OwinServerFactory.Initialize(props);
return OwinServerFactory.Create(appFunc, props);
}
}
public class TopShelfKatanaLoggerAdapter : ILogger
{
private readonly string _name;
private readonly LogWriter _logWriter;
public static TraceFactoryDelegate CreateOwinDelegate(LogWriter logWriter)
{
return (name) =>
{
var logger = new TopShelfKatanaLoggerAdapter(name, logWriter);
return logger.WriteCore;
};
}
public TopShelfKatanaLoggerAdapter(string name, LogWriter logWriter)
{
_name = name;
_logWriter = logWriter;
}
public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
switch (eventType)
{
case TraceEventType.Information:
_logWriter.Info(_name + ":" + state);
break;
case TraceEventType.Error:
case TraceEventType.Critical:
_logWriter.Error(_name + ":" + state, exception);
break;
default:
_logWriter.Debug(_name + ":" + state);
break;
}
return true;
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nmap.Internal;
using System;
using System.Linq;
using Testing.Common;
namespace Nmap.Testing
{
[TestClass]
public class MapValidatorTesting
{
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapDuplicated_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map,
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapIsNotForComplexTypes_ForSimpleTypes_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<string, string>().get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapIsNotForComplexTypes_ForEnumerableTypes_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity[], MainEntityModel[]>().get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapperOrTypeUnMapperIsNotDefined_OnlyMapper_ThrowsMapValidationException()
{
ReversiveTypeMap reversiveTypeMap = new ReversiveTypeMap(typeof(MainEntity), typeof(MainEntityModel));
reversiveTypeMap.set_Mapper(delegate(object DataSourceAttribute, object dest, TypeMappingContext context)
{
});
TypeMapBase[] array = new TypeMapBase[]
{
reversiveTypeMap
};
new MapValidator().Validate(reversiveTypeMap, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapperOrTypeUnMapperIsNotDefined_OnlyUnMapper_ThrowsMapValidationException()
{
ReversiveTypeMap reversiveTypeMap = new ReversiveTypeMap(typeof(MainEntity), typeof(MainEntityModel));
reversiveTypeMap.set_UnMapper(delegate(object source, object dest, TypeMappingContext context)
{
});
TypeMapBase[] array = new TypeMapBase[]
{
reversiveTypeMap
};
new MapValidator().Validate(reversiveTypeMap, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfTypeMapHasMapperAndPropertyMaps_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}).get_Map();
map.set_Mapper(delegate(object source, object dest, TypeMappingContext context)
{
});
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapDuplicated_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}).MapProperty((MainEntity o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapperOrPropertyUnMapperIsNotDefined_OnlyMapper_ThrowsMapValidationException()
{
ReversiveTypeMap map = MapBuilder.get_Instance().CreateReversiveMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}, delegate(MainEntityModel source, MainEntity dest, TypeMappingContext context)
{
}).get_Map();
map.get_PropertyMaps().First<ReversivePropertyMap>().set_UnMapper(null);
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapperOrPropertyUnMapperIsNotDefined_OnlyUnMapper_ThrowsMapValidationException()
{
ReversiveTypeMap map = MapBuilder.get_Instance().CreateReversiveMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}, delegate(MainEntityModel source, MainEntity dest, TypeMappingContext context)
{
}).get_Map();
map.get_PropertyMaps().First<ReversivePropertyMap>().set_Mapper(null);
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapHasMapperAndInheritanceMapsOrNothing_HasBoth_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}).get_Map();
map.get_PropertyMaps().First<PropertyMap>().get_InheritanceMaps().Add(MapBuilder.get_Instance().CreateMap<SubEntity, SubSubEntityModel>().get_Map());
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapHasMapperAndInheritanceMapsOrNothing_HasNothing_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext context)
{
}).get_Map();
map.get_PropertyMaps().First<PropertyMap>().set_Mapper(null);
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapIsForBothEnumerableOrComplexTypes_SourcePropertyIsEnumerable_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntityArrayToArray, (MainEntityModel o) => o.SubEntity, new TypeMap[]
{
MapBuilder.get_Instance().CreateMap<SubEntity, SubSubEntityModel>().get_Map()
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapIsForBothEnumerableOrComplexTypes_DestinationPropertyIsEnumerable_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => o.SubEntityArrayToArray, new TypeMap[]
{
MapBuilder.get_Instance().CreateMap<SubEntity, SubSubEntityModel>().get_Map()
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapIsForBothEnumerableOrComplexTypes_SourcePropertyIsSimple_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => (object)o.Simple, (MainEntityModel o) => o.SubEntity, new TypeMap[]
{
MapBuilder.get_Instance().CreateMap<SubEntity, SubSubEntityModel>().get_Map()
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfPropertyMapIsForBothEnumerableOrComplexTypes_DestinationPropertyIsSimple_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => (object)o.Simple, new TypeMap[]
{
MapBuilder.get_Instance().CreateMap<SubEntity, SubEntityModel>().get_Map()
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map
};
new MapValidator().Validate(map, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfInheritanceMapDuplicated_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<SubEntity, SubEntityModel>().get_Map();
TypeMap map2 = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => o.SubEntityArrayToArray, new TypeMap[]
{
map,
map
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map2
};
new MapValidator().Validate(map2, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfInheritanceMapIsNotForDerivedTypes_BadSourceType_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<SubEntity, SubSubEntityModel>().get_Map();
TypeMap map2 = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntityArrayToArray, (MainEntityModel o) => o.SubEntityArrayToArray, new TypeMap[]
{
map
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map2
};
new MapValidator().Validate(map2, array);
}
[ExpectedException(typeof(MapValidationException)), TestMethod]
public void Validate_IfInheritanceMapIsNotForDerivedTypes_BadDestinationType_ThrowsMapValidationException()
{
TypeMap map = MapBuilder.get_Instance().CreateMap<SubEntity, System.Type>().get_Map();
TypeMap map2 = MapBuilder.get_Instance().CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity o) => o.SubEntity, (MainEntityModel o) => o.SubEntity, new TypeMap[]
{
map
}).get_Map();
TypeMapBase[] array = new TypeMapBase[]
{
map2
};
new MapValidator().Validate(map2, array);
}
}
}
| |
//
// Copyright (c) 2004-2017 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
{
using System;
using System.ComponentModel;
using JetBrains.Annotations;
/// <content>
/// Auto-generated Logger members for binary compatibility with NLog 1.0.
/// </content>
[CLSCompliant(false)]
public partial interface ILoggerBase
{
#region Log() overloads
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="value">A <see langword="object" /> to be written.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
void Log(LogLevel level, object value);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="value">A <see langword="object" /> to be written.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
void Log(LogLevel level, IFormatProvider formatProvider, object value);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="arg1">First argument to format.</param>
/// <param name="arg2">Second argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, object arg1, object arg2);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="arg1">First argument to format.</param>
/// <param name="arg2">Second argument to format.</param>
/// <param name="arg3">Third argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, object arg1, object arg2, object arg3);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, bool argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, bool argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, char argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, char argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, byte argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, byte argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, string argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, string argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, int argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, int argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, long argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, long argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, float argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, float argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, double argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, double argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, decimal argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, decimal argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, object argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, object argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, sbyte argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, sbyte argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, uint argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, uint argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter and formatting it with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, string message, ulong argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified value as a parameter.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[StringFormatMethod("message")]
void Log(LogLevel level, string message, ulong argument);
#endregion
}
}
#endif
| |
/*
* Copyright 2014 Splunk, 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.
*/
namespace Splunk.Client.AcceptanceTests
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using Splunk.Client;
using Splunk.Client.Helpers;
using Xunit;
/// <summary>
/// This is the search test class
/// </summary>
public class SearchTest
{
/// <summary>
/// Search query which will give 'sg' tags
/// in output when "segmentation == raw".
/// </summary>
const string Search = "search index=_internal GET | head 3";
/// <summary>
/// Tests the result from a bad search argument.
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task BadOutputMode()
{
using (var service = await SdkHelper.CreateService())
{
var search = "invalidpart" + Search;
try
{
await service.Jobs.CreateAsync(search);
}
catch (BadRequestException)
{
return;
}
catch (Exception e)
{
Assert.True(false, string.Format("Unexpected exception: {0}\n{1}", e.Message, e.StackTrace));
}
Assert.True(false, string.Format("Expected BadRequestException but no exception was thrown."));
}
}
/// <summary>
/// Tests the result from a search argument.
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobSearchMode()
{
using (var service = await SdkHelper.CreateService())
{
JobArgs jobArgs = new JobArgs();
jobArgs.SearchMode = SearchMode.Normal;
Job job = await service.Jobs.CreateAsync(Search, args: jobArgs);
Assert.NotNull(job);
jobArgs.SearchMode = SearchMode.RealTime;
bool updatedSnapshot = await job.UpdateAsync(jobArgs);
Assert.True(updatedSnapshot);
await job.CancelAsync();
}
}
/// <summary>
/// Tests the result from a search argument.
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobExecutionMode()
{
using (var service = await SdkHelper.CreateService())
{
Job job;
job = await service.Jobs.CreateAsync(Search, mode: ExecutionMode.Normal);
Assert.NotNull(job);
job = await service.Jobs.CreateAsync(Search, mode: ExecutionMode.OneShot);
Assert.NotNull(job);
job = await service.Jobs.CreateAsync(Search, mode: ExecutionMode.Blocking);
Assert.NotNull(job);
await job.CancelAsync();
}
}
/// <summary>
/// Tests all output modes for Job.Events
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobEventsTruncationModeArgument()
{
using (var service = await SdkHelper.CreateService())
{
JobArgs jobArgs = new JobArgs();
await ForEachEnum(typeof(TruncationMode), async enumValue =>
{
var job = await service.Jobs.CreateAsync(Search, args: jobArgs);
var args = new SearchEventArgs
{
TruncationMode = (TruncationMode)Enum.Parse(typeof(TruncationMode), enumValue)
};
using (SearchResultStream stream = await job.GetSearchEventsAsync(args))
{ }
await job.CancelAsync();
});
}
}
/// <summary>
/// Test that Job.SearchEventsAsync() defaults to getting all search events
/// </summary>
[Trait("acceptance_test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobEventsDefaultsToAll()
{
using (var service = await SdkHelper.CreateService())
{
JobArgs jobArgs = new JobArgs();
var job = await service.Jobs.CreateAsync("search index=_* | head 101", args: jobArgs);
using (SearchResultStream stream = await job.GetSearchEventsAsync())
{
// Is the event count greater than the default of 100?
Assert.Equal(101, job.EventCount);
}
await job.CancelAsync();
}
}
/// <summary>
/// Test that Job.GetSearchPreviewAsync() defaults to getting all search events
/// </summary>
[Trait("acceptance_test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobPreviewDefaultsToAll()
{
using (var service = await SdkHelper.CreateService())
{
JobArgs jobArgs = new JobArgs();
var job = await service.Jobs.CreateAsync("search index=_* | head 101", args: jobArgs);
for (int delay = 1000; delay < 5000; delay += 1000)
{
try
{
await job.TransitionAsync(DispatchState.Done, delay);
break;
}
catch (TaskCanceledException)
{ }
}
using (SearchResultStream stream = await job.GetSearchPreviewAsync())
{
// Is the result preview count greater than the default of 100?
Assert.Equal(101, job.ResultPreviewCount);
}
await job.CancelAsync();
}
}
/// <summary>
/// Test that Job.GetSearchResponseMessageAsync() defaults to getting all search events
/// </summary>
[Trait("acceptance_test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobResponseMessageDefaultsToAll()
{
using (var service = await SdkHelper.CreateService())
{
foreach (OutputMode outputMode in Enum.GetValues(typeof(OutputMode)))
{
foreach (ExecutionMode executionMode in Enum.GetValues(typeof(ExecutionMode)))
{
var job = await service.Jobs.CreateAsync("search index=_* | head 101", mode: executionMode);
using (HttpResponseMessage message = await job.GetSearchResponseMessageAsync(outputMode: outputMode))
{
// Is the result preview count greater than the default of 100?
Assert.Equal(101, job.EventAvailableCount);
Assert.Equal(101, job.EventCount);
Assert.Equal(101, job.ResultPreviewCount);
Assert.Equal(101, job.ResultCount);
var streamReader = new StreamReader(await message.Content.ReadAsStreamAsync());
switch (outputMode)
{
case OutputMode.Default:
Assert.Equal("?count=0", message.RequestMessage.RequestUri.Query);
{
var result = XDocument.Load(streamReader);
}
break;
case OutputMode.Atom:
Assert.Equal("?count=0&output_mode=atom", message.RequestMessage.RequestUri.Query);
{
var result = XDocument.Load(streamReader);
}
break;
case OutputMode.Csv:
Assert.Equal("?count=0&output_mode=csv", message.RequestMessage.RequestUri.Query);
using (TextFieldParser parser = new TextFieldParser(streamReader))
{
parser.Delimiters = new string[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
var fields = parser.ReadFields();
var values = new List<string[]>();
while (!parser.EndOfData)
{
values.Add(parser.ReadFields());
}
Assert.Equal(101, values.Count);
}
break;
case OutputMode.Json:
Assert.Equal("?count=0&output_mode=json", message.RequestMessage.RequestUri.Query);
using (var reader = new JsonTextReader(streamReader))
{
var serializer = JsonSerializer.CreateDefault();
var result = serializer.Deserialize(reader);
}
break;
case OutputMode.JsonColumns:
Assert.Equal("?count=0&output_mode=json_cols", message.RequestMessage.RequestUri.Query);
using (var reader = new JsonTextReader(streamReader))
{
var serializer = JsonSerializer.CreateDefault();
var result = serializer.Deserialize(reader);
}
break;
case OutputMode.JsonRows:
Assert.Equal("?count=0&output_mode=json_rows", message.RequestMessage.RequestUri.Query);
using (var reader = new JsonTextReader(streamReader))
{
var serializer = JsonSerializer.CreateDefault();
var result = serializer.Deserialize(reader);
}
break;
case OutputMode.Raw:
Assert.Equal("?count=0&output_mode=raw", message.RequestMessage.RequestUri.Query);
{
var result = streamReader.ReadToEnd();
string s = result;
}
break;
case OutputMode.Xml:
Assert.Equal("?count=0&output_mode=xml", message.RequestMessage.RequestUri.Query);
{
var result = XDocument.Load(streamReader);
}
break;
}
}
await job.CancelAsync();
}
}
}
}
/// <summary>
/// Test that Job.SearchResultsAsync() defaults to getting all search events
/// </summary>
[Trait("acceptance_test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobResultsDefaultsToAll()
{
using (var service = await SdkHelper.CreateService())
{
JobArgs jobArgs = new JobArgs();
var job = await service.Jobs.CreateAsync("search index=_* | head 101", args: jobArgs);
using (SearchResultStream stream = await job.GetSearchResultsAsync())
{
// Is the result count greater than the default of 100?
Assert.Equal(101, job.ResultCount);
}
await job.CancelAsync();
}
}
/// <summary>
/// Tests all search modes
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobSearchModeArgument()
{
var type = typeof(SearchMode);
await RunJobForEachEnum(type, mode =>
new JobArgs()
{
SearchMode = (SearchMode)Enum.Parse(type, mode)
});
}
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task JobTransitionDelay()
{
using (var service = await SdkHelper.CreateService())
{
//// Reference: [Algorithms for calculating variance](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm)
var args = new JobArgs { SearchMode = SearchMode.RealTime };
var min = double.PositiveInfinity;
var max = double.NegativeInfinity;
var n = 0;
var mean = 0.0;
var variance = 0.0;
var sampleSize = 1; // increase to compute statistics used to derive Assert.InRange values
for (n = 1; n <= sampleSize; ++n)
{
Job job = await service.Jobs.CreateAsync("search index=_internal", args: args);
DateTime start = DateTime.Now;
int totalDelay = 0;
for (int delay = 1000; delay < 5000; delay += 1000)
{
try
{
await job.TransitionAsync(DispatchState.Done, delay);
break;
}
catch (TaskCanceledException)
{ }
totalDelay += delay;
}
var duration = DateTime.Now - start;
try
{
await job.CancelAsync();
}
catch (TaskCanceledException)
{ }
var x = duration.TotalMilliseconds - totalDelay;
if (x < min)
min = x;
if (x > max)
max = x;
var delta = x - mean;
mean += delta / n;
variance += delta * (x - mean);
// Statistically derived by repeated tests with sampleSize = 100; no failures in a test with sampleSize = 10,000
// This range is outside three standard deviations. Adjust as required to support your test environment.
Assert.InRange(x, 1000, 5000);
}
double sd;
if (--n < 2)
{
sd = variance = double.NaN;
}
else
{
variance /= n - 1;
sd = Math.Sqrt(variance);
}
Console.WriteLine("\n Mean: {0}\n SD: {1}\n Range: [{3}, {4}]\n N: {2}", mean, sd, min, max, n); // swallowed by Xunit version [1.0, 2.0)
}
}
/// <summary>
/// Tests all search modes for export
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task ExportSearchModeArgument()
{
var type = typeof(SearchMode);
await RunExportForEachEnum(Search, type, (mode) =>
new SearchExportArgs()
{
SearchMode = (SearchMode)Enum.Parse(type, mode)
});
}
/// <summary>
/// Tests all search modes for export
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task ExportTruncationModeArgument()
{
var type = typeof(TruncationMode);
await RunExportForEachEnum(Search, type, (mode) =>
new SearchExportArgs()
{
TruncationMode = (TruncationMode)Enum.Parse(type, mode)
});
}
[Trait("acceptance-test", "Splunk.Client.Job")]
[MockContext]
[Fact]
public async Task CanRefreshJob()
{
const string search = "search index=_internal * | head 1 | debug cmd=sleep param1=5";
using (var service = await SdkHelper.CreateService())
{
var job = await service.Jobs.CreateAsync(search);
await this.CheckJobAsync(job, service);
Assert.True(job.DispatchState < DispatchState.Done);
await job.TransitionAsync(DispatchState.Done, 10 * 1000);
await this.CheckJobAsync(job, service);
Assert.True(job.DispatchState == DispatchState.Done);
await job.CancelAsync();
}
}
[Trait("acceptance-test", "Splunk.Client.QueuedSearchCreate")]
[MockContext]
[Fact]
public async Task QueuedSearchCreate()
{
const string searchPrefix = "search index=_internal ";
int i = 0;
using (var service = await SdkHelper.CreateService())
{
List<Job> jobs = new List<Job>();
Job job = null;
do
{
JobArgs jobArgs = new JobArgs();
jobArgs.SearchMode = SearchMode.RealTime;
try
{
// Jobs should eventually be queued w/o waiting for them to get to running state
job = await service.Jobs.Create(searchPrefix + i.ToString(), args: jobArgs);
Assert.Equal(DispatchState.None, job.DispatchState);
await job.GetAsync();
jobs.Add(job);
i++;
} catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.GetBaseException().ToString());
break;
}
} while (job.DispatchState != DispatchState.Queued);
Assert.NotNull(job);
Assert.Equal(DispatchState.Queued, job.DispatchState);
// Cleanup
foreach (Job j in jobs)
{
await j.CancelAsync();
}
}
Assert.True(i > 0);
}
[Trait("acceptance-test", "Splunk.Client.QueuedSearchCreateAsync")]
[MockContext]
[Fact]
public async Task QueuedSearchCreateAsync()
{
const string searchPrefix = "search index=_internal ";
int i = 0;
using (var service = await SdkHelper.CreateService())
{
List<Job> jobs = new List<Job>();
Job job = null;
do
{
JobArgs jobArgs = new JobArgs();
jobArgs.SearchMode = SearchMode.RealTime;
try
{
// Jobs should eventually be queued w/o waiting for them to get to running state
job = await service.Jobs.CreateAsync(searchPrefix + i.ToString(), args: jobArgs);
jobs.Add(job);
i++;
}
catch (Exception ex)
{
break;
}
} while (job.DispatchState != DispatchState.Queued);
Assert.NotNull(job);
Assert.Equal(DispatchState.Queued, job.DispatchState);
// Cleanup
foreach (Job j in jobs)
{
await j.CancelAsync();
}
}
Assert.True(i > 0);
}
#region Helpers
/// <summary>
/// Touches the job after it is queryable.
/// </summary>
/// <param name="job">The job</param>
async Task CheckJobAsync(Job job, Service service)
{
string dummyString;
//string[] dummyList;
long dummyInt;
bool dummyBool;
DateTime dummyDateTime;
double dummyDouble;
dummyDateTime = job.CursorTime;
//dummyString = job.Delegate;
dummyInt = job.DiskUsage;
DispatchState dummyDispatchState = job.DispatchState;
dummyDouble = job.DoneProgress;
dummyInt = job.DropCount;
dummyDateTime = job.EarliestTime;
dummyInt = job.EventAvailableCount;
dummyInt = job.EventCount;
dummyInt = job.EventFieldCount;
dummyBool = job.EventIsStreaming;
dummyBool = job.EventIsTruncated;
dummyString = job.EventSearch;
SortDirection sordirection = job.EventSorting;
long indexEarliestTime = job.IndexEarliestTime;
long indexLatestTime = job.IndexLatestTime;
dummyString = job.Keywords;
//dummyString = job.Label;
ServerInfo serverInfo = await service.Server.GetInfoAsync();
if (serverInfo.Version.CompareTo(new Version(6, 0)) < 0)
{
dummyDateTime = job.LatestTime;
}
dummyInt = job.NumPreviews;
dummyInt = job.Priority;
dummyString = job.RemoteSearch;
//dummyString = job.ReportSearch;
dummyInt = job.ResultCount;
dummyBool = job.ResultIsStreaming;
dummyInt = job.ResultPreviewCount;
dummyDouble = job.RunDuration;
dummyInt = job.ScanCount;
dummyString = job.EventSearch;// Search;
DateTime jobearliestTime = job.EarliestTime;//SearchEarliestTime;
DateTime joblatestTime = job.LatestTime;
ReadOnlyCollection<string> providers = job.SearchProviders;
dummyString = job.Sid;
dummyInt = job.StatusBuckets;
dummyInt = job.Ttl;
dummyBool = job.IsDone;
dummyBool = job.IsFailed;
dummyBool = job.IsFinalized;
dummyBool = job.IsPaused;
dummyBool = job.IsPreviewEnabled;
dummyBool = job.IsRealTimeSearch;
dummyBool = job.IsRemoteTimeline;
dummyBool = job.IsSaved;
dummyBool = job.IsSavedSearch;
dummyBool = job.IsZombie;
Assert.Equal(job.Name, job.Sid);
}
/// <summary>
/// Run export for each enum value in an enum type.
/// </summary>
/// <param name="enumType">The enum type</param>
/// <param name="getJobExportArgs">
/// The funtion to get arguments to run a job.
/// </param>
async Task RunExportForEachEnum(string search, Type enumType, Func<string, SearchExportArgs> getJobExportArgs)
{
using (var service = await SdkHelper.CreateService())
{
await ForEachEnum(enumType, async @enum =>
{
using (SearchPreviewStream stream = await service.ExportSearchPreviewsAsync(search, getJobExportArgs(@enum)))
{ }
});
}
}
/// <summary>
/// Run a job for each enum value in an enum type.
/// </summary>
/// <param name="enumType">The enum type</param>
/// <param name="getJobArgs">
/// The funtion to get arguments to run a job.
/// </param>
async Task RunJobForEachEnum(Type enumType, Func<string, JobArgs> getJobArgs)
{
using (var service = await SdkHelper.CreateService())
{
await ForEachEnum(enumType, async @enum =>
{
var job = await service.Jobs.CreateAsync(Search, args: getJobArgs(@enum));
await job.CancelAsync();
});
}
}
/// <summary>
/// Perform an action for each enum value in an enum type.
/// </summary>
/// <param name="enumType">The enum type</param>
/// <param name="action">
/// The action to perform on an enum value
/// </param>
static async Task ForEachEnum(Type enumType, Func<string, Task> action)
{
var enums = Enum.GetNames(enumType);
foreach (var @enum in enums)
{
await action(@enum);
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
using osu.Framework.Utils;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
public class TimelineHitObjectBlueprint : SelectionBlueprint<HitObject>
{
private const float circle_size = 38;
private Container repeatsContainer;
public Action<DragEvent> OnDragHandled;
[UsedImplicitly]
private readonly Bindable<double> startTime;
private Bindable<int> indexInCurrentComboBindable;
private Bindable<int> comboIndexBindable;
private Bindable<int> comboIndexWithOffsetsBindable;
private Bindable<Color4> displayColourBindable;
private readonly ExtendableCircle circle;
private readonly Border border;
private readonly Container colouredComponents;
private readonly OsuSpriteText comboIndexText;
[Resolved]
private ISkinSource skin { get; set; }
public TimelineHitObjectBlueprint(HitObject item)
: base(item)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
startTime = item.StartTimeBindable.GetBoundCopy();
startTime.BindValueChanged(time => X = (float)time.NewValue, true);
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.X;
Height = circle_size;
AddRangeInternal(new Drawable[]
{
circle = new ExtendableCircle
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
border = new Border
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
colouredComponents = new Container
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
comboIndexText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
Y = -1,
Font = OsuFont.Default.With(size: circle_size * 0.5f, weight: FontWeight.Regular),
},
}
},
});
if (item is IHasDuration)
{
colouredComponents.Add(new DragArea(item)
{
OnDragHandled = e => OnDragHandled?.Invoke(e)
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
switch (Item)
{
case IHasDisplayColour displayColour:
displayColourBindable = displayColour.DisplayColour.GetBoundCopy();
displayColourBindable.BindValueChanged(_ => updateColour(), true);
break;
case IHasComboInformation comboInfo:
indexInCurrentComboBindable = comboInfo.IndexInCurrentComboBindable.GetBoundCopy();
indexInCurrentComboBindable.BindValueChanged(_ => updateComboIndex(), true);
comboIndexBindable = comboInfo.ComboIndexBindable.GetBoundCopy();
comboIndexWithOffsetsBindable = comboInfo.ComboIndexWithOffsetsBindable.GetBoundCopy();
comboIndexBindable.BindValueChanged(_ => updateColour());
comboIndexWithOffsetsBindable.BindValueChanged(_ => updateColour(), true);
skin.SourceChanged += updateColour;
break;
}
}
protected override void OnSelected()
{
// base logic hides selected blueprints when not selected, but timeline doesn't do that.
updateColour();
}
protected override void OnDeselected()
{
// base logic hides selected blueprints when not selected, but timeline doesn't do that.
updateColour();
}
private void updateComboIndex() => comboIndexText.Text = (indexInCurrentComboBindable.Value + 1).ToString();
private void updateColour()
{
Color4 colour;
switch (Item)
{
case IHasDisplayColour displayColour:
colour = displayColour.DisplayColour.Value;
break;
case IHasComboInformation combo:
colour = combo.GetComboColour(skin);
break;
default:
return;
}
if (IsSelected)
border.Show();
else
border.Hide();
if (Item is IHasDuration duration && duration.Duration > 0)
circle.Colour = ColourInfo.GradientHorizontal(colour, colour.Lighten(0.4f));
else
circle.Colour = colour;
var averageColour = Interpolation.ValueAt(0.5, circle.Colour.TopLeft, circle.Colour.TopRight, 0, 1);
colouredComponents.Colour = OsuColour.ForegroundTextColourFor(averageColour);
}
private SamplePointPiece sampleOverrideDisplay;
private DifficultyPointPiece difficultyOverrideDisplay;
private DifficultyControlPoint difficultyControlPoint;
private SampleControlPoint sampleControlPoint;
protected override void Update()
{
base.Update();
// no bindable so we perform this every update
float duration = (float)(Item.GetEndTime() - Item.StartTime);
if (Width != duration)
{
Width = duration;
// kind of haphazard but yeah, no bindables.
if (Item is IHasRepeats repeats)
updateRepeats(repeats);
}
if (difficultyControlPoint != Item.DifficultyControlPoint)
{
difficultyControlPoint = Item.DifficultyControlPoint;
difficultyOverrideDisplay?.Expire();
if (Item.DifficultyControlPoint != null && Item is IHasDistance)
{
AddInternal(difficultyOverrideDisplay = new DifficultyPointPiece(Item)
{
Anchor = Anchor.TopLeft,
Origin = Anchor.BottomCentre
});
}
}
if (sampleControlPoint != Item.SampleControlPoint)
{
sampleControlPoint = Item.SampleControlPoint;
sampleOverrideDisplay?.Expire();
if (Item.SampleControlPoint != null)
{
AddInternal(sampleOverrideDisplay = new SamplePointPiece(Item)
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopCentre
});
}
}
}
private void updateRepeats(IHasRepeats repeats)
{
repeatsContainer?.Expire();
colouredComponents.Add(repeatsContainer = new Container
{
RelativeSizeAxes = Axes.Both,
});
for (int i = 0; i < repeats.RepeatCount; i++)
{
repeatsContainer.Add(new Tick
{
X = (float)(i + 1) / (repeats.RepeatCount + 1)
});
}
}
protected override bool ShouldBeConsideredForInput(Drawable child) => true;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) =>
circle.ReceivePositionalInputAt(screenSpacePos);
public override Quad SelectionQuad => circle.ScreenSpaceDrawQuad;
public override Vector2 ScreenSpaceSelectionPoint => ScreenSpaceDrawQuad.TopLeft;
private class Tick : Circle
{
public Tick()
{
Size = new Vector2(circle_size / 4);
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
}
}
public class DragArea : Circle
{
private readonly HitObject hitObject;
[Resolved]
private Timeline timeline { get; set; }
public Action<DragEvent> OnDragHandled;
public override bool HandlePositionalInput => hitObject != null;
public DragArea(HitObject hitObject)
{
this.hitObject = hitObject;
CornerRadius = circle_size / 2;
Masking = true;
Size = new Vector2(circle_size, 1);
Anchor = Anchor.CentreRight;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
updateState();
FinishTransforms();
}
protected override bool OnHover(HoverEvent e)
{
updateState();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateState();
base.OnHoverLost(e);
}
private bool hasMouseDown;
protected override bool OnMouseDown(MouseDownEvent e)
{
hasMouseDown = true;
updateState();
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
hasMouseDown = false;
updateState();
base.OnMouseUp(e);
}
private void updateState()
{
float scale = 0.5f;
if (hasMouseDown)
scale = 0.6f;
else if (IsHovered)
scale = 0.7f;
this.ScaleTo(scale, 200, Easing.OutQuint);
this.FadeTo(IsHovered || hasMouseDown ? 1f : 0.9f, 200, Easing.OutQuint);
}
[Resolved]
private EditorBeatmap beatmap { get; set; }
[Resolved]
private IBeatSnapProvider beatSnapProvider { get; set; }
[Resolved(CanBeNull = true)]
private IEditorChangeHandler changeHandler { get; set; }
protected override bool OnDragStart(DragStartEvent e)
{
changeHandler?.BeginChange();
return true;
}
private ScheduledDelegate dragOperation;
protected override void OnDrag(DragEvent e)
{
base.OnDrag(e);
// schedule is temporary to ensure we don't process multiple times on a single update frame. we need to find a better method of doing this.
// without it, a hitobject's endtime may not always be in a valid state (ie. sliders, which needs to recompute their path).
dragOperation?.Cancel();
dragOperation = Scheduler.Add(() =>
{
OnDragHandled?.Invoke(e);
if (timeline.SnapScreenSpacePositionToValidTime(e.ScreenSpaceMousePosition).Time is double time)
{
switch (hitObject)
{
case IHasRepeats repeatHitObject:
double proposedDuration = time - hitObject.StartTime;
if (e.CurrentState.Keyboard.ShiftPressed)
{
if (hitObject.DifficultyControlPoint == DifficultyControlPoint.DEFAULT)
hitObject.DifficultyControlPoint = new DifficultyControlPoint();
double newVelocity = hitObject.DifficultyControlPoint.SliderVelocity * (repeatHitObject.Duration / proposedDuration);
if (Precision.AlmostEquals(newVelocity, hitObject.DifficultyControlPoint.SliderVelocity))
return;
hitObject.DifficultyControlPoint.SliderVelocity = newVelocity;
beatmap.Update(hitObject);
}
else
{
// find the number of repeats which can fit in the requested time.
double lengthOfOneRepeat = repeatHitObject.Duration / (repeatHitObject.RepeatCount + 1);
int proposedCount = Math.Max(0, (int)Math.Round(proposedDuration / lengthOfOneRepeat) - 1);
if (proposedCount == repeatHitObject.RepeatCount)
return;
repeatHitObject.RepeatCount = proposedCount;
beatmap.Update(hitObject);
}
break;
case IHasDuration endTimeHitObject:
double snappedTime = Math.Max(hitObject.StartTime, beatSnapProvider.SnapTime(time));
if (endTimeHitObject.EndTime == snappedTime || Precision.AlmostEquals(snappedTime, hitObject.StartTime, beatmap.GetBeatLengthAtTime(snappedTime)))
return;
endTimeHitObject.Duration = snappedTime - hitObject.StartTime;
beatmap.Update(hitObject);
break;
}
}
});
}
protected override void OnDragEnd(DragEndEvent e)
{
base.OnDragEnd(e);
OnDragHandled?.Invoke(null);
changeHandler?.EndChange();
}
}
public class Border : ExtendableCircle
{
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Content.Child.Alpha = 0;
Content.Child.AlwaysPresent = true;
Content.BorderColour = colours.Yellow;
Content.EdgeEffect = new EdgeEffectParameters();
}
}
/// <summary>
/// A circle with externalised end caps so it can take up the full width of a relative width area.
/// </summary>
public class ExtendableCircle : CompositeDrawable
{
protected readonly Circle Content;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Content.ReceivePositionalInputAt(screenSpacePos);
public override Quad ScreenSpaceDrawQuad => Content.ScreenSpaceDrawQuad;
public ExtendableCircle()
{
Padding = new MarginPadding { Horizontal = -circle_size / 2f };
InternalChild = Content = new Circle
{
BorderColour = OsuColour.Gray(0.75f),
BorderThickness = 4,
Masking = true,
RelativeSizeAxes = Axes.Both,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = 5,
Colour = Color4.Black.Opacity(0.4f)
}
};
}
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Services.GridService
{
public class GridService : GridServiceBase, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string LogHeader = "[GRID SERVICE]";
private bool m_DeleteOnUnregister = true;
private static GridService m_RootInstance = null;
protected IConfigSource m_config;
protected static HypergridLinker m_HypergridLinker;
protected IAuthenticationService m_AuthenticationService = null;
protected bool m_AllowDuplicateNames = false;
protected bool m_AllowHypergridMapSearch = false;
private static Dictionary<string,object> m_ExtraFeatures = new Dictionary<string, object>();
public GridService(IConfigSource config)
: base(config)
{
m_log.DebugFormat("[GRID SERVICE]: Starting...");
m_config = config;
IConfig gridConfig = config.Configs["GridService"];
bool suppressConsoleCommands = false;
if (gridConfig != null)
{
m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
string authService = gridConfig.GetString("AuthenticationService", String.Empty);
if (authService != String.Empty)
{
Object[] args = new Object[] { config };
m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
}
m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
// This service is also used locally by a simulator running in grid mode. This switches prevents
// inappropriate console commands from being registered
suppressConsoleCommands = gridConfig.GetBoolean("SuppressConsoleCommands", suppressConsoleCommands);
}
if (m_RootInstance == null)
{
m_RootInstance = this;
if (!suppressConsoleCommands && MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Regions", true,
"deregister region id",
"deregister region id <region-id>+",
"Deregister a region manually.",
String.Empty,
HandleDeregisterRegion);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show regions",
"show regions",
"Show details on all regions",
String.Empty,
HandleShowRegions);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region name",
"show region name <Region name>",
"Show details on a region",
String.Empty,
HandleShowRegion);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region at",
"show region at <x-coord> <y-coord>",
"Show details on a region at the given co-ordinate.",
"For example, show region at 1000 1000",
HandleShowRegionAt);
MainConsole.Instance.Commands.AddCommand("General", true,
"show grid size",
"show grid size",
"Show the current grid size (excluding hyperlink references)",
String.Empty,
HandleShowGridSize);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"set region flags",
"set region flags <Region name> <flags>",
"Set database flags for region",
String.Empty,
HandleSetFlags);
}
if (!suppressConsoleCommands)
SetExtraServiceURLs(config);
m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
}
}
private void SetExtraServiceURLs(IConfigSource config)
{
IConfig loginConfig = config.Configs["LoginService"];
IConfig gridConfig = config.Configs["GridService"];
if (loginConfig == null || gridConfig == null)
return;
string configVal;
configVal = loginConfig.GetString("SearchURL", string.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["search-server-url"] = configVal;
configVal = loginConfig.GetString("MapTileURL", string.Empty);
if (!string.IsNullOrEmpty(configVal))
{
// This URL must end with '/', the viewer doesn't check
configVal = configVal.Trim();
if (!configVal.EndsWith("/"))
configVal = configVal + "/";
m_ExtraFeatures["map-server-url"] = configVal;
}
configVal = loginConfig.GetString("DestinationGuide", string.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["destination-guide-url"] = configVal;
configVal = Util.GetConfigVarFromSections<string>(
config, "GatekeeperURI", new string[] { "Startup", "Hypergrid" }, String.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["GridURL"] = configVal;
configVal = Util.GetConfigVarFromSections<string>(
config, "GridName", new string[] { "Const", "Hypergrid" }, String.Empty);
if (string.IsNullOrEmpty(configVal))
configVal = Util.GetConfigVarFromSections<string>(
config, "gridname", new string[] { "GridInfo" }, String.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["GridName"] = configVal;
m_ExtraFeatures["ExportSupported"] = gridConfig.GetString("ExportSupported", "true");
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
{
IConfig gridConfig = m_config.Configs["GridService"];
if (regionInfos.RegionID == UUID.Zero)
return "Invalid RegionID - cannot be zero UUID";
if (regionInfos.RegionLocY <= Constants.MaximumRegionSize)
return "Region location reserved for HG links coord Y must be higher than " + (Constants.MaximumRegionSize/256).ToString();
String reason = "Region overlaps another region";
List<RegionData> rdatas = m_Database.Get(
regionInfos.RegionLocX,
regionInfos.RegionLocY,
regionInfos.RegionLocX + regionInfos.RegionSizeX - 1,
regionInfos.RegionLocY + regionInfos.RegionSizeY - 1 ,
scopeID);
RegionData region = null;
if(rdatas.Count > 1)
{
m_log.WarnFormat("{0} Register region overlaps with {1} regions", LogHeader, scopeID, rdatas.Count);
return reason;
}
else if(rdatas.Count == 1)
region = rdatas[0];
if ((region != null) && (region.RegionID != regionInfos.RegionID))
{
// If not same ID and same coordinates, this new region has conflicts and can't be registered.
m_log.WarnFormat("{0} Register region conflict in scope {1}. {2}", LogHeader, scopeID, reason);
return reason;
}
if (region != null)
{
// There is a preexisting record
//
// Get it's flags
//
OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]);
// Is this a reservation?
//
if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0)
{
// Regions reserved for the null key cannot be taken.
if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
return "Region location is reserved";
// Treat it as an auth request
//
// NOTE: Fudging the flags value here, so these flags
// should not be used elsewhere. Don't optimize
// this with the later retrieval of the same flags!
rflags |= OpenSim.Framework.RegionFlags.Authenticate;
}
if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0)
{
// Can we authenticate at all?
//
if (m_AuthenticationService == null)
return "No authentication possible";
if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
return "Bad authentication";
}
}
// If we get here, the destination is clear. Now for the real check.
if (!m_AllowDuplicateNames)
{
List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID);
if (dupe != null && dupe.Count > 0)
{
foreach (RegionData d in dupe)
{
if (d.RegionID != regionInfos.RegionID)
{
m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).",
regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID);
return "Duplicate region name";
}
}
}
}
// If there is an old record for us, delete it if it is elsewhere.
region = m_Database.Get(regionInfos.RegionID, scopeID);
if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
{
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0)
return "Can't move this region";
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0)
return "Region locked out";
// Region reregistering in other coordinates. Delete the old entry
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionCoordX, regionInfos.RegionCoordY);
try
{
m_Database.Delete(regionInfos.RegionID);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
}
// Everything is ok, let's register
RegionData rdata = RegionInfo2RegionData(regionInfos);
rdata.ScopeID = scopeID;
if (region != null)
{
int oldFlags = Convert.ToInt32(region.Data["flags"]);
oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation;
rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
}
else
{
rdata.Data["flags"] = "0";
if ((gridConfig != null) && rdata.RegionName != string.Empty)
{
int newFlags = 0;
string regionName = rdata.RegionName.Trim().Replace(' ', '_');
newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
rdata.Data["flags"] = newFlags.ToString();
}
}
int flags = Convert.ToInt32(rdata.Data["flags"]);
flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
try
{
rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
m_Database.Store(rdata);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
m_log.DebugFormat
("[GRID SERVICE]: Region {0} ({1}, {2}x{3}) registered at {4},{5} with flags {6}",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionSizeX, regionInfos.RegionSizeY,
regionInfos.RegionCoordX, regionInfos.RegionCoordY,
(OpenSim.Framework.RegionFlags)flags);
return String.Empty;
}
// String describing name and region location of passed region
private String RegionString(RegionData reg)
{
return String.Format("{0}/{1} at <{2},{3}>",
reg.RegionName, reg.RegionID, reg.coordX, reg.coordY);
}
// String describing name and region location of passed region
private String RegionString(GridRegion reg)
{
return String.Format("{0}/{1} at <{2},{3}>",
reg.RegionName, reg.RegionID, reg.RegionCoordX, reg.RegionCoordY);
}
public bool DeregisterRegion(UUID regionID)
{
RegionData region = m_Database.Get(regionID, UUID.Zero);
if (region == null)
return false;
m_log.DebugFormat(
"[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}",
region.RegionName, region.RegionID, region.coordX, region.coordY);
int flags = Convert.ToInt32(region.Data["flags"]);
if ((!m_DeleteOnUnregister) || ((flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0))
{
flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline;
region.Data["flags"] = flags.ToString();
region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
try
{
m_Database.Store(region);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
return true;
}
return m_Database.Delete(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
List<GridRegion> rinfos = new List<GridRegion>();
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
List<RegionData> rdatas = m_Database.Get(
region.posX - 1, region.posY - 1,
region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID);
foreach (RegionData rdata in rdatas)
{
if (rdata.RegionID != regionID)
{
int flags = Convert.ToInt32(rdata.Data["flags"]);
if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
// string rNames = "";
// foreach (GridRegion gr in rinfos)
// rNames += gr.RegionName + ",";
// m_log.DebugFormat("{0} region {1} has {2} neighbours ({3})",
// LogHeader, region.RegionName, rinfos.Count, rNames);
}
else
{
m_log.WarnFormat(
"[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found",
scopeID, regionID);
}
return rinfos;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
RegionData rdata = m_Database.Get(regionID, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
// The snapping is technically unnecessary but is harmless because regions are always
// multiples of the legacy region size (256).
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
uint regionX = Util.WorldToRegionLoc((uint)x);
uint regionY = Util.WorldToRegionLoc((uint)y);
int snapX = (int)Util.RegionToWorldLoc(regionX);
int snapY = (int)Util.RegionToWorldLoc(regionY);
RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
if (rdata != null)
{
m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in database. Pos=<{2},{3}>",
LogHeader, rdata.RegionName, regionX, regionY);
return RegionData2RegionInfo(rdata);
}
else
{
// m_log.DebugFormat("{0} GetRegionByPosition. Did not find region in database. Pos=<{1},{2}>",
// LogHeader, regionX, regionY);
return null;
}
}
public GridRegion GetRegionByName(UUID scopeID, string name)
{
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID);
if ((rdatas != null) && (rdatas.Count > 0))
return RegionData2RegionInfo(rdatas[0]); // get the first
if (m_AllowHypergridMapSearch)
{
GridRegion r = GetHypergridRegionByName(scopeID, name);
if (r != null)
return r;
}
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
// m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
List<RegionData> rdatas = m_Database.Get("%" + Util.EscapeForLike(name) + "%", scopeID);
int count = 0;
List<GridRegion> rinfos = new List<GridRegion>();
if (count < maxNumber && m_AllowHypergridMapSearch && name.Contains("."))
{
string regionURI = "";
string regionName = "";
if(!Util.buildHGRegionURI(name, out regionURI, out regionName))
return null;
string mapname;
bool localGrid = m_HypergridLinker.IsLocalGrid(regionURI);
if(localGrid)
mapname = regionName;
else
mapname = regionURI + regionName;
bool haveMatch = false;
if (rdatas != null && (rdatas.Count > 0))
{
// m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
if(rdata.RegionName == mapname)
{
haveMatch = true;
if(count == maxNumber)
{
rinfos.RemoveAt(count - 1);
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
}
if(haveMatch)
return rinfos;
}
rdatas = m_Database.Get(Util.EscapeForLike(mapname)+ "%", scopeID);
if (rdatas != null && (rdatas.Count > 0))
{
// m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
if(rdata.RegionName == mapname)
{
haveMatch = true;
if(count == maxNumber)
{
rinfos.RemoveAt(count - 1);
rinfos.Add(RegionData2RegionInfo(rdata));
break;
}
}
}
if(haveMatch)
return rinfos;
}
if(!localGrid && !string.IsNullOrWhiteSpace(regionURI))
{
string HGname = regionURI +" "+ regionName; // include space for compatibility
GridRegion r = m_HypergridLinker.LinkRegion(scopeID, HGname);
if (r != null)
{
if( count == maxNumber)
rinfos.RemoveAt(count - 1);
rinfos.Add(r);
}
}
}
else if (rdatas != null && (rdatas.Count > 0))
{
// m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
return rinfos;
}
/// <summary>
/// Get a hypergrid region.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name"></param>
/// <returns>null if no hypergrid region could be found.</returns>
protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
{
if (name.Contains("."))
{
string regionURI = "";
string regionName = "";
if(!Util.buildHGRegionURI(name, out regionURI, out regionName))
return null;
string mapname;
bool localGrid = m_HypergridLinker.IsLocalGrid(regionURI);
if(localGrid)
mapname = regionName;
else
mapname = regionURI + regionName;
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(mapname), scopeID);
if ((rdatas != null) && (rdatas.Count > 0))
return RegionData2RegionInfo(rdatas[0]); // get the first
if(!localGrid && !string.IsNullOrWhiteSpace(regionURI))
{
string HGname = regionURI +" "+ regionName;
return m_HypergridLinker.LinkRegion(scopeID, HGname);
}
}
return null;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
List<GridRegion> rinfos = new List<GridRegion>();
foreach (RegionData rdata in rdatas)
rinfos.Add(RegionData2RegionInfo(rdata));
return rinfos;
}
#endregion
#region Data structure conversions
public RegionData RegionInfo2RegionData(GridRegion rinfo)
{
RegionData rdata = new RegionData();
rdata.posX = (int)rinfo.RegionLocX;
rdata.posY = (int)rinfo.RegionLocY;
rdata.sizeX = rinfo.RegionSizeX;
rdata.sizeY = rinfo.RegionSizeY;
rdata.RegionID = rinfo.RegionID;
rdata.RegionName = rinfo.RegionName;
rdata.Data = rinfo.ToKeyValuePairs();
rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
return rdata;
}
public GridRegion RegionData2RegionInfo(RegionData rdata)
{
GridRegion rinfo = new GridRegion(rdata.Data);
rinfo.RegionLocX = rdata.posX;
rinfo.RegionLocY = rdata.posY;
rinfo.RegionSizeX = rdata.sizeX;
rinfo.RegionSizeY = rdata.sizeY;
rinfo.RegionID = rdata.RegionID;
rinfo.RegionName = rdata.RegionName;
rinfo.ScopeID = rdata.ScopeID;
return rinfo;
}
#endregion
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
int hgDefaultRegionsFoundOnline = regions.Count;
// For now, hypergrid default regions will always be given precedence but we will also return simple default
// regions in case no specific hypergrid regions are specified.
ret.AddRange(GetDefaultRegions(scopeID));
int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
m_log.DebugFormat(
"[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
return ret;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
return ret;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
int flags = Convert.ToInt32(region.Data["flags"]);
//m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
return flags;
}
else
return -1;
}
private void HandleDeregisterRegion(string module, string[] cmd)
{
if (cmd.Length < 4)
{
MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
return;
}
for (int i = 3; i < cmd.Length; i++)
{
string rawRegionUuid = cmd[i];
UUID regionUuid;
if (!UUID.TryParse(rawRegionUuid, out regionUuid))
{
MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid);
return;
}
GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid);
return;
}
if (DeregisterRegion(regionUuid))
{
MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid);
}
else
{
// I don't think this can ever occur if we know that the region exists.
MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid);
}
}
}
private void HandleShowRegions(string module, string[] cmd)
{
if (cmd.Length != 2)
{
MainConsole.Instance.Output("Syntax: show regions");
return;
}
List<RegionData> regions = m_Database.Get(0, 0, int.MaxValue, int.MaxValue, UUID.Zero);
OutputRegionsToConsoleSummary(regions);
}
private void HandleShowGridSize(string module, string[] cmd)
{
List<RegionData> regions = m_Database.Get(0, 0, int.MaxValue, int.MaxValue, UUID.Zero);
double size = 0;
foreach (RegionData region in regions)
{
int flags = Convert.ToInt32(region.Data["flags"]);
if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0)
size += region.sizeX * region.sizeY;
}
MainConsole.Instance.Output("This is a very rough approximation.");
MainConsole.Instance.Output("Although it will not count regions that are actually links to others over the Hypergrid, ");
MainConsole.Instance.Output("it will count regions that are inactive but were not deregistered from the grid service");
MainConsole.Instance.Output("(e.g. simulator crashed rather than shutting down cleanly).\n");
MainConsole.Instance.OutputFormat("Grid size: {0} km squared.", size / 1000000);
}
private void HandleShowRegion(string module, string[] cmd)
{
if (cmd.Length != 4)
{
MainConsole.Instance.Output("Syntax: show region name <region name>");
return;
}
string regionName = cmd[3];
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("No region with name {0} found", regionName);
return;
}
OutputRegionsToConsole(regions);
}
private void HandleShowRegionAt(string module, string[] cmd)
{
if (cmd.Length != 5)
{
MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
return;
}
uint x, y;
if (!uint.TryParse(cmd[3], out x))
{
MainConsole.Instance.Output("x-coord must be an integer");
return;
}
if (!uint.TryParse(cmd[4], out y))
{
MainConsole.Instance.Output("y-coord must be an integer");
return;
}
RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y);
return;
}
OutputRegionToConsole(region);
}
private void OutputRegionToConsole(RegionData r)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
ConsoleDisplayList dispList = new ConsoleDisplayList();
dispList.AddRow("Region Name", r.RegionName);
dispList.AddRow("Region ID", r.RegionID);
dispList.AddRow("Location", string.Format("{0},{1}", r.coordX, r.coordY));
dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY));
dispList.AddRow("URI", r.Data["serverURI"]);
dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
dispList.AddRow("Flags", flags);
MainConsole.Instance.Output(dispList.ToString());
}
private void OutputRegionsToConsole(List<RegionData> regions)
{
foreach (RegionData r in regions)
OutputRegionToConsole(r);
}
private void OutputRegionsToConsoleSummary(List<RegionData> regions)
{
ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
dispTable.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
dispTable.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
dispTable.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
dispTable.AddColumn("Size", 11);
dispTable.AddColumn("Flags", 60);
foreach (RegionData r in regions)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
dispTable.AddRow(
r.RegionName,
r.RegionID.ToString(),
string.Format("{0},{1}", r.coordX, r.coordY),
string.Format("{0}x{1}", r.sizeX, r.sizeY),
flags.ToString());
}
MainConsole.Instance.Output(dispTable.ToString());
}
private int ParseFlags(int prev, string flags)
{
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string p in parts)
{
int val;
try
{
if (p.StartsWith("+"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f |= (OpenSim.Framework.RegionFlags)val;
}
else if (p.StartsWith("-"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f &= ~(OpenSim.Framework.RegionFlags)val;
}
else
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
f |= (OpenSim.Framework.RegionFlags)val;
}
}
catch (Exception)
{
MainConsole.Instance.Output("Error in flag specification: " + p);
}
}
return (int)f;
}
private void HandleSetFlags(string module, string[] cmd)
{
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
return;
}
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("Region not found");
return;
}
foreach (RegionData r in regions)
{
int flags = Convert.ToInt32(r.Data["flags"]);
flags = ParseFlags(flags, cmd[4]);
r.Data["flags"] = flags.ToString();
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
m_Database.Store(r);
}
}
/// <summary>
/// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh
/// parameters in the viewer used to access services like map, search and destination guides.
/// <para>see "SimulatorFeaturesModule" </para>
/// </summary>
/// <returns>
/// The grid extra service URls.
/// </returns>
public Dictionary<string,object> GetExtraFeatures()
{
return m_ExtraFeatures;
}
}
}
| |
/// @license MIT License <https://opensource.org/licenses/MIT>
/// @copyright Copyright (C) Turbo Labz 2017 - All rights reserved
/// Source from this file can be used as per the license agreement
/// Open source
///
/// @author Mubeen Iqbal <mubeen@turbolabz.com>
/// @company Turbo Labz <http://turbolabz.com>
/// @date 2017-02-23 15:21:49 UTC+05:00
///
/// @description
/// [add_description_here]
using System;
using System.Collections.Generic;
namespace TurboLabz.UnityStateMachine
{
public class StateRepresentation<TState, TTrigger> : IStateRepresentation<TState, TTrigger>
{
// Remember that transitions are always outgoing for a state. They
// can never be incoming. Every state can only control where it can
// go next, not from where the state was reached.
// These transitions belong to this state only, not to the super states.
private readonly IDictionary<TTrigger, TState> _ownTransitions = new Dictionary<TTrigger, TState>();
private bool _isActive;
private readonly IList<Action> _entryActions = new List<Action>();
private readonly IList<Action> _exitActions = new List<Action>();
private readonly IList<IStateRepresentation<TState, TTrigger>> _subStates = new List<IStateRepresentation<TState, TTrigger>>();
public TState state { get; private set; }
public IStateRepresentation<TState, TTrigger> superState { get; set; }
// These are all the transitions i.e.
// inherited (from super states) + own transitions.
public IDictionary<TTrigger, TState> transitions
{
get
{
IDictionary<TTrigger, TState> allTransitions = new Dictionary<TTrigger, TState>();
if (superState != null)
{
foreach (KeyValuePair<TTrigger, TState> item in superState.transitions)
{
if (allTransitions.ContainsKey(item.Key))
{
throw new InvalidOperationException("The trigger '" + item.Key + "' is already present in one of the super state transitions of the state '" + item.Value + "'.");
}
allTransitions.Add(item);
}
}
foreach (KeyValuePair<TTrigger, TState> item in _ownTransitions)
{
if (allTransitions.ContainsKey(item.Key))
{
throw new InvalidOperationException("The trigger '" + item.Key + "' is already present in one of the super state transitions of the state '" + item.Value + "'.");
}
allTransitions.Add(item);
}
return allTransitions;
}
}
public ICollection<TTrigger> permittedTriggers
{
get
{
return transitions.Keys;
}
}
public StateRepresentation(TState state)
{
this.state = state;
}
public bool CanHandle(TTrigger trigger)
{
return transitions.ContainsKey(trigger);
}
public void AddTransition(TTrigger trigger, TState state)
{
if (_ownTransitions.ContainsKey(trigger))
{
throw new InvalidOperationException("The trigger '" + trigger + "' is already present in one of the transitions of the state '" + state + "'.");
}
_ownTransitions.Add(trigger, state);
}
public TState GetTransitionState(TTrigger trigger)
{
if (!transitions.ContainsKey(trigger))
{
throw new KeyNotFoundException("No transition present for trigger " + trigger);
}
return transitions[trigger];
}
public void OnEnter(ITransition<TState, TTrigger> transition)
{
// In order to enter this state we have to enter its super states
// first.
if (superState != null)
{
superState.OnEnter(transition);
}
if (_isActive)
{
return;
}
foreach (Action action in _entryActions)
{
action();
}
_isActive = true;
}
public void OnExit(ITransition<TState, TTrigger> transition)
{
// 1. If this state is inactive then we are not inside this state or
// any of its sub-states.
// 2. Don't call exit actions if this state or any of its sub-states
// are the destination state.
if (!_isActive || Includes(transition.destination))
{
return;
}
// Call the exit actions.
foreach (Action action in _exitActions)
{
action();
}
_isActive = false;
// Exit all super states recursively.
if (superState != null)
{
superState.OnExit(transition);
}
}
public void AddEntryAction(Action action)
{
if (action == null)
{
throw new ArgumentNullException("action", "Action parameter must not be null");
}
if (_entryActions.Contains(action))
{
throw new NotSupportedException("Action " + action + " is already added to entryActions");
}
_entryActions.Add(action);
}
public void AddExitAction(Action action)
{
if (action == null)
{
throw new ArgumentNullException("action", "Action parameter must not be null");
}
if (_exitActions.Contains(action))
{
throw new NotSupportedException("Action " + action + " is already added to exitActions");
}
_exitActions.Add(action);
}
public bool Includes(TState state)
{
bool includesState = false;
if (this.state.Equals(state))
{
includesState = true;
}
else
{
foreach (IStateRepresentation<TState, TTrigger> subState in _subStates)
{
if (subState.Includes(state))
{
includesState = true;
break;
}
}
}
return includesState;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.InteropServices
{
public static class ___ConstructorInfo
{
public static IObservable<System.UInt32> GetTypeInfoCount(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue, (_ConstructorInfoValueLambda) =>
{
System.UInt32 pcTInfoOutput = default(System.UInt32);
_ConstructorInfoValueLambda.GetTypeInfoCount(out pcTInfoOutput);
return pcTInfoOutput;
});
}
public static IObservable<System.Reactive.Unit> GetTypeInfo(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.UInt32> iTInfo, IObservable<System.UInt32> lcid, IObservable<System.IntPtr> ppTInfo)
{
return ObservableExt.ZipExecute(_ConstructorInfoValue, iTInfo, lcid, ppTInfo,
(_ConstructorInfoValueLambda, iTInfoLambda, lcidLambda, ppTInfoLambda) =>
_ConstructorInfoValueLambda.GetTypeInfo(iTInfoLambda, lcidLambda, ppTInfoLambda));
}
public static IObservable<System.Guid> GetIDsOfNames(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Guid> riid, IObservable<System.IntPtr> rgszNames, IObservable<System.UInt32> cNames,
IObservable<System.UInt32> lcid, IObservable<System.IntPtr> rgDispId)
{
return Observable.Zip(_ConstructorInfoValue, riid, rgszNames, cNames, lcid, rgDispId,
(_ConstructorInfoValueLambda, riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda, rgDispIdLambda) =>
{
_ConstructorInfoValueLambda.GetIDsOfNames(ref riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda,
rgDispIdLambda);
return riidLambda;
});
}
public static IObservable<System.Guid> Invoke(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.UInt32> dispIdMember, IObservable<System.Guid> riid, IObservable<System.UInt32> lcid,
IObservable<System.Int16> wFlags, IObservable<System.IntPtr> pDispParams,
IObservable<System.IntPtr> pVarResult, IObservable<System.IntPtr> pExcepInfo,
IObservable<System.IntPtr> puArgErr)
{
return Observable.Zip(_ConstructorInfoValue, dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult,
pExcepInfo, puArgErr,
(_ConstructorInfoValueLambda, dispIdMemberLambda, riidLambda, lcidLambda, wFlagsLambda,
pDispParamsLambda, pVarResultLambda, pExcepInfoLambda, puArgErrLambda) =>
{
_ConstructorInfoValueLambda.Invoke(dispIdMemberLambda, ref riidLambda, lcidLambda, wFlagsLambda,
pDispParamsLambda, pVarResultLambda, pExcepInfoLambda, puArgErrLambda);
return riidLambda;
});
}
public static IObservable<System.String> ToString(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.ToString());
}
public static IObservable<System.Boolean> Equals(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Object> other)
{
return Observable.Zip(_ConstructorInfoValue, other,
(_ConstructorInfoValueLambda, otherLambda) => _ConstructorInfoValueLambda.Equals(otherLambda));
}
public static IObservable<System.Int32> GetHashCode(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.GetHashCode());
}
public static IObservable<System.Type> GetType(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.GetType());
}
public static IObservable<System.Object[]> GetCustomAttributes(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(_ConstructorInfoValue, attributeType, inherit,
(_ConstructorInfoValueLambda, attributeTypeLambda, inheritLambda) =>
_ConstructorInfoValueLambda.GetCustomAttributes(attributeTypeLambda, inheritLambda));
}
public static IObservable<System.Object[]> GetCustomAttributes(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(_ConstructorInfoValue, inherit,
(_ConstructorInfoValueLambda, inheritLambda) =>
_ConstructorInfoValueLambda.GetCustomAttributes(inheritLambda));
}
public static IObservable<System.Boolean> IsDefined(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(_ConstructorInfoValue, attributeType, inherit,
(_ConstructorInfoValueLambda, attributeTypeLambda, inheritLambda) =>
_ConstructorInfoValueLambda.IsDefined(attributeTypeLambda, inheritLambda));
}
public static IObservable<System.Reflection.ParameterInfo[]> GetParameters(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.GetParameters());
}
public static IObservable<System.Reflection.MethodImplAttributes> GetMethodImplementationFlags(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.GetMethodImplementationFlags());
}
public static IObservable<System.Object> Invoke_2(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Object> obj, IObservable<System.Reflection.BindingFlags> invokeAttr,
IObservable<System.Reflection.Binder> binder, IObservable<System.Object[]> parameters,
IObservable<System.Globalization.CultureInfo> culture)
{
return Observable.Zip(_ConstructorInfoValue, obj, invokeAttr, binder, parameters, culture,
(_ConstructorInfoValueLambda, objLambda, invokeAttrLambda, binderLambda, parametersLambda, cultureLambda)
=>
_ConstructorInfoValueLambda.Invoke_2(objLambda, invokeAttrLambda, binderLambda, parametersLambda,
cultureLambda));
}
public static IObservable<System.Object> Invoke_3(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Object> obj, IObservable<System.Object[]> parameters)
{
return Observable.Zip(_ConstructorInfoValue, obj, parameters,
(_ConstructorInfoValueLambda, objLambda, parametersLambda) =>
_ConstructorInfoValueLambda.Invoke_3(objLambda, parametersLambda));
}
public static IObservable<System.Object> Invoke_4(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Reflection.BindingFlags> invokeAttr, IObservable<System.Reflection.Binder> binder,
IObservable<System.Object[]> parameters, IObservable<System.Globalization.CultureInfo> culture)
{
return Observable.Zip(_ConstructorInfoValue, invokeAttr, binder, parameters, culture,
(_ConstructorInfoValueLambda, invokeAttrLambda, binderLambda, parametersLambda, cultureLambda) =>
_ConstructorInfoValueLambda.Invoke_4(invokeAttrLambda, binderLambda, parametersLambda, cultureLambda));
}
public static IObservable<System.Object> Invoke_5(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue,
IObservable<System.Object[]> parameters)
{
return Observable.Zip(_ConstructorInfoValue, parameters,
(_ConstructorInfoValueLambda, parametersLambda) =>
_ConstructorInfoValueLambda.Invoke_5(parametersLambda));
}
public static IObservable<System.Reflection.MemberTypes> get_MemberType(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.MemberType);
}
public static IObservable<System.String> get_Name(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.Name);
}
public static IObservable<System.Type> get_DeclaringType(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.DeclaringType);
}
public static IObservable<System.Type> get_ReflectedType(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.ReflectedType);
}
public static IObservable<System.RuntimeMethodHandle> get_MethodHandle(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.MethodHandle);
}
public static IObservable<System.Reflection.MethodAttributes> get_Attributes(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.Attributes);
}
public static IObservable<System.Reflection.CallingConventions> get_CallingConvention(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.CallingConvention);
}
public static IObservable<System.Boolean> get_IsPublic(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsPublic);
}
public static IObservable<System.Boolean> get_IsPrivate(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsPrivate);
}
public static IObservable<System.Boolean> get_IsFamily(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsFamily);
}
public static IObservable<System.Boolean> get_IsAssembly(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsAssembly);
}
public static IObservable<System.Boolean> get_IsFamilyAndAssembly(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsFamilyAndAssembly);
}
public static IObservable<System.Boolean> get_IsFamilyOrAssembly(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsFamilyOrAssembly);
}
public static IObservable<System.Boolean> get_IsStatic(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsStatic);
}
public static IObservable<System.Boolean> get_IsFinal(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsFinal);
}
public static IObservable<System.Boolean> get_IsVirtual(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsVirtual);
}
public static IObservable<System.Boolean> get_IsHideBySig(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsHideBySig);
}
public static IObservable<System.Boolean> get_IsAbstract(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsAbstract);
}
public static IObservable<System.Boolean> get_IsSpecialName(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsSpecialName);
}
public static IObservable<System.Boolean> get_IsConstructor(
this IObservable<System.Runtime.InteropServices._ConstructorInfo> _ConstructorInfoValue)
{
return Observable.Select(_ConstructorInfoValue,
(_ConstructorInfoValueLambda) => _ConstructorInfoValueLambda.IsConstructor);
}
}
}
| |
/*++
Copyright (c) Microsoft Corporation
Module Name:
_SingleItemRequestCache.cs
Abstract:
Request Caching subsystem capable of caching one file at a time.
Used by, for example, auto-proxy script downloading.
Author:
Justin Brown - Aug 2, 2004
Revision History:
--*/
namespace System.Net.Cache
{
using System;
using System.Net;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Threading;
using System.Collections;
internal class SingleItemRequestCache :
#if !FEATURE_PAL
Microsoft.Win32.WinInetCache
#else
RequestCache
#endif
{
bool _UseWinInet;
FrozenCacheEntry _Entry;
private sealed class FrozenCacheEntry: RequestCacheEntry {
byte[] _StreamBytes;
string _Key;
public FrozenCacheEntry(string key, RequestCacheEntry entry, Stream stream): this(key, entry, GetBytes(stream))
{
}
public FrozenCacheEntry(string key, RequestCacheEntry entry, byte[] streamBytes): base()
{
_Key = key;
_StreamBytes = streamBytes;
IsPrivateEntry = entry.IsPrivateEntry;
StreamSize = entry.StreamSize;
ExpiresUtc = entry.ExpiresUtc;
HitCount = entry.HitCount;
LastAccessedUtc = entry.LastAccessedUtc;
entry.LastModifiedUtc = entry.LastModifiedUtc;
LastSynchronizedUtc = entry.LastSynchronizedUtc;
MaxStale = entry.MaxStale;
UsageCount = entry.UsageCount;
IsPartialEntry = entry.IsPartialEntry;
EntryMetadata = entry.EntryMetadata;
SystemMetadata = entry.SystemMetadata;
}
static byte[] GetBytes(Stream stream)
{
byte[] bytes;
bool resize = false;
if (stream.CanSeek)
bytes = new byte[stream.Length];
else
{
resize = true;
bytes = new byte[4096*2];
}
int offset = 0;
while (true)
{ int read = stream.Read(bytes, offset, bytes.Length-offset);
if (read == 0)
break;
if ((offset+=read) == bytes.Length && resize)
{
byte[] newBytes = new byte[bytes.Length+4096*2];
Buffer.BlockCopy(bytes, 0, newBytes, 0, offset);
bytes = newBytes;
}
}
if (resize)
{
byte[] newBytes = new byte[offset];
Buffer.BlockCopy(bytes, 0, newBytes, 0, offset);
bytes = newBytes;
}
return bytes;
}
public static FrozenCacheEntry Create(FrozenCacheEntry clonedObject)
{
return (object)clonedObject == (object)null? null: (FrozenCacheEntry) clonedObject.MemberwiseClone();
}
public byte[] StreamBytes { get {return _StreamBytes;}}
public string Key { get {return _Key;}}
}
internal SingleItemRequestCache(bool useWinInet) :
#if !FEATURE_PAL
base(true, true, false)
#else
base(true, true)
#endif
{
_UseWinInet = useWinInet;
}
// Returns a read data stream and metadata associated with a cached entry.
// Returns Stream.Null if there is no entry found.
// <remarks> An opened cache entry be preserved until the stream is closed. </remarks>
//
internal override Stream Retrieve(string key, out RequestCacheEntry cacheEntry)
{
Stream result;
if (!TryRetrieve(key, out cacheEntry, out result))
{
FileNotFoundException fileNotFoundException = new FileNotFoundException(null, key);
throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, fileNotFoundException.Message), fileNotFoundException);
}
return result;
}
// Returns a write cache stream associated with the string Key.
// Passed parameters allow cache to update an entry metadata accordingly.
// <remarks> The commit operation should happen on the stream closure. </remarks>
//
internal override Stream Store(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata)
{
Stream result;
if (!TryStore(key, contentLength, expiresUtc, lastModifiedUtc, maxStale, entryMetadata, systemMetadata, out result))
{
FileNotFoundException fileNotFoundException = new FileNotFoundException(null, key);
throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, fileNotFoundException.Message), fileNotFoundException);
}
return result;
}
//
// Removes an entry from the cache.
//
internal override void Remove(string key)
{
if (!TryRemove(key))
{
FileNotFoundException fileNotFoundException = new FileNotFoundException(null, key);
throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, fileNotFoundException.Message), fileNotFoundException);
}
}
//
// Updates only metadata associated with a cached entry.
//
internal override void Update(string key, DateTime expiresUtc, DateTime lastModifiedUtc, DateTime lastSynchronizedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata)
{
if (!TryUpdate(key, expiresUtc, lastModifiedUtc, lastSynchronizedUtc, maxStale, entryMetadata, systemMetadata))
{
FileNotFoundException fileNotFoundException = new FileNotFoundException(null, key);
throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, fileNotFoundException.Message), fileNotFoundException);
}
}
internal override bool TryRetrieve(string key, out RequestCacheEntry cacheEntry, out Stream readStream)
{
if (key == null)
throw new ArgumentNullException("key");
FrozenCacheEntry chkEntry = _Entry;
cacheEntry = null;
readStream = null;
if (chkEntry == null || chkEntry.Key != key)
{
#if !FEATURE_PAL
Stream realCacheStream;
RequestCacheEntry realCacheEntry;
if (!_UseWinInet || !base.TryRetrieve(key, out realCacheEntry, out realCacheStream))
return false;
chkEntry = new FrozenCacheEntry(key, realCacheEntry, realCacheStream);
// Relasing the WinInet entry earlier because we don't forward metadata-only updates ot it.
realCacheStream.Close();
_Entry = chkEntry;
#else
return false;
#endif
}
cacheEntry = FrozenCacheEntry.Create(chkEntry);
readStream = new ReadOnlyStream(chkEntry.StreamBytes);
return true;
}
internal override bool TryStore(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata, out Stream writeStream)
{
if (key == null)
throw new ArgumentNullException("key");
RequestCacheEntry requestCacheEntry = new RequestCacheEntry();
requestCacheEntry.IsPrivateEntry = this.IsPrivateCache;
requestCacheEntry.StreamSize = contentLength;
requestCacheEntry.ExpiresUtc = expiresUtc;
requestCacheEntry.LastModifiedUtc = lastModifiedUtc;
requestCacheEntry.LastAccessedUtc = DateTime.UtcNow;
requestCacheEntry.LastSynchronizedUtc = DateTime.UtcNow;
requestCacheEntry.MaxStale = maxStale;
requestCacheEntry.HitCount = 0;
requestCacheEntry.UsageCount = 0;
requestCacheEntry.IsPartialEntry = false;
requestCacheEntry.EntryMetadata = entryMetadata;
requestCacheEntry.SystemMetadata = systemMetadata;
writeStream = null;
Stream realWriteStream = null;
#if !FEATURE_PAL
if (_UseWinInet)
{
base.TryStore(key, contentLength, expiresUtc, lastModifiedUtc, maxStale, entryMetadata, systemMetadata, out realWriteStream);
}
#endif
writeStream = new WriteOnlyStream(key, this, requestCacheEntry, realWriteStream);
return true;
}
private void Commit(string key, RequestCacheEntry tempEntry, byte[] allBytes)
{
FrozenCacheEntry chkEntry = new FrozenCacheEntry(key, tempEntry, allBytes);
_Entry = chkEntry;
}
internal override bool TryRemove(string key)
{
if (key == null)
throw new ArgumentNullException("key");
#if !FEATURE_PAL
if (_UseWinInet)
{
base.TryRemove(key);
}
#endif
FrozenCacheEntry chkEntry = _Entry;
if (chkEntry != null && chkEntry.Key == key)
_Entry = null;
return true;
}
internal override bool TryUpdate(string key, DateTime expiresUtc, DateTime lastModifiedUtc, DateTime lastSynchronizedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata)
{
if (key == null)
throw new ArgumentNullException("key");
FrozenCacheEntry chkEntry = FrozenCacheEntry.Create(_Entry);
//
// This class does not forward metadata updates to WinInet to simplify the design and avoid interlocked ops
//
if (chkEntry == null || chkEntry.Key != key)
return true;
chkEntry.ExpiresUtc = expiresUtc;
chkEntry.LastModifiedUtc = lastModifiedUtc;
chkEntry.LastSynchronizedUtc = lastSynchronizedUtc;
chkEntry.MaxStale = maxStale;
chkEntry.EntryMetadata = entryMetadata;
chkEntry.SystemMetadata = systemMetadata;
_Entry = chkEntry;
return true;
}
//
// We've chosen to no forward to WinInet metadata-only updates
// Hence our entries are never locked and this method does nothing
//
internal override void UnlockEntry(Stream stream)
{
}
//
//
//
internal class ReadOnlyStream : Stream, IRequestLifetimeTracker {
private byte[] _Bytes;
private int _Offset;
private bool _Disposed;
private int _ReadTimeout;
private int _WriteTimeout;
private RequestLifetimeSetter m_RequestLifetimeSetter;
internal ReadOnlyStream(byte[] bytes): base()
{
_Bytes = bytes;
_Offset = 0;
_Disposed = false;
_ReadTimeout = _WriteTimeout = -1;
}
public override bool CanRead {get {return true;}}
public override bool CanSeek {get {return true;}}
public override bool CanTimeout {get {return true;}}
public override bool CanWrite {get {return false;}}
public override long Length {get {return _Bytes.Length;}}
public override long Position {
get {return _Offset;}
set {
if (value < 0 || value > (long)_Bytes.Length)
throw new ArgumentOutOfRangeException("value");
_Offset = (int)value;
}
}
public override int ReadTimeout {
get {return _ReadTimeout;}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite)
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
_ReadTimeout = value;
}
}
public override int WriteTimeout {
get {return _WriteTimeout;}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite)
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
_WriteTimeout = value;
}
}
public override void Flush() {}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
int result = Read(buffer, offset, count);
LazyAsyncResult ar = new LazyAsyncResult(null, state, callback);
ar.InvokeCallback(result);
return ar;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
LazyAsyncResult ar = (LazyAsyncResult) asyncResult;
if (ar.EndCalled) throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
ar.EndCalled = true;
return (int)ar.InternalWaitForCompletion();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_Disposed) throw new ObjectDisposedException(GetType().Name);
if (buffer==null) throw new ArgumentNullException("buffer");
if (offset<0 || offset>buffer.Length) throw new ArgumentOutOfRangeException("offset");
if (count<0 || count>buffer.Length-offset) throw new ArgumentOutOfRangeException("count");
if (_Offset == _Bytes.Length) return 0;
int chkOffset = (int)_Offset;
count = Math.Min(count, _Bytes.Length - chkOffset);
System.Buffer.BlockCopy(_Bytes, chkOffset, buffer, offset, count);
chkOffset += count;
_Offset = chkOffset;
return count;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
return Position = offset;
case SeekOrigin.Current:
return Position += offset;
/// <include file='doc\SeekOrigin.uex' path='docs/doc[@for="SeekOrigin.End"]/*' />
case SeekOrigin.End: return Position = _Bytes.Length-offset;
default:
throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "SeekOrigin"), "origin");
}
}
public override void SetLength(long length)
{
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
protected override void Dispose(bool disposing)
{
try {
if (!_Disposed) {
_Disposed = true;
if (disposing) {
RequestLifetimeSetter.Report(m_RequestLifetimeSetter);
}
}
}
finally {
base.Dispose(disposing);
}
}
internal byte[] Buffer
{
get
{
return _Bytes;
}
}
void IRequestLifetimeTracker.TrackRequestLifetime(long requestStartTimestamp)
{
Debug.Assert(m_RequestLifetimeSetter == null, "TrackRequestLifetime called more than once.");
m_RequestLifetimeSetter = new RequestLifetimeSetter(requestStartTimestamp);
}
}
//
//
//
private class WriteOnlyStream: Stream {
private string _Key;
private SingleItemRequestCache _Cache;
private RequestCacheEntry _TempEntry;
private Stream _RealStream;
private long _TotalSize;
private ArrayList _Buffers;
private bool _Disposed;
private int _ReadTimeout;
private int _WriteTimeout;
public WriteOnlyStream(string key, SingleItemRequestCache cache, RequestCacheEntry cacheEntry, Stream realWriteStream)
{
_Key = key;
_Cache = cache;
_TempEntry = cacheEntry;
_RealStream = realWriteStream;
_Buffers = new ArrayList();
}
public override bool CanRead {get {return false;}}
public override bool CanSeek {get {return false;}}
public override bool CanTimeout {get {return true;}}
public override bool CanWrite {get {return true;}}
public override long Length {get {throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}}
public override long Position {
get {throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
set {throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
}
public override int ReadTimeout {
get {return _ReadTimeout;}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite)
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
_ReadTimeout = value;
}
}
public override int WriteTimeout {
get {return _WriteTimeout;}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite)
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
_WriteTimeout = value;
}
}
public override void Flush() {}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
public override int EndRead(IAsyncResult asyncResult)
{throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
public override int Read(byte[] buffer, int offset, int count)
{throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
public override long Seek(long offset, SeekOrigin origin)
{throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
public override void SetLength(long length)
{throw new NotSupportedException(SR.GetString(SR.net_writeonlystream));}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Write(buffer, offset, count);
LazyAsyncResult ar = new LazyAsyncResult(null, state, callback);
ar.InvokeCallback(null);
return ar;
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
LazyAsyncResult ar = (LazyAsyncResult) asyncResult;
if (ar.EndCalled) throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndWrite"));
ar.EndCalled = true;
ar.InternalWaitForCompletion();
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_Disposed) throw new ObjectDisposedException(GetType().Name);
if (buffer==null) throw new ArgumentNullException("buffer");
if (offset<0 || offset>buffer.Length) throw new ArgumentOutOfRangeException("offset");
if (count<0 || count>buffer.Length-offset) throw new ArgumentOutOfRangeException("count");
if (_RealStream != null)
try {
_RealStream.Write(buffer, offset, count);
}
catch {
_RealStream.Close();
_RealStream = null;
}
byte[] chunk = new byte[count];
System.Buffer.BlockCopy(buffer, offset, chunk, 0, count);
_Buffers.Add(chunk);
_TotalSize += count;
}
protected override void Dispose(bool disposing)
{
_Disposed = true;
base.Dispose(disposing); // Do we mean to do this here????
if (disposing) {
if (_RealStream != null)
try {
_RealStream.Close();
}
catch {
}
byte[] allBytes = new byte[_TotalSize];
int offset = 0;
for (int i = 0; i < _Buffers.Count; ++i)
{
byte[] buffer = (byte[])_Buffers[i];
Buffer.BlockCopy(buffer, 0, allBytes, offset, buffer.Length);
offset += buffer.Length;
}
_Cache.Commit(_Key, _TempEntry, allBytes);
}
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for FindTab.
/// </summary>
internal class FindTab : System.Windows.Forms.Form
{
private System.Windows.Forms.TabPage tabFind;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtFind;
private System.Windows.Forms.RadioButton radioUp;
private System.Windows.Forms.RadioButton radioDown;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkCase;
public System.Windows.Forms.TabPage tabGoTo;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtLine;
private System.Windows.Forms.Button btnNext;
private RdlEditPreview rdlEdit;
private System.Windows.Forms.Button btnGoto;
private System.Windows.Forms.Button btnCancel;
public System.Windows.Forms.TabPage tabReplace;
private System.Windows.Forms.Button btnFindNext;
private System.Windows.Forms.CheckBox chkMatchCase;
private System.Windows.Forms.Button btnReplaceAll;
private System.Windows.Forms.Button btnReplace;
private System.Windows.Forms.TextBox txtFindR;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtReplace;
private System.Windows.Forms.Button bCloseReplace;
private System.Windows.Forms.Button bCloseGoto;
public System.Windows.Forms.TabControl tcFRG;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FindTab()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.AcceptButton = btnNext;
this.CancelButton = btnCancel;
txtFind.Focus();
}
internal FindTab(RdlEditPreview pad)
{
rdlEdit = pad;
InitializeComponent();
this.AcceptButton = btnNext;
this.CancelButton = btnCancel;
txtFind.Focus();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tcFRG = new System.Windows.Forms.TabControl();
this.tabFind = new System.Windows.Forms.TabPage();
this.btnCancel = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.chkCase = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioUp = new System.Windows.Forms.RadioButton();
this.radioDown = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.txtFind = new System.Windows.Forms.TextBox();
this.tabReplace = new System.Windows.Forms.TabPage();
this.bCloseReplace = new System.Windows.Forms.Button();
this.btnFindNext = new System.Windows.Forms.Button();
this.chkMatchCase = new System.Windows.Forms.CheckBox();
this.btnReplaceAll = new System.Windows.Forms.Button();
this.btnReplace = new System.Windows.Forms.Button();
this.txtFindR = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtReplace = new System.Windows.Forms.TextBox();
this.tabGoTo = new System.Windows.Forms.TabPage();
this.bCloseGoto = new System.Windows.Forms.Button();
this.txtLine = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.btnGoto = new System.Windows.Forms.Button();
this.tcFRG.SuspendLayout();
this.tabFind.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabReplace.SuspendLayout();
this.tabGoTo.SuspendLayout();
this.SuspendLayout();
//
// tcFRG
//
this.tcFRG.Controls.Add(this.tabFind);
this.tcFRG.Controls.Add(this.tabReplace);
this.tcFRG.Controls.Add(this.tabGoTo);
this.tcFRG.Location = new System.Drawing.Point(8, 8);
this.tcFRG.Name = "tcFRG";
this.tcFRG.SelectedIndex = 0;
this.tcFRG.Size = new System.Drawing.Size(432, 192);
this.tcFRG.TabIndex = 0;
this.tcFRG.Enter += new System.EventHandler(this.tcFRG_Enter);
this.tcFRG.SelectedIndexChanged += new System.EventHandler(this.tcFRG_SelectedIndexChanged);
//
// tabFind
//
this.tabFind.Controls.Add(this.btnCancel);
this.tabFind.Controls.Add(this.btnNext);
this.tabFind.Controls.Add(this.chkCase);
this.tabFind.Controls.Add(this.groupBox1);
this.tabFind.Controls.Add(this.label1);
this.tabFind.Controls.Add(this.txtFind);
this.tabFind.Location = new System.Drawing.Point(4, 22);
this.tabFind.Name = "tabFind";
this.tabFind.Size = new System.Drawing.Size(424, 166);
this.tabFind.TabIndex = 0;
this.tabFind.Tag = "find";
this.tabFind.Text = "Find";
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(344, 128);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Close";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnNext
//
this.btnNext.Enabled = false;
this.btnNext.Location = new System.Drawing.Point(344, 16);
this.btnNext.Name = "btnNext";
this.btnNext.TabIndex = 1;
this.btnNext.Text = "Find Next";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// chkCase
//
this.chkCase.Location = new System.Drawing.Point(208, 72);
this.chkCase.Name = "chkCase";
this.chkCase.Size = new System.Drawing.Size(88, 24);
this.chkCase.TabIndex = 2;
this.chkCase.Text = "Match Case";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioUp);
this.groupBox1.Controls.Add(this.radioDown);
this.groupBox1.Location = new System.Drawing.Point(16, 48);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(176, 64);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Search Direction";
//
// radioUp
//
this.radioUp.Location = new System.Drawing.Point(16, 24);
this.radioUp.Name = "radioUp";
this.radioUp.Size = new System.Drawing.Size(56, 24);
this.radioUp.TabIndex = 0;
this.radioUp.Text = "Up";
this.radioUp.CheckedChanged += new System.EventHandler(this.radioUp_CheckedChanged);
//
// radioDown
//
this.radioDown.Location = new System.Drawing.Point(104, 24);
this.radioDown.Name = "radioDown";
this.radioDown.Size = new System.Drawing.Size(56, 24);
this.radioDown.TabIndex = 1;
this.radioDown.Text = "Down";
//
// label1
//
this.label1.Location = new System.Drawing.Point(12, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Find";
//
// txtFind
//
this.txtFind.Location = new System.Drawing.Point(96, 16);
this.txtFind.Name = "txtFind";
this.txtFind.Size = new System.Drawing.Size(216, 20);
this.txtFind.TabIndex = 0;
this.txtFind.Text = "";
this.txtFind.TextChanged += new System.EventHandler(this.txtFind_TextChanged);
//
// tabReplace
//
this.tabReplace.Controls.Add(this.bCloseReplace);
this.tabReplace.Controls.Add(this.btnFindNext);
this.tabReplace.Controls.Add(this.chkMatchCase);
this.tabReplace.Controls.Add(this.btnReplaceAll);
this.tabReplace.Controls.Add(this.btnReplace);
this.tabReplace.Controls.Add(this.txtFindR);
this.tabReplace.Controls.Add(this.label3);
this.tabReplace.Controls.Add(this.label2);
this.tabReplace.Controls.Add(this.txtReplace);
this.tabReplace.Location = new System.Drawing.Point(4, 22);
this.tabReplace.Name = "tabReplace";
this.tabReplace.Size = new System.Drawing.Size(424, 166);
this.tabReplace.TabIndex = 1;
this.tabReplace.Tag = "replace";
this.tabReplace.Text = "Replace";
//
// bCloseReplace
//
this.bCloseReplace.Location = new System.Drawing.Point(344, 128);
this.bCloseReplace.Name = "bCloseReplace";
this.bCloseReplace.TabIndex = 6;
this.bCloseReplace.Text = "Close";
this.bCloseReplace.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnFindNext
//
this.btnFindNext.Enabled = false;
this.btnFindNext.Location = new System.Drawing.Point(344, 16);
this.btnFindNext.Name = "btnFindNext";
this.btnFindNext.TabIndex = 3;
this.btnFindNext.Text = "FindNext";
this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click);
//
// chkMatchCase
//
this.chkMatchCase.Location = new System.Drawing.Point(8, 88);
this.chkMatchCase.Name = "chkMatchCase";
this.chkMatchCase.TabIndex = 2;
this.chkMatchCase.Text = "Match Case";
//
// btnReplaceAll
//
this.btnReplaceAll.Enabled = false;
this.btnReplaceAll.Location = new System.Drawing.Point(344, 80);
this.btnReplaceAll.Name = "btnReplaceAll";
this.btnReplaceAll.TabIndex = 5;
this.btnReplaceAll.Text = "ReplaceAll";
this.btnReplaceAll.Click += new System.EventHandler(this.btnReplaceAll_Click);
//
// btnReplace
//
this.btnReplace.Enabled = false;
this.btnReplace.Location = new System.Drawing.Point(344, 48);
this.btnReplace.Name = "btnReplace";
this.btnReplace.TabIndex = 4;
this.btnReplace.Text = "Replace";
this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click);
//
// txtFindR
//
this.txtFindR.Location = new System.Drawing.Point(96, 16);
this.txtFindR.Name = "txtFindR";
this.txtFindR.Size = new System.Drawing.Size(224, 20);
this.txtFindR.TabIndex = 0;
this.txtFindR.Text = "";
this.txtFindR.TextChanged += new System.EventHandler(this.txtFindR_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(14, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(76, 23);
this.label3.TabIndex = 0;
this.label3.Text = "Find";
//
// label2
//
this.label2.Location = new System.Drawing.Point(14, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(76, 23);
this.label2.TabIndex = 5;
this.label2.Text = "Replace With";
//
// txtReplace
//
this.txtReplace.Location = new System.Drawing.Point(96, 56);
this.txtReplace.Name = "txtReplace";
this.txtReplace.Size = new System.Drawing.Size(224, 20);
this.txtReplace.TabIndex = 1;
this.txtReplace.Text = "";
//
// tabGoTo
//
this.tabGoTo.Controls.Add(this.bCloseGoto);
this.tabGoTo.Controls.Add(this.txtLine);
this.tabGoTo.Controls.Add(this.label4);
this.tabGoTo.Controls.Add(this.btnGoto);
this.tabGoTo.Location = new System.Drawing.Point(4, 22);
this.tabGoTo.Name = "tabGoTo";
this.tabGoTo.Size = new System.Drawing.Size(424, 166);
this.tabGoTo.TabIndex = 2;
this.tabGoTo.Tag = "goto";
this.tabGoTo.Text = "GoTo";
//
// bCloseGoto
//
this.bCloseGoto.Location = new System.Drawing.Point(344, 128);
this.bCloseGoto.Name = "bCloseGoto";
this.bCloseGoto.TabIndex = 2;
this.bCloseGoto.Text = "Close";
this.bCloseGoto.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtLine
//
this.txtLine.Location = new System.Drawing.Point(96, 16);
this.txtLine.Name = "txtLine";
this.txtLine.TabIndex = 0;
this.txtLine.Text = "";
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 16);
this.label4.Name = "label4";
this.label4.TabIndex = 2;
this.label4.Text = "Line Number";
//
// btnGoto
//
this.btnGoto.Location = new System.Drawing.Point(344, 16);
this.btnGoto.Name = "btnGoto";
this.btnGoto.TabIndex = 1;
this.btnGoto.Text = "GoTo";
this.btnGoto.Click += new System.EventHandler(this.btnGoto_Click);
//
// FindTab
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(448, 206);
this.Controls.Add(this.tcFRG);
this.Name = "FindTab";
this.Text = "Find";
this.TopMost = true;
this.tcFRG.ResumeLayout(false);
this.tabFind.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.tabReplace.ResumeLayout(false);
this.tabGoTo.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void radioUp_CheckedChanged(object sender, System.EventArgs e)
{
}
private void btnNext_Click(object sender, System.EventArgs e)
{
rdlEdit.FindNext(this, txtFind.Text, chkCase.Checked);
}
private void txtFind_TextChanged(object sender, System.EventArgs e)
{
if (txtFind.Text == "")
btnNext.Enabled = false;
else
btnNext.Enabled = true;
}
private void btnFindNext_Click(object sender, System.EventArgs e)
{
rdlEdit.FindNext(this, txtFindR.Text, chkCase.Checked);
txtFind.Focus();
}
private void btnReplace_Click(object sender, System.EventArgs e)
{
rdlEdit.FindNext(this, txtFindR.Text, chkCase.Checked);
rdlEdit.ReplaceNext(this, txtFindR.Text, txtReplace.Text, chkCase.Checked);
txtFindR.Focus();
}
private void txtFindR_TextChanged(object sender, System.EventArgs e)
{
bool bEnable = (txtFindR.Text == "") ? false : true;
btnFindNext.Enabled = bEnable;
btnReplace.Enabled = bEnable;
btnReplaceAll.Enabled = bEnable;
}
private void btnReplaceAll_Click(object sender, System.EventArgs e)
{
rdlEdit.ReplaceAll(this, txtFindR.Text, txtReplace.Text, chkCase.Checked);
txtFindR.Focus();
}
private void btnGoto_Click(object sender, System.EventArgs e)
{
try
{
try
{
int nLine = Int32.Parse(txtLine.Text);
rdlEdit.Goto(this, nLine);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Invalid Line Number");
}
txtLine.Focus();
}
catch(Exception er)
{
er.ToString();
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
Close();
}
private void tcFRG_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl) sender;
string tag = (string) tc.TabPages[tc.SelectedIndex].Tag;
switch (tag)
{
case "find":
this.AcceptButton = btnNext;
this.CancelButton = btnCancel;
txtFind.Focus();
break;
case "replace":
this.AcceptButton = this.btnFindNext;
this.CancelButton = this.bCloseReplace;
txtFindR.Focus();
break;
case "goto":
this.AcceptButton = btnGoto;
this.CancelButton = this.bCloseGoto;
txtLine.Focus();
break;
}
}
private void tcFRG_Enter(object sender, System.EventArgs e)
{
tcFRG_SelectedIndexChanged(this.tcFRG, new EventArgs());
}
}
}
| |
/*
* 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.Reflection;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using log4net;
namespace OpenSim.Region.Framework.Scenes.Tests
{
[TestFixture]
public class SceneObjectLinkingTests : OpenSimTestCase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Links to self should be ignored.
/// </summary>
[Test]
public void TestLinkToSelf()
{
TestHelpers.InMethod();
UUID ownerId = TestHelpers.ParseTail(0x1);
int nParts = 3;
TestScene scene = new SceneHelpers().SetupScene();
SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(nParts, ownerId, "TestLinkToSelf_", 0x10);
scene.AddSceneObject(sog1);
scene.LinkObjects(ownerId, sog1.LocalId, new List<uint>() { sog1.Parts[1].LocalId });
// sog1.LinkToGroup(sog1);
Assert.That(sog1.Parts.Length, Is.EqualTo(nParts));
}
[Test]
public void TestLinkDelink2SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
grp1.LinkToGroup(grp2);
// FIXME: Can't do this test yet since group 2 still has its root part! We can't yet null this since
// it might cause SOG.ProcessBackup() to fail due to the race condition. This really needs to be fixed.
Assert.That(grp2.IsDeleted, "SOG 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained children after delink.");
Assert.That(grp1.Parts.Length == 2);
if (debugtest)
{
m_log.Debug("parts: " + grp1.Parts.Length);
m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:"+ part1.OffsetPosition+", OffsetRotation:"+part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+part2.RotationOffset);
}
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position.");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not exactly sure what this is asserting...");
// Delink part 2
SceneObjectGroup grp3 = grp1.DelinkFromGroup(part2.LocalId);
if (debugtest)
m_log.Debug("Group2: Prim2: OffsetPosition:" + part2.AbsolutePosition + ", OffsetRotation:" + part2.RotationOffset);
Assert.That(grp1.Parts.Length, Is.EqualTo(1), "Group 1 still contained part2 after delink.");
Assert.That(part2.AbsolutePosition == Vector3.Zero, "The absolute position should be zero");
Assert.That(grp3.HasGroupChangedDueToDelink, Is.True);
}
[Test]
public void TestLinkDelink2groups4SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
SceneObjectGroup grp3 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part3 = grp3.RootPart;
SceneObjectGroup grp4 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part4 = grp4.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
grp3.AbsolutePosition = new Vector3(20, 20, 20);
grp4.AbsolutePosition = new Vector3(40, 40, 40);
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// <270,0,0>
// grp3.UpdateGroupRotationR(Quaternion.CreateFromEulers(270 * Utils.DEG_TO_RAD, 0, 0));
// <0,90,0>
grp4.UpdateGroupRotationR(Quaternion.CreateFromEulers(0, 90 * Utils.DEG_TO_RAD, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
grp4.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
grp1.LinkToGroup(grp2);
// Link grp4 to grp3.
grp3.LinkToGroup(grp4);
// At this point we should have 4 parts total in two groups.
Assert.That(grp1.Parts.Length == 2, "Group1 children count should be 2");
Assert.That(grp2.IsDeleted, "Group 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained parts after delink.");
Assert.That(grp3.Parts.Length == 2, "Group3 children count should be 2");
Assert.That(grp4.IsDeleted, "Group 4 was not registered as deleted after link.");
Assert.That(grp4.Parts.Length, Is.EqualTo(0), "Group 4 still contained parts after delink.");
if (debugtest)
{
m_log.Debug("--------After Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+ part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:"+grp3.AbsolutePosition+", Rot:"+grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:"+part3.OffsetPosition+", OffsetRotation:"+part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:"+part4.OffsetPosition+", OffsetRotation:"+part4.RotationOffset);
}
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation (again)");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position (again)");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not sure what this assertion is all about...");
// Now we're linking the first group to the third group. This will make the first group child parts of the third one.
grp3.LinkToGroup(grp1);
// Delink parts 2 and 3
grp3.DelinkFromGroup(part2.LocalId);
grp3.DelinkFromGroup(part3.LocalId);
if (debugtest)
{
m_log.Debug("--------After De-Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset);
}
Assert.That(part2.AbsolutePosition == Vector3.Zero, "Badness 1");
Assert.That(part4.OffsetPosition == new Vector3(20, 20, 20), "Badness 2");
Quaternion compareQuaternion = new Quaternion(0, 0.7071068f, 0, 0.7071068f);
Assert.That((part4.RotationOffset.X - compareQuaternion.X < 0.00003)
&& (part4.RotationOffset.Y - compareQuaternion.Y < 0.00003)
&& (part4.RotationOffset.Z - compareQuaternion.Z < 0.00003)
&& (part4.RotationOffset.W - compareQuaternion.W < 0.00003),
"Badness 3");
}
/// <summary>
/// Test that a new scene object which is already linked is correctly persisted to the persistence layer.
/// </summary>
[Test]
public void TestNewSceneObjectLinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
sog.AddPart(linkPart);
scene.AddNewSceneObject(sog, true);
// In a test, we have to crank the backup handle manually. Normally this would be done by the timer invoked
// scene backup thread.
scene.Backup(true);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.That(storedObjects.Count, Is.EqualTo(1));
Assert.That(storedObjects[0].Parts.Length, Is.EqualTo(2));
Assert.That(storedObjects[0].ContainsPart(rootPartUuid));
Assert.That(storedObjects[0].ContainsPart(linkPartUuid));
}
/// <summary>
/// Test that a delink of a previously linked object is correctly persisted to the database
/// </summary>
[Test]
public void TestDelinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
{ Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
sog.AddPart(linkPart);
scene.AddNewSceneObject(sog, true);
// In a test, we have to crank the backup handle manually. Normally this would be done by the timer invoked
// scene backup thread.
scene.Backup(true);
// These changes should occur immediately without waiting for a backup pass
SceneObjectGroup groupToDelete = sog.DelinkFromGroup(linkPart, false);
Assert.That(groupToDelete.HasGroupChangedDueToDelink, Is.True);
scene.DeleteSceneObject(groupToDelete, false);
Assert.That(groupToDelete.HasGroupChangedDueToDelink, Is.False);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.That(storedObjects.Count, Is.EqualTo(1));
Assert.That(storedObjects[0].Parts.Length, Is.EqualTo(1));
Assert.That(storedObjects[0].ContainsPart(rootPartUuid));
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Reflection
{
[System.FlagsAttribute]
public enum CallingConventions
{
Any = 3,
ExplicitThis = 64,
HasThis = 32,
Standard = 1,
VarArgs = 2,
}
[System.FlagsAttribute]
public enum EventAttributes
{
None = 0,
RTSpecialName = 1024,
SpecialName = 512,
}
[System.FlagsAttribute]
public enum FieldAttributes
{
Assembly = 3,
FamANDAssem = 2,
Family = 4,
FamORAssem = 5,
FieldAccessMask = 7,
HasDefault = 32768,
HasFieldMarshal = 4096,
HasFieldRVA = 256,
InitOnly = 32,
Literal = 64,
NotSerialized = 128,
PinvokeImpl = 8192,
Private = 1,
PrivateScope = 0,
Public = 6,
RTSpecialName = 1024,
SpecialName = 512,
Static = 16,
}
[System.FlagsAttribute]
public enum GenericParameterAttributes
{
Contravariant = 2,
Covariant = 1,
DefaultConstructorConstraint = 16,
None = 0,
NotNullableValueTypeConstraint = 8,
ReferenceTypeConstraint = 4,
SpecialConstraintMask = 28,
VarianceMask = 3,
}
[System.FlagsAttribute]
public enum MethodAttributes
{
Abstract = 1024,
Assembly = 3,
CheckAccessOnOverride = 512,
FamANDAssem = 2,
Family = 4,
FamORAssem = 5,
Final = 32,
HasSecurity = 16384,
HideBySig = 128,
MemberAccessMask = 7,
NewSlot = 256,
PinvokeImpl = 8192,
Private = 1,
PrivateScope = 0,
Public = 6,
RequireSecObject = 32768,
ReuseSlot = 0,
RTSpecialName = 4096,
SpecialName = 2048,
Static = 16,
UnmanagedExport = 8,
Virtual = 64,
VtableLayoutMask = 256,
}
public enum MethodImplAttributes
{
AggressiveInlining = 256,
CodeTypeMask = 3,
ForwardRef = 16,
IL = 0,
InternalCall = 4096,
Managed = 0,
ManagedMask = 4,
Native = 1,
NoInlining = 8,
NoOptimization = 64,
OPTIL = 2,
PreserveSig = 128,
Runtime = 3,
Synchronized = 32,
Unmanaged = 4,
}
[System.FlagsAttribute]
public enum ParameterAttributes
{
HasDefault = 4096,
HasFieldMarshal = 8192,
In = 1,
Lcid = 4,
None = 0,
Optional = 16,
Out = 2,
Retval = 8,
}
[System.FlagsAttribute]
public enum PropertyAttributes
{
HasDefault = 4096,
None = 0,
RTSpecialName = 1024,
SpecialName = 512,
}
[System.FlagsAttribute]
public enum TypeAttributes
{
Abstract = 128,
AnsiClass = 0,
AutoClass = 131072,
AutoLayout = 0,
BeforeFieldInit = 1048576,
Class = 0,
ClassSemanticsMask = 32,
CustomFormatClass = 196608,
CustomFormatMask = 12582912,
ExplicitLayout = 16,
HasSecurity = 262144,
Import = 4096,
Interface = 32,
LayoutMask = 24,
NestedAssembly = 5,
NestedFamANDAssem = 6,
NestedFamily = 4,
NestedFamORAssem = 7,
NestedPrivate = 3,
NestedPublic = 2,
NotPublic = 0,
Public = 1,
RTSpecialName = 2048,
Sealed = 256,
SequentialLayout = 8,
Serializable = 8192,
SpecialName = 1024,
StringFormatMask = 196608,
UnicodeClass = 65536,
VisibilityMask = 7,
WindowsRuntime = 16384,
}
}
namespace System.Reflection.Emit
{
public enum FlowControl
{
Branch = 0,
Break = 1,
Call = 2,
Cond_Branch = 3,
Meta = 4,
Next = 5,
Return = 7,
Throw = 8,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct OpCode
{
public System.Reflection.Emit.FlowControl FlowControl { get { return default(System.Reflection.Emit.FlowControl); } }
public string Name { get { return default(string); } }
public System.Reflection.Emit.OpCodeType OpCodeType { get { return default(System.Reflection.Emit.OpCodeType); } }
public System.Reflection.Emit.OperandType OperandType { get { return default(System.Reflection.Emit.OperandType); } }
public int Size { get { return default(int); } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { return default(System.Reflection.Emit.StackBehaviour); } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { return default(System.Reflection.Emit.StackBehaviour); } }
public short Value { get { return default(short); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Reflection.Emit.OpCode obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); }
public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); }
public override string ToString() { return default(string); }
}
public partial class OpCodes
{
internal OpCodes() { }
public static readonly System.Reflection.Emit.OpCode Add;
public static readonly System.Reflection.Emit.OpCode Add_Ovf;
public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode And;
public static readonly System.Reflection.Emit.OpCode Arglist;
public static readonly System.Reflection.Emit.OpCode Beq;
public static readonly System.Reflection.Emit.OpCode Beq_S;
public static readonly System.Reflection.Emit.OpCode Bge;
public static readonly System.Reflection.Emit.OpCode Bge_S;
public static readonly System.Reflection.Emit.OpCode Bge_Un;
public static readonly System.Reflection.Emit.OpCode Bge_Un_S;
public static readonly System.Reflection.Emit.OpCode Bgt;
public static readonly System.Reflection.Emit.OpCode Bgt_S;
public static readonly System.Reflection.Emit.OpCode Bgt_Un;
public static readonly System.Reflection.Emit.OpCode Bgt_Un_S;
public static readonly System.Reflection.Emit.OpCode Ble;
public static readonly System.Reflection.Emit.OpCode Ble_S;
public static readonly System.Reflection.Emit.OpCode Ble_Un;
public static readonly System.Reflection.Emit.OpCode Ble_Un_S;
public static readonly System.Reflection.Emit.OpCode Blt;
public static readonly System.Reflection.Emit.OpCode Blt_S;
public static readonly System.Reflection.Emit.OpCode Blt_Un;
public static readonly System.Reflection.Emit.OpCode Blt_Un_S;
public static readonly System.Reflection.Emit.OpCode Bne_Un;
public static readonly System.Reflection.Emit.OpCode Bne_Un_S;
public static readonly System.Reflection.Emit.OpCode Box;
public static readonly System.Reflection.Emit.OpCode Br;
public static readonly System.Reflection.Emit.OpCode Br_S;
public static readonly System.Reflection.Emit.OpCode Break;
public static readonly System.Reflection.Emit.OpCode Brfalse;
public static readonly System.Reflection.Emit.OpCode Brfalse_S;
public static readonly System.Reflection.Emit.OpCode Brtrue;
public static readonly System.Reflection.Emit.OpCode Brtrue_S;
public static readonly System.Reflection.Emit.OpCode Call;
public static readonly System.Reflection.Emit.OpCode Calli;
public static readonly System.Reflection.Emit.OpCode Callvirt;
public static readonly System.Reflection.Emit.OpCode Castclass;
public static readonly System.Reflection.Emit.OpCode Ceq;
public static readonly System.Reflection.Emit.OpCode Cgt;
public static readonly System.Reflection.Emit.OpCode Cgt_Un;
public static readonly System.Reflection.Emit.OpCode Ckfinite;
public static readonly System.Reflection.Emit.OpCode Clt;
public static readonly System.Reflection.Emit.OpCode Clt_Un;
public static readonly System.Reflection.Emit.OpCode Constrained;
public static readonly System.Reflection.Emit.OpCode Conv_I;
public static readonly System.Reflection.Emit.OpCode Conv_I1;
public static readonly System.Reflection.Emit.OpCode Conv_I2;
public static readonly System.Reflection.Emit.OpCode Conv_I4;
public static readonly System.Reflection.Emit.OpCode Conv_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R4;
public static readonly System.Reflection.Emit.OpCode Conv_R8;
public static readonly System.Reflection.Emit.OpCode Conv_U;
public static readonly System.Reflection.Emit.OpCode Conv_U1;
public static readonly System.Reflection.Emit.OpCode Conv_U2;
public static readonly System.Reflection.Emit.OpCode Conv_U4;
public static readonly System.Reflection.Emit.OpCode Conv_U8;
public static readonly System.Reflection.Emit.OpCode Cpblk;
public static readonly System.Reflection.Emit.OpCode Cpobj;
public static readonly System.Reflection.Emit.OpCode Div;
public static readonly System.Reflection.Emit.OpCode Div_Un;
public static readonly System.Reflection.Emit.OpCode Dup;
public static readonly System.Reflection.Emit.OpCode Endfilter;
public static readonly System.Reflection.Emit.OpCode Endfinally;
public static readonly System.Reflection.Emit.OpCode Initblk;
public static readonly System.Reflection.Emit.OpCode Initobj;
public static readonly System.Reflection.Emit.OpCode Isinst;
public static readonly System.Reflection.Emit.OpCode Jmp;
public static readonly System.Reflection.Emit.OpCode Ldarg;
public static readonly System.Reflection.Emit.OpCode Ldarg_0;
public static readonly System.Reflection.Emit.OpCode Ldarg_1;
public static readonly System.Reflection.Emit.OpCode Ldarg_2;
public static readonly System.Reflection.Emit.OpCode Ldarg_3;
public static readonly System.Reflection.Emit.OpCode Ldarg_S;
public static readonly System.Reflection.Emit.OpCode Ldarga;
public static readonly System.Reflection.Emit.OpCode Ldarga_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_0;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_2;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_3;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_5;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_6;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_7;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_8;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I8;
public static readonly System.Reflection.Emit.OpCode Ldc_R4;
public static readonly System.Reflection.Emit.OpCode Ldc_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem;
public static readonly System.Reflection.Emit.OpCode Ldelem_I;
public static readonly System.Reflection.Emit.OpCode Ldelem_I1;
public static readonly System.Reflection.Emit.OpCode Ldelem_I2;
public static readonly System.Reflection.Emit.OpCode Ldelem_I4;
public static readonly System.Reflection.Emit.OpCode Ldelem_I8;
public static readonly System.Reflection.Emit.OpCode Ldelem_R4;
public static readonly System.Reflection.Emit.OpCode Ldelem_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem_Ref;
public static readonly System.Reflection.Emit.OpCode Ldelem_U1;
public static readonly System.Reflection.Emit.OpCode Ldelem_U2;
public static readonly System.Reflection.Emit.OpCode Ldelem_U4;
public static readonly System.Reflection.Emit.OpCode Ldelema;
public static readonly System.Reflection.Emit.OpCode Ldfld;
public static readonly System.Reflection.Emit.OpCode Ldflda;
public static readonly System.Reflection.Emit.OpCode Ldftn;
public static readonly System.Reflection.Emit.OpCode Ldind_I;
public static readonly System.Reflection.Emit.OpCode Ldind_I1;
public static readonly System.Reflection.Emit.OpCode Ldind_I2;
public static readonly System.Reflection.Emit.OpCode Ldind_I4;
public static readonly System.Reflection.Emit.OpCode Ldind_I8;
public static readonly System.Reflection.Emit.OpCode Ldind_R4;
public static readonly System.Reflection.Emit.OpCode Ldind_R8;
public static readonly System.Reflection.Emit.OpCode Ldind_Ref;
public static readonly System.Reflection.Emit.OpCode Ldind_U1;
public static readonly System.Reflection.Emit.OpCode Ldind_U2;
public static readonly System.Reflection.Emit.OpCode Ldind_U4;
public static readonly System.Reflection.Emit.OpCode Ldlen;
public static readonly System.Reflection.Emit.OpCode Ldloc;
public static readonly System.Reflection.Emit.OpCode Ldloc_0;
public static readonly System.Reflection.Emit.OpCode Ldloc_1;
public static readonly System.Reflection.Emit.OpCode Ldloc_2;
public static readonly System.Reflection.Emit.OpCode Ldloc_3;
public static readonly System.Reflection.Emit.OpCode Ldloc_S;
public static readonly System.Reflection.Emit.OpCode Ldloca;
public static readonly System.Reflection.Emit.OpCode Ldloca_S;
public static readonly System.Reflection.Emit.OpCode Ldnull;
public static readonly System.Reflection.Emit.OpCode Ldobj;
public static readonly System.Reflection.Emit.OpCode Ldsfld;
public static readonly System.Reflection.Emit.OpCode Ldsflda;
public static readonly System.Reflection.Emit.OpCode Ldstr;
public static readonly System.Reflection.Emit.OpCode Ldtoken;
public static readonly System.Reflection.Emit.OpCode Ldvirtftn;
public static readonly System.Reflection.Emit.OpCode Leave;
public static readonly System.Reflection.Emit.OpCode Leave_S;
public static readonly System.Reflection.Emit.OpCode Localloc;
public static readonly System.Reflection.Emit.OpCode Mkrefany;
public static readonly System.Reflection.Emit.OpCode Mul;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Neg;
public static readonly System.Reflection.Emit.OpCode Newarr;
public static readonly System.Reflection.Emit.OpCode Newobj;
public static readonly System.Reflection.Emit.OpCode Nop;
public static readonly System.Reflection.Emit.OpCode Not;
public static readonly System.Reflection.Emit.OpCode Or;
public static readonly System.Reflection.Emit.OpCode Pop;
public static readonly System.Reflection.Emit.OpCode Prefix1;
public static readonly System.Reflection.Emit.OpCode Prefix2;
public static readonly System.Reflection.Emit.OpCode Prefix3;
public static readonly System.Reflection.Emit.OpCode Prefix4;
public static readonly System.Reflection.Emit.OpCode Prefix5;
public static readonly System.Reflection.Emit.OpCode Prefix6;
public static readonly System.Reflection.Emit.OpCode Prefix7;
public static readonly System.Reflection.Emit.OpCode Prefixref;
public static readonly System.Reflection.Emit.OpCode Readonly;
public static readonly System.Reflection.Emit.OpCode Refanytype;
public static readonly System.Reflection.Emit.OpCode Refanyval;
public static readonly System.Reflection.Emit.OpCode Rem;
public static readonly System.Reflection.Emit.OpCode Rem_Un;
public static readonly System.Reflection.Emit.OpCode Ret;
public static readonly System.Reflection.Emit.OpCode Rethrow;
public static readonly System.Reflection.Emit.OpCode Shl;
public static readonly System.Reflection.Emit.OpCode Shr;
public static readonly System.Reflection.Emit.OpCode Shr_Un;
public static readonly System.Reflection.Emit.OpCode Sizeof;
public static readonly System.Reflection.Emit.OpCode Starg;
public static readonly System.Reflection.Emit.OpCode Starg_S;
public static readonly System.Reflection.Emit.OpCode Stelem;
public static readonly System.Reflection.Emit.OpCode Stelem_I;
public static readonly System.Reflection.Emit.OpCode Stelem_I1;
public static readonly System.Reflection.Emit.OpCode Stelem_I2;
public static readonly System.Reflection.Emit.OpCode Stelem_I4;
public static readonly System.Reflection.Emit.OpCode Stelem_I8;
public static readonly System.Reflection.Emit.OpCode Stelem_R4;
public static readonly System.Reflection.Emit.OpCode Stelem_R8;
public static readonly System.Reflection.Emit.OpCode Stelem_Ref;
public static readonly System.Reflection.Emit.OpCode Stfld;
public static readonly System.Reflection.Emit.OpCode Stind_I;
public static readonly System.Reflection.Emit.OpCode Stind_I1;
public static readonly System.Reflection.Emit.OpCode Stind_I2;
public static readonly System.Reflection.Emit.OpCode Stind_I4;
public static readonly System.Reflection.Emit.OpCode Stind_I8;
public static readonly System.Reflection.Emit.OpCode Stind_R4;
public static readonly System.Reflection.Emit.OpCode Stind_R8;
public static readonly System.Reflection.Emit.OpCode Stind_Ref;
public static readonly System.Reflection.Emit.OpCode Stloc;
public static readonly System.Reflection.Emit.OpCode Stloc_0;
public static readonly System.Reflection.Emit.OpCode Stloc_1;
public static readonly System.Reflection.Emit.OpCode Stloc_2;
public static readonly System.Reflection.Emit.OpCode Stloc_3;
public static readonly System.Reflection.Emit.OpCode Stloc_S;
public static readonly System.Reflection.Emit.OpCode Stobj;
public static readonly System.Reflection.Emit.OpCode Stsfld;
public static readonly System.Reflection.Emit.OpCode Sub;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Switch;
public static readonly System.Reflection.Emit.OpCode Tailcall;
public static readonly System.Reflection.Emit.OpCode Throw;
public static readonly System.Reflection.Emit.OpCode Unaligned;
public static readonly System.Reflection.Emit.OpCode Unbox;
public static readonly System.Reflection.Emit.OpCode Unbox_Any;
public static readonly System.Reflection.Emit.OpCode Volatile;
public static readonly System.Reflection.Emit.OpCode Xor;
public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { return default(bool); }
}
public enum OpCodeType
{
Macro = 1,
Nternal = 2,
Objmodel = 3,
Prefix = 4,
Primitive = 5,
}
public enum OperandType
{
InlineBrTarget = 0,
InlineField = 1,
InlineI = 2,
InlineI8 = 3,
InlineMethod = 4,
InlineNone = 5,
InlineR = 7,
InlineSig = 9,
InlineString = 10,
InlineSwitch = 11,
InlineTok = 12,
InlineType = 13,
InlineVar = 14,
ShortInlineBrTarget = 15,
ShortInlineI = 16,
ShortInlineR = 17,
ShortInlineVar = 18,
}
public enum PackingSize
{
Size1 = 1,
Size128 = 128,
Size16 = 16,
Size2 = 2,
Size32 = 32,
Size4 = 4,
Size64 = 64,
Size8 = 8,
Unspecified = 0,
}
public enum StackBehaviour
{
Pop0 = 0,
Pop1 = 1,
Pop1_pop1 = 2,
Popi = 3,
Popi_pop1 = 4,
Popi_popi = 5,
Popi_popi_popi = 7,
Popi_popi8 = 6,
Popi_popr4 = 8,
Popi_popr8 = 9,
Popref = 10,
Popref_pop1 = 11,
Popref_popi = 12,
Popref_popi_pop1 = 28,
Popref_popi_popi = 13,
Popref_popi_popi8 = 14,
Popref_popi_popr4 = 15,
Popref_popi_popr8 = 16,
Popref_popi_popref = 17,
Push0 = 18,
Push1 = 19,
Push1_push1 = 20,
Pushi = 21,
Pushi8 = 22,
Pushr4 = 23,
Pushr8 = 24,
Pushref = 25,
Varpop = 26,
Varpush = 27,
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryAddTests
{
#region Test methods
[Fact]
public static void CheckByteAddTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteAdd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteAddTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteAdd(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortAddTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortAdd(array[i], array[j], useInterpreter);
VerifyUShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortAddTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortAdd(array[i], array[j], useInterpreter);
VerifyShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntAddTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntAdd(array[i], array[j], useInterpreter);
VerifyUIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntAddTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntAdd(array[i], array[j], useInterpreter);
VerifyIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongAddTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongAdd(array[i], array[j], useInterpreter);
VerifyULongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongAddTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongAdd(array[i], array[j], useInterpreter);
VerifyLongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatAddTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleAddTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalAddTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharAddTest(bool useInterpreter)
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharAdd(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteAdd(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifySByteAdd(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifyUShortAdd(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Add(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal((ushort)(a + b), f());
}
private static void VerifyUShortAddOvf(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < 0 || expected > ushort.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyShortAdd(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Add(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal((short)(a + b), f());
}
private static void VerifyShortAddOvf(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.AddChecked(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < short.MinValue || expected > short.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyUIntAdd(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Add(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyUIntAddOvf(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.AddChecked(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < 0 || expected > uint.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyIntAdd(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyIntAddOvf(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.AddChecked(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < int.MinValue || expected > int.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyULongAdd(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Add(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyULongAddOvf(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
ulong expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyLongAdd(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Add(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyLongAddOvf(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.AddChecked(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
long expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyFloatAdd(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Add(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
float expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDoubleAdd(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Add(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
double expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDecimalAdd(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Add(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
decimal expected = 0;
try
{
expected = a + b;
}
catch(OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyCharAdd(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Add(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceChecked()
{
Expression exp = Expression.AddChecked(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.Add(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Add(Expression.Constant(""), null));
}
[Fact]
public static void CheckedThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.AddChecked(null, Expression.Constant("")));
}
[Fact]
public static void CheckedThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.AddChecked(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.Add(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void CheckedThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.AddChecked(value, Expression.Constant(1)));
}
[Fact]
public static void CheckedThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
var e1 = Expression.Add(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e1.ToString());
var e2 = Expression.AddChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e2.ToString());
}
}
}
| |
//// Copyright (c) 2013 Enrique Juan Gil Izquierdo
////
//// 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 UnityEngine;
namespace iTweenFluent {
/// <summary>
/// Adds to a GameObject's scale over time.
/// </summary>
public class iTweenScaleAdd : iTweenFluent<iTweenScaleAdd> {
public static iTweenScaleAdd Create(GameObject target) {
return new iTweenScaleAdd( target );
}
public iTweenScaleAdd(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.ScaleAdd( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenScaleAdd ThisAsTSelf() {
return this;
}
/// <summary>
/// For the amount to be added to the GameObject's current scale.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public iTweenScaleAdd Amount(Vector3 amount) {
return AddArgument( "amount", amount );
}
/// <summary>
/// For the individual setting of the x axis.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenScaleAdd X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y axis
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenScaleAdd Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z axis.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenScaleAdd Z(float z) {
return AddArgument( "z", z );
}
/// <summary>
/// Can be used instead of time to allow animation based on speed.
/// </summary>
/// <param name="speed"></param>
/// <returns></returns>
public iTweenScaleAdd Speed(float speed) {
return AddArgument( "speed", speed );
}
}
/// <summary>
/// Multiplies a GameObject's scale over time.
/// </summary>
public class iTweenScaleBy : iTweenFluent<iTweenScaleBy> {
public static iTweenScaleBy Create(GameObject target) {
return new iTweenScaleBy( target );
}
public iTweenScaleBy(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.ScaleBy( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenScaleBy ThisAsTSelf() {
return this;
}
/// <summary>
/// For the amount to be added to the GameObject's current scale.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public iTweenScaleBy Amount(Vector3 amount) {
return AddArgument( "amount", amount );
}
/// <summary>
/// For the individual setting of the x axis.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenScaleBy X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y axis.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenScaleBy Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z axis.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenScaleBy Z(float z) {
return AddArgument( "z", z );
}
/// <summary>
/// Can be used instead of time to allow animation based on speed.
/// </summary>
/// <param name="speed"></param>
/// <returns></returns>
public iTweenScaleBy Speed(float speed) {
return AddArgument( "speed", speed );
}
}
/// <summary>
/// Instantly changes a GameObject's scale then returns it to it's starting
/// scale over time.
/// </summary>
public class iTweenScaleFrom : iTweenFluent<iTweenScaleFrom> {
public static iTweenScaleFrom Create(GameObject target) {
return new iTweenScaleFrom( target );
}
public iTweenScaleFrom(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.ScaleFrom( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenScaleFrom ThisAsTSelf() {
return this;
}
/// <summary>
/// For the initial scale.
/// </summary>
/// <param name="scale"></param>
/// <returns></returns>
public iTweenScaleFrom Scale(Transform scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the initial scale.
/// </summary>
/// <param name="scale"></param>
/// <returns></returns>
public iTweenScaleFrom Scale(Vector3 scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the individual setting of the x axis.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenScaleFrom X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y axis.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenScaleFrom Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z axis
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenScaleFrom Z(float z) {
return AddArgument( "z", z );
}
/// <summary>
/// Can be used instead of time to allow animation based on speed.
/// </summary>
/// <param name="speed"></param>
/// <returns></returns>
public iTweenScaleFrom Speed(float speed) {
return AddArgument( "speed", speed );
}
}
/// <summary>
/// Changes a GameObject's scale over time.
/// </summary>
public class iTweenScaleTo : iTweenFluent<iTweenScaleTo> {
public static iTweenScaleTo Create(GameObject target) {
return new iTweenScaleTo( target );
}
public iTweenScaleTo(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.ScaleTo( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenScaleTo ThisAsTSelf() {
return this;
}
/// <summary>
/// For the final scale.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public iTweenScaleTo Scale(Transform scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the final scale.
/// </summary>
/// <param name="scale"></param>
/// <returns></returns>
public iTweenScaleTo Scale(Vector3 scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the individual setting of the x axis.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenScaleTo X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y axis.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenScaleTo Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z axis.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenScaleTo Z(float z) {
return AddArgument( "z", z );
}
/// <summary>
/// Can be used instead of time to allow animation based on speed.
/// </summary>
/// <param name="speed"></param>
/// <returns></returns>
public iTweenScaleTo Speed(float speed) {
return AddArgument( "speed", speed );
}
}
/// <summary>
/// Applies a jolt of force to a GameObject's scale and wobbles it back to its
/// initial scale.
/// </summary>
public class iTweenPunchScale : iTweenFluent<iTweenPunchScale> {
public static iTweenPunchScale Create(GameObject target) {
return new iTweenPunchScale( target );
}
public iTweenPunchScale(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.PunchScale( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenPunchScale ThisAsTSelf() {
return this;
}
/// <summary>
/// For the scale the GameObject will animate to.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public iTweenPunchScale Amount(Vector3 amount) {
return AddArgument( "amount", amount );
}
/// <summary>
/// For the individual setting of the x magnitude.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenPunchScale X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y magnitude.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenPunchScale Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z magnitude.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenPunchScale Z(float z) {
return AddArgument( "z", z );
}
}
/// <summary>
/// Randomly shakes a GameObject's scale by a diminishing amount over time.
/// </summary>
public class iTweenShakeScale : iTweenFluent<iTweenShakeScale> {
public static iTweenShakeScale Create(GameObject target) {
return new iTweenShakeScale( target );
}
public iTweenShakeScale(GameObject target)
: base( target ) {
}
public override void Launch() {
iTween.ShakeScale( Target, new System.Collections.Hashtable( Arguments ) );
}
protected override iTweenShakeScale ThisAsTSelf() {
return this;
}
/// <summary>
/// For the magnitude of shake.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public iTweenShakeScale Amount(Vector3 amount) {
return AddArgument( "amount", amount );
}
/// <summary>
/// For the individual setting of the x magnitude.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenShakeScale X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y magnitude.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenShakeScale Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z magnitude.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenShakeScale Z(float z) {
return AddArgument( "z", z );
}
}
/// <summary>
/// Similar to ScaleTo but incredibly less expensive for usage inside the
/// Update function or similar looping situations involving a "live" set
/// of changing values. Does not utilize an EaseType.
/// </summary>
public class iTweenScaleUpdate {
private GameObject target;
private Dictionary<string, object> arguments = new Dictionary<string, object>();
public static iTweenScaleUpdate Create(GameObject target) {
return new iTweenScaleUpdate( target );
}
public iTweenScaleUpdate(GameObject target) {
this.target = target;
}
public void Launch() {
iTween.ScaleUpdate( target, new System.Collections.Hashtable( arguments ) );
}
/// <summary>
/// For the final scale.
/// </summary>
/// <param name="scale"></param>
/// <returns></returns>
public iTweenScaleUpdate Scale(Transform scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the final scale.
/// </summary>
/// <param name="scale"></param>
/// <returns></returns>
public iTweenScaleUpdate Scale(Vector3 scale) {
return AddArgument( "scale", scale );
}
/// <summary>
/// For the individual setting of the x axis.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public iTweenScaleUpdate X(float x) {
return AddArgument( "x", x );
}
/// <summary>
/// For the individual setting of the y axis.
/// </summary>
/// <param name="y"></param>
/// <returns></returns>
public iTweenScaleUpdate Y(float y) {
return AddArgument( "y", y );
}
/// <summary>
/// For the individual setting of the z axis.
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
public iTweenScaleUpdate Z(float z) {
return AddArgument( "z", z );
}
/// <summary>
/// For the time in seconds the animation will take to complete.
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public iTweenScaleUpdate Time(float time) {
return AddArgument( "time", time );
}
protected iTweenScaleUpdate AddArgument(string arg, object value) {
arguments[arg] = value;
return this;
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class TextAwesome : SpriteText
{
//public override FontFace FontFace => (int)Icon < 0xf000 ? FontFace.OsuFont : FontFace.FontAwesome;
private FontAwesome icon;
public FontAwesome Icon
{
get
{
return icon;
}
set
{
if (icon == value) return;
icon = value;
Text = ((char)icon).ToString();
}
}
public TextAwesome()
{
Origin = Framework.Graphics.Anchor.Centre;
}
}
public enum FontAwesome
{
fa_500px = 0xf26e,
fa_address_book = 0xf2b9,
fa_address_book_o = 0xf2ba,
fa_address_card = 0xf2bb,
fa_address_card_o = 0xf2bc,
fa_adjust = 0xf042,
fa_adn = 0xf170,
fa_align_center = 0xf037,
fa_align_justify = 0xf039,
fa_align_left = 0xf036,
fa_align_right = 0xf038,
fa_amazon = 0xf270,
fa_ambulance = 0xf0f9,
fa_american_sign_language_interpreting = 0xf2a3,
fa_anchor = 0xf13d,
fa_android = 0xf17b,
fa_angellist = 0xf209,
fa_angle_double_down = 0xf103,
fa_angle_double_left = 0xf100,
fa_angle_double_right = 0xf101,
fa_angle_double_up = 0xf102,
fa_angle_down = 0xf107,
fa_angle_left = 0xf104,
fa_angle_right = 0xf105,
fa_angle_up = 0xf106,
fa_apple = 0xf179,
fa_archive = 0xf187,
fa_area_chart = 0xf1fe,
fa_arrow_circle_down = 0xf0ab,
fa_arrow_circle_left = 0xf0a8,
fa_arrow_circle_o_down = 0xf01a,
fa_arrow_circle_o_left = 0xf190,
fa_arrow_circle_o_right = 0xf18e,
fa_arrow_circle_o_up = 0xf01b,
fa_arrow_circle_right = 0xf0a9,
fa_arrow_circle_up = 0xf0aa,
fa_arrow_down = 0xf063,
fa_arrow_left = 0xf060,
fa_arrow_right = 0xf061,
fa_arrow_up = 0xf062,
fa_arrows = 0xf047,
fa_arrows_alt = 0xf0b2,
fa_arrows_h = 0xf07e,
fa_arrows_v = 0xf07d,
fa_asl_interpreting = 0xf2a3,
fa_assistive_listening_systems = 0xf2a2,
fa_asterisk = 0xf069,
fa_at = 0xf1fa,
fa_audio_description = 0xf29e,
fa_automobile = 0xf1b9,
fa_backward = 0xf04a,
fa_balance_scale = 0xf24e,
fa_ban = 0xf05e,
fa_bandcamp = 0xf2d5,
fa_bank = 0xf19c,
fa_bar_chart = 0xf080,
fa_bar_chart_o = 0xf080,
fa_barcode = 0xf02a,
fa_bars = 0xf0c9,
fa_bath = 0xf2cd,
fa_bathtub = 0xf2cd,
fa_battery = 0xf240,
fa_battery_0 = 0xf244,
fa_battery_1 = 0xf243,
fa_battery_2 = 0xf242,
fa_battery_3 = 0xf241,
fa_battery_4 = 0xf240,
fa_battery_empty = 0xf244,
fa_battery_full = 0xf240,
fa_battery_half = 0xf242,
fa_battery_quarter = 0xf243,
fa_battery_three_quarters = 0xf241,
fa_bed = 0xf236,
fa_beer = 0xf0fc,
fa_behance = 0xf1b4,
fa_behance_square = 0xf1b5,
fa_bell = 0xf0f3,
fa_bell_o = 0xf0a2,
fa_bell_slash = 0xf1f6,
fa_bell_slash_o = 0xf1f7,
fa_bicycle = 0xf206,
fa_binoculars = 0xf1e5,
fa_birthday_cake = 0xf1fd,
fa_bitbucket = 0xf171,
fa_bitbucket_square = 0xf172,
fa_bitcoin = 0xf15a,
fa_black_tie = 0xf27e,
fa_blind = 0xf29d,
fa_bluetooth = 0xf293,
fa_bluetooth_b = 0xf294,
fa_bold = 0xf032,
fa_bolt = 0xf0e7,
fa_bomb = 0xf1e2,
fa_book = 0xf02d,
fa_bookmark = 0xf02e,
fa_bookmark_o = 0xf097,
fa_braille = 0xf2a1,
fa_briefcase = 0xf0b1,
fa_btc = 0xf15a,
fa_bug = 0xf188,
fa_building = 0xf1ad,
fa_building_o = 0xf0f7,
fa_bullhorn = 0xf0a1,
fa_bullseye = 0xf140,
fa_bus = 0xf207,
fa_buysellads = 0xf20d,
fa_cab = 0xf1ba,
fa_calculator = 0xf1ec,
fa_calendar = 0xf073,
fa_calendar_check_o = 0xf274,
fa_calendar_minus_o = 0xf272,
fa_calendar_o = 0xf133,
fa_calendar_plus_o = 0xf271,
fa_calendar_times_o = 0xf273,
fa_camera = 0xf030,
fa_camera_retro = 0xf083,
fa_car = 0xf1b9,
fa_caret_down = 0xf0d7,
fa_caret_left = 0xf0d9,
fa_caret_right = 0xf0da,
fa_caret_square_o_down = 0xf150,
fa_caret_square_o_left = 0xf191,
fa_caret_square_o_right = 0xf152,
fa_caret_square_o_up = 0xf151,
fa_caret_up = 0xf0d8,
fa_cart_arrow_down = 0xf218,
fa_cart_plus = 0xf217,
fa_cc = 0xf20a,
fa_cc_amex = 0xf1f3,
fa_cc_diners_club = 0xf24c,
fa_cc_discover = 0xf1f2,
fa_cc_jcb = 0xf24b,
fa_cc_mastercard = 0xf1f1,
fa_cc_paypal = 0xf1f4,
fa_cc_stripe = 0xf1f5,
fa_cc_visa = 0xf1f0,
fa_certificate = 0xf0a3,
fa_chain = 0xf0c1,
fa_chain_broken = 0xf127,
fa_check = 0xf00c,
fa_check_circle = 0xf058,
fa_check_circle_o = 0xf05d,
fa_check_square = 0xf14a,
fa_check_square_o = 0xf046,
fa_chevron_circle_down = 0xf13a,
fa_chevron_circle_left = 0xf137,
fa_chevron_circle_right = 0xf138,
fa_chevron_circle_up = 0xf139,
fa_chevron_down = 0xf078,
fa_chevron_left = 0xf053,
fa_chevron_right = 0xf054,
fa_chevron_up = 0xf077,
fa_child = 0xf1ae,
fa_chrome = 0xf268,
fa_circle = 0xf111,
fa_circle_o = 0xf10c,
fa_circle_o_notch = 0xf1ce,
fa_circle_thin = 0xf1db,
fa_clipboard = 0xf0ea,
fa_clock_o = 0xf017,
fa_clone = 0xf24d,
fa_close = 0xf00d,
fa_cloud = 0xf0c2,
fa_cloud_download = 0xf0ed,
fa_cloud_upload = 0xf0ee,
fa_cny = 0xf157,
fa_code = 0xf121,
fa_code_fork = 0xf126,
fa_codepen = 0xf1cb,
fa_codiepie = 0xf284,
fa_coffee = 0xf0f4,
fa_cog = 0xf013,
fa_cogs = 0xf085,
fa_columns = 0xf0db,
fa_comment = 0xf075,
fa_comment_o = 0xf0e5,
fa_commenting = 0xf27a,
fa_commenting_o = 0xf27b,
fa_comments = 0xf086,
fa_comments_o = 0xf0e6,
fa_compass = 0xf14e,
fa_compress = 0xf066,
fa_connectdevelop = 0xf20e,
fa_contao = 0xf26d,
fa_copy = 0xf0c5,
fa_copyright = 0xf1f9,
fa_creative_commons = 0xf25e,
fa_credit_card = 0xf09d,
fa_credit_card_alt = 0xf283,
fa_crop = 0xf125,
fa_crosshairs = 0xf05b,
fa_css3 = 0xf13c,
fa_cube = 0xf1b2,
fa_cubes = 0xf1b3,
fa_cut = 0xf0c4,
fa_cutlery = 0xf0f5,
fa_dashboard = 0xf0e4,
fa_dashcube = 0xf210,
fa_database = 0xf1c0,
fa_deaf = 0xf2a4,
fa_deafness = 0xf2a4,
fa_dedent = 0xf03b,
fa_delicious = 0xf1a5,
fa_desktop = 0xf108,
fa_deviantart = 0xf1bd,
fa_diamond = 0xf219,
fa_digg = 0xf1a6,
fa_dollar = 0xf155,
fa_dot_circle_o = 0xf192,
fa_download = 0xf019,
fa_dribbble = 0xf17d,
fa_drivers_license = 0xf2c2,
fa_drivers_license_o = 0xf2c3,
fa_dropbox = 0xf16b,
fa_drupal = 0xf1a9,
fa_edge = 0xf282,
fa_edit = 0xf044,
fa_eercast = 0xf2da,
fa_eject = 0xf052,
fa_ellipsis_h = 0xf141,
fa_ellipsis_v = 0xf142,
fa_empire = 0xf1d1,
fa_envelope = 0xf0e0,
fa_envelope_o = 0xf003,
fa_envelope_open = 0xf2b6,
fa_envelope_open_o = 0xf2b7,
fa_envelope_square = 0xf199,
fa_envira = 0xf299,
fa_eraser = 0xf12d,
fa_etsy = 0xf2d7,
fa_eur = 0xf153,
fa_euro = 0xf153,
fa_exchange = 0xf0ec,
fa_exclamation = 0xf12a,
fa_exclamation_circle = 0xf06a,
fa_exclamation_triangle = 0xf071,
fa_expand = 0xf065,
fa_expeditedssl = 0xf23e,
fa_external_link = 0xf08e,
fa_external_link_square = 0xf14c,
fa_eye = 0xf06e,
fa_eye_slash = 0xf070,
fa_eyedropper = 0xf1fb,
fa_fa = 0xf2b4,
fa_facebook = 0xf09a,
fa_facebook_f = 0xf09a,
fa_facebook_official = 0xf230,
fa_facebook_square = 0xf082,
fa_fast_backward = 0xf049,
fa_fast_forward = 0xf050,
fa_fax = 0xf1ac,
fa_feed = 0xf09e,
fa_female = 0xf182,
fa_fighter_jet = 0xf0fb,
fa_file = 0xf15b,
fa_file_archive_o = 0xf1c6,
fa_file_audio_o = 0xf1c7,
fa_file_code_o = 0xf1c9,
fa_file_excel_o = 0xf1c3,
fa_file_image_o = 0xf1c5,
fa_file_movie_o = 0xf1c8,
fa_file_o = 0xf016,
fa_file_pdf_o = 0xf1c1,
fa_file_photo_o = 0xf1c5,
fa_file_picture_o = 0xf1c5,
fa_file_powerpoint_o = 0xf1c4,
fa_file_sound_o = 0xf1c7,
fa_file_text = 0xf15c,
fa_file_text_o = 0xf0f6,
fa_file_video_o = 0xf1c8,
fa_file_word_o = 0xf1c2,
fa_file_zip_o = 0xf1c6,
fa_files_o = 0xf0c5,
fa_film = 0xf008,
fa_filter = 0xf0b0,
fa_fire = 0xf06d,
fa_fire_extinguisher = 0xf134,
fa_firefox = 0xf269,
fa_first_order = 0xf2b0,
fa_flag = 0xf024,
fa_flag_checkered = 0xf11e,
fa_flag_o = 0xf11d,
fa_flash = 0xf0e7,
fa_flask = 0xf0c3,
fa_flickr = 0xf16e,
fa_floppy_o = 0xf0c7,
fa_folder = 0xf07b,
fa_folder_o = 0xf114,
fa_folder_open = 0xf07c,
fa_folder_open_o = 0xf115,
fa_font = 0xf031,
fa_font_awesome = 0xf2b4,
fa_fonticons = 0xf280,
fa_fort_awesome = 0xf286,
fa_forumbee = 0xf211,
fa_forward = 0xf04e,
fa_foursquare = 0xf180,
fa_free_code_camp = 0xf2c5,
fa_frown_o = 0xf119,
fa_futbol_o = 0xf1e3,
fa_gamepad = 0xf11b,
fa_gavel = 0xf0e3,
fa_gbp = 0xf154,
fa_ge = 0xf1d1,
fa_gear = 0xf013,
fa_gears = 0xf085,
fa_genderless = 0xf22d,
fa_get_pocket = 0xf265,
fa_gg = 0xf260,
fa_gg_circle = 0xf261,
fa_gift = 0xf06b,
fa_git = 0xf1d3,
fa_git_square = 0xf1d2,
fa_github = 0xf09b,
fa_github_alt = 0xf113,
fa_github_square = 0xf092,
fa_gitlab = 0xf296,
fa_gittip = 0xf184,
fa_glass = 0xf000,
fa_glide = 0xf2a5,
fa_glide_g = 0xf2a6,
fa_globe = 0xf0ac,
fa_google = 0xf1a0,
fa_google_plus = 0xf0d5,
fa_google_plus_circle = 0xf2b3,
fa_google_plus_official = 0xf2b3,
fa_google_plus_square = 0xf0d4,
fa_google_wallet = 0xf1ee,
fa_graduation_cap = 0xf19d,
fa_gratipay = 0xf184,
fa_grav = 0xf2d6,
fa_group = 0xf0c0,
fa_h_square = 0xf0fd,
fa_hacker_news = 0xf1d4,
fa_hand_grab_o = 0xf255,
fa_hand_lizard_o = 0xf258,
fa_hand_o_down = 0xf0a7,
fa_hand_o_left = 0xf0a5,
fa_hand_o_right = 0xf0a4,
fa_hand_o_up = 0xf0a6,
fa_hand_paper_o = 0xf256,
fa_hand_peace_o = 0xf25b,
fa_hand_pointer_o = 0xf25a,
fa_hand_rock_o = 0xf255,
fa_hand_scissors_o = 0xf257,
fa_hand_spock_o = 0xf259,
fa_hand_stop_o = 0xf256,
fa_handshake_o = 0xf2b5,
fa_hard_of_hearing = 0xf2a4,
fa_hashtag = 0xf292,
fa_hdd_o = 0xf0a0,
fa_header = 0xf1dc,
fa_headphones = 0xf025,
fa_heart = 0xf004,
fa_heart_o = 0xf08a,
fa_heartbeat = 0xf21e,
fa_history = 0xf1da,
fa_home = 0xf015,
fa_hospital_o = 0xf0f8,
fa_hotel = 0xf236,
fa_hourglass = 0xf254,
fa_hourglass_1 = 0xf251,
fa_hourglass_2 = 0xf252,
fa_hourglass_3 = 0xf253,
fa_hourglass_end = 0xf253,
fa_hourglass_half = 0xf252,
fa_hourglass_o = 0xf250,
fa_hourglass_start = 0xf251,
fa_houzz = 0xf27c,
fa_html5 = 0xf13b,
fa_i_cursor = 0xf246,
fa_id_badge = 0xf2c1,
fa_id_card = 0xf2c2,
fa_id_card_o = 0xf2c3,
fa_ils = 0xf20b,
fa_image = 0xf03e,
fa_imdb = 0xf2d8,
fa_inbox = 0xf01c,
fa_indent = 0xf03c,
fa_industry = 0xf275,
fa_info = 0xf129,
fa_info_circle = 0xf05a,
fa_inr = 0xf156,
fa_instagram = 0xf16d,
fa_institution = 0xf19c,
fa_internet_explorer = 0xf26b,
fa_intersex = 0xf224,
fa_ioxhost = 0xf208,
fa_italic = 0xf033,
fa_joomla = 0xf1aa,
fa_jpy = 0xf157,
fa_jsfiddle = 0xf1cc,
fa_key = 0xf084,
fa_keyboard_o = 0xf11c,
fa_krw = 0xf159,
fa_language = 0xf1ab,
fa_laptop = 0xf109,
fa_lastfm = 0xf202,
fa_lastfm_square = 0xf203,
fa_leaf = 0xf06c,
fa_leanpub = 0xf212,
fa_legal = 0xf0e3,
fa_lemon_o = 0xf094,
fa_level_down = 0xf149,
fa_level_up = 0xf148,
fa_life_bouy = 0xf1cd,
fa_life_buoy = 0xf1cd,
fa_life_ring = 0xf1cd,
fa_life_saver = 0xf1cd,
fa_lightbulb_o = 0xf0eb,
fa_line_chart = 0xf201,
fa_link = 0xf0c1,
fa_linkedin = 0xf0e1,
fa_linkedin_square = 0xf08c,
fa_linode = 0xf2b8,
fa_linux = 0xf17c,
fa_list = 0xf03a,
fa_list_alt = 0xf022,
fa_list_ol = 0xf0cb,
fa_list_ul = 0xf0ca,
fa_location_arrow = 0xf124,
fa_lock = 0xf023,
fa_long_arrow_down = 0xf175,
fa_long_arrow_left = 0xf177,
fa_long_arrow_right = 0xf178,
fa_long_arrow_up = 0xf176,
fa_low_vision = 0xf2a8,
fa_magic = 0xf0d0,
fa_magnet = 0xf076,
fa_mail_forward = 0xf064,
fa_mail_reply = 0xf112,
fa_mail_reply_all = 0xf122,
fa_male = 0xf183,
fa_map = 0xf279,
fa_map_marker = 0xf041,
fa_map_o = 0xf278,
fa_map_pin = 0xf276,
fa_map_signs = 0xf277,
fa_mars = 0xf222,
fa_mars_double = 0xf227,
fa_mars_stroke = 0xf229,
fa_mars_stroke_h = 0xf22b,
fa_mars_stroke_v = 0xf22a,
fa_maxcdn = 0xf136,
fa_meanpath = 0xf20c,
fa_medium = 0xf23a,
fa_medkit = 0xf0fa,
fa_meetup = 0xf2e0,
fa_meh_o = 0xf11a,
fa_mercury = 0xf223,
fa_microchip = 0xf2db,
fa_microphone = 0xf130,
fa_microphone_slash = 0xf131,
fa_minus = 0xf068,
fa_minus_circle = 0xf056,
fa_minus_square = 0xf146,
fa_minus_square_o = 0xf147,
fa_mixcloud = 0xf289,
fa_mobile = 0xf10b,
fa_mobile_phone = 0xf10b,
fa_modx = 0xf285,
fa_money = 0xf0d6,
fa_moon_o = 0xf186,
fa_mortar_board = 0xf19d,
fa_motorcycle = 0xf21c,
fa_mouse_pointer = 0xf245,
fa_music = 0xf001,
fa_navicon = 0xf0c9,
fa_neuter = 0xf22c,
fa_newspaper_o = 0xf1ea,
fa_object_group = 0xf247,
fa_object_ungroup = 0xf248,
fa_odnoklassniki = 0xf263,
fa_odnoklassniki_square = 0xf264,
fa_opencart = 0xf23d,
fa_openid = 0xf19b,
fa_opera = 0xf26a,
fa_optin_monster = 0xf23c,
fa_outdent = 0xf03b,
fa_pagelines = 0xf18c,
fa_paint_brush = 0xf1fc,
fa_paper_plane = 0xf1d8,
fa_paper_plane_o = 0xf1d9,
fa_paperclip = 0xf0c6,
fa_paragraph = 0xf1dd,
fa_paste = 0xf0ea,
fa_pause = 0xf04c,
fa_pause_circle = 0xf28b,
fa_pause_circle_o = 0xf28c,
fa_paw = 0xf1b0,
fa_paypal = 0xf1ed,
fa_pencil = 0xf040,
fa_pencil_square = 0xf14b,
fa_pencil_square_o = 0xf044,
fa_percent = 0xf295,
fa_phone = 0xf095,
fa_phone_square = 0xf098,
fa_photo = 0xf03e,
fa_picture_o = 0xf03e,
fa_pie_chart = 0xf200,
fa_pied_piper = 0xf2ae,
fa_pied_piper_alt = 0xf1a8,
fa_pied_piper_pp = 0xf1a7,
fa_pinterest = 0xf0d2,
fa_pinterest_p = 0xf231,
fa_pinterest_square = 0xf0d3,
fa_plane = 0xf072,
fa_play = 0xf04b,
fa_play_circle = 0xf144,
fa_play_circle_o = 0xf01d,
fa_plug = 0xf1e6,
fa_plus = 0xf067,
fa_plus_circle = 0xf055,
fa_plus_square = 0xf0fe,
fa_plus_square_o = 0xf196,
fa_podcast = 0xf2ce,
fa_power_off = 0xf011,
fa_print = 0xf02f,
fa_product_hunt = 0xf288,
fa_puzzle_piece = 0xf12e,
fa_qq = 0xf1d6,
fa_qrcode = 0xf029,
fa_question = 0xf128,
fa_question_circle = 0xf059,
fa_question_circle_o = 0xf29c,
fa_quora = 0xf2c4,
fa_quote_left = 0xf10d,
fa_quote_right = 0xf10e,
fa_ra = 0xf1d0,
fa_random = 0xf074,
fa_ravelry = 0xf2d9,
fa_rebel = 0xf1d0,
fa_recycle = 0xf1b8,
fa_reddit = 0xf1a1,
fa_reddit_alien = 0xf281,
fa_reddit_square = 0xf1a2,
fa_refresh = 0xf021,
fa_registered = 0xf25d,
fa_remove = 0xf00d,
fa_renren = 0xf18b,
fa_reorder = 0xf0c9,
fa_repeat = 0xf01e,
fa_reply = 0xf112,
fa_reply_all = 0xf122,
fa_resistance = 0xf1d0,
fa_retweet = 0xf079,
fa_rmb = 0xf157,
fa_road = 0xf018,
fa_rocket = 0xf135,
fa_rotate_left = 0xf0e2,
fa_rotate_right = 0xf01e,
fa_rouble = 0xf158,
fa_rss = 0xf09e,
fa_rss_square = 0xf143,
fa_rub = 0xf158,
fa_ruble = 0xf158,
fa_rupee = 0xf156,
fa_s15 = 0xf2cd,
fa_safari = 0xf267,
fa_save = 0xf0c7,
fa_scissors = 0xf0c4,
fa_scribd = 0xf28a,
fa_search = 0xf002,
fa_search_minus = 0xf010,
fa_search_plus = 0xf00e,
fa_sellsy = 0xf213,
fa_send = 0xf1d8,
fa_send_o = 0xf1d9,
fa_server = 0xf233,
fa_share = 0xf064,
fa_share_alt = 0xf1e0,
fa_share_alt_square = 0xf1e1,
fa_share_square = 0xf14d,
fa_share_square_o = 0xf045,
fa_shekel = 0xf20b,
fa_sheqel = 0xf20b,
fa_shield = 0xf132,
fa_ship = 0xf21a,
fa_shirtsinbulk = 0xf214,
fa_shopping_bag = 0xf290,
fa_shopping_basket = 0xf291,
fa_shopping_cart = 0xf07a,
fa_shower = 0xf2cc,
fa_sign_in = 0xf090,
fa_sign_language = 0xf2a7,
fa_sign_out = 0xf08b,
fa_signal = 0xf012,
fa_signing = 0xf2a7,
fa_simplybuilt = 0xf215,
fa_sitemap = 0xf0e8,
fa_skyatlas = 0xf216,
fa_skype = 0xf17e,
fa_slack = 0xf198,
fa_sliders = 0xf1de,
fa_slideshare = 0xf1e7,
fa_smile_o = 0xf118,
fa_snapchat = 0xf2ab,
fa_snapchat_ghost = 0xf2ac,
fa_snapchat_square = 0xf2ad,
fa_snowflake_o = 0xf2dc,
fa_soccer_ball_o = 0xf1e3,
fa_sort = 0xf0dc,
fa_sort_alpha_asc = 0xf15d,
fa_sort_alpha_desc = 0xf15e,
fa_sort_amount_asc = 0xf160,
fa_sort_amount_desc = 0xf161,
fa_sort_asc = 0xf0de,
fa_sort_desc = 0xf0dd,
fa_sort_down = 0xf0dd,
fa_sort_numeric_asc = 0xf162,
fa_sort_numeric_desc = 0xf163,
fa_sort_up = 0xf0de,
fa_soundcloud = 0xf1be,
fa_space_shuttle = 0xf197,
fa_spinner = 0xf110,
fa_spoon = 0xf1b1,
fa_spotify = 0xf1bc,
fa_square = 0xf0c8,
fa_square_o = 0xf096,
fa_stack_exchange = 0xf18d,
fa_stack_overflow = 0xf16c,
fa_star = 0xf005,
fa_star_half = 0xf089,
fa_star_half_empty = 0xf123,
fa_star_half_full = 0xf123,
fa_star_half_o = 0xf123,
fa_star_o = 0xf006,
fa_steam = 0xf1b6,
fa_steam_square = 0xf1b7,
fa_step_backward = 0xf048,
fa_step_forward = 0xf051,
fa_stethoscope = 0xf0f1,
fa_sticky_note = 0xf249,
fa_sticky_note_o = 0xf24a,
fa_stop = 0xf04d,
fa_stop_circle = 0xf28d,
fa_stop_circle_o = 0xf28e,
fa_street_view = 0xf21d,
fa_strikethrough = 0xf0cc,
fa_stumbleupon = 0xf1a4,
fa_stumbleupon_circle = 0xf1a3,
fa_subscript = 0xf12c,
fa_subway = 0xf239,
fa_suitcase = 0xf0f2,
fa_sun_o = 0xf185,
fa_superpowers = 0xf2dd,
fa_superscript = 0xf12b,
fa_support = 0xf1cd,
fa_table = 0xf0ce,
fa_tablet = 0xf10a,
fa_tachometer = 0xf0e4,
fa_tag = 0xf02b,
fa_tags = 0xf02c,
fa_tasks = 0xf0ae,
fa_taxi = 0xf1ba,
fa_telegram = 0xf2c6,
fa_television = 0xf26c,
fa_tencent_weibo = 0xf1d5,
fa_terminal = 0xf120,
fa_text_height = 0xf034,
fa_text_width = 0xf035,
fa_th = 0xf00a,
fa_th_large = 0xf009,
fa_th_list = 0xf00b,
fa_themeisle = 0xf2b2,
fa_thermometer = 0xf2c7,
fa_thermometer_0 = 0xf2cb,
fa_thermometer_1 = 0xf2ca,
fa_thermometer_2 = 0xf2c9,
fa_thermometer_3 = 0xf2c8,
fa_thermometer_4 = 0xf2c7,
fa_thermometer_empty = 0xf2cb,
fa_thermometer_full = 0xf2c7,
fa_thermometer_half = 0xf2c9,
fa_thermometer_quarter = 0xf2ca,
fa_thermometer_three_quarters = 0xf2c8,
fa_thumb_tack = 0xf08d,
fa_thumbs_down = 0xf165,
fa_thumbs_o_down = 0xf088,
fa_thumbs_o_up = 0xf087,
fa_thumbs_up = 0xf164,
fa_ticket = 0xf145,
fa_times = 0xf00d,
fa_times_circle = 0xf057,
fa_times_circle_o = 0xf05c,
fa_times_rectangle = 0xf2d3,
fa_times_rectangle_o = 0xf2d4,
fa_tint = 0xf043,
fa_toggle_down = 0xf150,
fa_toggle_left = 0xf191,
fa_toggle_off = 0xf204,
fa_toggle_on = 0xf205,
fa_toggle_right = 0xf152,
fa_toggle_up = 0xf151,
fa_trademark = 0xf25c,
fa_train = 0xf238,
fa_transgender = 0xf224,
fa_transgender_alt = 0xf225,
fa_trash = 0xf1f8,
fa_trash_o = 0xf014,
fa_tree = 0xf1bb,
fa_trello = 0xf181,
fa_tripadvisor = 0xf262,
fa_trophy = 0xf091,
fa_truck = 0xf0d1,
fa_try = 0xf195,
fa_tty = 0xf1e4,
fa_tumblr = 0xf173,
fa_tumblr_square = 0xf174,
fa_turkish_lira = 0xf195,
fa_tv = 0xf26c,
fa_twitch = 0xf1e8,
fa_twitter = 0xf099,
fa_twitter_square = 0xf081,
fa_umbrella = 0xf0e9,
fa_underline = 0xf0cd,
fa_undo = 0xf0e2,
fa_universal_access = 0xf29a,
fa_university = 0xf19c,
fa_unlink = 0xf127,
fa_unlock = 0xf09c,
fa_unlock_alt = 0xf13e,
fa_unsorted = 0xf0dc,
fa_upload = 0xf093,
fa_usb = 0xf287,
fa_usd = 0xf155,
fa_user = 0xf007,
fa_user_circle = 0xf2bd,
fa_user_circle_o = 0xf2be,
fa_user_md = 0xf0f0,
fa_user_o = 0xf2c0,
fa_user_plus = 0xf234,
fa_user_secret = 0xf21b,
fa_user_times = 0xf235,
fa_users = 0xf0c0,
fa_vcard = 0xf2bb,
fa_vcard_o = 0xf2bc,
fa_venus = 0xf221,
fa_venus_double = 0xf226,
fa_venus_mars = 0xf228,
fa_viacoin = 0xf237,
fa_viadeo = 0xf2a9,
fa_viadeo_square = 0xf2aa,
fa_video_camera = 0xf03d,
fa_vimeo = 0xf27d,
fa_vimeo_square = 0xf194,
fa_vine = 0xf1ca,
fa_vk = 0xf189,
fa_volume_control_phone = 0xf2a0,
fa_volume_down = 0xf027,
fa_volume_off = 0xf026,
fa_volume_up = 0xf028,
fa_warning = 0xf071,
fa_wechat = 0xf1d7,
fa_weibo = 0xf18a,
fa_weixin = 0xf1d7,
fa_whatsapp = 0xf232,
fa_wheelchair = 0xf193,
fa_wheelchair_alt = 0xf29b,
fa_wifi = 0xf1eb,
fa_wikipedia_w = 0xf266,
fa_window_close = 0xf2d3,
fa_window_close_o = 0xf2d4,
fa_window_maximize = 0xf2d0,
fa_window_minimize = 0xf2d1,
fa_window_restore = 0xf2d2,
fa_windows = 0xf17a,
fa_won = 0xf159,
fa_wordpress = 0xf19a,
fa_wpbeginner = 0xf297,
fa_wpexplorer = 0xf2de,
fa_wpforms = 0xf298,
fa_wrench = 0xf0ad,
fa_xing = 0xf168,
fa_xing_square = 0xf169,
fa_y_combinator = 0xf23b,
fa_y_combinator_square = 0xf1d4,
fa_yahoo = 0xf19e,
fa_yc = 0xf23b,
fa_yc_square = 0xf1d4,
fa_yelp = 0xf1e9,
fa_yen = 0xf157,
fa_yoast = 0xf2b1,
fa_youtube = 0xf167,
fa_youtube_play = 0xf16a,
fa_youtube_square = 0xf166,
// gamemode icons in circles
fa_osu_osu_o = 0xe000,
fa_osu_mania_o = 0xe001,
fa_osu_fruits_o = 0xe002,
fa_osu_taiko_o = 0xe003,
// gamemode icons without circles
fa_osu_filled_circle = 0xe004,
fa_osu_cross_o = 0xe005,
fa_osu_logo = 0xe006,
fa_osu_chevron_down_o = 0xe007,
fa_osu_edit_o = 0xe033,
fa_osu_left_o = 0xe034,
fa_osu_right_o = 0xe035,
fa_osu_charts = 0xe036,
fa_osu_solo = 0xe037,
fa_osu_multi = 0xe038,
fa_osu_gear = 0xe039,
// misc icons
fa_osu_bat = 0xe008,
fa_osu_bubble = 0xe009,
fa_osu_bubble_pop = 0xe02e,
fa_osu_dice = 0xe011,
fa_osu_heart1 = 0xe02f,
fa_osu_heart1_break = 0xe030,
fa_osu_hot = 0xe031,
fa_osu_list_search = 0xe032,
//osu! playstyles
fa_osu_playstyle_tablet = 0xe02a,
fa_osu_playstyle_mouse = 0xe029,
fa_osu_playstyle_keyboard = 0xe02b,
fa_osu_playstyle_touch = 0xe02c,
// osu! difficulties
fa_osu_easy_osu = 0xe015,
fa_osu_normal_osu = 0xe016,
fa_osu_hard_osu = 0xe017,
fa_osu_insane_osu = 0xe018,
fa_osu_expert_osu = 0xe019,
// taiko difficulties
fa_osu_easy_taiko = 0xe01a,
fa_osu_normal_taiko = 0xe01b,
fa_osu_hard_taiko = 0xe01c,
fa_osu_insane_taiko = 0xe01d,
fa_osu_expert_taiko = 0xe01e,
// fruits difficulties
fa_osu_easy_fruits = 0xe01f,
fa_osu_normal_fruits = 0xe020,
fa_osu_hard_fruits = 0xe021,
fa_osu_insane_fruits = 0xe022,
fa_osu_expert_fruits = 0xe023,
// mania difficulties
fa_osu_easy_mania = 0xe024,
fa_osu_normal_mania = 0xe025,
fa_osu_hard_mania = 0xe026,
fa_osu_insane_mania = 0xe027,
fa_osu_expert_mania = 0xe028,
// mod icons
fa_osu_mod_perfect = 0xe02d,
fa_osu_mod_autopilot = 0xe03a,
fa_osu_mod_auto = 0xe03b,
fa_osu_mod_cinema = 0xe03c,
fa_osu_mod_doubletime = 0xe03d,
fa_osu_mod_easy = 0xe03e,
fa_osu_mod_flashlight = 0xe03f,
fa_osu_mod_halftime = 0xe040,
fa_osu_mod_hardrock = 0xe041,
fa_osu_mod_hidden = 0xe042,
fa_osu_mod_nightcore = 0xe043,
fa_osu_mod_nofail = 0xe044,
fa_osu_mod_relax = 0xe045,
fa_osu_mod_spunout = 0xe046,
fa_osu_mod_suddendeath = 0xe047,
fa_osu_mod_target = 0xe048,
fa_osu_mod_bg = 0xe04a,
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using System;
using System.Collections.Generic;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "If", "Logical Operators", "Conditional comparison between A with B.", null, KeyCode.None, true, false, null, null, true )]
public sealed class ConditionalIfNode : ParentNode
{
private const string UseUnityBranchesStr = "Dynamic Branching";
private const string UnityBranchStr = "UNITY_BRANCH ";
private readonly string[] IfOps = { "if( {0} > {1} )",
"if( {0} == {1} )",
"if( {0} < {1} )" };
private WirePortDataType m_inputMainDataType = WirePortDataType.FLOAT;
private WirePortDataType m_outputMainDataType = WirePortDataType.FLOAT;
private string[] m_results = { string.Empty, string.Empty, string.Empty };
[SerializeField]
private bool m_useUnityBranch = false;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddInputPort( WirePortDataType.FLOAT, true, "A" );
AddInputPort( WirePortDataType.FLOAT, true, "B" );
AddInputPort( WirePortDataType.FLOAT, false, "A > B" );
AddInputPort( WirePortDataType.FLOAT, false, "A == B" );
AddInputPort( WirePortDataType.FLOAT, false, "A < B" );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
m_textLabelWidth = 131;
m_useInternalPortData = true;
m_autoWrapProperties = true;
}
public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type );
UpdateConnection( inputPortId );
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
UpdateConnection( portId );
}
public override void DrawProperties()
{
base.DrawProperties();
m_useUnityBranch = EditorGUILayoutToggle( UseUnityBranchesStr, m_useUnityBranch );
}
public override void OnInputPortDisconnected( int portId )
{
UpdateConnection( portId );
}
//void TestMainInputDataType()
//{
// WirePortDataType newType = WirePortDataType.FLOAT;
// if ( m_inputPorts[ 0 ].IsConnected && UIUtils.GetPriority( m_inputPorts[ 0 ].DataType ) > UIUtils.GetPriority( newType ) )
// {
// newType = m_inputPorts[ 0 ].DataType;
// }
// if ( m_inputPorts[ 1 ].IsConnected && ( UIUtils.GetPriority( m_inputPorts[ 1 ].DataType ) > UIUtils.GetPriority( newType ) ) )
// {
// newType = m_inputPorts[ 1 ].DataType;
// }
// m_inputMainDataType = newType;
//}
void TestMainOutputDataType()
{
WirePortDataType newType = WirePortDataType.FLOAT;
for ( int i = 2; i < 5; i++ )
{
if ( m_inputPorts[ i ].IsConnected && ( UIUtils.GetPriority( m_inputPorts[ i ].DataType ) > UIUtils.GetPriority( newType ) ) )
{
newType = m_inputPorts[ i ].DataType;
}
}
if ( newType != m_outputMainDataType )
{
m_outputMainDataType = newType;
m_outputPorts[ 0 ].ChangeType( m_outputMainDataType, false );
}
}
public void UpdateConnection( int portId )
{
m_inputPorts[ portId ].MatchPortToConnection();
switch ( portId )
{
//case 0:
//case 1:
//{
// TestMainInputDataType();
//}
//break;
case 2:
case 3:
case 4:
{
TestMainOutputDataType();
}
break;
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if ( m_outputPorts[ 0 ].IsLocalValue )
return m_outputPorts[ 0 ].LocalValue;
string AValue = m_inputPorts[ 0 ].GenerateShaderForOutput( ref dataCollector, m_inputMainDataType, ignoreLocalvar, true );
string BValue = m_inputPorts[ 1 ].GenerateShaderForOutput( ref dataCollector, m_inputMainDataType, ignoreLocalvar, true );
m_results[ 0 ] = m_inputPorts[ 2 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true );
m_results[ 1 ] = m_inputPorts[ 3 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true );
m_results[ 2 ] = m_inputPorts[ 4 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true );
string localVarName = "ifLocalVar" + UniqueId;
string localVarDec = string.Format( "{0} {1} = 0;", UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ), localVarName );
bool firstIf = true;
List<string> instructions = new List<string>();
instructions.Add( localVarDec );
for ( int i = 2; i < 5; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
{
int idx = i - 2;
string ifOp = string.Format( IfOps[ idx ], AValue, BValue );
if ( m_useUnityBranch )
{
ifOp = UnityBranchStr + ifOp;
}
instructions.Add( firstIf ? ifOp : "else " + ifOp );
instructions.Add( string.Format( "\t{0} = {1};", localVarName, m_results[ idx ] ) );
firstIf = false;
}
}
if ( firstIf )
{
UIUtils.ShowMessage( "No result inputs connectect on If Node. Using node internal data." );
// no input nodes connected ... use port default values
for ( int i = 2; i < 5; i++ )
{
int idx = i - 2;
string ifOp = string.Format( IfOps[ idx ], AValue, BValue );
if ( m_useUnityBranch )
{
ifOp = UnityBranchStr + ifOp;
}
instructions.Add( firstIf ? ifOp : "else " + ifOp );
instructions.Add( string.Format( "\t{0} = {1};", localVarName, m_results[ idx ] ) );
firstIf = false;
}
}
for ( int i = 0; i < instructions.Count; i++ )
{
dataCollector.AddToLocalVariables( dataCollector.PortCategory, UniqueId, instructions[ i ] , true );
}
//dataCollector.AddInstructions( true, true, instructions.ToArray() );
instructions.Clear();
instructions = null;
m_outputPorts[ 0 ].SetLocalValue( localVarName );
return localVarName;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
if ( UIUtils.CurrentShaderVersion() > 4103 )
{
m_useUnityBranch = Convert.ToBoolean( GetCurrentParam( ref nodeParams ));
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_useUnityBranch );
}
}
}
| |
// 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.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.NodejsTools.Profiling
{
/// <summary>
/// Provides a view model for the ProfilingTarget class.
/// </summary>
public sealed class ProfilingTargetView : INotifyPropertyChanged
{
private ReadOnlyCollection<ProjectTargetView> _availableProjects;
private ProjectTargetView _project;
private bool _isProjectSelected, _isStandaloneSelected;
private StandaloneTargetView _standalone;
private readonly string _startText;
private bool _isValid;
/// <summary>
/// Create a ProfilingTargetView with default values.
/// </summary>
public ProfilingTargetView()
{
var solution = NodejsProfilingPackage.Instance.Solution;
var availableProjects = new List<ProjectTargetView>();
foreach (var project in solution.EnumerateLoadedProjects(onlyNodeProjects: true))
{
availableProjects.Add(new ProjectTargetView((IVsHierarchy)project));
}
_availableProjects = new ReadOnlyCollection<ProjectTargetView>(availableProjects);
_project = null;
_standalone = new StandaloneTargetView();
_isProjectSelected = true;
_isValid = false;
PropertyChanged += new PropertyChangedEventHandler(ProfilingTargetView_PropertyChanged);
_standalone.PropertyChanged += new PropertyChangedEventHandler(Standalone_PropertyChanged);
var startupProject = NodejsProfilingPackage.Instance.GetStartupProjectGuid();
Project = AvailableProjects.FirstOrDefault(p => p.Guid == startupProject) ??
AvailableProjects.FirstOrDefault();
if (Project != null)
{
IsStandaloneSelected = false;
IsProjectSelected = true;
}
else
{
IsProjectSelected = false;
IsStandaloneSelected = true;
}
_startText = Resources.ProfilingStart;
}
/// <summary>
/// Create a ProfilingTargetView with values taken from a template.
/// </summary>
/// <param name="template"></param>
public ProfilingTargetView(ProfilingTarget template)
: this()
{
if (template.ProjectTarget != null)
{
Project = new ProjectTargetView(template.ProjectTarget);
IsStandaloneSelected = false;
IsProjectSelected = true;
}
else if (template.StandaloneTarget != null)
{
Standalone = new StandaloneTargetView(template.StandaloneTarget);
IsProjectSelected = false;
IsStandaloneSelected = true;
}
_startText = Resources.ProfilingOk;
}
/// <summary>
/// Returns a ProfilingTarget with the values set from the view model.
/// </summary>
public ProfilingTarget GetTarget()
{
if (IsValid)
{
return new ProfilingTarget
{
ProjectTarget = IsProjectSelected ? Project.GetTarget() : null,
StandaloneTarget = IsStandaloneSelected ? Standalone.GetTarget() : null
};
}
else
{
return null;
}
}
public ReadOnlyCollection<ProjectTargetView> AvailableProjects
{
get
{
return _availableProjects;
}
}
/// <summary>
/// True if AvailableProjects has at least one item.
/// </summary>
public bool IsAnyAvailableProjects
{
get
{
return _availableProjects.Count > 0;
}
}
/// <summary>
/// A view of the details of the current project.
/// </summary>
public ProjectTargetView Project
{
get
{
return _project;
}
set
{
if (_project != value)
{
_project = value;
OnPropertyChanged(nameof(Project));
}
}
}
/// <summary>
/// True if a project is the currently selected target; otherwise, false.
/// </summary>
public bool IsProjectSelected
{
get
{
return _isProjectSelected;
}
set
{
if (_isProjectSelected != value)
{
_isProjectSelected = value;
OnPropertyChanged(nameof(IsProjectSelected));
}
}
}
/// <summary>
/// A view of the details of the current standalone script.
/// </summary>
public StandaloneTargetView Standalone
{
get
{
return _standalone;
}
set
{
if (_standalone != value)
{
if (_standalone != null)
{
_standalone.PropertyChanged -= Standalone_PropertyChanged;
}
_standalone = value;
if (_standalone != null)
{
_standalone.PropertyChanged += Standalone_PropertyChanged;
}
OnPropertyChanged(nameof(Standalone));
}
}
}
/// <summary>
/// True if a standalone script is the currently selected target; otherwise, false.
/// </summary>
public bool IsStandaloneSelected
{
get
{
return _isStandaloneSelected;
}
set
{
if (_isStandaloneSelected != value)
{
_isStandaloneSelected = value;
OnPropertyChanged(nameof(IsStandaloneSelected));
}
}
}
/// <summary>
/// Receives our own property change events to update IsValid.
/// </summary>
private void ProfilingTargetView_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Debug.Assert(sender == this);
if (e.PropertyName != "IsValid")
{
IsValid = (IsProjectSelected != IsStandaloneSelected) &&
(IsProjectSelected ?
Project != null :
(Standalone != null && Standalone.IsValid));
}
}
/// <summary>
/// Propagate property change events from Standalone.
/// </summary>
private void Standalone_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Debug.Assert(Standalone == sender);
OnPropertyChanged(nameof(Standalone));
}
/// <summary>
/// True if all settings are valid; otherwise, false.
/// </summary>
public bool IsValid
{
get
{
return _isValid;
}
private set
{
if (_isValid != value)
{
_isValid = value;
OnPropertyChanged(nameof(IsValid));
}
}
}
public string StartText
{
get
{
return _startText;
}
}
private void OnPropertyChanged(string propertyName)
{
var evt = PropertyChanged;
if (evt != null)
{
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CouponAutoApplyConditions
/// </summary>
[DataContract]
public partial class CouponAutoApplyConditions : IEquatable<CouponAutoApplyConditions>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CouponAutoApplyConditions" /> class.
/// </summary>
/// <param name="error">error.</param>
/// <param name="metadata">metadata.</param>
/// <param name="requiredItems">requiredItems.</param>
/// <param name="subtotalLevels">subtotalLevels.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="warning">warning.</param>
public CouponAutoApplyConditions(Error error = default(Error), ResponseMetadata metadata = default(ResponseMetadata), List<CouponAutoApplyCondition> requiredItems = default(List<CouponAutoApplyCondition>), List<CouponAutoApplyCondition> subtotalLevels = default(List<CouponAutoApplyCondition>), bool? success = default(bool?), Warning warning = default(Warning))
{
this.Error = error;
this.Metadata = metadata;
this.RequiredItems = requiredItems;
this.SubtotalLevels = subtotalLevels;
this.Success = success;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Gets or Sets RequiredItems
/// </summary>
[DataMember(Name="required_items", EmitDefaultValue=false)]
public List<CouponAutoApplyCondition> RequiredItems { get; set; }
/// <summary>
/// Gets or Sets SubtotalLevels
/// </summary>
[DataMember(Name="subtotal_levels", EmitDefaultValue=false)]
public List<CouponAutoApplyCondition> SubtotalLevels { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { 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 CouponAutoApplyConditions {\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" RequiredItems: ").Append(RequiredItems).Append("\n");
sb.Append(" SubtotalLevels: ").Append(SubtotalLevels).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Warning: ").Append(Warning).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CouponAutoApplyConditions);
}
/// <summary>
/// Returns true if CouponAutoApplyConditions instances are equal
/// </summary>
/// <param name="input">Instance of CouponAutoApplyConditions to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CouponAutoApplyConditions input)
{
if (input == null)
return false;
return
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.RequiredItems == input.RequiredItems ||
this.RequiredItems != null &&
this.RequiredItems.SequenceEqual(input.RequiredItems)
) &&
(
this.SubtotalLevels == input.SubtotalLevels ||
this.SubtotalLevels != null &&
this.SubtotalLevels.SequenceEqual(input.SubtotalLevels)
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.RequiredItems != null)
hashCode = hashCode * 59 + this.RequiredItems.GetHashCode();
if (this.SubtotalLevels != null)
hashCode = hashCode * 59 + this.SubtotalLevels.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DotVVM.Framework.Compilation.Parser.Binding.Tokenizer;
using DotVVM.Framework.Resources;
namespace DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer
{
/// <summary>
/// Reads the Dothtml content and returns tokens.
/// </summary>
public class DothtmlTokenizer : TokenizerBase<DothtmlToken, DothtmlTokenType>
{
public override void Tokenize(string sourceText)
{
TokenizeInternal(sourceText, () => { ReadDocument(); return true; });
}
public bool TokenizeBinding(string sourceText, bool usesDoubleBraces = false)
{
return TokenizeInternal(sourceText, () =>
{
ReadBinding(usesDoubleBraces);
//Finished?
Assert(Peek() == NullChar);
//Propertly opened/closed
Assert((Tokens.FirstOrDefault()?.Length ?? 0) > 0);
Assert((Tokens.LastOrDefault()?.Length ?? 0) > 0);
return true;
});
}
/// <summary>
/// Gets the type of the text token.
/// </summary>
protected override DothtmlTokenType TextTokenType
{
get { return DothtmlTokenType.Text; }
}
/// <summary>
/// Gets the type of the white space token.
/// </summary>
protected override DothtmlTokenType WhiteSpaceTokenType
{
get { return DothtmlTokenType.WhiteSpace; }
}
/// <summary>
/// Tokenizes whole dothtml document from start to end.
/// </summary>
private void ReadDocument()
{
var directivesAllowed = true;
// read the body
while (Peek() != NullChar)
{
if (Peek() == '@' && directivesAllowed)
{
ReadDirective();
}
else if (Peek() == '<')
{
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.Text);
}
// HTML element
var elementType = ReadElement();
if (elementType != ReadElementType.Comment && elementType != ReadElementType.ServerComment)
{
directivesAllowed = false;
}
}
else if (Peek() == '{')
{
// possible binding
Read();
if (Peek() == '{')
{
if (DistanceSinceLastToken > 1)
{
CreateToken(DothtmlTokenType.Text, 1);
}
// it really is a binding
ReadBinding(true);
}
directivesAllowed = false;
}
else
{
if (!char.IsWhiteSpace(Peek()))
{
directivesAllowed = false;
}
// text content
Read();
}
}
// treat remaining content as text
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.Text);
}
}
private void ReadDirective()
{
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.WhiteSpace);
}
// the directive started
Read();
CreateToken(DothtmlTokenType.DirectiveStart);
// identifier
if (!ReadIdentifier(DothtmlTokenType.DirectiveName, '\r', '\n'))
{
CreateToken(DothtmlTokenType.DirectiveName, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveNameExpected));
}
SkipWhitespace(false);
// whitespace
if (LastToken.Type != DothtmlTokenType.WhiteSpace)
{
CreateToken(DothtmlTokenType.WhiteSpace, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveValueExpected));
}
// directive value
if (Peek() == '\r' || Peek() == '\n' || Peek() == NullChar)
{
CreateToken(DothtmlTokenType.DirectiveValue, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveValueExpected));
SkipWhitespace();
}
else
{
ReadTextUntilNewLine(DothtmlTokenType.DirectiveValue);
}
}
private static readonly HashSet<char> EnabledIdentifierChars = new HashSet<char>()
{
':', '_', '-', '.'
};
/// <summary>
/// Reads the identifier.
/// </summary>
private bool ReadIdentifier(DothtmlTokenType tokenType, params char[] stopChars)
{
// read first character
if ((!char.IsLetter(Peek()) && Peek() != '_') || stopChars.Contains(Peek()))
return false;
// read identifier
while ((Char.IsLetterOrDigit(Peek()) || EnabledIdentifierChars.Contains(Peek())) && !stopChars.Contains(Peek()))
{
Read();
}
CreateToken(tokenType);
return true;
}
/// <summary>
/// Reads the element.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private ReadElementType ReadElement(bool wasOpenBraceRead = false)
{
var isClosingTag = false;
if (!wasOpenBraceRead)
{
// open tag brace
Assert(Peek() == '<');
Read();
}
if (Peek() == '!' || Peek() == '?' || Peek() == '%')
{
return ReadHtmlSpecial(true);
}
if (!char.IsLetterOrDigit(Peek()) && Peek() != '/' && Peek() != ':')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, "'<' char is not allowed in normal text"));
return ReadElementType.Error;
}
CreateToken(DothtmlTokenType.OpenTag);
if (Peek() == '/')
{
// it is a closing tag
Read();
CreateToken(DothtmlTokenType.Slash);
isClosingTag = true;
}
// read tag name
if (!ReadTagOrAttributeName(isAttributeName: false))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.TagNameExpected));
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError());
return ReadElementType.Error;
}
// read tag attributes
SkipWhitespace();
if (!isClosingTag)
{
while (Peek() != '/' && Peek() != '>')
{
if (Peek() == '<')
{
// comment inside element
Read();
if (Peek() == '!' || Peek() == '%')
{
var c = ReadOneOf("!--", "%--");
if (c == null) CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, ""));
else if (c == "!--") ReadComment();
else if (c == "%--") ReadServerComment();
else throw new Exception();
SkipWhitespace();
}
else
{
CreateToken(DothtmlTokenType.CloseTag, charsFromEndToSkip: 1, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.InvalidCharactersInTag, isCritical: true));
ReadElement(wasOpenBraceRead: true);
return ReadElementType.Error;
}
}
else
if (!ReadAttribute())
{
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.InvalidCharactersInTag, isCritical: true));
return ReadElementType.Error;
}
}
}
if (Peek() == '/' && !isClosingTag)
{
// self closing tag
Read();
CreateToken(DothtmlTokenType.Slash);
}
if (Peek() != '>')
{
// tag is not closed
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.TagNotClosed));
return ReadElementType.Error;
}
Read();
CreateToken(DothtmlTokenType.CloseTag);
return ReadElementType.ValidTag;
}
public enum ReadElementType
{
Error,
ValidTag,
CData,
Comment,
Doctype,
XmlProcessingInstruction,
ServerComment
}
public ReadElementType ReadHtmlSpecial(bool openBraceConsumed = false)
{
var s = ReadOneOf("![CDATA[", "!--", "!DOCTYPE", "?", "%--");
if (s == "![CDATA[")
{
return ReadCData();
}
else if (s == "!--")
{
return ReadComment();
}
else if (s == "%--")
{
return ReadServerComment();
}
else if (s == "!DOCTYPE")
{
return ReadDoctype();
}
else if (s == "?")
{
return ReadXmlPI();
}
return ReadElementType.Error;
}
private ReadElementType ReadCData()
{
CreateToken(DothtmlTokenType.OpenCData);
if (ReadTextUntil(DothtmlTokenType.CDataBody, "]]>", false))
{
CreateToken(DothtmlTokenType.CloseCData);
return ReadElementType.CData;
}
else
{
CreateToken(DothtmlTokenType.CDataBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseCData, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenCData, DothtmlTokenizerErrors.CDataNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadComment()
{
CreateToken(DothtmlTokenType.OpenComment);
if (ReadTextUntil(DothtmlTokenType.CommentBody, "-->", false))
{
CreateToken(DothtmlTokenType.CloseComment);
return ReadElementType.Comment;
}
else
{
CreateToken(DothtmlTokenType.CommentBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseComment, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenComment, DothtmlTokenizerErrors.CommentNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadServerComment()
{
CreateToken(DothtmlTokenType.OpenServerComment);
if (ReadTextUntil(DothtmlTokenType.CommentBody, "--%>", false, nestString: "<%--"))
{
CreateToken(DothtmlTokenType.CloseComment);
return ReadElementType.ServerComment;
}
else
{
CreateToken(DothtmlTokenType.CommentBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseComment, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenComment, DothtmlTokenizerErrors.CommentNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadDoctype()
{
CreateToken(DothtmlTokenType.OpenDoctype);
if (ReadTextUntil(DothtmlTokenType.DoctypeBody, ">", true))
{
CreateToken(DothtmlTokenType.CloseDoctype);
return ReadElementType.Doctype;
}
else
{
CreateToken(DothtmlTokenType.DoctypeBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseDoctype, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenDoctype, DothtmlTokenizerErrors.DoctypeNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadXmlPI()
{
CreateToken(DothtmlTokenType.OpenXmlProcessingInstruction);
if (ReadTextUntil(DothtmlTokenType.XmlProcessingInstructionBody, "?>", true))
{
CreateToken(DothtmlTokenType.CloseXmlProcessingInstruction);
return ReadElementType.XmlProcessingInstruction;
}
else
{
CreateToken(DothtmlTokenType.XmlProcessingInstructionBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseXmlProcessingInstruction, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenXmlProcessingInstruction, DothtmlTokenizerErrors.XmlProcessingInstructionNotClosed));
return ReadElementType.Error;
}
}
private void Assert(bool expression)
{
if (!expression)
{
throw new Exception("Assertion failed!");
}
}
/// <summary>
/// Reads the name of the tag or attribute.
/// </summary>
private bool ReadTagOrAttributeName(bool isAttributeName)
{
if (Peek() != ':')
{
// read the identifier
if (!ReadIdentifier(DothtmlTokenType.Text, ':'))
{
return false;
}
}
else
{
// missing tag prefix
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.MissingTagPrefix));
}
if (Peek() == ':')
{
Read();
CreateToken(DothtmlTokenType.Colon);
if (!ReadIdentifier(DothtmlTokenType.Text))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.MissingTagName));
return true;
}
}
SkipWhitespace();
return true;
}
/// <summary>
/// Reads the attribute of a tag.
/// </summary>
private bool ReadAttribute()
{
// attribute name
if (!ReadTagOrAttributeName(isAttributeName: true))
{
return false;
}
if (Peek() == '=')
{
// equals sign
Read();
CreateToken(DothtmlTokenType.Equals);
SkipWhitespace();
// attribute value
if (Peek() == '\'' || Peek() == '"')
{
// single or double quotes
if (!ReadQuotedAttributeValue())
{
return false;
}
}
else
{
// unquoted value
if (Peek() == '>' || Peek() == '<')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.Text, DothtmlTokenizerErrors.MissingAttributeValue));
return false;
}
do
{
if (Read() == NullChar || Peek() == '<') { CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError()); return false; }
} while (!char.IsWhiteSpace(Peek()) && Peek() != '/' && Peek() != '>');
CreateToken(DothtmlTokenType.Text);
SkipWhitespace();
}
}
//else
//{
// CreateToken(DothtmlTokenType.Equals, errorProvider: t => CreateTokenError());
// CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.Text, DothtmlTokenizerErrors.MissingAttributeValue));
// return false;
//}
return true;
}
/// <summary>
/// Reads the quoted attribute value.
/// </summary>
private bool ReadQuotedAttributeValue()
{
// read the beginning quotes
var quotes = Peek();
var quotesToken = quotes == '\'' ? DothtmlTokenType.SingleQuote : DothtmlTokenType.DoubleQuote;
Read();
CreateToken(quotesToken);
// read value
if (Peek() == '{')
{
// binding
ReadBinding(false);
}
else
{
// read text
while (Peek() != quotes)
{
var ch = Peek();
if (ch == NullChar || ch == '<' || ch == '>')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError());
CreateToken(quotesToken, errorProvider: t => CreateTokenError(t, quotesToken, DothtmlTokenizerErrors.AttributeValueNotClosed));
return false;
}
Read();
}
CreateToken(DothtmlTokenType.Text);
}
// read the ending quotes
if (Peek() != quotes)
{
CreateToken(quotesToken, errorProvider: t => CreateTokenError(t, quotesToken, DothtmlTokenizerErrors.AttributeValueNotClosed));
}
else
{
Read();
CreateToken(quotesToken);
SkipWhitespace();
}
return true;
}
/// <summary>
/// Reads the binding.
/// </summary>
private void ReadBinding(bool doubleCloseBrace)
{
// read open brace
Assert(Peek() == '{');
Read();
if (!doubleCloseBrace && Peek() == '{')
{
doubleCloseBrace = true;
Read();
}
CreateToken(DothtmlTokenType.OpenBinding);
SkipWhitespace();
// read binding name
if (!ReadIdentifier(DothtmlTokenType.Text, ':'))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
SkipWhitespace();
}
// colon
if (Peek() != ':')
{
CreateToken(DothtmlTokenType.Colon, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
Read();
CreateToken(DothtmlTokenType.Colon);
SkipWhitespace();
}
// binding value
if (Peek() == '}')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
char ch;
while ((ch = Peek()) != '}')
{
if (ch == '\'' || ch == '"')
{
// string literal - ignore curly braces inside
string errorMessage;
BindingTokenizer.ReadStringLiteral(Peek, Read, out errorMessage);
}
else if (ch == NullChar)
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingNotClosed));
return;
}
else
{
Read();
}
}
CreateToken(DothtmlTokenType.Text);
}
// close brace
if (Peek() != '}')
{
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingNotClosed));
return;
}
Read();
if (doubleCloseBrace)
{
if (Peek() != '}')
{
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.DoubleBraceBindingNotClosed));
return;
}
Read();
}
CreateToken(DothtmlTokenType.CloseBinding);
}
protected override DothtmlToken NewToken()
{
return new DothtmlToken();
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
namespace OpenTK.Graphics.ES10
{
using System;
using System.Text;
using System.Runtime.InteropServices;
#pragma warning disable 3019
#pragma warning disable 1591
partial class GL
{
internal static partial class Core
{
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glActiveTexture", ExactSpelling = true)]
internal extern static void ActiveTexture(OpenTK.Graphics.ES10.All texture);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glAlphaFunc", ExactSpelling = true)]
internal extern static void AlphaFunc(OpenTK.Graphics.ES10.All func, Single @ref);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glAlphaFuncx", ExactSpelling = true)]
internal extern static void AlphaFuncx(OpenTK.Graphics.ES10.All func, int @ref);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBindTexture", ExactSpelling = true)]
internal extern static void BindTexture(OpenTK.Graphics.ES10.All target, UInt32 texture);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glBlendFunc", ExactSpelling = true)]
internal extern static void BlendFunc(OpenTK.Graphics.ES10.All sfactor, OpenTK.Graphics.ES10.All dfactor);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClear", ExactSpelling = true)]
internal extern static void Clear(UInt32 mask);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearColor", ExactSpelling = true)]
internal extern static void ClearColor(Single red, Single green, Single blue, Single alpha);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearColorx", ExactSpelling = true)]
internal extern static void ClearColorx(int red, int green, int blue, int alpha);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthf", ExactSpelling = true)]
internal extern static void ClearDepthf(Single depth);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearDepthx", ExactSpelling = true)]
internal extern static void ClearDepthx(int depth);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClearStencil", ExactSpelling = true)]
internal extern static void ClearStencil(Int32 s);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glClientActiveTexture", ExactSpelling = true)]
internal extern static void ClientActiveTexture(OpenTK.Graphics.ES10.All texture);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4f", ExactSpelling = true)]
internal extern static void Color4f(Single red, Single green, Single blue, Single alpha);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColor4x", ExactSpelling = true)]
internal extern static void Color4x(int red, int green, int blue, int alpha);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColorMask", ExactSpelling = true)]
internal extern static void ColorMask(bool red, bool green, bool blue, bool alpha);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glColorPointer", ExactSpelling = true)]
internal extern static void ColorPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCompressedTexImage2D", ExactSpelling = true)]
internal extern static void CompressedTexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, OpenTK.Graphics.ES10.All internalformat, Int32 width, Int32 height, Int32 border, Int32 imageSize, IntPtr data);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCompressedTexSubImage2D", ExactSpelling = true)]
internal extern static void CompressedTexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, Int32 imageSize, IntPtr data);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCopyTexImage2D", ExactSpelling = true)]
internal extern static void CopyTexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, OpenTK.Graphics.ES10.All internalformat, Int32 x, Int32 y, Int32 width, Int32 height, Int32 border);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCopyTexSubImage2D", ExactSpelling = true)]
internal extern static void CopyTexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 x, Int32 y, Int32 width, Int32 height);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glCullFace", ExactSpelling = true)]
internal extern static void CullFace(OpenTK.Graphics.ES10.All mode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDeleteTextures", ExactSpelling = true)]
internal extern static unsafe void DeleteTextures(Int32 n, UInt32* textures);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthFunc", ExactSpelling = true)]
internal extern static void DepthFunc(OpenTK.Graphics.ES10.All func);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthMask", ExactSpelling = true)]
internal extern static void DepthMask(bool flag);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangef", ExactSpelling = true)]
internal extern static void DepthRangef(Single zNear, Single zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDepthRangex", ExactSpelling = true)]
internal extern static void DepthRangex(int zNear, int zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDisable", ExactSpelling = true)]
internal extern static void Disable(OpenTK.Graphics.ES10.All cap);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDisableClientState", ExactSpelling = true)]
internal extern static void DisableClientState(OpenTK.Graphics.ES10.All array);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawArrays", ExactSpelling = true)]
internal extern static void DrawArrays(OpenTK.Graphics.ES10.All mode, Int32 first, Int32 count);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glDrawElements", ExactSpelling = true)]
internal extern static void DrawElements(OpenTK.Graphics.ES10.All mode, Int32 count, OpenTK.Graphics.ES10.All type, IntPtr indices);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEnable", ExactSpelling = true)]
internal extern static void Enable(OpenTK.Graphics.ES10.All cap);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glEnableClientState", ExactSpelling = true)]
internal extern static void EnableClientState(OpenTK.Graphics.ES10.All array);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFinish", ExactSpelling = true)]
internal extern static void Finish();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFlush", ExactSpelling = true)]
internal extern static void Flush();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogf", ExactSpelling = true)]
internal extern static void Fogf(OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogfv", ExactSpelling = true)]
internal extern static unsafe void Fogfv(OpenTK.Graphics.ES10.All pname, Single* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogx", ExactSpelling = true)]
internal extern static void Fogx(OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFogxv", ExactSpelling = true)]
internal extern static unsafe void Fogxv(OpenTK.Graphics.ES10.All pname, int* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrontFace", ExactSpelling = true)]
internal extern static void FrontFace(OpenTK.Graphics.ES10.All mode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumf", ExactSpelling = true)]
internal extern static void Frustumf(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glFrustumx", ExactSpelling = true)]
internal extern static void Frustumx(int left, int right, int bottom, int top, int zNear, int zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGenTextures", ExactSpelling = true)]
internal extern static unsafe void GenTextures(Int32 n, UInt32* textures);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetError", ExactSpelling = true)]
internal extern static OpenTK.Graphics.ES10.All GetError();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetIntegerv", ExactSpelling = true)]
internal extern static unsafe void GetIntegerv(OpenTK.Graphics.ES10.All pname, Int32* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glGetString", ExactSpelling = true)]
internal extern static unsafe System.IntPtr GetString(OpenTK.Graphics.ES10.All name);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glHint", ExactSpelling = true)]
internal extern static void Hint(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All mode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightf", ExactSpelling = true)]
internal extern static void Lightf(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightfv", ExactSpelling = true)]
internal extern static unsafe void Lightfv(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, Single* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelf", ExactSpelling = true)]
internal extern static void LightModelf(OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelfv", ExactSpelling = true)]
internal extern static unsafe void LightModelfv(OpenTK.Graphics.ES10.All pname, Single* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelx", ExactSpelling = true)]
internal extern static void LightModelx(OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightModelxv", ExactSpelling = true)]
internal extern static unsafe void LightModelxv(OpenTK.Graphics.ES10.All pname, int* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightx", ExactSpelling = true)]
internal extern static void Lightx(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLightxv", ExactSpelling = true)]
internal extern static unsafe void Lightxv(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, int* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLineWidth", ExactSpelling = true)]
internal extern static void LineWidth(Single width);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLineWidthx", ExactSpelling = true)]
internal extern static void LineWidthx(int width);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadIdentity", ExactSpelling = true)]
internal extern static void LoadIdentity();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadMatrixf", ExactSpelling = true)]
internal extern static unsafe void LoadMatrixf(Single* m);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLoadMatrixx", ExactSpelling = true)]
internal extern static unsafe void LoadMatrixx(int* m);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glLogicOp", ExactSpelling = true)]
internal extern static void LogicOp(OpenTK.Graphics.ES10.All opcode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialf", ExactSpelling = true)]
internal extern static void Materialf(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialfv", ExactSpelling = true)]
internal extern static unsafe void Materialfv(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, Single* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialx", ExactSpelling = true)]
internal extern static void Materialx(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMaterialxv", ExactSpelling = true)]
internal extern static unsafe void Materialxv(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, int* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMatrixMode", ExactSpelling = true)]
internal extern static void MatrixMode(OpenTK.Graphics.ES10.All mode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultiTexCoord4f", ExactSpelling = true)]
internal extern static void MultiTexCoord4f(OpenTK.Graphics.ES10.All target, Single s, Single t, Single r, Single q);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultiTexCoord4x", ExactSpelling = true)]
internal extern static void MultiTexCoord4x(OpenTK.Graphics.ES10.All target, int s, int t, int r, int q);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultMatrixf", ExactSpelling = true)]
internal extern static unsafe void MultMatrixf(Single* m);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glMultMatrixx", ExactSpelling = true)]
internal extern static unsafe void MultMatrixx(int* m);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormal3f", ExactSpelling = true)]
internal extern static void Normal3f(Single nx, Single ny, Single nz);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormal3x", ExactSpelling = true)]
internal extern static void Normal3x(int nx, int ny, int nz);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glNormalPointer", ExactSpelling = true)]
internal extern static void NormalPointer(OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthof", ExactSpelling = true)]
internal extern static void Orthof(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glOrthox", ExactSpelling = true)]
internal extern static void Orthox(int left, int right, int bottom, int top, int zNear, int zFar);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPixelStorei", ExactSpelling = true)]
internal extern static void PixelStorei(OpenTK.Graphics.ES10.All pname, Int32 param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSize", ExactSpelling = true)]
internal extern static void PointSize(Single size);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPointSizex", ExactSpelling = true)]
internal extern static void PointSizex(int size);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPolygonOffset", ExactSpelling = true)]
internal extern static void PolygonOffset(Single factor, Single units);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPolygonOffsetx", ExactSpelling = true)]
internal extern static void PolygonOffsetx(int factor, int units);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPopMatrix", ExactSpelling = true)]
internal extern static void PopMatrix();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glPushMatrix", ExactSpelling = true)]
internal extern static void PushMatrix();
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glReadPixels", ExactSpelling = true)]
internal extern static void ReadPixels(Int32 x, Int32 y, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRotatef", ExactSpelling = true)]
internal extern static void Rotatef(Single angle, Single x, Single y, Single z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glRotatex", ExactSpelling = true)]
internal extern static void Rotatex(int angle, int x, int y, int z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSampleCoverage", ExactSpelling = true)]
internal extern static void SampleCoverage(Single value, bool invert);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glSampleCoveragex", ExactSpelling = true)]
internal extern static void SampleCoveragex(int value, bool invert);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScalef", ExactSpelling = true)]
internal extern static void Scalef(Single x, Single y, Single z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScalex", ExactSpelling = true)]
internal extern static void Scalex(int x, int y, int z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glScissor", ExactSpelling = true)]
internal extern static void Scissor(Int32 x, Int32 y, Int32 width, Int32 height);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glShadeModel", ExactSpelling = true)]
internal extern static void ShadeModel(OpenTK.Graphics.ES10.All mode);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilFunc", ExactSpelling = true)]
internal extern static void StencilFunc(OpenTK.Graphics.ES10.All func, Int32 @ref, UInt32 mask);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilMask", ExactSpelling = true)]
internal extern static void StencilMask(UInt32 mask);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glStencilOp", ExactSpelling = true)]
internal extern static void StencilOp(OpenTK.Graphics.ES10.All fail, OpenTK.Graphics.ES10.All zfail, OpenTK.Graphics.ES10.All zpass);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexCoordPointer", ExactSpelling = true)]
internal extern static void TexCoordPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvf", ExactSpelling = true)]
internal extern static void TexEnvf(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvfv", ExactSpelling = true)]
internal extern static unsafe void TexEnvfv(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvx", ExactSpelling = true)]
internal extern static void TexEnvx(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexEnvxv", ExactSpelling = true)]
internal extern static unsafe void TexEnvxv(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int* @params);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexImage2D", ExactSpelling = true)]
internal extern static void TexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 internalformat, Int32 width, Int32 height, Int32 border, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterf", ExactSpelling = true)]
internal extern static void TexParameterf(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexParameterx", ExactSpelling = true)]
internal extern static void TexParameterx(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int param);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTexSubImage2D", ExactSpelling = true)]
internal extern static void TexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTranslatef", ExactSpelling = true)]
internal extern static void Translatef(Single x, Single y, Single z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glTranslatex", ExactSpelling = true)]
internal extern static void Translatex(int x, int y, int z);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glVertexPointer", ExactSpelling = true)]
internal extern static void VertexPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[System.Runtime.InteropServices.DllImport(GL.Library, EntryPoint = "glViewport", ExactSpelling = true)]
internal extern static void Viewport(Int32 x, Int32 y, Int32 width, Int32 height);
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceLineItem (editable child object).<br/>
/// This is a generated <see cref="InvoiceLineItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="InvoiceLineCollection"/> collection.
/// </remarks>
[Serializable]
public partial class InvoiceLineItem : BusinessBase<InvoiceLineItem>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceLineId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> InvoiceLineIdProperty = RegisterProperty<Guid>(p => p.InvoiceLineId, "Invoice Line Id");
/// <summary>
/// Gets or sets the Invoice Line Id.
/// </summary>
/// <value>The Invoice Line Id.</value>
public Guid InvoiceLineId
{
get { return GetProperty(InvoiceLineIdProperty); }
set { SetProperty(InvoiceLineIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductId"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id");
/// <summary>
/// Gets or sets the Product Id.
/// </summary>
/// <value>The Product Id.</value>
public Guid ProductId
{
get { return GetProperty(ProductIdProperty); }
set { SetProperty(ProductIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Cost"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> CostProperty = RegisterProperty<decimal>(p => p.Cost, "Cost");
/// <summary>
/// Gets or sets the Cost.
/// </summary>
/// <value>The Cost.</value>
public decimal Cost
{
get { return GetProperty(CostProperty); }
set { SetProperty(CostProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="PercentDiscount"/> property.
/// </summary>
public static readonly PropertyInfo<byte> PercentDiscountProperty = RegisterProperty<byte>(p => p.PercentDiscount, "Percent Discount");
/// <summary>
/// Gets or sets the Percent Discount.
/// </summary>
/// <value>The Percent Discount.</value>
public byte PercentDiscount
{
get { return GetProperty(PercentDiscountProperty); }
set { SetProperty(PercentDiscountProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceLineItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceLineItem()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="InvoiceLineItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(InvoiceLineIdProperty, Guid.NewGuid());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="InvoiceLineItem"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(InvoiceLineIdProperty, dr.GetGuid("InvoiceLineId"));
LoadProperty(ProductIdProperty, dr.GetGuid("ProductId"));
LoadProperty(CostProperty, dr.GetDecimal("Cost"));
LoadProperty(PercentDiscountProperty, dr.GetByte("PercentDiscount"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="InvoiceLineItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(InvoiceEdit parent)
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.InvoiceId,
InvoiceLineId,
ProductId,
Cost,
PercentDiscount
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="InvoiceLineItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
dal.Update(
InvoiceLineId,
ProductId,
Cost,
PercentDiscount
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="InvoiceLineItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(InvoiceLineIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[Serializable]
public sealed class EncoderExceptionFallback : EncoderFallback
{
// Construction
public EncoderExceptionFallback()
{
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderExceptionFallbackBuffer();
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 0;
}
}
public override bool Equals(Object value)
{
EncoderExceptionFallback that = value as EncoderExceptionFallback;
if (that != null)
{
return (true);
}
return (false);
}
public override int GetHashCode()
{
return 654;
}
}
public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer
{
public EncoderExceptionFallbackBuffer(){}
public override bool Fallback(char charUnknown, int index)
{
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
(int)charUnknown, index), charUnknown, index);
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow);
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
iTemp, index), charUnknownHigh, charUnknownLow, index);
}
public override char GetNextChar()
{
return (char)0;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
return false;
}
// Exceptions are always empty
public override int Remaining
{
get
{
return 0;
}
}
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class EncoderFallbackException : ArgumentException
{
char charUnknown;
char charUnknownHigh;
char charUnknownLow;
int index;
public EncoderFallbackException()
: base(Environment.GetResourceString("Arg_ArgumentException"))
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message)
: base(message)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal EncoderFallbackException(
String message, char charUnknown, int index) : base(message)
{
this.charUnknown = charUnknown;
this.index = index;
}
internal EncoderFallbackException(
String message, char charUnknownHigh, char charUnknownLow, int index) : base(message)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
this.charUnknownHigh = charUnknownHigh;
this.charUnknownLow = charUnknownLow;
this.index = index;
}
public char CharUnknown
{
get
{
return (charUnknown);
}
}
public char CharUnknownHigh
{
get
{
return (charUnknownHigh);
}
}
public char CharUnknownLow
{
get
{
return (charUnknownLow);
}
}
public int Index
{
get
{
return index;
}
}
// Return true if the unknown character is a surrogate pair.
public bool IsUnknownSurrogate()
{
return (this.charUnknownHigh != '\0');
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DotNet.Cli.Compiler.Common;
using NuGet.Frameworks;
namespace Microsoft.DotNet.ProjectModel.Workspaces
{
public class ProjectJsonWorkspace : Workspace
{
private Dictionary<string, AssemblyMetadata> _cache = new Dictionary<string, AssemblyMetadata>();
public ProjectJsonWorkspace(ProjectContext context) : base(MefHostServices.DefaultHost, "Custom")
{
AddProject(context);
}
public ProjectJsonWorkspace(string projectPath) : this(new[] { projectPath })
{
}
public ProjectJsonWorkspace(IEnumerable<string> projectPaths) : base(MefHostServices.DefaultHost, "Custom")
{
Initialize(projectPaths);
}
private void Initialize(IEnumerable<string> projectPaths)
{
foreach (var projectPath in projectPaths)
{
AddProject(projectPath);
}
}
private void AddProject(string projectPath)
{
// Get all of the specific projects (there is a project per framework)
foreach (var p in ProjectContext.CreateContextForEachFramework(projectPath))
{
AddProject(p);
}
}
private ProjectId AddProject(ProjectContext project)
{
// Create the framework specific project and add it to the workspace
var projectInfo = ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
project.ProjectFile.Name + "+" + project.TargetFramework,
project.ProjectFile.Name,
LanguageNames.CSharp,
project.ProjectFile.ProjectFilePath);
OnProjectAdded(projectInfo);
// TODO: ctor argument?
var configuration = "Debug";
var compilationOptions = project.GetLanguageSpecificCompilerOptions(project.TargetFramework, configuration);
var compilationSettings = ToCompilationSettings(compilationOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory);
OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines));
OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);
foreach (var file in project.ProjectFile.Files.SourceFiles)
{
AddSourceFile(projectInfo, file);
}
var exporter = project.CreateExporter(configuration);
foreach (var dependency in exporter.GetDependencies())
{
var projectDependency = dependency.Library as ProjectDescription;
if (projectDependency != null)
{
var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework);
var id = AddProject(projectDependencyContext);
OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id));
}
else
{
foreach (var asset in dependency.CompilationAssemblies)
{
OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath));
}
}
foreach (var file in dependency.SourceReferences)
{
AddSourceFile(projectInfo, file);
}
}
return projectInfo.Id;
}
private void AddSourceFile(ProjectInfo projectInfo, string file)
{
using (var stream = File.OpenRead(file))
{
var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
var id = DocumentId.CreateNewId(projectInfo.Id);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));
OnDocumentAdded(DocumentInfo.Create(id, file, filePath: file, loader: loader));
}
}
private MetadataReference GetMetadataReference(string path)
{
AssemblyMetadata assemblyMetadata;
if (!_cache.TryGetValue(path, out assemblyMetadata))
{
using (var stream = File.OpenRead(path))
{
var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);
_cache[path] = assemblyMetadata;
}
}
return assemblyMetadata.GetReference();
}
private static CompilationSettings ToCompilationSettings(CommonCompilerOptions compilerOptions,
NuGetFramework targetFramework,
string projectDirectory)
{
var options = GetCompilationOptions(compilerOptions, projectDirectory);
options = options.WithSpecificDiagnosticOptions(compilerOptions.SuppressWarnings.ToDictionary(
suppress => suppress, _ => ReportDiagnostic.Suppress));
AssemblyIdentityComparer assemblyIdentityComparer =
targetFramework.IsDesktop() ?
DesktopAssemblyIdentityComparer.Default :
null;
options = options.WithAssemblyIdentityComparer(assemblyIdentityComparer);
LanguageVersion languageVersion;
if (!Enum.TryParse<LanguageVersion>(value: compilerOptions.LanguageVersion,
ignoreCase: true,
result: out languageVersion))
{
languageVersion = LanguageVersion.CSharp6;
}
var settings = new CompilationSettings
{
LanguageVersion = languageVersion,
Defines = compilerOptions.Defines ?? Enumerable.Empty<string>(),
CompilationOptions = options
};
return settings;
}
private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory)
{
var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ?
OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary;
var options = new CSharpCompilationOptions(outputKind);
string platformValue = compilerOptions.Platform;
bool allowUnsafe = compilerOptions.AllowUnsafe ?? false;
bool optimize = compilerOptions.Optimize ?? false;
bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false;
Platform platform;
if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform))
{
platform = Platform.AnyCpu;
}
options = options
.WithAllowUnsafe(allowUnsafe)
.WithPlatform(platform)
.WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
.WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug);
return AddSigningOptions(options, compilerOptions, projectDirectory);
}
private static CSharpCompilationOptions AddSigningOptions(CSharpCompilationOptions options, CommonCompilerOptions compilerOptions, string projectDirectory)
{
var useOssSigning = compilerOptions.PublicSign == true;
var keyFile = compilerOptions.KeyFile;
if (!string.IsNullOrEmpty(keyFile))
{
keyFile = Path.GetFullPath(Path.Combine(projectDirectory, compilerOptions.KeyFile));
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || useOssSigning)
{
return options.WithCryptoPublicKey(
SnkUtils.ExtractPublicKey(File.ReadAllBytes(keyFile)));
}
options = options.WithCryptoKeyFile(keyFile);
return options.WithDelaySign(compilerOptions.DelaySign);
}
return options;
}
private class CompilationSettings
{
public LanguageVersion LanguageVersion { get; set; }
public IEnumerable<string> Defines { get; set; }
public CSharpCompilationOptions CompilationOptions { get; set; }
}
}
}
| |
using System;
using Mono.Cecil.PE;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class FieldTests : BaseTestFixture {
[Test]
public void TypeDefField ()
{
TestCSharp ("Fields.cs", module => {
var type = module.Types [1];
Assert.AreEqual ("Foo", type.Name);
Assert.AreEqual (1, type.Fields.Count);
var field = type.Fields [0];
Assert.AreEqual ("bar", field.Name);
Assert.AreEqual (1, field.MetadataToken.RID);
Assert.IsNotNull (field.FieldType);
Assert.AreEqual ("Bar", field.FieldType.FullName);
Assert.AreEqual (TokenType.Field, field.MetadataToken.TokenType);
Assert.IsFalse (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void PrimitiveTypes ()
{
TestCSharp ("Fields.cs", module => {
var type = module.GetType ("Baz");
AssertField (type, "char", typeof (char));
AssertField (type, "bool", typeof (bool));
AssertField (type, "sbyte", typeof (sbyte));
AssertField (type, "byte", typeof (byte));
AssertField (type, "int16", typeof (short));
AssertField (type, "uint16", typeof (ushort));
AssertField (type, "int32", typeof (int));
AssertField (type, "uint32", typeof (uint));
AssertField (type, "int64", typeof (long));
AssertField (type, "uint64", typeof (ulong));
AssertField (type, "single", typeof (float));
AssertField (type, "double", typeof (double));
AssertField (type, "string", typeof (string));
AssertField (type, "object", typeof (object));
});
}
[Test]
public void VolatileField ()
{
TestCSharp ("Fields.cs", module => {
var type = module.GetType ("Bar");
Assert.IsTrue (type.HasFields);
Assert.AreEqual (1, type.Fields.Count);
var field = type.Fields [0];
Assert.AreEqual ("oiseau", field.Name);
Assert.AreEqual ("System.Int32 modreq(System.Runtime.CompilerServices.IsVolatile)", field.FieldType.FullName);
Assert.IsFalse (field.HasConstant);
});
}
[Test]
public void FieldLayout ()
{
TestCSharp ("Layouts.cs", module => {
var foo = module.GetType ("Foo");
Assert.IsNotNull (foo);
Assert.IsTrue (foo.HasFields);
var fields = foo.Fields;
var field = fields [0];
Assert.AreEqual ("Bar", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (0, field.Offset);
field = fields [1];
Assert.AreEqual ("Baz", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (2, field.Offset);
field = fields [2];
Assert.AreEqual ("Gazonk", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (4, field.Offset);
});
}
[Test]
public void FieldRVA ()
{
TestCSharp ("Layouts.cs", module => {
var priv_impl = GetPrivateImplementationType (module);
Assert.IsNotNull (priv_impl);
Assert.AreEqual (1, priv_impl.Fields.Count);
var field = priv_impl.Fields [0];
Assert.IsNotNull (field);
Assert.AreNotEqual (0, field.RVA);
Assert.IsNotNull (field.InitialValue);
Assert.AreEqual (16, field.InitialValue.Length);
var buffer = new ByteBuffer (field.InitialValue);
Assert.AreEqual (1, buffer.ReadUInt32 ());
Assert.AreEqual (2, buffer.ReadUInt32 ());
Assert.AreEqual (3, buffer.ReadUInt32 ());
Assert.AreEqual (4, buffer.ReadUInt32 ());
});
}
[Test]
public void GenericFieldDefinition ()
{
TestCSharp ("Generics.cs", module => {
var bar = module.GetType ("Bar`1");
Assert.IsNotNull (bar);
Assert.IsTrue (bar.HasGenericParameters);
var t = bar.GenericParameters [0];
Assert.AreEqual ("T", t.Name);
Assert.AreEqual (t.Owner, bar);
var bang = bar.GetField ("bang");
Assert.IsNotNull (bang);
Assert.AreEqual (t, bang.FieldType);
});
}
[Test]
public void ArrayFields ()
{
TestIL ("types.il", module => {
var types = module.GetType ("Types");
Assert.IsNotNull (types);
var rank_two = types.GetField ("rank_two");
var array = rank_two.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (2, array.Rank);
Assert.IsFalse (array.Dimensions [0].IsSized);
Assert.IsFalse (array.Dimensions [1].IsSized);
var rank_two_low_bound_zero = types.GetField ("rank_two_low_bound_zero");
array = rank_two_low_bound_zero.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (2, array.Rank);
Assert.IsTrue (array.Dimensions [0].IsSized);
Assert.AreEqual (0, array.Dimensions [0].LowerBound);
Assert.AreEqual (null, array.Dimensions [0].UpperBound);
Assert.IsTrue (array.Dimensions [1].IsSized);
Assert.AreEqual (0, array.Dimensions [1].LowerBound);
Assert.AreEqual (null, array.Dimensions [1].UpperBound);
var rank_one_low_bound_m1 = types.GetField ("rank_one_low_bound_m1");
array = rank_one_low_bound_m1.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (1, array.Rank);
Assert.IsTrue (array.Dimensions [0].IsSized);
Assert.AreEqual (-1, array.Dimensions [0].LowerBound);
Assert.AreEqual (4, array.Dimensions [0].UpperBound);
});
}
[Test]
public void EnumFieldsConstant ()
{
TestCSharp ("Fields.cs", module => {
var pim = module.GetType ("Pim");
Assert.IsNotNull (pim);
var field = pim.GetField ("Pam");
Assert.IsTrue (field.HasConstant);
Assert.AreEqual (1, (int) field.Constant);
field = pim.GetField ("Poum");
Assert.AreEqual (2, (int) field.Constant);
});
}
[Test]
public void StringAndClassConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("Peter");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
field = panpan.GetField ("QQ");
Assert.AreEqual ("qq", (string) field.Constant);
field = panpan.GetField ("nil");
Assert.AreEqual (null, (string) field.Constant);
});
}
[Test]
public void ObjectConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("obj");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void NullPrimitiveConstant ()
{
TestIL ("types.il", module => {
var fields = module.GetType ("Fields");
var field = fields.GetField ("int32_nullref");
Assert.IsTrue (field.HasConstant);
Assert.AreEqual (null, field.Constant);
});
}
[Test]
public void ArrayConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("ints");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void ConstantCoalescing ()
{
TestIL ("types.il", module => {
var fields = module.GetType ("Fields");
var field = fields.GetField ("int32_int16");
Assert.AreEqual ("System.Int32", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (short), field.Constant);
Assert.AreEqual ((short) 1, field.Constant);
field = fields.GetField ("int16_int32");
Assert.AreEqual ("System.Int16", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (int), field.Constant);
Assert.AreEqual (1, field.Constant);
field = fields.GetField ("char_int16");
Assert.AreEqual ("System.Char", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (short), field.Constant);
Assert.AreEqual ((short) 1, field.Constant);
field = fields.GetField ("int16_char");
Assert.AreEqual ("System.Int16", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (char), field.Constant);
Assert.AreEqual ('s', field.Constant);
});
}
[Test]
public void NestedEnumOfGenericTypeDefinition ()
{
TestCSharp ("Generics.cs", module => {
var dang = module.GetType ("Bongo`1/Dang");
Assert.IsNotNull (dang);
var field = dang.GetField ("Ding");
Assert.IsNotNull (field);
Assert.AreEqual (2, field.Constant);
field = dang.GetField ("Dong");
Assert.IsNotNull (field);
Assert.AreEqual (12, field.Constant);
});
}
[Test]
public void MarshalAsFixedStr ()
{
TestModule ("marshal.dll", module => {
var boc = module.GetType ("Boc");
var field = boc.GetField ("a");
Assert.IsNotNull (field);
Assert.IsTrue (field.HasMarshalInfo);
var info = (FixedSysStringMarshalInfo) field.MarshalInfo;
Assert.AreEqual (42, info.Size);
});
}
[Test]
public void MarshalAsFixedArray ()
{
TestModule ("marshal.dll", module => {
var boc = module.GetType ("Boc");
var field = boc.GetField ("b");
Assert.IsNotNull (field);
Assert.IsTrue (field.HasMarshalInfo);
var info = (FixedArrayMarshalInfo) field.MarshalInfo;
Assert.AreEqual (12, info.Size);
Assert.AreEqual (NativeType.Boolean, info.ElementType);
});
}
[Test]
public void UnattachedField ()
{
var field = new FieldDefinition ("Field", FieldAttributes.Public, typeof (int).ToDefinition ());
Assert.IsFalse (field.HasConstant);
Assert.IsNull (field.Constant);
}
static TypeDefinition GetPrivateImplementationType (ModuleDefinition module)
{
foreach (var type in module.Types)
if (type.FullName.Contains ("<PrivateImplementationDetails>"))
return type;
return null;
}
static void AssertField (TypeDefinition type, string name, Type expected)
{
var field = type.GetField (name);
Assert.IsNotNull (field, name);
Assert.AreEqual (expected.FullName, field.FieldType.FullName);
}
}
}
| |
//------------------------------------------------------------------
// <summary>
// A P/Invoke wrapper for TaskDialog. Usability was given preference to perf and size.
// </summary>
//
// <remarks/>
//------------------------------------------------------------------
namespace MLifter.Controls
{
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The active Task Dialog window. Provides several methods for acting on the active TaskDialog.
/// You should not use this object after the TaskDialog Destroy notification callback. Doing so
/// will result in undefined behavior and likely crash.
/// </summary>
public class VistaActiveTaskDialog : IWin32Window
{
/// <summary>
/// The Task Dialog's window handle.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // We don't own the window.
private IntPtr handle;
/// <summary>
/// Creates a ActiveTaskDialog.
/// </summary>
/// <param name="handle">The Task Dialog's window handle.</param>
internal VistaActiveTaskDialog(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
throw new ArgumentNullException("handle");
}
this.handle = handle;
}
/// <summary>
/// The Task Dialog's window handle.
/// </summary>
public IntPtr Handle
{
get { return this.handle; }
}
//// Not supported. Task Dialog Spec does not indicate what this is for.
////public void NavigatePage()
////{
//// // TDM_NAVIGATE_PAGE = WM_USER+101,
//// UnsafeNativeMethods.SendMessage(
//// this.windowHandle,
//// (uint)UnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_NAVIGATE_PAGE,
//// IntPtr.Zero,
//// //a UnsafeNativeMethods.TASKDIALOGCONFIG value);
////}
/// <summary>
/// Simulate the action of a button click in the TaskDialog. This can be a DialogResult value
/// or the ButtonID set on a TasDialogButton set on TaskDialog.Buttons.
/// </summary>
/// <param name="buttonId">Indicates the button ID to be selected.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool ClickButton(int buttonId)
{
// TDM_CLICK_BUTTON = WM_USER+102, // wParam = Button ID
return VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_BUTTON,
(IntPtr)buttonId,
IntPtr.Zero) != IntPtr.Zero;
}
/// <summary>
/// Used to indicate whether the hosted progress bar should be displayed in marquee mode or not.
/// </summary>
/// <param name="marquee">Specifies whether the progress bar sbould be shown in Marquee mode.
/// A value of true turns on Marquee mode.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetMarqueeProgressBar(bool marquee)
{
// TDM_SET_MARQUEE_PROGRESS_BAR = WM_USER+103, // wParam = 0 (nonMarque) wParam != 0 (Marquee)
return VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_MARQUEE_PROGRESS_BAR,
(marquee ? (IntPtr)1 : IntPtr.Zero),
IntPtr.Zero) != IntPtr.Zero;
// Future: get more detailed error from and throw.
}
/// <summary>
/// Sets the state of the progress bar.
/// </summary>
/// <param name="newState">The state to set the progress bar.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetProgressBarState(VistaProgressBarState newState)
{
// TDM_SET_PROGRESS_BAR_STATE = WM_USER+104, // wParam = new progress state
return VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_STATE,
(IntPtr)newState,
IntPtr.Zero) != IntPtr.Zero;
// Future: get more detailed error from and throw.
}
/// <summary>
/// Set the minimum and maximum values for the hosted progress bar.
/// </summary>
/// <param name="minRange">Minimum range value. By default, the minimum value is zero.</param>
/// <param name="maxRange">Maximum range value. By default, the maximum value is 100.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetProgressBarRange(Int16 minRange, Int16 maxRange)
{
// TDM_SET_PROGRESS_BAR_RANGE = WM_USER+105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
// #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
// #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
IntPtr lparam = (IntPtr)((((Int32)minRange) & 0xffff) | ((((Int32)maxRange) & 0xffff) << 16));
return VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_RANGE,
IntPtr.Zero,
lparam) != IntPtr.Zero;
// Return value is actually prior range.
}
/// <summary>
/// Set the current position for a progress bar.
/// </summary>
/// <param name="newPosition">The new position.</param>
/// <returns>Returns the previous value if successful, or zero otherwise.</returns>
public int SetProgressBarPosition(int newPosition)
{
// TDM_SET_PROGRESS_BAR_POS = WM_USER+106, // wParam = new position
return (int)VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_POS,
(IntPtr)newPosition,
IntPtr.Zero);
}
/// <summary>
/// Sets the animation state of the Marquee Progress Bar.
/// </summary>
/// <param name="startMarquee">true starts the marquee animation and false stops it.</param>
/// <param name="speed">The time in milliseconds between refreshes.</param>
public void SetProgressBarMarquee(bool startMarquee, uint speed)
{
// TDM_SET_PROGRESS_BAR_MARQUEE = WM_USER+107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_MARQUEE,
(startMarquee ? new IntPtr(1) : IntPtr.Zero),
(IntPtr)speed);
}
/// <summary>
/// Updates the content Text.
/// </summary>
/// <param name="content">The new value.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetContent(string content)
{
// TDE_CONTENT,
// TDM_SET_ELEMENT_TEXT = WM_USER+108 // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
return VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_CONTENT,
content) != IntPtr.Zero;
}
/// <summary>
/// Updates the Expanded Information Text.
/// </summary>
/// <param name="expandedInformation">The new value.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetExpandedInformation(string expandedInformation)
{
// TDE_EXPANDED_INFORMATION,
// TDM_SET_ELEMENT_TEXT = WM_USER+108 // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
return VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_EXPANDED_INFORMATION,
expandedInformation) != IntPtr.Zero;
}
/// <summary>
/// Updates the Footer Text.
/// </summary>
/// <param name="footer">The new value.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetFooter(string footer)
{
// TDE_FOOTER,
// TDM_SET_ELEMENT_TEXT = WM_USER+108 // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
return VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_FOOTER,
footer) != IntPtr.Zero;
}
/// <summary>
/// Updates the Main Instruction.
/// </summary>
/// <param name="mainInstruction">The new value.</param>
/// <returns>If the function succeeds the return value is true.</returns>
public bool SetMainInstruction(string mainInstruction)
{
// TDE_MAIN_INSTRUCTION
// TDM_SET_ELEMENT_TEXT = WM_USER+108 // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
return VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_MAIN_INSTRUCTION,
mainInstruction) != IntPtr.Zero;
}
/// <summary>
/// Simulate the action of a radio button click in the TaskDialog.
/// The passed buttonID is the ButtonID set on a TaskDialogButton set on TaskDialog.RadioButtons.
/// </summary>
/// <param name="buttonId">Indicates the button ID to be selected.</param>
public void ClickRadioButton(int buttonId)
{
// TDM_CLICK_RADIO_BUTTON = WM_USER+110, // wParam = Radio Button ID
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_RADIO_BUTTON,
(IntPtr)buttonId,
IntPtr.Zero);
}
/// <summary>
/// Enable or disable a button in the TaskDialog.
/// The passed buttonID is the ButtonID set on a TaskDialogButton set on TaskDialog.Buttons
/// or a common button ID.
/// </summary>
/// <param name="buttonId">Indicates the button ID to be enabled or diabled.</param>
/// <param name="enable">Enambe the button if true. Disable the button if false.</param>
public void EnableButton(int buttonId, bool enable)
{
// TDM_ENABLE_BUTTON = WM_USER+111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_ENABLE_BUTTON,
(IntPtr)buttonId,
(IntPtr)(enable ? 0 : 1));
}
/// <summary>
/// Enable or disable a radio button in the TaskDialog.
/// The passed buttonID is the ButtonID set on a TaskDialogButton set on TaskDialog.RadioButtons.
/// </summary>
/// <param name="buttonId">Indicates the button ID to be enabled or diabled.</param>
/// <param name="enable">Enambe the button if true. Disable the button if false.</param>
public void EnableRadioButton(int buttonId, bool enable)
{
// TDM_ENABLE_RADIO_BUTTON = WM_USER+112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_ENABLE_RADIO_BUTTON,
(IntPtr)buttonId,
(IntPtr)(enable ? 0 : 1));
}
/// <summary>
/// Check or uncheck the verification checkbox in the TaskDialog.
/// </summary>
/// <param name="checkedState">The checked state to set the verification checkbox.</param>
/// <param name="setKeyboardFocusToCheckBox">True to set the keyboard focus to the checkbox, and fasle otherwise.</param>
public void ClickVerification(bool checkedState, bool setKeyboardFocusToCheckBox)
{
// TDM_CLICK_VERIFICATION = WM_USER+113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_VERIFICATION,
(checkedState ? new IntPtr(1) : IntPtr.Zero),
(setKeyboardFocusToCheckBox ? new IntPtr(1) : IntPtr.Zero));
}
/// <summary>
/// Updates the content Text.
/// </summary>
/// <param name="content">The new value.</param>
public void UpdateContent(string content)
{
// TDE_CONTENT,
// TDM_UPDATE_ELEMENT_TEXT = WM_USER+114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_CONTENT,
content);
}
/// <summary>
/// Updates the Expanded Information Text. No effect if it was previously set to null.
/// </summary>
/// <param name="expandedInformation">The new value.</param>
public void UpdateExpandedInformation(string expandedInformation)
{
// TDE_EXPANDED_INFORMATION,
// TDM_UPDATE_ELEMENT_TEXT = WM_USER+114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_EXPANDED_INFORMATION,
expandedInformation);
}
/// <summary>
/// Updates the Footer Text. No Effect if it was perviously set to null.
/// </summary>
/// <param name="footer">The new value.</param>
public void UpdateFooter(string footer)
{
// TDE_FOOTER,
// TDM_UPDATE_ELEMENT_TEXT = WM_USER+114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_FOOTER,
footer);
}
/// <summary>
/// Updates the Main Instruction.
/// </summary>
/// <param name="mainInstruction">The new value.</param>
public void UpdateMainInstruction(string mainInstruction)
{
// TDE_MAIN_INSTRUCTION
// TDM_UPDATE_ELEMENT_TEXT = WM_USER+114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element Text (LPCWSTR)
VistaUnsafeNativeMethods.SendMessageWithString(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ELEMENT_TEXT,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ELEMENTS.TDE_MAIN_INSTRUCTION,
mainInstruction);
}
/// <summary>
/// Designate whether a given Task Dialog button or command link should have a User Account Control (UAC) shield icon.
/// </summary>
/// <param name="buttonId">ID of the push button or command link to be updated.</param>
/// <param name="elevationRequired">False to designate that the action invoked by the button does not require elevation;
/// true to designate that the action does require elevation.</param>
public void SetButtonElevationRequiredState(int buttonId, bool elevationRequired)
{
// TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = WM_USER+115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE,
(IntPtr)buttonId,
(IntPtr)(elevationRequired ? new IntPtr(1) : IntPtr.Zero));
}
/// <summary>
/// Updates the main instruction icon. Note the type (standard via enum or
/// custom via Icon type) must be used when upating the icon.
/// </summary>
/// <param name="icon">Task Dialog standard icon.</param>
public void UpdateMainIcon(VistaTaskDialogIcon icon)
{
// TDM_UPDATE_ICON = WM_USER+116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ICON,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ICON_ELEMENTS.TDIE_ICON_MAIN,
(IntPtr)icon);
}
/// <summary>
/// Updates the main instruction icon. Note the type (standard via enum or
/// custom via Icon type) must be used when upating the icon.
/// </summary>
/// <param name="icon">The icon to set.</param>
public void UpdateMainIcon(Icon icon)
{
// TDM_UPDATE_ICON = WM_USER+116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ICON,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ICON_ELEMENTS.TDIE_ICON_MAIN,
(icon == null ? IntPtr.Zero : icon.Handle));
}
/// <summary>
/// Updates the footer icon. Note the type (standard via enum or
/// custom via Icon type) must be used when upating the icon.
/// </summary>
/// <param name="icon">Task Dialog standard icon.</param>
public void UpdateFooterIcon(VistaTaskDialogIcon icon)
{
// TDM_UPDATE_ICON = WM_USER+116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ICON,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ICON_ELEMENTS.TDIE_ICON_FOOTER,
(IntPtr)icon);
}
/// <summary>
/// Updates the footer icon. Note the type (standard via enum or
/// custom via Icon type) must be used when upating the icon.
/// </summary>
/// <param name="icon">The icon to set.</param>
public void UpdateFooterIcon(Icon icon)
{
// TDM_UPDATE_ICON = WM_USER+116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
VistaUnsafeNativeMethods.SendMessage(
this.handle,
(uint)VistaUnsafeNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ICON,
(IntPtr)VistaUnsafeNativeMethods.TASKDIALOG_ICON_ELEMENTS.TDIE_ICON_FOOTER,
(icon == null ? IntPtr.Zero : icon.Handle));
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3074
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.VPS {
public partial class VdcImportServer {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// breadcrumb control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.Breadcrumb breadcrumb;
/// <summary>
/// menu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.Menu menu;
/// <summary>
/// imgIcon control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image imgIcon;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTitle;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// validatorsSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary validatorsSummary;
/// <summary>
/// locHyperVService control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locHyperVService;
/// <summary>
/// HyperVServices control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList HyperVServices;
/// <summary>
/// RequireHyperVService control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequireHyperVService;
/// <summary>
/// locVirtualMachine control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locVirtualMachine;
/// <summary>
/// VirtualMachines control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList VirtualMachines;
/// <summary>
/// RequiredVirtualMachine control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredVirtualMachine;
/// <summary>
/// secOsTemplate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secOsTemplate;
/// <summary>
/// OsTemplatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel OsTemplatePanel;
/// <summary>
/// locOsTemplate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locOsTemplate;
/// <summary>
/// OsTemplates control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList OsTemplates;
/// <summary>
/// RequiredOsTemplate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredOsTemplate;
/// <summary>
/// EnableRemoteDesktop control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox EnableRemoteDesktop;
/// <summary>
/// AdminPasswordPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow AdminPasswordPanel;
/// <summary>
/// locAdminPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locAdminPassword;
/// <summary>
/// adminPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox adminPassword;
/// <summary>
/// RequiredAdminPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredAdminPassword;
/// <summary>
/// VirtualMachinePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel VirtualMachinePanel;
/// <summary>
/// secConfiguration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secConfiguration;
/// <summary>
/// ConfigurationPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ConfigurationPanel;
/// <summary>
/// locCPU control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCPU;
/// <summary>
/// CpuCores control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal CpuCores;
/// <summary>
/// locRAM control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locRAM;
/// <summary>
/// RamSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal RamSize;
/// <summary>
/// locHDD control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locHDD;
/// <summary>
/// HddSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal HddSize;
/// <summary>
/// locVhdPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locVhdPath;
/// <summary>
/// VhdPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal VhdPath;
/// <summary>
/// secBios control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secBios;
/// <summary>
/// BiosPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel BiosPanel;
/// <summary>
/// BootFromCd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption BootFromCd;
/// <summary>
/// locBootFromCd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locBootFromCd;
/// <summary>
/// NumLockEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption NumLockEnabled;
/// <summary>
/// locNumLockEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNumLockEnabled;
/// <summary>
/// secDvd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secDvd;
/// <summary>
/// DvdPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel DvdPanel;
/// <summary>
/// DvdInstalled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption DvdInstalled;
/// <summary>
/// locDvdInstalled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDvdInstalled;
/// <summary>
/// secAllowedActions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secAllowedActions;
/// <summary>
/// AllowedActionsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AllowedActionsPanel;
/// <summary>
/// AllowStartShutdown control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox AllowStartShutdown;
/// <summary>
/// AllowReboot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox AllowReboot;
/// <summary>
/// AllowPause control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox AllowPause;
/// <summary>
/// AllowReset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox AllowReset;
/// <summary>
/// secExternalNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secExternalNetwork;
/// <summary>
/// ExternalNetworkPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ExternalNetworkPanel;
/// <summary>
/// locExternalAdapter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locExternalAdapter;
/// <summary>
/// ExternalAdapters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ExternalAdapters;
/// <summary>
/// ExternalAddressesRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ExternalAddressesRow;
/// <summary>
/// locExternalAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locExternalAddresses;
/// <summary>
/// ExternalAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ListBox ExternalAddresses;
/// <summary>
/// RequiredExternalAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredExternalAddresses;
/// <summary>
/// secManagementNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secManagementNetwork;
/// <summary>
/// ManagementNetworkPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ManagementNetworkPanel;
/// <summary>
/// locManagementAdapter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locManagementAdapter;
/// <summary>
/// ManagementAdapters control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ManagementAdapters;
/// <summary>
/// ManagementAddressesRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ManagementAddressesRow;
/// <summary>
/// locManagementAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locManagementAddresses;
/// <summary>
/// ManagementAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ListBox ManagementAddresses;
/// <summary>
/// RequiredManagementAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredManagementAddresses;
/// <summary>
/// btnImport control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnImport;
/// <summary>
/// btnCancel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancel;
/// <summary>
/// FormComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize FormComments;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using DocIdSet = Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
namespace Lucene.Net.Util
{
/// <summary>
/// An "open" BitSet implementation that allows direct access to the array of words
/// storing the bits.
/// <p/>
/// Unlike java.util.bitset, the fact that bits are packed into an array of longs
/// is part of the interface. This allows efficient implementation of other algorithms
/// by someone other than the author. It also allows one to efficiently implement
/// alternate serialization or interchange formats.
/// <p/>
/// <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations
/// and *much* faster at calculating cardinality of sets and results of set operations.
/// It can also handle sets of larger cardinality (up to 64 * 2**32-1)
/// <p/>
/// The goals of <code>OpenBitSet</code> are the fastest implementation possible, and
/// maximum code reuse. Extra safety and encapsulation
/// may always be built on top, but if that's built in, the cost can never be removed (and
/// hence people re-implement their own version in order to get better performance).
/// If you want a "safe", totally encapsulated (and slower and limited) BitSet
/// class, use <code>java.util.BitSet</code>.
/// <p/>
/// <h3>Performance Results</h3>
/// </summary>
[Serializable]
public class OpenBitSet : DocIdSet, System.ICloneable
{
protected long[] bits;
protected int wlen; // number of words (elements) used in the array
/** Constructs an OpenBitSet large enough to hold numBits.
*
* @param numBits
*/
public OpenBitSet(long numBits)
{
bits = new long[bits2words(numBits)];
wlen = bits.Length;
}
public OpenBitSet()
: this(64)
{
}
/** Constructs an OpenBitSet from an existing long[].
* <br/>
* The first 64 bits are in long[0],
* with bit index 0 at the least significant bit, and bit index 63 at the most significant.
* Given a bit index,
* the word containing it is long[index/64], and it is at bit number index%64 within that word.
* <p>
* numWords are the number of elements in the array that contain
* set bits (non-zero longs).
* numWords should be <= bits.length, and
* any existing words in the array at position >= numWords should be zero.
*
*/
public OpenBitSet(long[] bits, int numWords)
{
this.bits = bits;
this.wlen = numWords;
}
public override DocIdSetIterator Iterator()
{
return new OpenBitSetIterator(bits, wlen);
}
/** Returns the current capacity in bits (1 greater than the index of the last bit) */
public long Capacity() { return bits.Length << 6; }
/**
* Returns the current capacity of this set. Included for
* compatibility. This is *not* equal to {@link #cardinality}
*/
public long Size()
{
return Capacity();
}
/** Returns true if there are no set bits */
public bool IsEmpty() { return Cardinality() == 0; }
/** Expert: returns the long[] storing the bits */
public long[] GetBits() { return bits; }
/** Expert: sets a new long[] to use as the bit storage */
public void SetBits(long[] bits) { this.bits = bits; }
/** Expert: gets the number of longs in the array that are in use */
public int GetNumWords() { return wlen; }
/** Expert: sets the number of longs in the array that are in use */
public void SetNumWords(int nWords) { this.wlen = nWords; }
/** Returns true or false for the specified bit index. */
public bool Get(int index)
{
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
if (i >= bits.Length) return false;
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size
*/
public bool FastGet(int index)
{
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index
*/
public bool Get(long index)
{
int i = (int)(index >> 6); // div 64
if (i >= bits.Length) return false;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size.
*/
public bool FastGet(long index)
{
int i = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/*
// alternate implementation of get()
public bool get1(int index) {
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((bits[i]>>>bit) & 0x01) != 0;
// this does a long shift and a bittest (on x86) vs
// a long shift, and a long AND, (the test for zero is prob a no-op)
// testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0;
}
*/
/** returns 1 if the bit is set, 0 if not.
* The index should be less than the OpenBitSet size
*/
public int GetBit(int index)
{
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//return ((int)(bits[i]>>>bit)) & 0x01;
return ((int)((ulong)(bits[i]) >> bit)) & 0x01;
}
/*
public bool get2(int index) {
int word = index >> 6; // div 64
int bit = index & 0x0000003f; // mod 64
return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed
// we could right shift and check for parity bit, if it was available to us.
}
*/
/** sets a bit, expanding the set size if necessary */
public void Set(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void FastSet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void FastSet(long index)
{
int wordNum = (int)(index >> 6);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to set
*/
public void Set(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
long startmask = -1L << (int)startIndex;
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
//Arrays.fill(bits, startWord+1, endWord, -1L);
for (int i = startWord + 1; i < endWord; i++)
bits[i] = -1L;
bits[endWord] |= endmask;
}
protected int ExpandingWordNum(long index)
{
int wordNum = (int)(index >> 6);
if (wordNum >= wlen)
{
EnsureCapacity(index + 1);
wlen = wordNum + 1;
}
return wordNum;
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void FastClear(int index)
{
int wordNum = index >> 6;
int bit = index & 0x03f;
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
// hmmm, it takes one more instruction to clear than it does to set... any
// way to work around this? If there were only 63 bits per word, we could
// use a right shift of 10111111...111 in binary to position the 0 in the
// correct place (using sign extension).
// Could also use Long.rotateRight() or rotateLeft() *if* they were converted
// by the JVM into a native instruction.
// bits[word] &= Long.rotateLeft(0xfffffffe,bit);
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void FastClear(long index)
{
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** clears a bit, allowing access beyond the current set size without changing the size.*/
public void Clear(long index)
{
int wordNum = (int)(index >> 6); // div 64
if (wordNum >= wlen) return;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** Clears a range of bits. Clearing past the end does not change the size of the set.
*
* @param startIndex lower index
* @param endIndex one-past the last bit to clear
*/
public void Clear(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex >> 6);
if (startWord >= wlen) return;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = (int)((endIndex - 1) >> 6);
long startmask = -1L << (int)startIndex;
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord)
{
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.Min(wlen, endWord);
//Arrays.fill(bits, startWord+1, middle, 0L);
for (int i = startWord + 1; i < middle; i++)
bits[i] = 0L;
if (endWord < wlen)
{
bits[endWord] &= endmask;
}
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public bool GetAndSet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public bool GetAndSet(long index)
{
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void FastFlip(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void FastFlip(long index)
{
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit, expanding the set size if necessary */
public void Flip(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public bool FlipAndGet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public bool FlipAndGet(long index)
{
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** Flips a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to flip
*/
public void Flip(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int oldlen = wlen;
int startWord = (int)(startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
/*** Grrr, java shifting wraps around so -1L>>>64 == -1
* for that reason, make sure not to use endmask if the bits to flip will
* be zero in the last word (redefine endWord to be the last changed...)
long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
***/
long startmask = -1L << (int)startIndex;
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/*
public static int pop(long v0, long v1, long v2, long v3) {
// derived from pop_array by setting last four elems to 0.
// exchanges one pop() call for 10 elementary operations
// saving about 7 instructions... is there a better way?
long twosA=v0 & v1;
long ones=v0^v1;
long u2=ones^v2;
long twosB =(ones&v2)|(u2&v3);
ones=u2^v3;
long fours=(twosA&twosB);
long twos=twosA^twosB;
return (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones);
}
*/
/** @return the number of set bits */
public long Cardinality()
{
return BitUtil.pop_array(bits, 0, wlen);
}
/** Returns the popcount or cardinality of the intersection of the two sets.
* Neither set is modified.
*/
public static long IntersectionCount(OpenBitSet a, OpenBitSet b)
{
return BitUtil.pop_intersect(a.bits, b.bits, 0, Math.Min(a.wlen, b.wlen));
}
/** Returns the popcount or cardinality of the union of the two sets.
* Neither set is modified.
*/
public static long UnionCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.pop_union(a.bits, b.bits, 0, Math.Min(a.wlen, b.wlen));
if (a.wlen < b.wlen)
{
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen - a.wlen);
}
else if (a.wlen > b.wlen)
{
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of "a and not b"
* or "intersection(a, not(b))".
* Neither set is modified.
*/
public static long AndNotCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.Min(a.wlen, b.wlen));
if (a.wlen > b.wlen)
{
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of the exclusive-or of the two sets.
* Neither set is modified.
*/
public static long XorCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.Min(a.wlen, b.wlen));
if (a.wlen < b.wlen)
{
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen - a.wlen);
}
else if (a.wlen > b.wlen)
{
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public int NextSetBit(int index)
{
int i = index >> 6;
if (i >= wlen) return -1;
int subIndex = index & 0x3f; // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word != 0)
{
return (i << 6) + subIndex + BitUtil.ntz(word);
}
while (++i < wlen)
{
word = bits[i];
if (word != 0) return (i << 6) + BitUtil.ntz(word);
}
return -1;
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public long NextSetBit(long index)
{
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//int i = (int)(index>>>6);
//if (i>=wlen) return -1;
//int subIndex = (int)index & 0x3f; // index within the word
//long word = bits[i] >>> subIndex; // skip all the bits to the right of index
int i = (int)((ulong)index >> 6);
if (i >= wlen) return -1;
int subIndex = (int)index & 0x3f; // index within the word
long word = (long)((ulong)(bits[i]) >> subIndex); // skip all the bits to the right of index
if (word != 0)
{
return (((long)i) << 6) + (subIndex + BitUtil.ntz(word));
}
while (++i < wlen)
{
word = bits[i];
if (word != 0) return (((long)i) << 6) + BitUtil.ntz(word);
}
return -1;
}
public virtual object Clone()
{
//try
//{
// OpenBitSet obs = (OpenBitSet)super.clone();
// obs.bits = (long[])obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy
// return obs;
//}
//catch (CloneNotSupportedException e)
//{
// throw new RuntimeException(e);
//}
return new OpenBitSet((long[])bits.Clone(), wlen);
}
/** this = this AND other */
public void Intersect(OpenBitSet other)
{
int newLen = Math.Min(this.wlen, other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
// testing against zero can be more efficient
int pos = newLen;
while (--pos >= 0)
{
thisArr[pos] &= otherArr[pos];
}
if (this.wlen > newLen)
{
// fill zeros from the new shorter length to the old length
//Arrays.fill(bits, newLen, this.wlen, 0);
for (int i = newLen; i < this.wlen; i++)
bits[i] = 0L;
}
this.wlen = newLen;
}
/** this = this OR other */
public void Union(OpenBitSet other)
{
int newLen = Math.Max(wlen, other.wlen);
EnsureCapacityWords(newLen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.Min(wlen, other.wlen);
while (--pos >= 0)
{
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen)
{
//System.Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
}
/** Remove all elements set in other. this = this AND_NOT other */
public void Remove(OpenBitSet other)
{
int idx = Math.Min(wlen, other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--idx >= 0)
{
thisArr[idx] &= ~otherArr[idx];
}
}
/** this = this XOR other */
public void Xor(OpenBitSet other)
{
int newLen = Math.Max(wlen, other.wlen);
EnsureCapacityWords(newLen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.Min(wlen, other.wlen);
while (--pos >= 0)
{
thisArr[pos] ^= otherArr[pos];
}
if (this.wlen < newLen)
{
//System.Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
}
// some BitSet compatability methods
//** see {@link intersect} */
public void And(OpenBitSet other)
{
Intersect(other);
}
//** see {@link union} */
public void Or(OpenBitSet other)
{
Union(other);
}
//** see {@link andNot} */
public void AndNot(OpenBitSet other)
{
Remove(other);
}
/** returns true if the sets have any elements in common */
public bool Intersects(OpenBitSet other)
{
int pos = Math.Min(this.wlen, other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--pos >= 0)
{
if ((thisArr[pos] & otherArr[pos]) != 0) return true;
}
return false;
}
/** Expand the long[] with the size given as a number of words (64 bit longs).
* getNumWords() is unchanged by this call.
*/
public void EnsureCapacityWords(int numWords)
{
if (bits.Length < numWords)
{
long[] newBits = new long[numWords];
//System.Array.Copy(bits, 0, newBits, 0, wlen);
Array.Copy(bits, 0, newBits, 0, wlen);
bits = newBits;
}
}
/** Ensure that the long[] is big enough to hold numBits, expanding it if necessary.
* getNumWords() is unchanged by this call.
*/
public void EnsureCapacity(long numBits)
{
EnsureCapacityWords(bits2words(numBits));
}
/** Lowers numWords, the number of words in use,
* by checking for trailing zero words.
*/
public void trimTrailingZeros()
{
int idx = wlen - 1;
while (idx >= 0 && bits[idx] == 0) idx--;
wlen = idx + 1;
}
/** returns the number of 64 bit words it would take to hold numBits */
public static int bits2words(long numBits)
{
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
//return (int)(((numBits-1)>>>6)+1);
return (int)(((ulong)(numBits - 1) >> 6) + 1);
}
/** returns true if both sets have the same bits set */
public override bool Equals(object o)
{
if (this == o) return true;
if (!(o is OpenBitSet)) return false;
OpenBitSet a;
OpenBitSet b = (OpenBitSet)o;
// make a the larger set.
if (b.wlen > this.wlen)
{
a = b; b = this;
}
else
{
a = this;
}
// check for any set bits out of the range of b
for (int i = a.wlen - 1; i >= b.wlen; i--)
{
if (a.bits[i] != 0) return false;
}
for (int i = b.wlen - 1; i >= 0; i--)
{
if (a.bits[i] != b.bits[i]) return false;
}
return true;
}
public override int GetHashCode()
{
//{DOUG-2.4.0: mod'd to do logical right shift (>>>); have to use unsigned types and >>
// long h = 0x98761234; // something non-zero for length==0
// for (int i = bits.length; --i>=0;) {
// h ^= bits[i];
// h = (h << 1) | (h >>> 63); // rotate left
//return (int)((h>>32) ^ h); // fold leftmost bits into right
long h = 0x98761234; // something non-zero for length==0
for (int i = bits.Length; --i >= 0; )
{
h ^= bits[i];
h = (h << 1) | (long)((ulong)h >> 63); // rotate left
}
return (int)((h >> 32) ^ h); // fold leftmost bits into right
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Linq;
namespace UnityCloudData
{
public static class CloudDataTypeSerialization
{
static Dictionary<Type, Func<object, string>> k_SerializationMap = new Dictionary<Type, Func<object, string>>
{
{typeof(object), val => val.SerializeForCloudData()},
{typeof(int), val => val.SerializeForCloudData()},
{typeof(long), val => val.SerializeForCloudData()},
{typeof(float), val => val.SerializeForCloudData()},
{typeof(double), val => val.SerializeForCloudData()},
{typeof(bool), val => ((bool)val).SerializeForCloudData()},
{typeof(string), val => ((string)val).SerializeForCloudData()},
{typeof(List<string>), val => ((List<string>)val).SerializeForCloudData()},
{typeof(Vector2), val => ((Vector2)val).SerializeForCloudData()},
{typeof(Vector3), val => ((Vector3)val).SerializeForCloudData()},
{typeof(Vector4), val => ((Vector4)val).SerializeForCloudData()},
{typeof(Color), val => ((Color)val).SerializeForCloudData()}
};
delegate bool DeserializeDelegate(Dictionary<string, object> dict, out object outObj);
static Dictionary<string, DeserializeDelegate> k_DeserializationMap = new Dictionary<string, DeserializeDelegate>
{
{typeof(Color).FullName, TryParseColor},
{typeof(Vector2).FullName, TryParseVector2},
{typeof(Vector3).FullName, TryParseVector3},
{typeof(Vector4).FullName, TryParseVector4}
};
public static string SerializeValue(object val, System.Type valType)
{
string formattedValue = "";
try
{
formattedValue = k_SerializationMap[valType](val);
}
catch (Exception ex)
{
Debug.Log("[Unity Cloud Data] serialization error for"+valType+": "+ex.Message);
formattedValue = val.ToString();
}
return formattedValue;
}
private static string SerializeForCloudData(this object val)
{
return val.ToString();
}
private static string SerializeForCloudData(this bool val)
{
return (bool)val ? "true" : "false";
}
private static string SerializeForCloudData(this string val)
{
return "\"" + val + "\"";
}
private static string SerializeForCloudData(this List<string> val)
{
return MiniJSON.Json.Serialize(val);
}
private static string SerializeForCloudData(this Vector2 val)
{
return "{"+
"\"x\": "+ val.x.ToString() +","+
"\"y\": "+ val.y.ToString() +","+
"\"_type\": \""+typeof(Vector2)+"\""+
"}";
}
private static string SerializeForCloudData(this Vector3 val)
{
return "{"+
"\"x\": "+ val.x.ToString() +","+
"\"y\": "+ val.y.ToString() +","+
"\"z\": "+ val.z.ToString() +","+
"\"_type\": \""+typeof(Vector3)+"\""+
"}";
}
private static string SerializeForCloudData(this Vector4 val)
{
return "{"+
"\"x\": "+ val.x.ToString() +","+
"\"y\": "+ val.y.ToString() +","+
"\"z\": "+ val.z.ToString() +","+
"\"w\": "+ val.w.ToString() +","+
"\"_type\": \""+typeof(Vector4)+"\""+
"}";
}
private static string SerializeForCloudData(this Color val)
{
return "{"+
"\"a\": "+ val.a.ToString() +","+
"\"b\": "+ val.b.ToString() +","+
"\"g\": "+ val.g.ToString() +","+
"\"r\": "+ val.r.ToString() +","+
"\"_type\": \""+typeof(Color)+"\""+
"}";
}
public static void DeserializeValue(object owningObject, FieldInfo info, object newval)
{
// check for numeric field type (will require some conversion)
var fieldType = info.FieldType;
var fieldIsNumericType = (fieldType == typeof(int) || fieldType == typeof(long) || fieldType == typeof(float) || fieldType == typeof(double));
if(fieldIsNumericType)
{
newval = ConvertNumericValue(newval, fieldType);
}
// check assignability
var newValType = (newval != null) ? newval.GetType() : null;
if(fieldType.IsAssignableFrom(newValType))
{
info.SetValue(owningObject, newval);
}
else if(newValType == typeof(List<object>))
{
// TODO: support lists of other primitives
List<object> newlist = newval as List<object>;
List<string> list = newlist.Select(i => i.ToString()).ToList();
info.SetValue(owningObject, list);
}
else if(newValType == typeof(Dictionary<string,object>))
{
Dictionary<string,object> dict = newval as Dictionary<string,object>;
string _type = (string)dict["_type"];
if(k_DeserializationMap.ContainsKey(_type))
{
var parseCustomValue = k_DeserializationMap[_type];
object parsedVal;
if (parseCustomValue(dict, out parsedVal))
{
info.SetValue(owningObject, parsedVal);
}
else
{
Debug.LogWarning(string.Format("[CloudDataTypeSerialization] Unable to assign value type '{0}' to {1}.{2}", _type, owningObject.GetType().FullName, info.Name));
}
}
else
{
Debug.LogError(string.Format("[CloudDataTypeSerialization] No deserialization method defined for type '{0}' - {1}.{2}", _type, owningObject.GetType().FullName, info.Name));
}
}
else
{
string valStr = newval == null ? "<NULL>" : newval.ToString();
Debug.LogWarning(string.Format("[CloudDataTypeSerialization] Unable to assign value '{0}' of type '{1}' to {2}.{3} of type '{4}'", valStr, newValType, owningObject.GetType().FullName, info.Name, fieldType));
}
}
private static object ConvertNumericValue(object newval, Type fieldType)
{
try
{
var fieldTypeCode = Type.GetTypeCode(fieldType);
switch(fieldTypeCode)
{
case TypeCode.Int32:
return Convert.ToInt32(newval);
case TypeCode.Int64:
return Convert.ToInt64(newval);
case TypeCode.Single:
return Convert.ToSingle(newval);
case TypeCode.Double:
return Convert.ToDouble(newval);
default:
return newval;
}
}
catch(Exception ex)
{
string valStr = newval == null ? "<NULL>" : newval.ToString();
Debug.LogWarning(string.Format("[CloudDataTypeSerialization] Failed trying to convert '{0}' to numeric value. {1}", valStr, ex.ToString()));
return newval;
}
}
private static bool TryParseColor(Dictionary<string, object> dict, out object outObj)
{
outObj = null;
if( !dict.ContainsKey("r") ||
!dict.ContainsKey("g") ||
!dict.ContainsKey("b") ||
!dict.ContainsKey("a") )
{
return false;
}
Color color = new Color();
color.r = Convert.ToSingle(dict["r"]);
color.g = Convert.ToSingle(dict["g"]);
color.b = Convert.ToSingle(dict["b"]);
color.a = Convert.ToSingle(dict["a"]);
outObj = color;
return true;
}
private static bool TryParseVector2(Dictionary<string, object> dict, out object outObj)
{
outObj = null;
if( !dict.ContainsKey("x") ||
!dict.ContainsKey("y") )
{
return false;
}
Vector2 vec = new Vector2();
vec.x = Convert.ToSingle(dict["x"]);
vec.y = Convert.ToSingle(dict["y"]);
outObj = vec;
return true;
}
private static bool TryParseVector3(Dictionary<string, object> dict, out object outObj)
{
outObj = null;
if( !dict.ContainsKey("x") ||
!dict.ContainsKey("y") ||
!dict.ContainsKey("z") )
{
return false;
}
Vector3 vec = new Vector3();
vec.x = Convert.ToSingle(dict["x"]);
vec.y = Convert.ToSingle(dict["y"]);
vec.z = Convert.ToSingle(dict["z"]);
outObj = vec;
return true;
}
private static bool TryParseVector4(Dictionary<string, object> dict, out object outObj)
{
outObj = null;
if( !dict.ContainsKey("x") ||
!dict.ContainsKey("y") ||
!dict.ContainsKey("z") ||
!dict.ContainsKey("w") )
{
return false;
}
Vector4 vec = new Vector4();
vec.x = Convert.ToSingle(dict["x"]);
vec.y = Convert.ToSingle(dict["y"]);
vec.z = Convert.ToSingle(dict["z"]);
vec.w = Convert.ToSingle(dict["w"]);
outObj = vec;
return true;
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
/// Tests grid exceptions propagation.
/// </summary>
public class ExceptionsTest
{
/** */
private const string ExceptionTask = "org.apache.ignite.platform.PlatformExceptionTask";
/// <summary>
/// Before test.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.KillProcesses();
}
/// <summary>
/// After test.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
var grid = StartGrid();
Assert.Throws<ArgumentException>(() => grid.GetCache<object, object>("invalidCacheName"));
var e = Assert.Throws<ClusterGroupEmptyException>(() => grid.GetCluster().ForRemotes().GetMetrics());
Assert.IsNotNull(e.InnerException);
Assert.IsTrue(e.InnerException.Message.StartsWith(
"class org.apache.ignite.cluster.ClusterGroupEmptyException: Cluster group is empty."));
// Check all exceptions mapping.
var comp = grid.GetCompute();
CheckException<BinaryObjectException>(comp, "BinaryObjectException");
CheckException<IgniteException>(comp, "IgniteException");
CheckException<BinaryObjectException>(comp, "BinaryObjectException");
CheckException<ClusterTopologyException>(comp, "ClusterTopologyException");
CheckException<ComputeExecutionRejectedException>(comp, "ComputeExecutionRejectedException");
CheckException<ComputeJobFailoverException>(comp, "ComputeJobFailoverException");
CheckException<ComputeTaskCancelledException>(comp, "ComputeTaskCancelledException");
CheckException<ComputeTaskTimeoutException>(comp, "ComputeTaskTimeoutException");
CheckException<ComputeUserUndeclaredException>(comp, "ComputeUserUndeclaredException");
CheckException<TransactionOptimisticException>(comp, "TransactionOptimisticException");
CheckException<TransactionTimeoutException>(comp, "TransactionTimeoutException");
CheckException<TransactionRollbackException>(comp, "TransactionRollbackException");
CheckException<TransactionHeuristicException>(comp, "TransactionHeuristicException");
CheckException<TransactionDeadlockException>(comp, "TransactionDeadlockException");
CheckException<IgniteFutureCancelledException>(comp, "IgniteFutureCancelledException");
// Check stopped grid.
grid.Dispose();
Assert.Throws<InvalidOperationException>(() => grid.GetCache<object, object>("cache1"));
}
/// <summary>
/// Checks the exception.
/// </summary>
private static void CheckException<T>(ICompute comp, string name) where T : Exception
{
var ex = Assert.Throws<T>(() => comp.ExecuteJavaTask<string>(ExceptionTask, name));
var javaEx = ex.InnerException as JavaException;
Assert.IsNotNull(javaEx);
Assert.IsTrue(javaEx.Message.Contains("at " + ExceptionTask));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateException()
{
// Primitive type
TestPartialUpdateException(false, (x, g) => x);
// User type
TestPartialUpdateException(false, (x, g) => new BinarizableEntry(x));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation in binary mode.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionBinarizable()
{
// User type
TestPartialUpdateException(false, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x)));
}
/// <summary>
/// Tests CachePartialUpdateException serialization.
/// </summary>
[Test]
public void TestPartialUpdateExceptionSerialization()
{
// Inner exception
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg",
new IgniteException("Inner msg")));
// Primitive keys
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] {1, 2, 3}));
// User type keys
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg",
new object[]
{
new SerializableEntry(1),
new SerializableEntry(2),
new SerializableEntry(3)
}));
}
/// <summary>
/// Tests that all exceptions have mandatory constructors and are serializable.
/// </summary>
[Test]
public void TestAllExceptionsConstructors()
{
var types = typeof(IIgnite).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Exception)));
foreach (var type in types)
{
Assert.IsTrue(type.IsSerializable, "Exception is not serializable: " + type);
// Default ctor.
var defCtor = type.GetConstructor(new Type[0]);
Assert.IsNotNull(defCtor);
var ex = (Exception) defCtor.Invoke(new object[0]);
Assert.AreEqual(string.Format("Exception of type '{0}' was thrown.", type.FullName), ex.Message);
// Message ctor.
var msgCtor = type.GetConstructor(new[] {typeof(string)});
Assert.IsNotNull(msgCtor);
ex = (Exception) msgCtor.Invoke(new object[] {"myMessage"});
Assert.AreEqual("myMessage", ex.Message);
// Serialization.
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, ex);
stream.Seek(0, SeekOrigin.Begin);
ex = (Exception) formatter.Deserialize(stream);
Assert.AreEqual("myMessage", ex.Message);
// Message+cause ctor.
var msgCauseCtor = type.GetConstructor(new[] { typeof(string), typeof(Exception) });
Assert.IsNotNull(msgCauseCtor);
ex = (Exception) msgCauseCtor.Invoke(new object[] {"myMessage", new Exception("innerEx")});
Assert.AreEqual("myMessage", ex.Message);
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("innerEx", ex.InnerException.Message);
}
}
/// <summary>
/// Tests CachePartialUpdateException serialization.
/// </summary>
private static void TestPartialUpdateExceptionSerialization(Exception ex)
{
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, ex);
stream.Seek(0, SeekOrigin.Begin);
var ex0 = (Exception) formatter.Deserialize(stream);
var updateEx = ((CachePartialUpdateException) ex);
try
{
Assert.AreEqual(updateEx.GetFailedKeys<object>(),
((CachePartialUpdateException) ex0).GetFailedKeys<object>());
}
catch (Exception e)
{
if (typeof(IgniteException) != e.GetType())
throw;
}
while (ex != null && ex0 != null)
{
Assert.AreEqual(ex0.GetType(), ex.GetType());
Assert.AreEqual(ex.Message, ex0.Message);
ex = ex.InnerException;
ex0 = ex0.InnerException;
}
Assert.AreEqual(ex, ex0);
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionAsync()
{
// Primitive type
TestPartialUpdateException(true, (x, g) => x);
// User type
TestPartialUpdateException(true, (x, g) => new BinarizableEntry(x));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation in binary mode.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionAsyncBinarizable()
{
TestPartialUpdateException(true, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x)));
}
/// <summary>
/// Tests that invalid spring URL results in a meaningful exception.
/// </summary>
[Test]
public void TestInvalidSpringUrl()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = "z:\\invalid.xml"
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
Assert.IsTrue(ex.ToString().Contains("Spring XML configuration path is invalid: z:\\invalid.xml"));
}
/// <summary>
/// Tests that invalid configuration parameter results in a meaningful exception.
/// </summary>
[Test]
public void TestInvalidConfig()
{
var disco = TestUtils.GetStaticDiscovery();
disco.SocketTimeout = TimeSpan.FromSeconds(-1); // set invalid timeout
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi = disco
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
Assert.IsTrue(ex.ToString().Contains("SPI parameter failed condition check: sockTimeout > 0"));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
private static void TestPartialUpdateException<TK>(bool async, Func<int, IIgnite, TK> keyFunc)
{
using (var grid = StartGrid())
{
var cache = grid.GetCache<TK, int>("partitioned_atomic").WithNoRetries();
if (typeof (TK) == typeof (IBinaryObject))
cache = cache.WithKeepBinary<TK, int>();
// Do cache puts in parallel
var putTask = Task.Factory.StartNew(() =>
{
try
{
// Do a lot of puts so that one fails during Ignite stop
for (var i = 0; i < 1000000; i++)
{
// ReSharper disable once AccessToDisposedClosure
// ReSharper disable once AccessToModifiedClosure
var dict = Enumerable.Range(1, 100).ToDictionary(k => keyFunc(k, grid), k => i);
if (async)
cache.PutAllAsync(dict).Wait();
else
cache.PutAll(dict);
}
}
catch (AggregateException ex)
{
CheckPartialUpdateException<TK>((CachePartialUpdateException) ex.InnerException);
return;
}
catch (CachePartialUpdateException ex)
{
CheckPartialUpdateException<TK>(ex);
return;
}
Assert.Fail("CachePartialUpdateException has not been thrown.");
});
while (true)
{
Thread.Sleep(1000);
Ignition.Stop("grid_2", true);
StartGrid("grid_2");
Thread.Sleep(1000);
if (putTask.Exception != null)
throw putTask.Exception;
if (putTask.IsCompleted)
return;
}
}
}
/// <summary>
/// Checks the partial update exception.
/// </summary>
private static void CheckPartialUpdateException<TK>(CachePartialUpdateException ex)
{
var failedKeys = ex.GetFailedKeys<TK>();
Assert.IsTrue(failedKeys.Any());
var failedKeysObj = ex.GetFailedKeys<object>();
Assert.IsTrue(failedKeysObj.Any());
}
/// <summary>
/// Starts the grid.
/// </summary>
private static IIgnite StartGrid(string gridName = null)
{
return Ignition.Start(new IgniteConfiguration
{
SpringConfigUrl = "config\\native-client-test-cache.xml",
JvmOptions = TestUtils.TestJavaOptions(),
JvmClasspath = TestUtils.CreateTestClasspath(),
GridName = gridName,
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration(typeof (BinarizableEntry))
}
}
});
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
/** Value. */
private readonly int _val;
/** <inheritDot /> */
public override int GetHashCode()
{
return _val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
_val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj is BinarizableEntry && ((BinarizableEntry)obj)._val == _val;
}
}
/// <summary>
/// Serializable entry.
/// </summary>
[Serializable]
private class SerializableEntry
{
/** Value. */
private readonly int _val;
/** <inheritDot /> */
public override int GetHashCode()
{
return _val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public SerializableEntry(int val)
{
_val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj is SerializableEntry && ((SerializableEntry)obj)._val == _val;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using DevExpress.XtraReports.UI;
using EIDSS.FlexibleForms.DataBase;
using EIDSS.FlexibleForms.Helpers;
using EIDSS.FlexibleForms.Helpers.ReportHelper.DataItems;
using EIDSS.FlexibleForms.Helpers.ReportHelper.Tree;
using EIDSS.Reports.BaseControls.Form;
using EIDSS.Reports.Flexible;
using EIDSS.Tests.Core;
using NUnit.Framework;
namespace EIDSS.Tests.Reports
{
[TestFixture]
public class TreeTests : BaseFormTest
{
[Test]
public void RootTest()
{
FlexNode rootNode = FlexNode.CreateRoot();
Assert.IsTrue(rootNode.IsRoot);
Assert.IsNull(rootNode.ParentNode);
Assert.AreEqual(0, rootNode.Count);
}
[Test]
public void ChildenTest()
{
FlexNode rootNode = FlexNode.CreateRoot();
FlexibleFormsDS.LabelsDataTable labelsDataTable = GetLabelsDataTable();
FlexibleFormsDS.LinesDataTable linesDataTable = GetLinesDataTable();
rootNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[0]);
Assert.AreEqual(1, rootNode.Count);
FlexNode firstNode = rootNode[0];
Assert.IsFalse(firstNode.IsRoot);
Assert.AreEqual(rootNode, firstNode.ParentNode);
Assert.IsTrue(firstNode.DataItem is FlexLabelItem);
Assert.AreEqual("section", ((FlexLabelItem) firstNode.DataItem).Text);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[1]);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[2]);
firstNode.Add((FlexibleFormsDS.LinesRow) linesDataTable.Rows[0]);
firstNode.Add((FlexibleFormsDS.LinesRow) linesDataTable.Rows[1]);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[3]);
Assert.AreEqual(5, firstNode.Count);
Assert.IsTrue(firstNode[0].DataItem is FlexLabelItem);
Assert.AreEqual("national1", ((FlexLabelItem) firstNode[0].DataItem).Text);
Assert.IsTrue(firstNode[1].DataItem is FlexLabelItem);
Assert.AreEqual("national2", ((FlexLabelItem) firstNode[1].DataItem).Text);
Assert.IsTrue(firstNode[2].DataItem is FlexLineItem);
Assert.IsTrue(firstNode[3].DataItem is FlexLineItem);
FlexNode secondNode = firstNode[4];
Assert.IsTrue(secondNode.DataItem is FlexLabelItem);
secondNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[4]);
secondNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[5]);
Assert.AreEqual(firstNode, firstNode[0].ParentNode);
Assert.IsFalse(firstNode[0].IsRoot);
Assert.AreEqual(firstNode, firstNode[1].ParentNode);
Assert.IsFalse(firstNode[1].IsRoot);
Assert.AreEqual(firstNode, firstNode[2].ParentNode);
Assert.IsFalse(firstNode[2].IsRoot);
Assert.AreEqual(firstNode, firstNode[3].ParentNode);
Assert.IsFalse(firstNode[3].IsRoot);
Assert.AreEqual(firstNode, secondNode.ParentNode);
Assert.IsFalse(secondNode.IsRoot);
Assert.AreEqual(2, secondNode.Count);
Assert.IsTrue(secondNode[0].DataItem is FlexLabelItem);
Assert.AreEqual("param name", ((FlexLabelItem) secondNode[0].DataItem).Text);
Assert.IsTrue(secondNode[1].DataItem is FlexLabelItem);
Assert.AreEqual("param value", ((FlexLabelItem) secondNode[1].DataItem).Text);
}
[Test]
public void ListReportVisitorTest()
{
FlexReport rootReport = FlexFactory.CreateFlexReport(CreateListTree(), "", null);
Assert.AreEqual(1, rootReport.DetailBand.Controls.Count);
Assert.IsTrue(rootReport.DetailBand.Controls[0] is XRSubreport);
XRSubreport firstSubreport = ((XRSubreport) rootReport.DetailBand.Controls[0]);
Assert.IsTrue(firstSubreport.ReportSource is FlexReport);
FlexReport firstReport = (FlexReport) firstSubreport.ReportSource;
Assert.AreEqual(5, firstReport.DetailBand.Controls.Count);
Assert.IsTrue(firstReport.DetailBand.Controls[0] is XRLabel);
Assert.IsTrue(firstReport.DetailBand.Controls[1] is XRLabel);
Assert.IsTrue(firstReport.DetailBand.Controls[2] is XRShape);
Assert.IsTrue(firstReport.DetailBand.Controls[3] is XRShape);
Assert.IsTrue(firstReport.DetailBand.Controls[4] is XRSubreport);
Assert.AreEqual("national1", firstReport.DetailBand.Controls[0].Text);
Assert.AreEqual("national2", firstReport.DetailBand.Controls[1].Text);
XRSubreport secondSubreport = ((XRSubreport) firstReport.DetailBand.Controls[4]);
Assert.IsTrue(secondSubreport.ReportSource is FlexReport);
FlexReport secondReport = (FlexReport) secondSubreport.ReportSource;
Assert.AreEqual(2, secondReport.DetailBand.Controls.Count);
Assert.IsTrue(secondReport.DetailBand.Controls[0] is XRLabel);
Assert.IsTrue(secondReport.DetailBand.Controls[1] is XRLabel);
}
[Test]
public void TableReportVisitorTest()
{
FlexReport rootReport = FlexFactory.CreateFlexReport(CreateTableTree(), "", null);
Assert.AreEqual(1, rootReport.DetailBand.Controls.Count);
//Assert.AreEqual(2, rootReport.HeaderBand.Controls.Count);
Assert.IsTrue(rootReport.DetailBand.Controls[0] is XRSubreport);
XRSubreport firstSubreport = ((XRSubreport) rootReport.DetailBand.Controls[0]);
Assert.IsTrue(firstSubreport.ReportSource is FlexReport);
FlexReport firstReport = (FlexReport) firstSubreport.ReportSource;
Assert.AreEqual(2, firstReport.HeaderBand.Controls.Count);
Assert.IsTrue(firstReport.HeaderBand.Controls[0] is XRLabel);
Assert.IsTrue(firstReport.HeaderBand.Controls[1] is FlexTable);
Assert.AreEqual("", firstReport.HeaderBand.Controls[0].Text);
FlexTable firstTable = (FlexTable) firstReport.HeaderBand.Controls[1];
Assert.AreEqual("national table", firstTable.HeaderCell.Text);
Assert.AreEqual(2, firstTable.InnerRow.Cells.Count);
Assert.AreEqual(1, firstTable.InnerRow.Cells[0].Controls.Count);
Assert.AreEqual(0, firstTable.InnerRow.Cells[1].Controls.Count);
Assert.IsTrue(firstTable.InnerRow.Cells[0].Controls[0] is FlexTable);
FlexTable leftTable = (FlexTable) firstTable.InnerRow.Cells[0].Controls[0];
Assert.AreEqual("left cell", leftTable.HeaderCell.Text);
Assert.AreEqual("right cell", firstTable.InnerRow.Cells[1].Text);
Assert.AreEqual(2, leftTable.InnerRow.Cells.Count);
Assert.AreEqual(0, leftTable.InnerRow.Cells[0].Controls.Count);
Assert.AreEqual(0, leftTable.InnerRow.Cells[1].Controls.Count);
Assert.AreEqual("child left cell", leftTable.InnerRow.Cells[0].Text);
Assert.AreEqual("child right cell", leftTable.InnerRow.Cells[1].Text);
}
[Test]
[Ignore("Manual test")]
public void ReportListTest()
{
ShowReport(delegate { return FlexFactory.CreateFlexReport(CreateListTree(), "", null); });
}
[Test]
[Ignore("Manual test")]
public void ReportTableTest()
{
ShowReport(delegate { return FlexFactory.CreateFlexReport(CreateTableTree(), "", null); });
}
[Test]
[Ignore("Manual test")]
public void ReportViewTableTest()
{
IReportForm reportForm = new ReportForm();
TestKeeper keeper = new TestKeeper();
keeper.GenerateReportInjection = delegate() { return GenerateTableReport(); };
reportForm.ShowReport(keeper);
keeper.ReloadReport(true);
}
[Test]
[Ignore("Manual test")]
public void ReportViewDynamicParametersTest()
{
IReportForm reportForm = new ReportForm();
TestKeeper keeper = new TestKeeper();
keeper.GenerateReportInjection = delegate()
{
TemplateHelper templateHelper = new TemplateHelper();
List<long> observations = new List<long>();
const long observation = 776990000000;
observations.Add(observation);
templateHelper.LoadTemplate(observations, 500000000, FFType.HumanClinicalSigns);
FlexNode node = templateHelper.GetFlexNodeFromTemplate(observation);
FlexReport report = FlexFactory.CreateFlexReport(node, "", 600);
report.Landscape = true;
return report;
};
reportForm.ShowReport(keeper);
keeper.ReloadReport(true);
}
private static FlexReport GenerateTableReport()
{
TemplateHelper templateHelper = new TemplateHelper();
const long idfsFormTemplate = 250420000000;
const long idfObservation = 22450000241;
templateHelper.LoadTemplate(FFType.VetEpizooticActionDiagnosisInv, idfsFormTemplate, new long[] { idfObservation },
new AggregateCaseSection[] { AggregateCaseSection.DiagnosticAction });
FlexNode flexNode = templateHelper.GetFlexNodeFromTemplate(idfObservation);
FlexReport report = FlexFactory.CreateFlexReport(flexNode, "", 600);
report.Landscape = true;
return report;
}
[Test]
[Ignore("Manual test")]
public void ReportViewSimpleTest()
{
ShowReport(delegate { return GenerateReport(FFType.AggregateCase, 250410000000, 18920000241); });
}
[Test]
[Ignore("Manual test")]
public void ReportViewSectionsTest()
{
ShowReport(delegate { return GenerateReport(FFType.HumanClinicalSigns, 249470000000, 18980000241); });
}
[Test]
[Ignore("Manual test")]
public void ReportViewNestedSectionsTest()
{
ShowReport(delegate { return GenerateReport(FFType.HumanClinicalSigns, 249640000000, 19230000241); });
}
public void ShowReport(GenerateReportDelegate reportCreator)
{
IReportForm reportForm = new ReportForm();
TestKeeper keeper = new TestKeeper();
keeper.GenerateReportInjection = reportCreator;
reportForm.ShowReport(keeper);
keeper.ReloadReport(true);
}
private static FlexReport GenerateReport(FFType formType, long idfsFormTemplate, long observation)
{
TemplateHelper templateHelper = new TemplateHelper();
List<long> observations = new List<long>();
observations.Add(observation);
templateHelper.LoadTemplate(formType, idfsFormTemplate, observations, null);
Assert.IsTrue(templateHelper.ParameterTemplate.Count > 0, "parameters not loaded!");
FlexNode flexNode = templateHelper.GetFlexNodeFromTemplate(observations[0]);
Console.WriteLine(flexNode.Count);
FlexReport report = FlexFactory.CreateFlexReport(flexNode, "", null);
return report;
}
private static FlexNode CreateListTree()
{
FlexNode rootNode = FlexNode.CreateRoot();
FlexibleFormsDS.LabelsDataTable labelsDataTable = GetLabelsDataTable();
FlexibleFormsDS.LinesDataTable linesDataTable = GetLinesDataTable();
rootNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[0]);
FlexNode firstNode = rootNode[0];
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[1]);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[2]);
firstNode.Add((FlexibleFormsDS.LinesRow) linesDataTable.Rows[0]);
firstNode.Add((FlexibleFormsDS.LinesRow) linesDataTable.Rows[1]);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[3]);
FlexNode secondNode = firstNode[4];
secondNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[4]);
secondNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[5]);
return rootNode;
}
private static FlexNode CreateTableTree()
{
FlexNode rootNode = FlexNode.CreateRoot();
FlexibleFormsDS.SectionTemplateDataTable dataTable = GetTablesDataTable();
FlexibleFormsDS.LabelsDataTable labelsDataTable = GetTableLabelsDataTable();
rootNode.Add((FlexibleFormsDS.SectionTemplateRow) dataTable.Rows[0]);
FlexNode firstNode = rootNode[0];
firstNode.Add((FlexibleFormsDS.SectionTemplateRow) dataTable.Rows[1]);
firstNode.Add((FlexibleFormsDS.LabelsRow) labelsDataTable.Rows[0]);
FlexNode secondNode = firstNode[0];
secondNode.Add((FlexibleFormsDS.LabelsRow)labelsDataTable.Rows[1]);
secondNode.Add((FlexibleFormsDS.LabelsRow)labelsDataTable.Rows[2]);
return rootNode;
}
private static FlexibleFormsDS.LabelsDataTable GetLabelsDataTable()
{
FlexibleFormsDS.LabelsDataTable labelsDataTable = new FlexibleFormsDS.LabelsDataTable();
labelsDataTable.AddLabelsRow(1, 2, "en", 3, 4, 5, 6, 700, 500, 0, 10, Color.Black.ToArgb(), "section",
"section", Color.Black, 11);
labelsDataTable.AddLabelsRow(10, 20, "en", 30, 40, 50, 60, 70, 80, 6, 20, Color.Red.ToArgb(), "default1",
"national1", Color.Red, 110);
labelsDataTable.AddLabelsRow(11, 21, "en", 31, 41, 150, 160, 70, 81, 0, 11, Color.Green.ToArgb(), "default1",
"national2", Color.Green, 111);
labelsDataTable.AddLabelsRow(1, 2, "en", 3, 4, 5, 400, 500, 200, 0, 10, Color.Black.ToArgb(), "subsection",
"subsection", Color.Black, 11);
labelsDataTable.AddLabelsRow(10, 20, "en", 30, 40, 50, 0, 70, 80, 2, 16, Color.Navy.ToArgb(), "default1",
"param name", Color.Navy, 110);
labelsDataTable.AddLabelsRow(11, 21, "en", 31, 41, 200, 0, 70, 80, 4, 16, Color.Blue.ToArgb(), "default1",
"param value", Color.Blue, 111);
return labelsDataTable;
}
private static FlexibleFormsDS.LinesDataTable GetLinesDataTable()
{
FlexibleFormsDS.LinesDataTable labelsDataTable = new FlexibleFormsDS.LinesDataTable();
labelsDataTable.AddLinesRow(1, "en", 3, 4, 111, 200, 100, 1, Color.DarkViolet.ToArgb(), true,
Color.DarkViolet, 1, 10);
labelsDataTable.AddLinesRow(1, "en", 3, 4, 300, 200, 1, 100, Color.Green.ToArgb(), false, Color.Green, 1, 10);
return labelsDataTable;
}
private static FlexibleFormsDS.SectionTemplateDataTable GetTablesDataTable()
{
FlexibleFormsDS.SectionTemplateDataTable dataTable = new FlexibleFormsDS.SectionTemplateDataTable();
dataTable.AddSectionTemplateRow(1, 2, 3, 4, true, true, 10, 20, 300, 100, "default table",
"national table", "en", true, true, 1, true, 10, 20);
dataTable.AddSectionTemplateRow(5, 6, 7, 8, true, true, 0, 0, 200, 50, "left",
"left cell", "en", true, true, 1, true, 10, 20);
return dataTable;
}
private static FlexibleFormsDS.LabelsDataTable GetTableLabelsDataTable()
{
FlexibleFormsDS.LabelsDataTable labelsDataTable = new FlexibleFormsDS.LabelsDataTable();
labelsDataTable.AddLabelsRow(17, 18, "en", 19, 20, 0, 0, 100, 50, 4, 12, Color.Green.ToArgb(), " right cell",
"right cell", Color.Red, 111);
labelsDataTable.AddLabelsRow(11, 21, "en", 31, 41, 0, 0, 130, 50, 4, 10, Color.Blue.ToArgb(),
"child left cell",
"child left cell", Color.Blue, 111);
labelsDataTable.AddLabelsRow(17, 18, "en", 19, 20, 0, 0, 70, 50, 4, 10, Color.Red.ToArgb(),
"child right cell",
"child right cell", Color.Red, 111);
return labelsDataTable;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GitVersion.Cache;
using GitVersion.Configuration;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using LibGit2Sharp;
using Microsoft.Extensions.Options;
namespace GitVersion.VersionCalculation.Cache
{
public class GitVersionCacheKeyFactory : IGitVersionCacheKeyFactory
{
private readonly IFileSystem fileSystem;
private readonly ILog log;
private readonly IOptions<GitVersionOptions> options;
private readonly IConfigFileLocator configFileLocator;
public GitVersionCacheKeyFactory(IFileSystem fileSystem, ILog log, IOptions<GitVersionOptions> options, IConfigFileLocator configFileLocator)
{
this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.configFileLocator = configFileLocator ?? throw new ArgumentNullException(nameof(configFileLocator));
}
public GitVersionCacheKey Create(Config overrideConfig)
{
var gitSystemHash = GetGitSystemHash();
var configFileHash = GetConfigFileHash();
var repositorySnapshotHash = GetRepositorySnapshotHash();
var overrideConfigHash = GetOverrideConfigHash(overrideConfig);
var compositeHash = GetHash(gitSystemHash, configFileHash, repositorySnapshotHash, overrideConfigHash);
return new GitVersionCacheKey(compositeHash);
}
private string GetGitSystemHash()
{
var dotGitDirectory = options.Value.DotGitDirectory;
// traverse the directory and get a list of files, use that for GetHash
var contents = CalculateDirectoryContents(Path.Combine(dotGitDirectory, "refs"));
return GetHash(contents.ToArray());
}
// based on https://msdn.microsoft.com/en-us/library/bb513869.aspx
private List<string> CalculateDirectoryContents(string root)
{
var result = new List<string>();
// Data structure to hold names of subfolders to be
// examined for files.
var dirs = new Stack<string>();
if (!Directory.Exists(root))
{
throw new DirectoryNotFoundException($"Root directory does not exist: {root}");
}
dirs.Push(root);
while (dirs.Any())
{
var currentDir = dirs.Pop();
var di = new DirectoryInfo(currentDir);
result.Add(di.Name);
string[] subDirs;
try
{
subDirs = Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
log.Error(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
log.Error(e.Message);
continue;
}
string[] files;
try
{
files = Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
log.Error(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
log.Error(e.Message);
continue;
}
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
result.Add(fi.Name);
result.Add(File.ReadAllText(file));
}
catch (IOException e)
{
log.Error(e.Message);
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
// push in reverse order
for (var i = subDirs.Length - 1; i >= 0; i--)
{
dirs.Push(subDirs[i]);
}
}
return result;
}
private string GetRepositorySnapshotHash()
{
using var repo = new Repository(options.Value.DotGitDirectory);
var head = repo.Head;
if (head.Tip == null)
{
return head.CanonicalName;
}
var hash = string.Join(":", head.CanonicalName, head.Tip.Sha);
return GetHash(hash);
}
private static string GetOverrideConfigHash(Config overrideConfig)
{
if (overrideConfig == null)
{
return string.Empty;
}
// Doesn't depend on command line representation and
// includes possible changes in default values of Config per se.
var stringBuilder = new StringBuilder();
using (var stream = new StringWriter(stringBuilder))
{
ConfigSerializer.Write(overrideConfig, stream);
stream.Flush();
}
var configContent = stringBuilder.ToString();
return GetHash(configContent);
}
private string GetConfigFileHash()
{
// will return the same hash even when config file will be moved
// from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same.
var configFilePath = configFileLocator.SelectConfigFilePath(options.Value);
if (!fileSystem.Exists(configFilePath))
{
return string.Empty;
}
var configFileContent = fileSystem.ReadAllText(configFilePath);
return GetHash(configFileContent);
}
private static string GetHash(params string[] textsToHash)
{
var textToHash = string.Join(":", textsToHash);
return GetHash(textToHash);
}
private static string GetHash(string textToHash)
{
if (string.IsNullOrEmpty(textToHash))
{
return string.Empty;
}
using var sha1 = SHA1.Create();
var bytes = Encoding.UTF8.GetBytes(textToHash);
var hashedBytes = sha1.ComputeHash(bytes);
var hashedString = BitConverter.ToString(hashedBytes);
return hashedString.Replace("-", "");
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.Linq;
using StrumpyShaderEditor;
using Object = UnityEngine.Object;
namespace StrumpyShaderEditor
{
public class PreviewWindowInternal : EditorWindow
{
private NodeEditor _parent;
private readonly PreviewRenderer _renderer = new PreviewRenderer();
private RenderTexture _previewTexture;
private GUIContent _previewTextureContent;
private Vector2 _cameraRotation;
private Mesh _previewMesh;
private Camera _previewCamera;
private IEnumerable<Light> _previewLights;
private GUIContent _hotControlHash;
private bool _initialized = false;
public bool ShouldUpdate = false;
public void Initialize(NodeEditor parent)
{
_parent = parent;
_parent.UpdateShader();
if (_initialized)
return;
_previewCamera = EditorUtility.CreateGameObjectWithHideFlags("RenderPreviewCamera", HideFlags.HideAndDontSave, new[] { typeof(Camera) }).GetComponent<Camera>();
_previewCamera.enabled = false;
_previewCamera.clearFlags = CameraClearFlags.Color;
_previewCamera.backgroundColor = new Color(0.15f, 0.15f, 0.15f, 1.0f);
_previewCamera.fieldOfView = 30.0f;
_previewCamera.renderingPath = RenderingPath.DeferredLighting;
var lights = new List<Light>();
for (var i = 0; i < 2; i++)
{
var l = EditorUtility.CreateGameObjectWithHideFlags("PreRenderLight", HideFlags.HideAndDontSave, new[] { typeof(Light) }).GetComponent<Light>();
l.type = LightType.Directional;
l.intensity = 0.5f;
l.enabled = false;
lights.Add(l);
}
lights[0].color = Color.grey;
lights[0].intensity = 0.8f;
lights[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f);
lights[1].color = new Color(0.4f, 0.4f, 0.45f, 0f) * 0.7f;
lights[1].intensity = 0.8f;
lights[1].transform.rotation = Quaternion.Euler(340f, 218f, 177f);
_previewLights = lights;
// Object.DontDestroyOnLoad(_previewCamera);
// Object.DontDestroyOnLoad(lights[0]);
// Object.DontDestroyOnLoad(lights[1]);
_hotControlHash = new GUIContent("GUIPREVIEWTEXTURE");
_previewMaterial = null;
var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
_previewMesh = go.GetComponent<MeshFilter>().sharedMesh;
// GameObject.DestroyImmediate(go);
_initialized = true;
UpdatePreviewTexture();
}
private void UpdatePreviewTexture()
{
if (_previewTexture != null)
{
RenderTexture.ReleaseTemporary(_previewTexture);
}
_previewTexture = RenderTexture.GetTemporary((int)position.width, (int)position.height - 40, 24, RenderTextureFormat.ARGB32);
_previewTextureContent = new GUIContent(_previewTexture);
}
private Material _previewMaterial;
public Material PreviewMaterial
{
get
{
if (_previewMaterial == null)
{
_previewMaterial = new Material(Shader.Find("Diffuse"));
Object.DontDestroyOnLoad(_previewMaterial);
}
return _previewMaterial;
}
set
{
_previewMaterial = value;
Object.DontDestroyOnLoad(_previewMaterial);
}
}
private void UpdateMaterial()
{
var material = PreviewMaterial;
var shaderProperties = _parent.CurrentGraph.GetProperties();
foreach (var property in shaderProperties)
{
if (!material.HasProperty(property.PropertyName))
{
continue;
}
var colorProperty = property as ColorProperty;
if (colorProperty != null)
{
material.SetColor(colorProperty.PropertyName, colorProperty.Color);
}
var textureProperty = property as Texture2DProperty;
if (textureProperty != null)
{
material.SetTexture(textureProperty.PropertyName, textureProperty.Texture);
}
var textureCubeProperty = property as TextureCubeProperty;
if (textureCubeProperty != null)
{
material.SetTexture(textureCubeProperty.PropertyName, textureCubeProperty.Cubemap);
}
var floatProperty = property as FloatProperty;
if (floatProperty != null)
{
material.SetFloat(floatProperty.PropertyName, floatProperty.Float);
}
var float4Property = property as Float4Property;
if (float4Property != null)
{
material.SetVector(float4Property.PropertyName, float4Property.Float4);
}
var rangeProperty = property as RangeProperty;
if (rangeProperty != null)
{
material.SetFloat(rangeProperty.PropertyName, rangeProperty.Range.Value);
}
}
}
public void OnLostFocus()
{
GUIUtility.hotControl = 0;
}
void OnGUI()
{
var drawPos = new Rect(0, 0, (int)position.width, (int)position.height - 40);
if (_previewTexture != null)
lock (_previewTexture)
{
GUI.Box(drawPos, _previewTextureContent);
}
if (_parent.ShaderNeedsUpdate())
{
GUILayout.BeginArea(new Rect(0, 0, (int)position.width, (int)position.height - 40));
GUILayout.BeginHorizontal();
var oColor = GUI.color; // Cache old content color
GUI.color = Color.red; // Make the warning red
var oldFontSize = GUI.skin.label.fontSize;
GUI.skin.label.fontSize = 20;
GUILayout.FlexibleSpace(); // Flexible space (ensures buttohns don't move)
GUILayout.Label("Shader Needs Updating"); // Draw the warning
GUILayout.FlexibleSpace();
GUI.skin.label.fontSize = oldFontSize;
GUILayout.EndHorizontal();
GUILayout.EndArea();
GUI.color = oColor; // Revert the color
}
int dragControl = GUIUtility.GetControlID(_hotControlHash, FocusType.Passive);
switch (Event.current.type)
{
case EventType.MouseDown:
if (drawPos.Contains(Event.current.mousePosition))
{
GUIUtility.hotControl = dragControl;
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == dragControl)
{
_cameraRotation -= Event.current.delta;
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == dragControl)
{
GUIUtility.hotControl = 0;
}
break;
}
GUILayout.FlexibleSpace();
_previewMesh = (Mesh)EditorGUILayout.ObjectField("Mesh:", _previewMesh, typeof(Mesh));
GUILayout.BeginHorizontal();
_drawBackground = EditorExtensions.ToggleButton(_drawBackground, "Draw Background");
if (GUILayout.Button("Update Preview"))
{
_parent.UpdateShader();
}
GUILayout.EndHorizontal();
}
private bool _drawBackground;
private DateTime _lastRenderTime = DateTime.Now;
public void Update()
{
if (!ShouldUpdate)
return;
Bounds bounds = _previewMesh ? _previewMesh.bounds : new Bounds(Vector3.zero, Vector3.one);
float magnitude = bounds.extents.magnitude;
float distance = magnitude * 3.5f;
_previewCamera.DrawMeshOnly();
//Set up the camera location...
_cameraRotation.y = ClampAngle(_cameraRotation.y);
_cameraRotation.x = ClampAngle(_cameraRotation.x);
_previewCamera.transform.rotation = Quaternion.Euler(_cameraRotation.y, 0.0f, 0f) * Quaternion.Euler(0.0f, _cameraRotation.x, 0.0f);
_previewCamera.transform.position = _previewCamera.transform.rotation * new Vector3(0.0f, 0.0f, -distance);
_previewCamera.nearClipPlane = distance - (magnitude * 1.1f);
_previewCamera.farClipPlane = distance + (magnitude * 1.1f);
//Lock rendering to 33hz (30fps).
if (DateTime.Now > _lastRenderTime + new TimeSpan(0, 0, 0, 0, 33))
{
if (position.width != _previewTexture.width || position.height != _previewTexture.height)
{
UpdatePreviewTexture();
}
_lastRenderTime = DateTime.Now;
UpdateMaterial();
_renderer.Render(_previewMesh, Vector3.zero, Quaternion.identity, _previewCamera, _previewLights, new Color(0.1f, 0.1f, 0.1f, 0f), PreviewMaterial, _previewTexture, _drawBackground);
Repaint();
}
}
private static float ClampAngle(float angle)
{
while (angle < -360)
angle += 360;
while (angle > 360)
angle -= 360;
return angle;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// The Service Management API includes operations for listing the
/// available data center locations for a hosted service in your
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for
/// more information)
/// </summary>
internal partial class LocationOperations : IServiceOperations<ManagementClient>, ILocationOperations
{
/// <summary>
/// Initializes a new instance of the LocationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocationOperations(ManagementClient client)
{
this._client = client;
}
private ManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ManagementClient.
/// </summary>
public ManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Locations operation lists all of the data center locations
/// that are valid for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Locations operation response.
/// </returns>
public async Task<LocationsListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/locations";
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LocationsListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocationsListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement locationsSequenceElement = responseDoc.Element(XName.Get("Locations", "http://schemas.microsoft.com/windowsazure"));
if (locationsSequenceElement != null)
{
foreach (XElement locationsElement in locationsSequenceElement.Elements(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")))
{
LocationsListResponse.Location locationInstance = new LocationsListResponse.Location();
result.Locations.Add(locationInstance);
XElement nameElement = locationsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
locationInstance.Name = nameInstance;
}
XElement displayNameElement = locationsElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure"));
if (displayNameElement != null)
{
string displayNameInstance = displayNameElement.Value;
locationInstance.DisplayName = displayNameInstance;
}
XElement availableServicesSequenceElement = locationsElement.Element(XName.Get("AvailableServices", "http://schemas.microsoft.com/windowsazure"));
if (availableServicesSequenceElement != null)
{
foreach (XElement availableServicesElement in availableServicesSequenceElement.Elements(XName.Get("AvailableService", "http://schemas.microsoft.com/windowsazure")))
{
locationInstance.AvailableServices.Add(availableServicesElement.Value);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Hosting;
namespace Orleans.Runtime.Messaging
{
internal class Gateway
{
private readonly MessageCenter messageCenter;
private readonly MessageFactory messageFactory;
private readonly GatewayAcceptor acceptor;
private readonly Lazy<GatewaySender>[] senders;
private readonly GatewayClientCleanupAgent dropper;
// clients is the main authorative collection of all connected clients.
// Any client currently in the system appears in this collection.
// In addition, we use clientSockets collection for fast retrival of ClientState.
// Anything that appears in those 2 collections should also appear in the main clients collection.
private readonly ConcurrentDictionary<GrainId, ClientState> clients;
private readonly ConcurrentDictionary<Socket, ClientState> clientSockets;
private readonly SiloAddress gatewayAddress;
private int nextGatewaySenderToUseForRoundRobin;
private readonly ClientsReplyRoutingCache clientsReplyRoutingCache;
private ClientObserverRegistrar clientRegistrar;
private readonly object lockable;
private readonly SerializationManager serializationManager;
private readonly ExecutorService executorService;
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private readonly SiloMessagingOptions messagingOptions;
public Gateway(
MessageCenter msgCtr,
ILocalSiloDetails siloDetails,
MessageFactory messageFactory,
SerializationManager serializationManager,
ExecutorService executorService,
ILoggerFactory loggerFactory,
IOptions<EndpointOptions> endpointOptions,
IOptions<SiloMessagingOptions> options,
IOptions<MultiClusterOptions> multiClusterOptions,
OverloadDetector overloadDetector)
{
this.messagingOptions = options.Value;
this.loggerFactory = loggerFactory;
messageCenter = msgCtr;
this.messageFactory = messageFactory;
this.logger = this.loggerFactory.CreateLogger<Gateway>();
this.serializationManager = serializationManager;
this.executorService = executorService;
acceptor = new GatewayAcceptor(
msgCtr,
this,
endpointOptions.Value.GetListeningProxyEndpoint(),
this.messageFactory,
this.serializationManager,
executorService,
siloDetails,
multiClusterOptions,
loggerFactory,
overloadDetector);
senders = new Lazy<GatewaySender>[messagingOptions.GatewaySenderQueues];
nextGatewaySenderToUseForRoundRobin = 0;
dropper = new GatewayClientCleanupAgent(this, executorService, loggerFactory, messagingOptions.ClientDropTimeout);
clients = new ConcurrentDictionary<GrainId, ClientState>();
clientSockets = new ConcurrentDictionary<Socket, ClientState>();
clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout);
this.gatewayAddress = siloDetails.GatewayAddress;
lockable = new object();
}
internal void Start(ClientObserverRegistrar clientRegistrar)
{
this.clientRegistrar = clientRegistrar;
this.clientRegistrar.SetGateway(this);
acceptor.Start();
for (int i = 0; i < senders.Length; i++)
{
int capture = i;
senders[capture] = new Lazy<GatewaySender>(() =>
{
var sender = new GatewaySender("GatewaySiloSender_" + capture, this, this.messageFactory, this.serializationManager, this.executorService, this.loggerFactory);
sender.Start();
return sender;
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
dropper.Start();
}
internal void Stop()
{
dropper.Stop();
foreach (var sender in senders)
{
if (sender != null && sender.IsValueCreated)
sender.Value.Stop();
}
acceptor.Stop();
}
internal ICollection<GrainId> GetConnectedClients()
{
return clients.Keys;
}
internal void RecordOpenedSocket(Socket sock, GrainId clientId)
{
lock (lockable)
{
logger.Info(ErrorCode.GatewayClientOpenedSocket, "Recorded opened socket from endpoint {0}, client ID {1}.", sock.RemoteEndPoint, clientId);
ClientState clientState;
if (clients.TryGetValue(clientId, out clientState))
{
var oldSocket = clientState.Socket;
if (oldSocket != null)
{
// The old socket will be closed by itself later.
ClientState ignore;
clientSockets.TryRemove(oldSocket, out ignore);
}
QueueRequest(clientState, null);
}
else
{
int gatewayToUse = nextGatewaySenderToUseForRoundRobin % senders.Length;
nextGatewaySenderToUseForRoundRobin++; // under Gateway lock
clientState = new ClientState(clientId, gatewayToUse, messagingOptions.ClientDropTimeout);
clients[clientId] = clientState;
MessagingStatisticsGroup.ConnectedClientCount.Increment();
}
clientState.RecordConnection(sock);
clientSockets[sock] = clientState;
clientRegistrar.ClientAdded(clientId);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
}
}
internal void RecordClosedSocket(Socket sock)
{
if (sock == null) return;
lock (lockable)
{
ClientState cs = null;
if (!clientSockets.TryGetValue(sock, out cs)) return;
EndPoint endPoint = null;
try
{
endPoint = sock.RemoteEndPoint;
}
catch (Exception) { } // guard against ObjectDisposedExceptions
logger.Info(ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {0}, client ID {1}.", endPoint != null ? endPoint.ToString() : "null", cs.Id);
ClientState ignore;
clientSockets.TryRemove(sock, out ignore);
cs.RecordDisconnection();
}
}
internal SiloAddress TryToReroute(Message msg)
{
// ** Special routing rule for system target here **
// When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either
// - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap)
// - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget
// activation that is on a silo on which there is no gateway available (or if the client is not
// connected to that gateway)
// So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward
// it to this address...
// EXCEPT if the value is equal to the current GatewayAdress: in this case we will return
// null and the local dispatcher will forward the Message to a local SystemTarget activation
if (msg.TargetGrain.IsSystemTarget && !IsTargetingLocalGateway(msg.TargetSilo))
return msg.TargetSilo;
// for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back.
if (!msg.SendingGrain.IsClient || !msg.TargetGrain.IsClient) return null;
if (msg.Direction != Message.Directions.Response) return null;
SiloAddress gateway;
return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null;
}
internal void DropDisconnectedClients()
{
lock (lockable)
{
List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList();
foreach (ClientState client in clientsToDrop)
DropClient(client);
}
}
internal void DropExpiredRoutingCachedEntries()
{
lock (lockable)
{
clientsReplyRoutingCache.DropExpiredEntries();
}
}
private bool IsTargetingLocalGateway(SiloAddress siloAddress)
{
// Special case if the address used by the client was loopback
return this.gatewayAddress.Matches(siloAddress)
|| (IPAddress.IsLoopback(siloAddress.Endpoint.Address)
&& siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port
&& siloAddress.Generation == this.gatewayAddress.Generation);
}
// This function is run under global lock
// There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket.
private void DropClient(ClientState client)
{
logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect",
client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince));
ClientState ignore;
clients.TryRemove(client.Id, out ignore);
clientRegistrar.ClientDropped(client.Id);
Socket oldSocket = client.Socket;
if (oldSocket != null)
{
// this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure.
client.RecordDisconnection();
clientSockets.TryRemove(oldSocket, out ignore);
SocketManager.CloseSocket(oldSocket);
}
MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1);
}
/// <summary>
/// See if this message is intended for a grain we're proxying, and queue it for delivery if so.
/// </summary>
/// <param name="msg"></param>
/// <returns>true if the message should be delivered to a proxied grain, false if not.</returns>
internal bool TryDeliverToProxy(Message msg)
{
// See if it's a grain we're proxying.
ClientState client;
// not taking global lock on the crytical path!
if (!clients.TryGetValue(msg.TargetGrain, out client))
return false;
// when this Gateway receives a message from client X to client addressale object Y
// it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to)
// it will use this Gateway to re-route the REPLY from Y back to X.
if (msg.SendingGrain.IsClient && msg.TargetGrain.IsClient)
{
clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo);
}
msg.TargetSilo = null;
// Override the SendingSilo only if the sending grain is not
// a system target
if (!msg.SendingGrain.IsSystemTarget)
msg.SendingSilo = gatewayAddress;
QueueRequest(client, msg);
return true;
}
private void QueueRequest(ClientState clientState, Message msg)
{
//int index = senders.Length == 1 ? 0 : Math.Abs(clientId.GetHashCode()) % senders.Length;
int index = clientState.GatewaySenderNumber;
senders[index].Value.QueueRequest(new OutgoingClientMessage(clientState.Id, msg));
}
internal void SendMessage(Message msg)
{
messageCenter.SendMessage(msg);
}
private class ClientState
{
private readonly TimeSpan clientDropTimeout;
internal Queue<Message> PendingToSend { get; private set; }
internal Queue<List<Message>> PendingBatchesToSend { get; private set; }
internal Socket Socket { get; private set; }
internal DateTime DisconnectedSince { get; private set; }
internal GrainId Id { get; private set; }
internal int GatewaySenderNumber { get; private set; }
internal bool IsConnected { get { return Socket != null; } }
internal ClientState(GrainId id, int gatewaySenderNumber, TimeSpan clientDropTimeout)
{
Id = id;
GatewaySenderNumber = gatewaySenderNumber;
this.clientDropTimeout = clientDropTimeout;
PendingToSend = new Queue<Message>();
PendingBatchesToSend = new Queue<List<Message>>();
}
internal void RecordDisconnection()
{
if (Socket == null) return;
DisconnectedSince = DateTime.UtcNow;
Socket = null;
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
internal void RecordConnection(Socket sock)
{
Socket = sock;
DisconnectedSince = DateTime.MaxValue;
}
internal bool ReadyToDrop()
{
return !IsConnected &&
(DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout);
}
}
private class GatewayClientCleanupAgent : DedicatedAsynchAgent
{
private readonly Gateway gateway;
private readonly TimeSpan clientDropTimeout;
internal GatewayClientCleanupAgent(Gateway gateway, ExecutorService executorService, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout)
:base(executorService, loggerFactory)
{
this.gateway = gateway;
this.clientDropTimeout = clientDropTimeout;
}
protected override void Run()
{
while (!Cts.IsCancellationRequested)
{
gateway.DropDisconnectedClients();
gateway.DropExpiredRoutingCachedEntries();
Thread.Sleep(clientDropTimeout);
}
}
}
// this cache is used to record the addresses of Gateways from which clients connected to.
// it is used to route replies to clients from client addressable objects
// without this cache this Gateway will not know how to route the reply back to the client
// (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined).
private class ClientsReplyRoutingCache
{
// for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway.
private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes;
private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
internal ClientsReplyRoutingCache(TimeSpan responseTimeout)
{
clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>();
TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5);
}
internal void RecordClientRoute(GrainId client, SiloAddress gateway)
{
var now = DateTime.UtcNow;
clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now));
}
internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway)
{
gateway = null;
Tuple<SiloAddress, DateTime> tuple;
bool ret = clientRoutes.TryGetValue(client, out tuple);
if (ret)
gateway = tuple.Item1;
return ret;
}
internal void DropExpiredEntries()
{
List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList();
foreach (GrainId client in clientsToDrop)
{
Tuple<SiloAddress, DateTime> tuple;
clientRoutes.TryRemove(client, out tuple);
}
}
private bool Expired(DateTime lastUsed)
{
return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
}
}
private class GatewaySender : AsynchQueueAgent<OutgoingClientMessage>
{
private readonly Gateway gateway;
private readonly MessageFactory messageFactory;
private readonly CounterStatistic gatewaySends;
private readonly SerializationManager serializationManager;
internal GatewaySender(string name, Gateway gateway, MessageFactory messageFactory, SerializationManager serializationManager, ExecutorService executorService, ILoggerFactory loggerFactory)
: base(name, executorService, loggerFactory)
{
this.gateway = gateway;
this.messageFactory = messageFactory;
this.serializationManager = serializationManager;
gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
OnFault = FaultBehavior.RestartOnFault;
}
protected override void Process(OutgoingClientMessage request)
{
if (Cts.IsCancellationRequested) return;
var client = request.Item1;
var msg = request.Item2;
// Find the client state
ClientState clientState;
bool found;
// TODO: Why do we need this lock here if clients is a ConcurrentDictionary?
//lock (gateway.lockable)
{
found = gateway.clients.TryGetValue(client, out clientState);
}
// This should never happen -- but make sure to handle it reasonably, just in case
if (!found || (clientState == null))
{
if (msg == null) return;
Log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), client);
MessagingStatisticsGroup.OnFailedSentMessage(msg);
// Message for unrecognized client -- reject it
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(
msg,
Message.RejectionTypes.Unrecoverable,
"Unknown client " + client);
gateway.SendMessage(error);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
return;
}
// if disconnected - queue for later.
if (!clientState.IsConnected)
{
if (msg == null) return;
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
return;
}
// if the queue is non empty - drain it first.
if (clientState.PendingToSend.Count > 0)
{
if (msg != null)
clientState.PendingToSend.Enqueue(msg);
// For now, drain in-line, although in the future this should happen in yet another asynch agent
Drain(clientState);
return;
}
// the queue was empty AND we are connected.
// If the request includes a message to send, send it (or enqueue it for later)
if (msg == null) return;
if (!Send(msg, clientState.Socket))
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
}
else
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sent message {0} to client {1}", msg, client);
}
}
private void Drain(ClientState clientState)
{
// For now, drain in-line, although in the future this should happen in yet another asynch agent
while (clientState.PendingToSend.Count > 0)
{
var m = clientState.PendingToSend.Peek();
if (Send(m, clientState.Socket))
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sent queued message {0} to client {1}", m, clientState.Id);
clientState.PendingToSend.Dequeue();
}
else
{
return;
}
}
}
private bool Send(Message msg, Socket sock)
{
if (Cts.IsCancellationRequested) return false;
if (sock == null) return false;
// Send the message
List<ArraySegment<byte>> data;
int headerLength;
try
{
int bodyLength;
data = msg.Serialize(this.serializationManager, out headerLength, out bodyLength);
if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold)
{
Log.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
headerLength + bodyLength + Message.LENGTH_HEADER_SIZE, headerLength, bodyLength, data.Count, this.ToString());
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sending large message {0}", msg.ToLongString());
}
}
catch (Exception exc)
{
this.OnMessageSerializationFailure(msg, exc);
return true;
}
int length = data.Sum(x => x.Count);
int bytesSent = 0;
bool exceptionSending = false;
bool countMismatchSending = false;
string sendErrorStr;
try
{
bytesSent = sock.Send(data);
if (bytesSent != length)
{
// The complete message wasn't sent, even though no error was reported; treat this as an error
countMismatchSending = true;
sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length);
Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr);
}
}
catch (Exception exc)
{
exceptionSending = true;
string remoteEndpoint = "";
if (!(exc is ObjectDisposedException))
{
try
{
remoteEndpoint = sock.RemoteEndPoint.ToString();
}
catch (Exception){}
}
sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc);
Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc);
}
MessagingStatisticsGroup.OnMessageSend(msg.TargetSilo, msg.Direction, bytesSent, headerLength, SocketDirection.GatewayToClient);
bool sendError = exceptionSending || countMismatchSending;
if (sendError)
{
gateway.RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
gatewaySends.Increment();
msg.ReleaseBodyAndHeaderBuffers();
return !sendError;
}
private void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
this.Log.LogWarning(
(int)ErrorCode.Messaging_Gateway_SerializationError,
"Unexpected error serializing message {Message}: {Exception}",
msg,
exc);
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
var retryCount = msg.RetryCount ?? 0;
if (msg.Direction == Message.Directions.Request)
{
this.gateway.messageCenter.SendRejection(msg, Message.RejectionTypes.Unrecoverable, exc.ToString());
}
else if (msg.Direction == Message.Directions.Response && retryCount < 1)
{
// if we failed sending an original response, turn the response body into an error and reply with it.
// unless we have already tried sending the response multiple times.
msg.Result = Message.ResponseTypes.Error;
msg.BodyObject = Response.ExceptionResponse(exc);
msg.RetryCount = retryCount + 1;
this.gateway.messageCenter.SendMessage(msg);
}
else
{
this.Log.LogWarning(
(int)ErrorCode.Messaging_OutgoingMS_DroppingMessage,
"Gateway {GatewayAddress} is dropping message which failed during serialization: {Message}. Exception = {Exception}",
this.gateway.gatewayAddress,
msg,
exc);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
}
}
}
| |
// Code from https://github.com/aspnet/Options/blob/edc21af4166574ecd45d8f8dbd381dfec044f367/src/Microsoft.Extensions.Options/OptionsBuilder.cs
// This will be removed and superseded Mirosoft.Extensions.Options v2.1.0.0 once it ships.
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Orleans.Configuration
{
/// <summary>
/// Used to configure TOptions instances. This will be deprecated and superseded Mirosoft.Extensions.Options v2.1.0.0 once it ships.
/// </summary>
/// <typeparam name="TOptions">The type of options being requested.</typeparam>
public class OptionsBuilder<TOptions> where TOptions : class
{
/// <summary>
/// The default name of the TOptions instance.
/// </summary>
public string Name { get; }
/// <summary>
/// The <see cref="IServiceCollection"/> for the options being configured.
/// </summary>
public IServiceCollection Services { get; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> for the options being configured.</param>
/// <param name="name">The default name of the TOptions instance, if null Options.DefaultName is used.</param>
public OptionsBuilder(IServiceCollection services, string name)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
Services = services;
Name = name ?? Options.DefaultName;
}
/// <summary>
/// Registers an action used to configure a particular type of options.
/// Note: These are run before all <seealso cref="PostConfigure(Action{TOptions})"/>.
/// </summary>
/// <param name="configureOptions">The action used to configure the options.</param>
public virtual OptionsBuilder<TOptions> Configure(Action<TOptions> configureOptions)
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddSingleton<IConfigureOptions<TOptions>>(new ConfigureNamedOptions<TOptions>(Name, configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> Configure<TDep>(Action<TOptions, TDep> configureOptions)
where TDep : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IConfigureOptions<TOptions>>(sp =>
new ConfigureNamedOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions)
where TDep1 : class
where TDep2 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IConfigureOptions<TOptions>>(sp =>
new ConfigureNamedOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IConfigureOptions<TOptions>>(
sp => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
where TDep4 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IConfigureOptions<TOptions>>(
sp => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
sp.GetRequiredService<TDep4>(),
configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
where TDep4 : class
where TDep5 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IConfigureOptions<TOptions>>(
sp => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
sp.GetRequiredService<TDep4>(),
sp.GetRequiredService<TDep5>(),
configureOptions));
return this;
}
/// <summary>
/// Registers an action used to configure a particular type of options.
/// Note: These are run after all <seealso cref="Configure(Action{TOptions})"/>.
/// </summary>
/// <param name="configureOptions">The action used to configure the options.</param>
public virtual OptionsBuilder<TOptions> PostConfigure(Action<TOptions> configureOptions)
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddSingleton<IPostConfigureOptions<TOptions>>(new PostConfigureOptions<TOptions>(Name, configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> PostConfigure<TDep>(Action<TOptions, TDep> configureOptions)
where TDep : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IPostConfigureOptions<TOptions>>(sp =>
new PostConfigureOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions)
where TDep1 : class
where TDep2 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IPostConfigureOptions<TOptions>>(sp =>
new PostConfigureOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IPostConfigureOptions<TOptions>>(
sp => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
where TDep4 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IPostConfigureOptions<TOptions>>(
sp => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
sp.GetRequiredService<TDep4>(),
configureOptions));
return this;
}
public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions)
where TDep1 : class
where TDep2 : class
where TDep3 : class
where TDep4 : class
where TDep5 : class
{
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
Services.AddTransient<IPostConfigureOptions<TOptions>>(
sp => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(
Name,
sp.GetRequiredService<TDep1>(),
sp.GetRequiredService<TDep2>(),
sp.GetRequiredService<TDep3>(),
sp.GetRequiredService<TDep4>(),
sp.GetRequiredService<TDep5>(),
configureOptions));
return this;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Ab3d.OculusWrap;
using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using Buffer = SharpDX.Direct3D11.Buffer;
using Device = SharpDX.Direct3D11.Device;
using ovrSession = System.IntPtr;
using ovrTextureSwapChain = System.IntPtr;
using ovrMirrorTexture = System.IntPtr;
using Result = Ab3d.OculusWrap.Result;
namespace Ab3d.OculusWrap.DemoDX11
{
/// <summary>
/// SharpDX MiniCube Direct3D 11 Sample
/// </summary>
static class Program
{
private static void Main()
{
RenderForm form = new RenderForm("OculusWrap SharpDX demo");
IntPtr sessionPtr;
InputLayout inputLayout = null;
Buffer contantBuffer = null;
Buffer vertexBuffer = null;
ShaderSignature shaderSignature = null;
PixelShader pixelShader = null;
ShaderBytecode pixelShaderByteCode = null;
VertexShader vertexShader = null;
ShaderBytecode vertexShaderByteCode = null;
Texture2D mirrorTextureD3D = null;
EyeTexture[] eyeTextures = null;
DeviceContext immediateContext = null;
DepthStencilState depthStencilState = null;
DepthStencilView depthStencilView = null;
Texture2D depthBuffer = null;
RenderTargetView backBufferRenderTargetView = null;
Texture2D backBuffer = null;
SharpDX.DXGI.SwapChain swapChain = null;
Factory factory = null;
MirrorTexture mirrorTexture = null;
Guid textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c"); // Interface ID of the Direct3D Texture2D interface.
Result result;
OvrWrap OVR = OvrWrap.Create();
// Define initialization parameters with debug flag.
InitParams initializationParameters = new InitParams();
initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion;
initializationParameters.RequestedMinorVersion = 17;
// Initialize the Oculus runtime.
string errorReason = null;
try
{
result = OVR.Initialize(initializationParameters);
if (result < Result.Success)
errorReason = result.ToString();
}
catch (Exception ex)
{
errorReason = ex.Message;
}
if (errorReason != null)
{
MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Use the head mounted display.
sessionPtr = IntPtr.Zero;
var graphicsLuid = new GraphicsLuid();
result = OVR.Create(ref sessionPtr, ref graphicsLuid);
if (result < Result.Success)
{
MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var hmdDesc = OVR.GetHmdDesc(sessionPtr);
try
{
// Create a set of layers to submit.
eyeTextures = new EyeTexture[2];
// Create DirectX drawing device.
SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug);
// Create DirectX Graphics Interface factory, used to create the swap chain.
factory = new SharpDX.DXGI.Factory4();
immediateContext = device.ImmediateContext;
// Define the properties of the swap chain.
SwapChainDescription swapChainDescription = new SwapChainDescription();
swapChainDescription.BufferCount = 1;
swapChainDescription.IsWindowed = true;
swapChainDescription.OutputHandle = form.Handle;
swapChainDescription.SampleDescription = new SampleDescription(1, 0);
swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput;
swapChainDescription.SwapEffect = SwapEffect.Sequential;
swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch;
swapChainDescription.ModeDescription.Width = form.Width;
swapChainDescription.ModeDescription.Height = form.Height;
swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm;
swapChainDescription.ModeDescription.RefreshRate.Numerator = 0;
swapChainDescription.ModeDescription.RefreshRate.Denominator = 1;
// Create the swap chain.
swapChain = new SwapChain(factory, device, swapChainDescription);
// Retrieve the back buffer of the swap chain.
backBuffer = swapChain.GetBackBuffer<Texture2D>(0);
backBufferRenderTargetView = new RenderTargetView(device, backBuffer);
// Create a depth buffer, using the same width and height as the back buffer.
Texture2DDescription depthBufferDescription = new Texture2DDescription();
depthBufferDescription.Format = Format.D32_Float;
depthBufferDescription.ArraySize = 1;
depthBufferDescription.MipLevels = 1;
depthBufferDescription.Width = form.Width;
depthBufferDescription.Height = form.Height;
depthBufferDescription.SampleDescription = new SampleDescription(1, 0);
depthBufferDescription.Usage = ResourceUsage.Default;
depthBufferDescription.BindFlags = BindFlags.DepthStencil;
depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
depthBufferDescription.OptionFlags = ResourceOptionFlags.None;
// Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription();
depthStencilStateDescription.IsDepthEnabled = true;
depthStencilStateDescription.DepthComparison = Comparison.Less;
depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;
// Create the depth buffer.
depthBuffer = new Texture2D(device, depthBufferDescription);
depthStencilView = new DepthStencilView(device, depthBuffer);
depthStencilState = new DepthStencilState(device, depthStencilStateDescription);
var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.Resolution.Height, 0.0f, 1.0f);
immediateContext.OutputMerger.SetDepthStencilState(depthStencilState);
immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView);
immediateContext.Rasterizer.SetViewport(viewport);
// Retrieve the DXGI device, in order to set the maximum frame latency.
using(SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>())
{
dxgiDevice.MaximumFrameLatency = 1;
}
var layerEyeFov = new LayerEyeFov();
layerEyeFov.Header.Type = LayerType.EyeFov;
layerEyeFov.Header.Flags = LayerFlags.None;
for (int eyeIndex=0; eyeIndex<2; eyeIndex++)
{
EyeType eye = (EyeType)eyeIndex;
var eyeTexture = new EyeTexture();
eyeTextures[eyeIndex] = eyeTexture;
// Retrieve size and position of the texture for the current eye.
eyeTexture.FieldOfView = hmdDesc.DefaultEyeFov[eyeIndex];
eyeTexture.TextureSize = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f);
eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);
eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyePose.Position;
eyeTexture.ViewportSize.Position = new Vector2i(0, 0);
eyeTexture.ViewportSize.Size = eyeTexture.TextureSize;
eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f);
// Define a texture at the size recommended for the eye texture.
eyeTexture.Texture2DDescription = new Texture2DDescription();
eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width;
eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height;
eyeTexture.Texture2DDescription.ArraySize = 1;
eyeTexture.Texture2DDescription.MipLevels = 1;
eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm;
eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0);
eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default;
eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None;
eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;
// Convert the SharpDX texture description to the Oculus texture swap chain description.
TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription);
// Create a texture swap chain, which will contain the textures to render to, for the current eye.
IntPtr textureSwapChainPtr;
result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr);
WriteErrorDetails(OVR, result, "Failed to create swap chain.");
eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr);
// Retrieve the number of buffers of the created swap chain.
int textureSwapChainBufferCount;
result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount);
WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain.");
// Create room for each DirectX texture in the SwapTextureSet.
eyeTexture.Textures = new Texture2D[textureSwapChainBufferCount];
eyeTexture.RenderTargetViews = new RenderTargetView[textureSwapChainBufferCount];
// Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
for (int textureIndex=0; textureIndex<textureSwapChainBufferCount; textureIndex++)
{
// Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer.
IntPtr swapChainTextureComPtr = IntPtr.Zero;
result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr);
WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain.");
// Create a managed Texture2D, based on the unmanaged texture pointer.
eyeTexture.Textures[textureIndex] = new Texture2D(swapChainTextureComPtr);
// Create a render target view for the current Texture2D.
eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]);
}
// Define the depth buffer, at the size recommended for the eye texture.
eyeTexture.DepthBufferDescription = new Texture2DDescription();
eyeTexture.DepthBufferDescription.Format = Format.D32_Float;
eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width;
eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height;
eyeTexture.DepthBufferDescription.ArraySize = 1;
eyeTexture.DepthBufferDescription.MipLevels = 1;
eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0);
eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default;
eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil;
eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None;
// Create the depth buffer.
eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription);
eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer);
// Specify the texture to show on the HMD.
if (eyeIndex == 0)
{
layerEyeFov.ColorTextureLeft = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0);
layerEyeFov.ViewportLeft.Size = eyeTexture.TextureSize;
layerEyeFov.FovLeft = eyeTexture.FieldOfView;
}
else
{
layerEyeFov.ColorTextureRight = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
layerEyeFov.ViewportRight.Position = new Vector2i(0, 0);
layerEyeFov.ViewportRight.Size = eyeTexture.TextureSize;
layerEyeFov.FovRight = eyeTexture.FieldOfView;
}
}
MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc();
mirrorTextureDescription.Format = TextureFormat.R8G8B8A8_UNorm_SRgb;
mirrorTextureDescription.Width = form.Width;
mirrorTextureDescription.Height = form.Height;
mirrorTextureDescription.MiscFlags = TextureMiscFlags.None;
// Create the texture used to display the rendered result on the computer monitor.
IntPtr mirrorTexturePtr;
result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr);
WriteErrorDetails(OVR, result, "Failed to create mirror texture.");
mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr);
// Retrieve the Direct3D texture contained in the Oculus MirrorTexture.
IntPtr mirrorTextureComPtr = IntPtr.Zero;
result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr);
WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer.");
// Create a managed Texture2D, based on the unmanaged texture pointer.
mirrorTextureD3D = new Texture2D(mirrorTextureComPtr);
#region Vertex and pixel shader
// Create vertex shader.
vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderPositionColor", "vs_4_0");
vertexShader = new VertexShader(device, vertexShaderByteCode);
// Create pixel shader.
pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderPositionColor", "ps_4_0");
pixelShader = new PixelShader(device, pixelShaderByteCode);
shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
// Specify that each vertex consists of a single vertex position and color.
InputElement[] inputElements = new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
};
// Define an input layout to be passed to the vertex shader.
inputLayout = new InputLayout(device, shaderSignature, inputElements);
// Create a vertex buffer, containing our 3D model.
vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, m_vertices);
// Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader.
contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
// Setup the immediate context to use the shaders and model we defined.
immediateContext.InputAssembler.InputLayout = inputLayout;
immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, sizeof(float)*4*2, 0));
immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer);
immediateContext.VertexShader.Set(vertexShader);
immediateContext.PixelShader.Set(pixelShader);
#endregion
DateTime startTime = DateTime.Now;
Vector3 position = new Vector3(0, 0, -1);
#region Render loop
RenderLoop.Run(form, () =>
{
Vector3f[] hmdToEyeViewOffsets = {eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset};
double displayMidpoint = OVR.GetPredictedDisplayTime(sessionPtr, 0);
TrackingState trackingState = OVR.GetTrackingState(sessionPtr, displayMidpoint, true);
Posef[] eyePoses = new Posef[2];
// Calculate the position and orientation of each eye.
OVR.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses);
float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds;
for(int eyeIndex = 0; eyeIndex < 2; eyeIndex ++)
{
EyeType eye = (EyeType)eyeIndex;
EyeTexture eyeTexture = eyeTextures[eyeIndex];
if (eyeIndex == 0)
layerEyeFov.RenderPoseLeft = eyePoses[0];
else
layerEyeFov.RenderPoseRight = eyePoses[1];
// Update the render description at each frame, as the HmdToEyeOffset can change at runtime.
eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);
// Retrieve the index of the active texture
int textureIndex;
result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex);
WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index.");
immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);
// Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion);
Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();
Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();
Matrix world = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart/10f) * Matrix.RotationY(timeSinceStart*2/10f) * Matrix.RotationZ(timeSinceStart*3/10f);
Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition+lookAt, lookUp);
Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix();
projectionMatrix.Transpose();
Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
worldViewProjection.Transpose();
// Update the transformation matrix.
immediateContext.UpdateSubresource(ref worldViewProjection, contantBuffer);
// Draw the cube
immediateContext.Draw(m_vertices.Length/2, 0);
// Commits any pending changes to the TextureSwapChain, and advances its current index
result = eyeTexture.SwapTextureSet.Commit();
WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture.");
}
result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov);
WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers.");
immediateContext.CopyResource(mirrorTextureD3D, backBuffer);
swapChain.Present(0, PresentFlags.None);
});
#endregion
}
finally
{
if(immediateContext != null)
{
immediateContext.ClearState();
immediateContext.Flush();
}
// Release all resources
Dispose(inputLayout);
Dispose(contantBuffer);
Dispose(vertexBuffer);
Dispose(shaderSignature);
Dispose(pixelShader);
Dispose(pixelShaderByteCode);
Dispose(vertexShader);
Dispose(vertexShaderByteCode);
Dispose(mirrorTextureD3D);
Dispose(mirrorTexture);
Dispose(eyeTextures[0]);
Dispose(eyeTextures[1]);
Dispose(immediateContext);
Dispose(depthStencilState);
Dispose(depthStencilView);
Dispose(depthBuffer);
Dispose(backBufferRenderTargetView);
Dispose(backBuffer);
Dispose(swapChain);
Dispose(factory);
// Disposing the device, before the hmd, will cause the hmd to fail when disposing.
// Disposing the device, after the hmd, will cause the dispose of the device to fail.
// It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
// device.Dispose();
OVR.Destroy(sessionPtr);
}
}
/// <summary>
/// Write out any error details received from the Oculus SDK, into the debug output window.
///
/// Please note that writing text to the debug output window is a slow operation and will affect performance,
/// if too many messages are written in a short timespan.
/// </summary>
/// <param name="OVR">OvrWrap object for which the error occurred.</param>
/// <param name="result">Error code to write in the debug text.</param>
/// <param name="message">Error message to include in the debug text.</param>
public static void WriteErrorDetails(OvrWrap OVR, Result result, string message)
{
if(result >= Result.Success)
return;
// Retrieve the error message from the last occurring error.
ErrorInfo errorInformation = OVR.GetLastErrorInfo();
string formattedMessage = string.Format("{0}. \nMessage: {1} (Error code={2})", message, errorInformation.ErrorString, errorInformation.Result);
Trace.WriteLine(formattedMessage);
MessageBox.Show(formattedMessage, message);
throw new Exception(formattedMessage);
}
/// <summary>
/// Dispose the specified object, unless it's a null object.
/// </summary>
/// <param name="disposable">Object to dispose.</param>
public static void Dispose(IDisposable disposable)
{
if(disposable != null)
disposable.Dispose();
}
static Vector4[] m_vertices = new Vector4[]
{
// Near
new Vector4( 1, 1, -1, 1), new Vector4(1, 0, 0, 1),
new Vector4( 1, -1, -1, 1), new Vector4(1, 0, 0, 1),
new Vector4(-1, -1, -1, 1), new Vector4(1, 0, 0, 1),
new Vector4(-1, 1, -1, 1), new Vector4(1, 0, 0, 1),
new Vector4( 1, 1, -1, 1), new Vector4(1, 0, 0, 1),
new Vector4(-1, -1, -1, 1), new Vector4(1, 0, 0, 1),
// Far
new Vector4(-1, -1, 1, 1), new Vector4(0, 1, 0, 1),
new Vector4( 1, -1, 1, 1), new Vector4(0, 1, 0, 1),
new Vector4( 1, 1, 1, 1), new Vector4(0, 1, 0, 1),
new Vector4( 1, 1, 1, 1), new Vector4(0, 1, 0, 1),
new Vector4(-1, 1, 1, 1), new Vector4(0, 1, 0, 1),
new Vector4(-1, -1, 1, 1), new Vector4(0, 1, 0, 1),
// Left
new Vector4(-1, 1, 1, 1), new Vector4(0, 0, 1, 1),
new Vector4(-1, 1, -1, 1), new Vector4(0, 0, 1, 1),
new Vector4(-1, -1, -1, 1), new Vector4(0, 0, 1, 1),
new Vector4(-1, -1, -1, 1), new Vector4(0, 0, 1, 1),
new Vector4(-1, -1, 1, 1), new Vector4(0, 0, 1, 1),
new Vector4(-1, 1, 1, 1), new Vector4(0, 0, 1, 1),
// Right
new Vector4( 1, -1, -1, 1), new Vector4(1, 1, 0, 1),
new Vector4( 1, 1, -1, 1), new Vector4(1, 1, 0, 1),
new Vector4( 1, 1, 1, 1), new Vector4(1, 1, 0, 1),
new Vector4( 1, 1, 1, 1), new Vector4(1, 1, 0, 1),
new Vector4( 1, -1, 1, 1), new Vector4(1, 1, 0, 1),
new Vector4( 1, -1, -1, 1), new Vector4(1, 1, 0, 1),
// Bottom
new Vector4(-1, -1, -1, 1), new Vector4(1, 0, 1, 1),
new Vector4( 1, -1, -1, 1), new Vector4(1, 0, 1, 1),
new Vector4( 1, -1, 1, 1), new Vector4(1, 0, 1, 1),
new Vector4( 1, -1, 1, 1), new Vector4(1, 0, 1, 1),
new Vector4(-1, -1, 1, 1), new Vector4(1, 0, 1, 1),
new Vector4(-1, -1, -1, 1), new Vector4(1, 0, 1, 1),
// Top
new Vector4( 1, 1, 1, 1), new Vector4(0, 1, 1, 1),
new Vector4( 1, 1, -1, 1), new Vector4(0, 1, 1, 1),
new Vector4(-1, 1, -1, 1), new Vector4(0, 1, 1, 1),
new Vector4(-1, 1, -1, 1), new Vector4(0, 1, 1, 1),
new Vector4(-1, 1, 1, 1), new Vector4(0, 1, 1, 1),
new Vector4( 1, 1, 1, 1), new Vector4(0, 1, 1, 1)
};
}
}
| |
/*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Amib.Threading;
using Dapper;
using SteamKit2;
namespace SteamDatabaseBackend
{
class DepotProcessor
{
public class ManifestJob
{
public uint ChangeNumber;
public uint DepotID;
public int BuildID;
public ulong ManifestID;
public string DepotName;
public string CDNToken;
public string Server;
public byte[] DepotKey;
public EResult Result = EResult.Fail;
public bool Anonymous;
}
private readonly CDNClient CDNClient;
private readonly List<string> CDNServers;
private readonly Dictionary<uint, byte> DepotLocks;
private string UpdateScript;
private SpinLock UpdateScriptLock;
private bool SaveLocalConfig;
public int DepotLocksCount
{
get
{
return DepotLocks.Count;
}
}
public DepotProcessor(SteamClient client, CallbackManager manager)
{
UpdateScript = Path.Combine(Application.Path, "files", "update.sh");
UpdateScriptLock = new SpinLock();
DepotLocks = new Dictionary<uint, byte>();
CDNClient = new CDNClient(client);
FileDownloader.SetCDNClient(CDNClient);
manager.Subscribe<SteamClient.ServerListCallback>(OnServerList);
CDNServers = new List<string>();
}
private void OnServerList(SteamClient.ServerListCallback callback)
{
var serverList = new List<CDNClient.Server>();
try
{
serverList = CDNClient.FetchServerList();
}
catch (Exception e)
{
Log.WriteError("Depot Downloader", "Exception retrieving server list: {0}", e.Message);
return;
}
foreach (var server in serverList)
{
if (server.Type == "CDN")
{
Log.WriteDebug("Depot Downloader", "Adding server as CDN: {0}", server.Host);
CDNServers.Add(server.Host);
}
}
}
public void Process(uint appID, uint changeNumber, KeyValue depots)
{
var requests = new List<ManifestJob>();
// Get data in format we want first
foreach (var depot in depots.Children)
{
// Ignore these for now, parent app should be updated too anyway
if (depot["depotfromapp"].Value != null)
{
continue;
}
var request = new ManifestJob
{
ChangeNumber = changeNumber,
DepotName = depot["name"].AsString()
};
// Ignore keys that aren't integers, for example "branches"
if (!uint.TryParse(depot.Name, out request.DepotID))
{
continue;
}
// TODO: instead of locking we could wait for current process to finish
if (DepotLocks.ContainsKey(request.DepotID))
{
continue;
}
// If there is no public manifest for this depot, it still could have some sort of open beta
if (depot["manifests"]["public"].Value == null || !ulong.TryParse(depot["manifests"]["public"].Value, out request.ManifestID))
{
var branch = depot["manifests"].Children.FirstOrDefault(x => x.Name != "local");
if (branch == null || !ulong.TryParse(branch.Value, out request.ManifestID))
{
using (var db = Database.GetConnection())
{
db.Execute("INSERT INTO `Depots` (`DepotID`, `Name`) VALUES (@DepotID, @DepotName) ON DUPLICATE KEY UPDATE `Name` = VALUES(`Name`)", new { request.DepotID, request.DepotName });
}
continue;
}
request.BuildID = branch["build"].AsInteger();
}
else
{
request.BuildID = depots["branches"]["public"]["buildid"].AsInteger();
}
requests.Add(request);
}
if (!requests.Any())
{
return;
}
var depotsToDownload = new List<ManifestJob>();
using (var db = Database.GetConnection())
{
var dbDepots = db.Query<Depot>("SELECT `DepotID`, `Name`, `BuildID`, `ManifestID`, `LastManifestID` FROM `Depots` WHERE `DepotID` IN @Depots", new { Depots = requests.Select(x => x.DepotID) })
.ToDictionary(x => x.DepotID, x => x);
foreach (var request in requests)
{
Depot dbDepot;
if (dbDepots.ContainsKey(request.DepotID))
{
dbDepot = dbDepots[request.DepotID];
if (dbDepot.BuildID > request.BuildID)
{
// buildid went back in time? this either means a rollback, or a shared depot that isn't synced properly
Log.WriteDebug("Depot Processor", "Skipping depot {0} due to old buildid: {1} > {2}", request.DepotID, dbDepot.BuildID, request.BuildID);
continue;
}
if (dbDepot.LastManifestID == request.ManifestID && dbDepot.ManifestID == request.ManifestID && Settings.Current.FullRun <= FullRunState.Normal)
{
// Update depot name if changed
if (!request.DepotName.Equals(dbDepot.Name))
{
db.Execute("UPDATE `Depots` SET `Name` = @DepotName WHERE `DepotID` = @DepotID", new { request.DepotID, request.DepotName });
}
continue;
}
}
else
{
dbDepot = new Depot();
}
if (dbDepot.BuildID != request.BuildID || dbDepot.ManifestID != request.ManifestID || !request.DepotName.Equals(dbDepot.Name))
{
db.Execute(@"INSERT INTO `Depots` (`DepotID`, `Name`, `BuildID`, `ManifestID`) VALUES (@DepotID, @DepotName, @BuildID, @ManifestID)
ON DUPLICATE KEY UPDATE `LastUpdated` = unix_timestamp(), `Name` = VALUES(`Name`), `BuildID` = VALUES(`BuildID`), `ManifestID` = VALUES(`ManifestID`)",
new {
request.DepotID,
request.DepotName,
request.BuildID,
request.ManifestID
});
}
if (dbDepot.ManifestID != request.ManifestID)
{
MakeHistory(db, request, string.Empty, "manifest_change", dbDepot.ManifestID, request.ManifestID);
}
var owned = LicenseList.OwnedApps.ContainsKey(request.DepotID);
if (!owned)
{
request.Anonymous = owned = LicenseList.AnonymousApps.ContainsKey(request.DepotID);
if (owned)
{
Log.WriteWarn("Depot Processor", "Will download depot {0} using anonymous account", request.DepotID);
}
}
if (owned || Settings.Current.FullRun == FullRunState.WithForcedDepots || Settings.Current.FullRun == FullRunState.ImportantOnly)
{
lock (DepotLocks)
{
// This doesn't really save us from concurrency issues
if (DepotLocks.ContainsKey(request.DepotID))
{
Log.WriteWarn("Depot Processor", "Depot {0} was locked in another thread", request.DepotID);
continue;
}
DepotLocks.Add(request.DepotID, 1);
}
depotsToDownload.Add(request);
}
#if DEBUG
else
{
Log.WriteDebug("Depot Processor", "Skipping depot {0} from app {1} because we don't own it", request.DepotID, appID);
}
#endif
}
}
if (depotsToDownload.Any())
{
PICSProductInfo.ProcessorThreadPool.QueueWorkItem(async () =>
{
try
{
await DownloadDepots(appID, depotsToDownload);
}
catch (Exception e)
{
ErrorReporter.Notify(e);
}
foreach (var depot in depotsToDownload)
{
RemoveLock(depot.DepotID);
}
});
}
}
private async Task<byte[]> GetDepotDecryptionKey(SteamApps instance, uint depotID, uint appID)
{
using (var db = Database.GetConnection())
{
var currentDecryptionKey = db.ExecuteScalar<string>("SELECT `Key` FROM `DepotsKeys` WHERE `DepotID` = @DepotID", new { depotID });
if (currentDecryptionKey != null)
{
return Utils.StringToByteArray(currentDecryptionKey);
}
}
var task = instance.GetDepotDecryptionKey(depotID, appID);
task.Timeout = TimeSpan.FromMinutes(15);
SteamApps.DepotKeyCallback callback;
try
{
callback = await task;
}
catch (TaskCanceledException)
{
Log.WriteError("Depot Processor", "Decryption key timed out for {0}", depotID);
return null;
}
if (callback.Result != EResult.OK)
{
if (callback.Result != EResult.AccessDenied)
{
Log.WriteError("Depot Processor", "No access to depot {0} ({1})", depotID, callback.Result);
}
return null;
}
Log.WriteDebug("Depot Downloader", "Got a new depot key for depot {0}", depotID);
using (var db = Database.GetConnection())
{
db.Execute("INSERT INTO `DepotsKeys` (`DepotID`, `Key`) VALUES (@DepotID, @Key) ON DUPLICATE KEY UPDATE `Key` = VALUES(`Key`)", new { depotID, Key = Utils.ByteArrayToString(callback.DepotKey) });
}
return callback.DepotKey;
}
private async Task<LocalConfig.CDNAuthToken> GetCDNAuthToken(SteamApps instance, uint appID, uint depotID)
{
if (LocalConfig.CDNAuthTokens.ContainsKey(depotID))
{
var token = LocalConfig.CDNAuthTokens[depotID];
if (DateTime.Now < token.Expiration)
{
return token;
}
#if DEBUG
Log.WriteDebug("Depot Downloader", "Token for depot {0} expired, will request a new one", depotID);
}
else
{
Log.WriteDebug("Depot Downloader", "Requesting a new token for depot {0}", depotID);
#endif
}
var newToken = new LocalConfig.CDNAuthToken
{
Server = GetContentServer()
};
var task = instance.GetCDNAuthToken(appID, depotID, newToken.Server);
task.Timeout = TimeSpan.FromMinutes(15);
SteamApps.CDNAuthTokenCallback tokenCallback;
try
{
tokenCallback = await task;
}
catch (TaskCanceledException)
{
Log.WriteError("Depot Processor", "CDN auth token timed out for {0}", depotID);
return null;
}
#if DEBUG
Log.WriteDebug("Depot Downloader", "Token for depot {0} result: {1}", depotID, tokenCallback.Result);
#endif
if (tokenCallback.Result != EResult.OK)
{
return null;
}
newToken.Token = tokenCallback.Token;
newToken.Expiration = tokenCallback.Expiration.Subtract(TimeSpan.FromMinutes(1));
LocalConfig.CDNAuthTokens[depotID] = newToken;
SaveLocalConfig = true;
return newToken;
}
private async Task DownloadDepots(uint appID, List<ManifestJob> depots)
{
Log.WriteDebug("Depot Downloader", "Will process {0} depots ({1} depot locks left)", depots.Count(), DepotLocks.Count);
var processTasks = new List<Task<EResult>>();
bool anyFilesDownloaded = false;
foreach (var depot in depots)
{
var instance = depot.Anonymous ? Steam.Anonymous.Apps : Steam.Instance.Apps;
depot.DepotKey = await GetDepotDecryptionKey(instance, depot.DepotID, appID);
if (depot.DepotKey == null)
{
RemoveLock(depot.DepotID);
continue;
}
var cdnToken = await GetCDNAuthToken(instance, appID, depot.DepotID);
if (cdnToken == null)
{
RemoveLock(depot.DepotID);
Log.WriteDebug("Depot Downloader", "Got a depot key for depot {0} but no cdn auth token", depot.DepotID);
continue;
}
depot.CDNToken = cdnToken.Token;
depot.Server = cdnToken.Server;
DepotManifest depotManifest = null;
string lastError = string.Empty;
for (var i = 0; i <= 5; i++)
{
try
{
depotManifest = CDNClient.DownloadManifest(depot.DepotID, depot.ManifestID, depot.Server, depot.CDNToken, depot.DepotKey);
break;
}
catch (Exception e)
{
Log.WriteWarn("Depot Downloader", "[{0}] Manifest download failed: {1} - {2}", depot.DepotID, e.GetType(), e.Message);
lastError = e.Message;
}
// TODO: get new auth key if auth fails
if (depotManifest == null)
{
await Task.Delay(Utils.ExponentionalBackoff(i));
}
}
if (depotManifest == null)
{
RemoveLock(depot.DepotID);
Log.WriteError("Depot Processor", "Failed to download depot manifest for app {0} depot {1} ({2}: {3})", appID, depot.DepotID, depot.Server, lastError);
if (FileDownloader.IsImportantDepot(depot.DepotID))
{
IRC.Instance.SendOps("{0}[{1}]{2} Failed to download app {3} depot {4} manifest ({5}: {6})",
Colors.OLIVE, Steam.GetAppName(appID), Colors.NORMAL, appID, depot.DepotID, depot.Server, lastError);
}
continue;
}
var task = TaskManager.Run(() =>
{
using (var db = Database.GetConnection())
{
using (var transaction = db.BeginTransaction())
{
var result = ProcessDepotAfterDownload(db, depot, depotManifest);
transaction.Commit();
return result;
}
}
});
processTasks.Add(task);
if (FileDownloader.IsImportantDepot(depot.DepotID))
{
task = TaskManager.Run(() =>
{
var result = FileDownloader.DownloadFilesFromDepot(appID, depot, depotManifest);
if (result == EResult.OK)
{
anyFilesDownloaded = true;
}
return result;
}, TaskCreationOptions.LongRunning);
TaskManager.RegisterErrorHandler(task);
processTasks.Add(task);
}
}
if (SaveLocalConfig)
{
SaveLocalConfig = false;
LocalConfig.Save();
}
await Task.WhenAll(processTasks);
Log.WriteDebug("Depot Downloader", "{0} depot downloads finished", depots.Count());
// TODO: use ContinueWith on tasks
if (!anyFilesDownloaded)
{
foreach (var depot in depots)
{
RemoveLock(depot.DepotID);
}
return;
}
if (!File.Exists(UpdateScript))
{
return;
}
bool lockTaken = false;
try
{
UpdateScriptLock.Enter(ref lockTaken);
foreach (var depot in depots)
{
if (depot.Result == EResult.OK)
{
RunUpdateScript(string.Format("{0} no-git", depot.DepotID));
}
RemoveLock(depot.DepotID);
}
// Only commit changes if all depots downloaded
if (processTasks.All(x => x.Result == EResult.OK || x.Result == EResult.Ignored))
{
if (!RunUpdateScript(appID))
{
RunUpdateScript("0");
}
}
else
{
Log.WriteDebug("Depot Processor", "Reprocessing the app {0} because some files failed to download", appID);
IRC.Instance.SendOps("{0}[{1}]{2} Reprocessing the app due to download failures",
Colors.OLIVE, Steam.GetAppName(appID), Colors.NORMAL
);
JobManager.AddJob(() => Steam.Instance.Apps.PICSGetAccessTokens(appID, null));
}
}
finally
{
if (lockTaken)
{
UpdateScriptLock.Exit();
}
}
}
private void RunUpdateScript(string arg)
{
var process = new System.Diagnostics.Process();
process.StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = UpdateScript,
Arguments = arg,
};
process.Start();
process.WaitForExit(120000);
}
private bool RunUpdateScript(uint appID)
{
var downloadFolder = FileDownloader.GetAppDownloadFolder(appID);
if (downloadFolder == null)
{
return false;
}
var updateScript = Path.Combine(Application.Path, "files", downloadFolder, "update.sh");
if(!File.Exists(updateScript))
{
return false;
}
var process = new System.Diagnostics.Process();
process.StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = updateScript
};
process.Start();
process.WaitForExit(120000);
return true;
}
private EResult ProcessDepotAfterDownload(IDbConnection db, ManifestJob request, DepotManifest depotManifest)
{
var filesOld = db.Query<DepotFile>("SELECT `ID`, `File`, `Hash`, `Size`, `Flags` FROM `DepotsFiles` WHERE `DepotID` = @DepotID", new { request.DepotID }).ToDictionary(x => x.File, x => x);
var filesNew = new List<DepotFile>();
var filesAdded = new List<DepotFile>();
var shouldHistorize = filesOld.Any(); // Don't historize file additions if we didn't have any data before
foreach (var file in depotManifest.Files)
{
var name = file.FileName.Replace('\\', '/');
// safe guard
if (name.Length > 255)
{
ErrorReporter.Notify(new OverflowException(string.Format("File \"{0}\" in depot {1} is too long", name, request.DepotID)));
continue;
}
var depotFile = new DepotFile
{
DepotID = request.DepotID,
File = name,
Size = file.TotalSize,
Flags = file.Flags
};
if (file.FileHash.Length > 0 && !file.Flags.HasFlag(EDepotFileFlag.Directory))
{
depotFile.Hash = Utils.ByteArrayToString(file.FileHash);
}
else
{
depotFile.Hash = "0000000000000000000000000000000000000000";
}
filesNew.Add(depotFile);
}
foreach (var file in filesNew)
{
if (filesOld.ContainsKey(file.File))
{
var oldFile = filesOld[file.File];
var updateFile = false;
if (oldFile.Size != file.Size || !file.Hash.Equals(oldFile.Hash))
{
MakeHistory(db, request, file.File, "modified", oldFile.Size, file.Size);
updateFile = true;
}
if (oldFile.Flags != file.Flags)
{
MakeHistory(db, request, file.File, "modified_flags", (ulong)oldFile.Flags, (ulong)file.Flags);
updateFile = true;
}
if (updateFile)
{
file.ID = oldFile.ID;
db.Execute("UPDATE `DepotsFiles` SET `Hash` = @Hash, `Size` = @Size, `Flags` = @Flags WHERE `DepotID` = @DepotID AND `ID` = @ID", file);
}
filesOld.Remove(file.File);
}
else
{
// We want to historize modifications first, and only then deletions and additions
filesAdded.Add(file);
}
}
if (filesOld.Any())
{
db.Execute("DELETE FROM `DepotsFiles` WHERE `DepotID` = @DepotID AND `ID` IN @Files", new { request.DepotID, Files = filesOld.Select(x => x.Value.ID) });
db.Execute(GetHistoryQuery(), filesOld.Select(x => new DepotHistory
{
DepotID = request.DepotID,
ChangeID = request.ChangeNumber,
Action = "removed",
File = x.Value.File
}));
}
if (filesAdded.Any())
{
db.Execute("INSERT INTO `DepotsFiles` (`DepotID`, `File`, `Hash`, `Size`, `Flags`) VALUES (@DepotID, @File, @Hash, @Size, @Flags)", filesAdded);
if (shouldHistorize)
{
db.Execute(GetHistoryQuery(), filesAdded.Select(x => new DepotHistory
{
DepotID = request.DepotID,
ChangeID = request.ChangeNumber,
Action = "added",
File = x.File
}));
}
}
db.Execute("UPDATE `Depots` SET `LastManifestID` = @ManifestID WHERE `DepotID` = @DepotID", new { request.DepotID, request.ManifestID });
return EResult.OK;
}
public static string GetHistoryQuery()
{
return "INSERT INTO `DepotsHistory` (`ChangeID`, `DepotID`, `File`, `Action`, `OldValue`, `NewValue`) VALUES (@ChangeID, @DepotID, @File, @Action, @OldValue, @NewValue)";
}
private static void MakeHistory(IDbConnection db, ManifestJob request, string file, string action, ulong oldValue = 0, ulong newValue = 0)
{
db.Execute(GetHistoryQuery(),
new DepotHistory
{
DepotID = request.DepotID,
ChangeID = request.ChangeNumber,
Action = action,
File = file,
OldValue = oldValue,
NewValue = newValue
}
);
}
private void RemoveLock(uint depotID)
{
lock (DepotLocks)
{
if (DepotLocks.Remove(depotID))
{
Log.WriteInfo("Depot Downloader", "Processed depot {0} ({1} depot locks left)", depotID, DepotLocks.Count);
}
}
}
private string GetContentServer()
{
var i = Utils.NextRandom(CDNServers.Count);
return CDNServers[i];
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class PythonProjectTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
public TestContext TestContext { get; set; }
[TestMethod, Priority(1)]
public void MergeRequirements() {
// Comments should be preserved, only package specs should change.
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(new[] {
"a # with a comment",
"B==0.2",
"# just a comment B==01234",
"",
"x < 1",
"d==1.0 e==2.0 f==3.0"
}, new[] {
"b==0.1",
"a==0.2",
"c==0.3",
"e==4.0",
"x==0.8"
}.Select(p => PackageSpec.FromRequirement(p)), false),
"a==0.2 # with a comment",
"b==0.1",
"# just a comment B==01234",
"",
"x==0.8",
"d==1.0 e==4.0 f==3.0"
);
// addNew is true, so the c==0.3 should be added.
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(new[] {
"a # with a comment",
"b==0.2",
"# just a comment B==01234"
}, new[] {
"B==0.1", // case is updated
"a==0.2",
"c==0.3"
}.Select(p => PackageSpec.FromRequirement(p)), true),
"a==0.2 # with a comment",
"B==0.1",
"# just a comment B==01234",
"c==0.3"
);
// No existing entries, so the new ones are sorted and returned.
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(null, new[] {
"b==0.2",
"a==0.1",
"c==0.3"
}.Select(p => PackageSpec.FromRequirement(p)), false),
"a==0.1",
"b==0.2",
"c==0.3"
);
// Check all the inequalities
const string inequalities = "<=|>=|<|>|!=|==";
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(
inequalities.Split('|').Select(s => "a " + s + " 1.2.3"),
new[] { "a==0" }.Select(p => PackageSpec.FromRequirement(p)),
false
),
inequalities.Split('|').Select(_ => "a==0").ToArray()
);
}
[TestMethod, Priority(1)]
public void MergeRequirementsMismatchedCase() {
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(new[] {
"aaaaaa==0.0",
"BbBbBb==0.1",
"CCCCCC==0.2"
}, new[] {
"aaaAAA==0.1",
"bbbBBB==0.2",
"cccCCC==0.3"
}.Select(p => PackageSpec.FromRequirement(p)), false),
"aaaAAA==0.1",
"bbbBBB==0.2",
"cccCCC==0.3"
);
// https://pytools.codeplex.com/workitem/2465
AssertUtil.AreEqual(
PythonProjectNode.MergeRequirements(new[] {
"Flask==0.10.1",
"itsdangerous==0.24",
"Jinja2==2.7.3",
"MarkupSafe==0.23",
"Werkzeug==0.9.6"
}, new[] {
"flask==0.10.1",
"itsdangerous==0.24",
"jinja2==2.7.3",
"markupsafe==0.23",
"werkzeug==0.9.6"
}.Select(p => PackageSpec.FromRequirement(p)), false),
"flask==0.10.1",
"itsdangerous==0.24",
"jinja2==2.7.3",
"markupsafe==0.23",
"werkzeug==0.9.6"
);
}
[TestMethod, Priority(1)]
public void FindRequirementsRegexTest() {
var r = PythonProjectNode.FindRequirementRegex;
AssertUtil.AreEqual(r.Matches("aaaa bbbb cccc").Cast<Match>().Select(m => m.Value),
"aaaa",
"bbbb",
"cccc"
);
AssertUtil.AreEqual(r.Matches("aaaa#a\r\nbbbb#b\r\ncccc#c\r\n").Cast<Match>().Select(m => m.Value),
"aaaa",
"bbbb",
"cccc"
);
AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast<Match>().Select(m => m.Value),
"a==1",
"b!=2",
"c<=3"
);
AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast<Match>().Select(m => m.Groups["name"].Value),
"a",
"b",
"c"
);
AssertUtil.AreEqual(r.Matches("a==1#a\r\nb!=2#b\r\nc<=3#c\r\n").Cast<Match>().Select(m => m.Value),
"a==1",
"b!=2",
"c<=3"
);
AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast<Match>().Select(m => m.Value),
"a == 1",
"b != 2",
"c <= 3"
);
AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast<Match>().Select(m => m.Groups["name"].Value),
"a",
"b",
"c"
);
AssertUtil.AreEqual(r.Matches("a -u b -f:x c").Cast<Match>().Select(m => m.Groups["name"].Value),
"a",
"b",
"c"
);
}
[TestMethod, Priority(1)]
public void UpdateWorkerRoleServiceDefinitionTest() {
var doc = new XmlDocument();
doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
<WorkerRole name=""PythonApplication1"" vmsize=""Small"" />
<WebRole name=""PythonApplication2"" />
</ServiceDefinition>");
PythonProjectNode.UpdateServiceDefinition(doc, "Worker", "PythonApplication1");
AssertUtil.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
<WorkerRole name=""PythonApplication1"" vmsize=""Small"">
<Startup>
<Task commandLine=""bin\ps.cmd ConfigureCloudService.ps1"" executionContext=""elevated"" taskType=""simple"">
<Environment>
<Variable name=""EMULATED"">
<RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
</Variable>
</Environment>
</Task>
</Startup>
<Runtime>
<Environment>
<Variable name=""EMULATED"">
<RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
</Variable>
</Environment>
<EntryPoint>
<ProgramEntryPoint commandLine=""bin\ps.cmd LaunchWorker.ps1 worker.py"" setReadyOnProcessStart=""true"" />
</EntryPoint>
</Runtime>
</WorkerRole>
<WebRole name=""PythonApplication2"" />
</ServiceDefinition>", doc);
}
[TestMethod, Priority(1)]
public void UpdateWebRoleServiceDefinitionTest() {
var doc = new XmlDocument();
doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
<WorkerRole name=""PythonApplication1"" vmsize=""Small"" />
<WebRole name=""PythonApplication2"" />
</ServiceDefinition>");
PythonProjectNode.UpdateServiceDefinition(doc, "Web", "PythonApplication2");
AssertUtil.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
<WorkerRole name=""PythonApplication1"" vmsize=""Small"" />
<WebRole name=""PythonApplication2"">
<Startup>
<Task commandLine=""ps.cmd ConfigureCloudService.ps1"" executionContext=""elevated"" taskType=""simple"">
<Environment>
<Variable name=""EMULATED"">
<RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
</Variable>
</Environment>
</Task>
</Startup>
</WebRole>
</ServiceDefinition>", doc);
}
[TestMethod, Priority(1)]
public void LoadAndUnloadModule() {
var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 3)) };
using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0])) {
var m1Path = TestData.GetPath("TestData\\SimpleImport\\module1.py");
var m2Path = TestData.GetPath("TestData\\SimpleImport\\module2.py");
var taskEntry1 = analyzer.AnalyzeFileAsync(m1Path);
var taskEntry2 = analyzer.AnalyzeFileAsync(m2Path);
taskEntry1.Wait(CancellationTokens.After5s);
taskEntry2.Wait(CancellationTokens.After5s);
var entry1 = taskEntry1.Result;
var entry2 = taskEntry2.Result;
var cancel = CancellationTokens.After60s;
analyzer.WaitForCompleteAnalysis(_ => !cancel.IsCancellationRequested);
cancel.ThrowIfCancellationRequested();
var loc = new Microsoft.PythonTools.Parsing.SourceLocation(0, 1, 1);
AssertUtil.ContainsExactly(
analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
"module2"
);
AssertUtil.ContainsExactly(
analyzer.GetValueDescriptions(entry2, "x", loc),
"int"
);
analyzer.UnloadFileAsync(entry1).Wait();
analyzer.WaitForCompleteAnalysis(_ => true);
// Even though module1 has been unloaded, we still know that
// module2 imports it.
AssertUtil.ContainsExactly(
analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
"module2"
);
AssertUtil.ContainsExactly(
analyzer.GetValueDescriptions(entry2, "x", loc)
);
analyzer.AnalyzeFileAsync(m1Path).Wait();
analyzer.WaitForCompleteAnalysis(_ => true);
AssertUtil.ContainsExactly(
analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
"module2"
);
AssertUtil.ContainsExactly(
analyzer.GetValueDescriptions(entry2, "x", loc),
"int"
);
}
}
[TestMethod, Priority(1)]
public void AnalyzeBadEgg() {
var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 4)) };
using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0])) {
analyzer.SetSearchPathsAsync(new[] { TestData.GetPath(@"TestData\BadEgg.egg") }).Wait();
analyzer.WaitForCompleteAnalysis(_ => true);
// Analysis result must contain the module for the filename inside the egg that is a valid identifier,
// and no entries for the other filename which is not.
var moduleNames = analyzer.GetModulesResult(true).Result.Select(x => x.Name);
AssertUtil.Contains(moduleNames, "module");
AssertUtil.DoesntContain(moduleNames, "42");
}
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.ReplacePropertyWithMethods;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplacePropertyWithMethods
{
public class ReplacePropertyWithMethodsTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ReplacePropertyWithMethodsCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetWithBody()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPublicProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { Prop = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToRef1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToOut1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUsedInAttribute1()
{
await TestInRegularAndScriptAsync(
@"using System;
class CAttribute : Attribute
{
public int [||]Prop
{
get
{
return 0;
}
}
}
[C(Prop = 1)]
class D
{
}",
@"using System;
class CAttribute : Attribute
{
public int GetProp()
{
return 0;
}
}
[C({|Conflict:Prop|} = 1)]
class D
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetWithBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetReference1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
void M()
{
this.Prop = 1;
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetterAccessibilityChange()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
private set
{
var v = value;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestIncrement1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop++;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDecrement2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop--;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() - 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveGet()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return this.Prop + 1;
}
}
}",
@"class C
{
private int GetProp()
{
return this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveSet()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
this.Prop = value + 1;
}
}
}",
@"class C
{
private void SetProp(int value)
{
this.SetProp(value + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x + y;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * (x + y));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestMissingAccessors()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { }
void M()
{
var v = this.Prop;
}
}",
@"class C
{
void M()
{
var v = this.GetProp();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedProp()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 1;
}",
@"class C
{
private int GetProp()
{
return 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTrivia()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 1; // Comment
}",
@"class C
{
private int GetProp()
{
return 1; // Comment
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Foo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}",
@"class C
{
private int GetFoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTriviaAfterArrow()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop => /* return 42 */ 42;
}",
@"class C
{
public int GetProp()
{
/* return 42 */
return 42;
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAbstractProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public abstract int [||]Prop { get; }
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public abstract int GetProp();
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestVirtualProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public virtual int [||]Prop
{
get
{
return 1;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public virtual int GetProp()
{
return 1;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestInterfaceProperty()
{
await TestInRegularAndScriptAsync(
@"interface I
{
int [||]Prop { get; }
}",
@"interface I
{
int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop++;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty3()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop *= x + y;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() * (x + y);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty4()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; } = 1;
}",
@"class C
{
private readonly int prop = 1;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty5()
{
await TestInRegularAndScriptAsync(
@"class C
{
private int prop;
public int [||]Prop { get; } = 1;
}",
@"class C
{
private int prop;
private readonly int prop1 = 1;
public int GetProp()
{
return prop1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty6()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]PascalCase { get; }
}",
@"class C
{
private readonly int pascalCase;
public int GetPascalCase()
{
return pascalCase;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public abstract int GetProp();
}",
@"class C
{
public int GetProp1()
{
return 0;
}
public abstract int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
set
{
}
}
public abstract void SetProp(int i);
}",
@"class C
{
public void SetProp1(int value)
{
}
public abstract void SetProp(int i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName3()
{
await TestInRegularAndScriptAsync(
@"class C
{
public object [||]Prop
{
set
{
}
}
public abstract void SetProp(dynamic i);
}",
@"class C
{
public void SetProp1(object value)
{
}
public abstract void SetProp(dynamic i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop++;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop++; /* Trailing */
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1); /* Trailing */
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop += 1 /* Trailing */ ;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1 /* Trailing */ );
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop = Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop *= Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() * (GetProp() + 1));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
[WorkItem(16157, "https://github.com/dotnet/roslyn/issues/16157")]
public async Task TestWithConditionalBinding1()
{
await TestInRegularAndScriptAsync(
@"public class Foo
{
public bool [||]Any { get; } // Replace 'Any' with method
public static void Bar()
{
var foo = new Foo();
bool f = foo?.Any == true;
}
}",
@"public class Foo
{
private readonly bool any;
public bool GetAny()
{
return any;
}
public static void Bar()
{
var foo = new Foo();
bool f = foo?.GetAny() == true;
}
}");
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
private int GetProp() => 0;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
throw e;
}
}
}",
@"class C
{
private int GetProp() => 0;
private void SetProp(int value) => throw e;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get => 0;
set => throw e;
}
}",
@"class C
{
private int GetProp() => 0;
private void SetProp(int value) => throw e;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 0;
}",
@"class C
{
private int GetProp() => 0;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle5()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; }
}",
@"class C
{
private readonly int prop;
private int GetProp() => prop;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle6()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
}",
@"class C
{
private int prop;
private int GetProp() => prop;
private void SetProp(int value) => prop = value;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle7()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
A();
return B();
}
}
}",
@"class C
{
private int GetProp()
{
A();
return B();
}
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
private IDictionary<OptionKey, object> PreferExpressionBodiedMethods =>
OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using XenAdmin.Controls;
using XenAdmin.Model;
using XenAdmin.Network;
using XenAdmin.Properties;
using XenAdmin.XenSearch;
using XenAPI;
using XenAdmin.Commands;
namespace XenAdmin.Dialogs
{
public partial class FolderChangeDialog : XenDialogBase
{
private readonly string orig_folder;
public FolderChangeDialog(string orig_folder)
: base(null)
{
this.orig_folder = orig_folder;
InitializeComponent();
ConnectionsManager.XenConnections.CollectionChanged += XenConnections_CollectionChanged;
XenConnections_CollectionChanged(null, null);
treeView.BeginUpdate();
treeView.ImageList = new ImageList();
treeView.ImageList.Images.Add("folder", Properties.Resources._000_Folder_open_h32bit_16); // if there is only one image, all nodes will get it
treeView.ImageList.ColorDepth = ColorDepth.Depth32Bit;
treeView.ImageList.TransparentColor = Color.Transparent;
treeView.expandOnDoubleClick = false;
InitState();
PopulateTree();
treeView.EndUpdate();
}
protected override void OnClosed(EventArgs e)
{
ConnectionsManager.XenConnections.CollectionChanged -= XenConnections_CollectionChanged;
foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy)
connection.Cache.DeregisterBatchCollectionChanged<Folder>(foldersChanged);
}
private void EmptyTree()
{
treeView.Nodes.Clear();
}
private void PopulateTree()
{
VirtualTreeNode selectedNode = treeView.SelectedNode;
Folder selectedFolder = selectedNode==null?null: selectedNode.Tag as Folder;
EmptyTree();
TreeNodeGroupAcceptor tnga = new TreeNodeGroupAcceptor(treeView, true);
Search.SearchForAllFolders().PopulateAdapters(tnga);
if (selectedFolder != null)
{
// try the one we were on: if that's no longer present, back off to the one we started with
if (!SelectNode(selectedFolder.opaque_ref))
{
string folder = orig_folder;
SelectNode(folder);
}
}
else
SelectNode(null);
}
private void InitState()
{
SelectNode(orig_folder);
if (orig_folder == "")
{
radioButtonNone.Checked = true;
}
else
{
radioButtonChoose.Checked = true;
ActiveControl = treeView;
}
}
// Select the named node. If found it, return true.
// If not, select the first node (if there are any) and return false.
private bool SelectNode(string tag)
{
VirtualTreeNode node = FindNode(tag);
if (node != null)
{
treeView.SelectedNode = node;
return true;
}
else if (treeView.Nodes.Count != 0)
treeView.SelectedNode = treeView.Nodes[0];
return false;
}
private void XenConnections_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy)
connection.Cache.RegisterBatchCollectionChanged<Folder>(foldersChanged);
}
private void foldersChanged(object sender, EventArgs e)
{
PopulateTree();
}
private VirtualTreeNode FindNode(string tag)
{
foreach (VirtualTreeNode node in treeView.Nodes)
{
VirtualTreeNode found = FindNode(tag, node);
if (found != null)
return found;
}
return null;
}
private VirtualTreeNode FindNode(string tag, VirtualTreeNode node)
{
Folder folder = node.Tag as Folder;
if (folder != null && folder.opaque_ref == tag)
return node;
foreach (VirtualTreeNode subNode in node.Nodes)
{
VirtualTreeNode found = FindNode(tag, subNode);
if (found != null)
return found;
}
return null;
}
public Folder CurrentFolder
{
get
{
if (radioButtonChoose.Checked && treeView.SelectedNode != null)
return treeView.SelectedNode.Tag as Folder;
else
return null;
}
}
public bool FolderChanged
{
get
{
Folder folder = CurrentFolder;
string folderName = (folder == null ? String.Empty : folder.opaque_ref);
return (orig_folder != folderName);
}
}
private void EnableTreeView(bool enabled)
{
treeView.Enabled = enabled;
newButton.Enabled = enabled;
}
private void SetOKButtonEnablement()
{
okButton.Enabled = FolderChanged;
}
private void radioButtonNone_Click(object sender, EventArgs e)
{
EnableTreeView(false);
SetOKButtonEnablement();
}
private void radioButtonChoose_Click(object sender, EventArgs e)
{
EnableTreeView(true);
SetOKButtonEnablement();
}
private void okButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void newButton_Click(object sender, EventArgs e)
{
new NewFolderCommand(Program.MainWindow, null, this).Execute();
}
private void newMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item == null)
return;
Folder folder = item.Tag as Folder;
if (folder == null)
return;
new NewFolderCommand(Program.MainWindow, folder, this).Execute();
}
private void treeView_NodeMouseClick(object sender, VirtualTreeNodeMouseClickEventArgs e)
{
if (e.Button != MouseButtons.Right || e.Node == null)
return;
Folder folder = e.Node.Tag as Folder;
if (folder == null)
return;
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem item = new ToolStripMenuItem(Messages.NEW_FOLDER, Resources._000_Folder_open_h32bit_16, newMenuItem_Click);
item.Tag = folder;
menu.Items.Add(item);
menu.Show(treeView, e.Location);
}
private void treeView_AfterSelect(object sender, VirtualTreeViewEventArgs e)
{
SetOKButtonEnablement();
}
private void treeView_NodeMouseDoubleClick(object sender, VirtualTreeNodeMouseClickEventArgs e)
{
if (okButton.Enabled)
okButton_Click(sender, null);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
#if false
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Research.Dryad.ProcessService
{
internal class Cache
{
// Callback object for appends to IDFs, implemented by the writer classes
internal interface IAppendCompletion
{
// Cache calls Success once the append has been accepted. If the cache
// is throttling writes, Success will not be called until the throttle
// has unblocked, so this is the mechanism for throttling and
// writers need to wait for it.
void Success();
// Cache calls Fail if there is an error, typically either because the entry
// doesn't exist, or because there was a spill write error.
void Fail(string errorString);
}
private class CacheBlock
{
// data bytes corresponding to a block of an Intermediate Data File (IDF)
public byte[] data;
// prefix of bytes in the array that are valid data
public Int64 validLength;
// offset into the IDF where the block begins
public Int64 offset;
// linked list pointer
public CacheBlock next;
public CacheBlock(Int64 size)
{
data = new byte[size];
}
}
private class FreeList
{
// size of blocks in that we are cacheing
public Int64 blockSize;
// head of the list of unused cache blocks
public CacheBlock head;
public FreeList(Int64 size)
{
blockSize = size;
}
}
private class CacheEntry
{
// total length of the IDF being cached
Int64 length;
// linked list of blocks corresponding to the IDF if it is held in memory,
// null otherwise. These are freed as the file is read, so in general
// correspond to a suffix of the file
CacheBlock blockHead;
CacheBlock blockTail;
// name of the spill file if the IDF has been partially or completely spilled to disk, null otherwise
string fileName;
// offset in the disk file where this IDF begins
Int64 fileOffset;
// the file may only have a suffix spilled to disk, and may be in the process
// of being spilled. The range of bytes of the IDF that can be read from the file
// is [fileDataStart,fileDataStart+fileDataWritten). If there are bytes that have
// not yet been written then they should still be present as blocks in the blockList.
Int64 fileDataStart;
Int64 fileDataWritten;
// flag indicating if a spilling write is currently in progress, i.e. whether or not
// there is a region of the spill file beyond fileDataWritten that is in use
bool writingFile;
public bool InMemory { get { return (fileName == null); } }
// Add data to the current cache entry, using blocks from freeList if possible and allocating
// new blocks otherwise
public Task AppendInMemory(System.IO.Stream data, Int64 offset, Int64 dataLength, FreeList freeList)
{
Task<Int64> finalTask = null;
Int64 stashed = 0;
// we are willing to use a block from the free list if it's going to be at least 90%
// full, i.e. data*10 >= blockSize*9
Int64 blockSizeX9 = freeList.blockSize * 9;
if (offset != length)
{
throw new InvalidOperationException("Offset " + offset + " does not match current length " + length);
}
if (fileName != null)
{
throw new InvalidOperationException("Can't append in memory since already spilling");
}
while (stashed < dataLength)
{
CacheBlock b = null;
Int64 needed = dataLength - stashed;
Int64 neededX10 = needed * 10;
bool largeEnough = (neededX10 >= blockSizeX9);
if (largeEnough) // we aren't dealing with a small data fragment
{
lock (freeList)
{
if (freeList.head != null)
{
// Remove a block from the free list
b = freeList.head;
freeList.head = b.next;
}
}
if (b == null) // The list was empty so make a new block
{
b = new CacheBlock(freeList.blockSize);
}
}
else // we are dealing with a small data fragment
{
b = new CacheBlock(needed);
}
// Add the block to the tail of the cache entry
if (blockHead == null)
{
blockHead = b;
blockTail = b;
}
else
{
blockTail.next = b;
blockTail = b;
}
b.next = null;
if (finalTask == null)
{
finalTask = Task<Int64>.Factory.StartNew((obj) =>
{
var cb = (CacheBlock)obj;
Int64 nRead = data.ReadAsync(cb.data, 0, cb.data.Length).Result;
cb.validLength = nRead;
return nRead;
},
b,
TaskCreationOptions.AttachedToParent);
}
else
{
finalTask = finalTask.ContinueWith<Int64>((previousTask, obj) =>
{
var cb = (CacheBlock)obj;
Int64 nRead = data.ReadAsync(cb.data, 0, cb.data.Length).Result;
cb.validLength = nRead;
return previousTask.Result + nRead;
},
b,
TaskContinuationOptions.AttachedToParent);
}
Int64 toCopy = Math.Max(b.data.LongLength, needed);
stashed += toCopy;
}
return finalTask.ContinueWith(previousTask => length += previousTask.Result);
}
public Task AppendSpilling(System.IO.Stream data, Int64 offset)
{
return Task.Factory.StartNew(() => { });
}
}
private class Entries
{
// all entries currently being managed. key is the URI by which an entry is referenced
public Dictionary<string, CacheEntry> data;
// total size of data cached in RAM
public Int64 cachedDataSize;
public Entries()
{
data = new Dictionary<string, CacheEntry>();
}
}
// the dictionary of IDFs being cached, either in RAM or spill files
Entries entries;
// size below which it is permitted to cache more data
Int64 cacheHighWatermark;
// size to spill down to when spilling is required
Int64 cacheLowWatermark;
// all active spill files. The key is the filename, the value is a reference count of the
// number of active IDFs in the spill file
Dictionary<string, int> spillFile;
// free list of unused cache blocks
FreeList freeList;
public Cache(Int64 lowWaterMark, Int64 highWaterMark, Int64 blockSize)
{
entries = new Entries();
spillFile = new Dictionary<string, int>();
cacheLowWatermark = lowWaterMark;
cacheHighWatermark = highWaterMark;
freeList = new FreeList(blockSize);
}
public bool CreateEntry(string name)
{
CacheEntry e = new CacheEntry();
lock (entries)
{
if (entries.data.ContainsKey(name))
{
return false;
}
else
{
entries.data.Add(name, e);
return true;
}
}
}
public Task AppendEntry(string name, System.IO.Stream data, Int64 offset, Int64 length)
{
bool spaceExists = false;
CacheEntry e = null;
lock (entries)
{
bool exists = entries.data.TryGetValue(name, out e);
if (exists)
{
lock (e)
{
if (e.InMemory && entries.cachedDataSize + length <= cacheHighWatermark)
{
entries.cachedDataSize += length;
spaceExists = true;
}
}
}
}
if (e != null) // the cache entry existed
{
lock (e)
{
if (spaceExists) // there's enough space to cache it
{
return e.AppendInMemory(data, offset, length, freeList);
}
else
{
return e.AppendSpilling(data, offset);
}
}
}
else
{
throw new InvalidOperationException("Can't append to unknown IDF " + name);
}
}
}
}
#endif
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// Generates Aztec 2D barcodes.
/// </summary>
/// <author>Rustam Abdullaev</author>
public static class Encoder
{
public const int DEFAULT_EC_PERCENT = 33; // default minimal percentage of error check words
public const int DEFAULT_AZTEC_LAYERS = 0;
private const int MAX_NB_BITS = 32;
private const int MAX_NB_BITS_COMPACT = 4;
private static readonly int[] WORD_SIZE = {
4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12
};
/// <summary>
/// Encodes the given binary content as an Aztec symbol
/// </summary>
/// <param name="data">input data string</param>
/// <returns>Aztec symbol matrix with metadata</returns>
public static AztecCode encode(byte[] data)
{
return encode(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS);
}
/// <summary>
/// Encodes the given binary content as an Aztec symbol
/// </summary>
/// <param name="data">input data string</param>
/// <param name="minECCPercent">minimal percentage of error check words (According to ISO/IEC 24778:2008,
/// a minimum of 23% + 3 words is recommended)</param>
/// <param name="userSpecifiedLayers">if non-zero, a user-specified value for the number of layers</param>
/// <returns>
/// Aztec symbol matrix with metadata
/// </returns>
public static AztecCode encode(byte[] data, int minECCPercent, int userSpecifiedLayers)
{
// High-level encode
var bits = new HighLevelEncoder(data).encode();
// stuff bits and choose symbol size
int eccBits = bits.Size*minECCPercent/100 + 11;
int totalSizeBits = bits.Size + eccBits;
bool compact;
int layers;
int totalBitsInLayer;
int wordSize;
BitArray stuffedBits;
if (userSpecifiedLayers != DEFAULT_AZTEC_LAYERS)
{
compact = userSpecifiedLayers < 0;
layers = Math.Abs(userSpecifiedLayers);
if (layers > (compact ? MAX_NB_BITS_COMPACT : MAX_NB_BITS))
{
throw new ArgumentException(
String.Format("Illegal value {0} for layers", userSpecifiedLayers));
}
totalBitsInLayer = TotalBitsInLayer(layers, compact);
wordSize = WORD_SIZE[layers];
int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer%wordSize);
stuffedBits = stuffBits(bits, wordSize);
if (stuffedBits.Size + eccBits > usableBitsInLayers)
{
throw new ArgumentException("Data to large for user specified layer");
}
if (compact && stuffedBits.Size > wordSize*64)
{
// Compact format only allows 64 data words, though C4 can hold more words than that
throw new ArgumentException("Data to large for user specified layer");
}
}
else
{
wordSize = 0;
stuffedBits = null;
// We look at the possible table sizes in the order Compact1, Compact2, Compact3,
// Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1)
// is the same size, but has more data.
for (int i = 0;; i++)
{
if (i > MAX_NB_BITS)
{
throw new ArgumentException("Data too large for an Aztec code");
}
compact = i <= 3;
layers = compact ? i + 1 : i;
totalBitsInLayer = TotalBitsInLayer(layers, compact);
if (totalSizeBits > totalBitsInLayer)
{
continue;
}
// [Re]stuff the bits if this is the first opportunity, or if the
// wordSize has changed
if (wordSize != WORD_SIZE[layers])
{
wordSize = WORD_SIZE[layers];
stuffedBits = stuffBits(bits, wordSize);
}
if (stuffedBits == null)
{
continue;
}
int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer%wordSize);
if (compact && stuffedBits.Size > wordSize*64)
{
// Compact format only allows 64 data words, though C4 can hold more words than that
continue;
}
if (stuffedBits.Size + eccBits <= usableBitsInLayers)
{
break;
}
}
}
BitArray messageBits = generateCheckWords(stuffedBits, totalBitsInLayer, wordSize);
// generate mode message
int messageSizeInWords = stuffedBits.Size / wordSize;
var modeMessage = generateModeMessage(compact, layers, messageSizeInWords);
// allocate symbol
int baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines
var alignmentMap = new int[baseMatrixSize];
int matrixSize;
if (compact)
{
// no alignment marks in compact mode, alignmentMap is a no-op
matrixSize = baseMatrixSize;
for (int i = 0; i < alignmentMap.Length; i++)
{
alignmentMap[i] = i;
}
}
else
{
matrixSize = baseMatrixSize + 1 + 2*((baseMatrixSize/2 - 1)/15);
int origCenter = baseMatrixSize/2;
int center = matrixSize/2;
for (int i = 0; i < origCenter; i++)
{
int newOffset = i + i/15;
alignmentMap[origCenter - i - 1] = center - newOffset - 1;
alignmentMap[origCenter + i] = center + newOffset + 1;
}
}
var matrix = new BitMatrix(matrixSize);
// draw data bits
for (int i = 0, rowOffset = 0; i < layers; i++)
{
int rowSize = (layers - i) * 4 + (compact ? 9 : 12);
for (int j = 0; j < rowSize; j++)
{
int columnOffset = j*2;
for (int k = 0; k < 2; k++)
{
if (messageBits[rowOffset + columnOffset + k])
{
matrix[alignmentMap[i*2 + k], alignmentMap[i*2 + j]] = true;
}
if (messageBits[rowOffset + rowSize*2 + columnOffset + k])
{
matrix[alignmentMap[i*2 + j], alignmentMap[baseMatrixSize - 1 - i*2 - k]] = true;
}
if (messageBits[rowOffset + rowSize*4 + columnOffset + k])
{
matrix[alignmentMap[baseMatrixSize - 1 - i*2 - k], alignmentMap[baseMatrixSize - 1 - i*2 - j]] = true;
}
if (messageBits[rowOffset + rowSize*6 + columnOffset + k])
{
matrix[alignmentMap[baseMatrixSize - 1 - i*2 - j], alignmentMap[i*2 + k]] = true;
}
}
}
rowOffset += rowSize*8;
}
// draw mode message
drawModeMessage(matrix, compact, matrixSize, modeMessage);
// draw alignment marks
if (compact)
{
drawBullsEye(matrix, matrixSize/2, 5);
}
else
{
drawBullsEye(matrix, matrixSize/2, 7);
for (int i = 0, j = 0; i < baseMatrixSize/2 - 1; i += 15, j += 16)
{
for (int k = (matrixSize/2) & 1; k < matrixSize; k += 2)
{
matrix[matrixSize/2 - j, k] = true;
matrix[matrixSize/2 + j, k] = true;
matrix[k, matrixSize/2 - j] = true;
matrix[k, matrixSize/2 + j] = true;
}
}
}
return new AztecCode
{
isCompact = compact,
Size = matrixSize,
Layers = layers,
CodeWords = messageSizeInWords,
Matrix = matrix
};
}
private static void drawBullsEye(BitMatrix matrix, int center, int size)
{
for (var i = 0; i < size; i += 2)
{
for (var j = center - i; j <= center + i; j++)
{
matrix[j, center - i] = true;
matrix[j, center + i] = true;
matrix[center - i, j] = true;
matrix[center + i, j] = true;
}
}
matrix[center - size, center - size] = true;
matrix[center - size + 1, center - size] = true;
matrix[center - size, center - size + 1] = true;
matrix[center + size, center - size] = true;
matrix[center + size, center - size + 1] = true;
matrix[center + size, center + size - 1] = true;
}
internal static BitArray generateModeMessage(bool compact, int layers, int messageSizeInWords)
{
var modeMessage = new BitArray();
if (compact)
{
modeMessage.appendBits(layers - 1, 2);
modeMessage.appendBits(messageSizeInWords - 1, 6);
modeMessage = generateCheckWords(modeMessage, 28, 4);
}
else
{
modeMessage.appendBits(layers - 1, 5);
modeMessage.appendBits(messageSizeInWords - 1, 11);
modeMessage = generateCheckWords(modeMessage, 40, 4);
}
return modeMessage;
}
private static void drawModeMessage(BitMatrix matrix, bool compact, int matrixSize, BitArray modeMessage)
{
int center = matrixSize / 2;
if (compact)
{
for (var i = 0; i < 7; i++)
{
int offset = center - 3 + i;
if (modeMessage[i])
{
matrix[offset, center - 5] = true;
}
if (modeMessage[i + 7])
{
matrix[center + 5, offset] = true;
}
if (modeMessage[20 - i])
{
matrix[offset, center + 5] = true;
}
if (modeMessage[27 - i])
{
matrix[center - 5, offset] = true;
}
}
}
else
{
for (var i = 0; i < 10; i++)
{
int offset = center - 5 + i + i / 5;
if (modeMessage[i])
{
matrix[offset, center - 7] = true;
}
if (modeMessage[i + 10])
{
matrix[center + 7, offset] = true;
}
if (modeMessage[29 - i])
{
matrix[offset, center + 7] = true;
}
if (modeMessage[39 - i])
{
matrix[center - 7, offset] = true;
}
}
}
}
private static BitArray generateCheckWords(BitArray bitArray, int totalBits, int wordSize)
{
if (bitArray.Size % wordSize != 0)
throw new InvalidOperationException("size of bit array is not a multiple of the word size");
// bitArray is guaranteed to be a multiple of the wordSize, so no padding needed
int messageSizeInWords = bitArray.Size / wordSize;
var rs = new ReedSolomonEncoder(getGF(wordSize));
var totalWords = totalBits / wordSize;
var messageWords = bitsToWords(bitArray, wordSize, totalWords);
rs.encode(messageWords, totalWords - messageSizeInWords);
var startPad = totalBits % wordSize;
var messageBits = new BitArray();
messageBits.appendBits(0, startPad);
foreach (var messageWord in messageWords)
{
messageBits.appendBits(messageWord, wordSize);
}
return messageBits;
}
private static int[] bitsToWords(BitArray stuffedBits, int wordSize, int totalWords)
{
var message = new int[totalWords];
int i;
int n;
for (i = 0, n = stuffedBits.Size / wordSize; i < n; i++)
{
int value = 0;
for (int j = 0; j < wordSize; j++)
{
value |= stuffedBits[i * wordSize + j] ? (1 << wordSize - j - 1) : 0;
}
message[i] = value;
}
return message;
}
private static GenericGF getGF(int wordSize)
{
switch (wordSize)
{
case 4:
return GenericGF.AZTEC_PARAM;
case 6:
return GenericGF.AZTEC_DATA_6;
case 8:
return GenericGF.AZTEC_DATA_8;
case 10:
return GenericGF.AZTEC_DATA_10;
case 12:
return GenericGF.AZTEC_DATA_12;
default:
throw new ArgumentException("Unsupported word size " + wordSize);
}
}
internal static BitArray stuffBits(BitArray bits, int wordSize)
{
var @out = new BitArray();
int n = bits.Size;
int mask = (1 << wordSize) - 2;
for (int i = 0; i < n; i += wordSize)
{
int word = 0;
for (int j = 0; j < wordSize; j++)
{
if (i + j >= n || bits[i + j])
{
word |= 1 << (wordSize - 1 - j);
}
}
if ((word & mask) == mask)
{
@out.appendBits(word & mask, wordSize);
i--;
}
else if ((word & mask) == 0)
{
@out.appendBits(word | 1, wordSize);
i--;
}
else
{
@out.appendBits(word, wordSize);
}
}
return @out;
}
private static int TotalBitsInLayer(int layers, bool compact)
{
return ((compact ? 88 : 112) + 16 * layers) * layers;
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Helpers;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Contacts module
/// </summary>
public partial class Contacts : PortalModuleControl
{
/// <summary>
///
/// </summary>
protected DataView myDataView;
/// <summary>
///
/// </summary>
protected string sortField;
/// <summary>
///
/// </summary>
protected string sortDirection;
/// <summary>
/// The Page_Load event handler on this User Control is used to
/// obtain a DataReader of contact information from the Contacts
/// table, and then databind the results to a DataGrid
/// server control. It uses the Rainbow.ContactsDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
//MH: Added 01/10/2003 [mario@hartmann.net]
//set visibility of the columns
myDataGrid.Columns[3].Visible = (Settings["SHOW_COLUMN_EMAIL"] != null)
? bool.Parse(Settings["SHOW_COLUMN_EMAIL"].ToString())
: true;
myDataGrid.Columns[4].Visible = (Settings["SHOW_COLUMN_CONTACT1"] != null)
? bool.Parse(Settings["SHOW_COLUMN_CONTACT1"].ToString())
: true;
myDataGrid.Columns[5].Visible = (Settings["SHOW_COLUMN_CONTACT2"] != null)
? bool.Parse(Settings["SHOW_COLUMN_CONTACT2"].ToString())
: true;
myDataGrid.Columns[6].Visible = (Settings["SHOW_COLUMN_FAX"] != null)
? bool.Parse(Settings["SHOW_COLUMN_FAX"].ToString())
: true;
myDataGrid.Columns[7].Visible = (Settings["SHOW_COLUMN_ADDRESS"] != null)
? bool.Parse(Settings["SHOW_COLUMN_ADDRESS"].ToString())
: true;
//MH: End
if (Page.IsPostBack == false)
{
sortField = "Name";
sortDirection = "ASC";
if (sortField == "DueDate")
sortDirection = "DESC";
ViewState["SortField"] = sortField;
ViewState["SortDirection"] = sortDirection;
}
else
{
sortField = (string) ViewState["SortField"];
sortDirection = (string) ViewState["sortDirection"];
}
myDataView = new DataView();
// Obtain contact information from Contacts table
// and bind to the DataGrid Control
ContactsDB contacts = new ContactsDB();
DataSet contactData = contacts.GetContacts(ModuleID, Version);
myDataView = contactData.Tables[0].DefaultView;
if (!Page.IsPostBack)
myDataView.Sort = sortField + " " + sortDirection;
BindGrid();
}
/// <summary>
/// Binds the grid.
/// </summary>
protected void BindGrid()
{
myDataGrid.DataSource = myDataView;
myDataGrid.DataBind();
}
/// <summary>
/// Construcotor - set module settings
/// </summary>
public Contacts()
{
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
int groupBase = (int) group;
// end of modification
// Change by Geert.Audenaert@Syntegra.Com
// Date: 27/2/2003
SupportsWorkflow = true;
// End Change Geert.Audenaert@Syntegra.Com
//MH: Added 01/10/2003 [mario@hartmann.net]
// Hiding the Email, Contact1 and/or Contact2 Column
SettingItem setItem = new SettingItem(new BooleanDataType());
setItem.Value = "True";
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
// setItem.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// setItem.Order = 1;
setItem.Group = group;
setItem.Order = groupBase + 20;
// end of modification
setItem.Description = "Switch for displaying the email column or not.";
_baseSettings.Add("SHOW_COLUMN_EMAIL", setItem);
setItem = new SettingItem(new BooleanDataType());
setItem.Value = "True";
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
// setItem.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// setItem.Order = 1;
setItem.Group = group;
setItem.Order = groupBase + 25;
// end of modification
setItem.Description = "Switch for displaying the contact1 column or not.";
_baseSettings.Add("SHOW_COLUMN_CONTACT1", setItem);
setItem = new SettingItem(new BooleanDataType());
setItem.Value = "True";
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
// setItem.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// setItem.Order = 2;
setItem.Group = group;
setItem.Order = groupBase + 30;
// end of modification
setItem.Description = "Switch for displaying the contact2 column or not.";
_baseSettings.Add("SHOW_COLUMN_CONTACT2", setItem);
//MH: End
setItem = new SettingItem(new BooleanDataType());
setItem.Value = "True";
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
// setItem.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// setItem.Order = 3;
setItem.Group = group;
setItem.Order = groupBase + 35;
// end of modification
setItem.Description = "Switch for displaying the Fax column or not.";
_baseSettings.Add("SHOW_COLUMN_FAX", setItem);
setItem = new SettingItem(new BooleanDataType());
setItem.Value = "True";
// Modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
// setItem.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// setItem.Order = 4;
setItem.Group = group;
setItem.Order = groupBase + 40;
// end of modification
setItem.Description = "Switch for displaying the Address column or not.";
_baseSettings.Add("SHOW_COLUMN_ADDRESS", setItem);
}
#region Global Implementation
/// <summary>
/// GuidID
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{2502DB18-B580-4F90-8CB4-C15E6E5339EF}"); }
}
#region Search Implementation
/// <summary>
/// Searchable module
/// </summary>
/// <value></value>
public override bool Searchable
{
get { return true; }
}
/// <summary>
/// Searchable module implementation
/// </summary>
/// <param name="portalID">The portal ID</param>
/// <param name="userID">ID of the user is searching</param>
/// <param name="searchString">The text to search</param>
/// <param name="searchField">The fields where perfoming the search</param>
/// <returns>
/// The SELECT sql to perform a search on the current module
/// </returns>
public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField)
{
// Parameters:
// Table Name: the table that holds the data
// Title field: the field that contains the title for result, must be a field in the table
// Abstract field: the field that contains the text for result, must be a field in the table
// Search field: pass the searchField parameter you recieve.
SearchDefinition s =
new SearchDefinition("rb_Contacts", "Role", "Name", "CreatedByUser", "CreatedDate", searchField);
//Add extra search fields here, this way
s.ArrSearchFields.Add("itm.Email");
s.ArrSearchFields.Add("itm.Contact1");
s.ArrSearchFields.Add("itm.Contact2");
// Builds and returns the SELECT query
return s.SearchSqlSelect(portalID, userID, searchString);
}
#endregion
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
# endregion
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.myDataGrid.SortCommand += new DataGridSortCommandEventHandler(this.myDataGrid_SortCommand);
this.Load += new EventHandler(this.Page_Load);
// Create a new Title the control
// ModuleTitle = new DesktopModuleTitle();
// Set here title properties
// Add support for the edit page
this.AddText = "CONTACTS_ADD";
this.AddUrl = "~/DesktopModules/CommunityModules/Contacts/ContactsEdit.aspx";
// Add title ad the very beginnig of
// the control's controls collection
// Controls.AddAt(0, ModuleTitle);
base.OnInit(e);
}
#endregion
/// <summary>
/// Handles the SortCommand event of the myDataGrid control.
/// </summary>
/// <param name="source">The source of the event.</param>
/// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridSortCommandEventArgs"/> instance containing the event data.</param>
private void myDataGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
if (sortField == e.SortExpression)
{
if (sortDirection == "ASC")
sortDirection = "DESC";
else
sortDirection = "ASC";
}
ViewState["SortField"] = e.SortExpression;
ViewState["sortDirection"] = sortDirection;
myDataView.Sort = e.SortExpression + " " + sortDirection;
BindGrid();
}
}
}
| |
/*
Copyright (c) 2011 Microsoft Corporation. All rights reserved.
Use of this sample source code is subject to the terms of the Microsoft license
agreement under which you licensed this sample source code and is provided AS-IS.
If you did not accept the terms of the license agreement, you are not authorized
to use this sample source code. For the terms of the license, please see the
license agreement between you and Microsoft.
To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604
*/
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace LocalDatabaseSample.Model
{
public class ToDoDataContext : DataContext
{
// Pass the connection string to the base class.
public ToDoDataContext(string connectionString)
: base(connectionString)
{ }
// Specify a table for the to-do items.
public Table<ToDoItem> Items;
// Specify a table for the categories.
public Table<ToDoCategory> Categories;
}
[Table]
public class ToDoItem : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private int _toDoItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ToDoItemId
{
get { return _toDoItemId; }
set
{
if (_toDoItemId != value)
{
NotifyPropertyChanging("ToDoItemId");
_toDoItemId = value;
NotifyPropertyChanged("ToDoItemId");
}
}
}
// Define item name: private field, public property, and database column.
private string _itemName;
[Column]
public string ItemName
{
get { return _itemName; }
set
{
if (_itemName != value)
{
NotifyPropertyChanging("ItemName");
_itemName = value;
NotifyPropertyChanged("ItemName");
}
}
}
[Column]
public string Background
{
get { return _background; }
set
{
if (_background != value)
{
NotifyPropertyChanging("Background");
_background = value;
NotifyPropertyChanged("Background");
}
}
}
private string _background = "Transparent";
[Column]
public string Foreground
{
get { return _foreground; }
set {
if (_foreground != value)
{
NotifyPropertyChanging("Foreground");
_foreground = value;
NotifyPropertyChanged("Foreground");
}
}
}
private string _foreground = "White";
// Define completion value: private field, public property, and database column.
private bool _isComplete;
[Column]
public bool IsComplete
{
get { return _isComplete; }
set
{
if (_isComplete != value)
{
NotifyPropertyChanging("IsComplete");
_isComplete = value;
NotifyPropertyChanged("IsComplete");
}
}
}
// Version column aids update performance.
[Column(IsVersion = true)]
private Binary _version;
// Internal column for the associated ToDoCategory ID value
[Column]
internal int _categoryId;
// Entity reference, to identify the ToDoCategory "storage" table
private EntityRef<ToDoCategory> _category;
// Association, to describe the relationship between this key and that "storage" table
[Association(Storage = "_category", ThisKey = "_categoryId", OtherKey = "Id", IsForeignKey = true)]
public ToDoCategory Category
{
get { return _category.Entity; }
set
{
NotifyPropertyChanging("Category");
_category.Entity = value;
if (value != null)
{
_categoryId = value.Id;
}
NotifyPropertyChanging("Category");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify that a property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify that a property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
[Table]
public class ToDoCategory : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private int _id;
[Column(DbType = "INT NOT NULL IDENTITY", IsDbGenerated = true, IsPrimaryKey = true)]
public int Id
{
get { return _id; }
set
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanged("Id");
}
}
// Define category name: private field, public property, and database column.
private string _name;
[Column]
public string Name
{
get { return _name; }
set
{
NotifyPropertyChanging("Name");
_name = value;
NotifyPropertyChanged("Name");
}
}
// Version column aids update performance.
[Column(IsVersion = true)]
private Binary _version;
// Define the entity set for the collection side of the relationship.
private EntitySet<ToDoItem> _todos;
[Association(Storage = "_todos", OtherKey = "_categoryId", ThisKey = "Id")]
public EntitySet<ToDoItem> ToDos
{
get { return this._todos; }
set { this._todos.Assign(value); }
}
// Assign handlers for the add and remove operations, respectively.
public ToDoCategory()
{
_todos = new EntitySet<ToDoItem>(
new Action<ToDoItem>(this.attach_ToDo),
new Action<ToDoItem>(this.detach_ToDo)
);
}
// Called during an add operation
private void attach_ToDo(ToDoItem toDo)
{
NotifyPropertyChanging("ToDoItem");
toDo.Category = this;
}
// Called during a remove operation
private void detach_ToDo(ToDoItem toDo)
{
NotifyPropertyChanging("ToDoItem");
toDo.Category = null;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify that a property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify that a property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
}
| |
/*
* XmlAttributeCollection.cs - Implementation of the
* "System.Xml.XmlAttributeCollection" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml
{
using System;
using System.Collections;
using System.Runtime.CompilerServices;
#if ECMA_COMPAT
internal
#else
public
#endif
class XmlAttributeCollection : XmlNamedNodeMap, ICollection
{
// Constructor.
internal XmlAttributeCollection(XmlNode parent) : base(parent) {}
// Retrieve items from this attribute collection.
[IndexerName("ItemOf")]
public virtual XmlAttribute this[int i]
{
get
{
return (XmlAttribute)(Item(i));
}
}
[IndexerName("ItemOf")]
public virtual XmlAttribute this[String name]
{
get
{
return (XmlAttribute)(GetNamedItem(name));
}
}
[IndexerName("ItemOf")]
public virtual XmlAttribute this[String name, String ns]
{
get
{
return (XmlAttribute)(GetNamedItem(name, ns));
}
}
// Append an attribute to this collection.
public virtual XmlAttribute Append(XmlAttribute node)
{
SetOrAppend(node, true);
return node;
}
// Copy the attributes in this collection to an array.
public void CopyTo(XmlAttribute[] array, int index)
{
int count = Count;
int posn;
for(posn = 0; posn < count; ++posn)
{
array[index++] = (XmlAttribute)(Item(posn));
}
}
// Get the index of a specific node within this collection.
internal int IndexOf(XmlAttribute refNode)
{
int count = Count;
int posn;
for(posn = 0; posn < count; ++posn)
{
if(Item(posn) == refNode)
{
return posn;
}
}
return -1;
}
// Get the position of a reference node within this collection.
private int GetItemPosition(XmlAttribute refNode)
{
int posn = IndexOf(refNode);
if(posn != -1)
{
return posn;
}
throw new ArgumentException
(S._("Xml_NotAttrCollectionMember"), "refNode");
}
// Insert a node after another one.
public virtual XmlAttribute InsertAfter
(XmlAttribute newNode, XmlAttribute refNode)
{
if(newNode == null)
{
throw new ArgumentException
(S._("Xml_NotSameDocument"), "node");
}
RemoveNamedItem(newNode.Name);
if(refNode == null)
{
map.Insert(0, newNode);
}
else
{
map.Insert(GetItemPosition(refNode) + 1, newNode);
}
return newNode;
}
// Insert a node before another one.
public virtual XmlAttribute InsertBefore
(XmlAttribute newNode, XmlAttribute refNode)
{
if(newNode == null)
{
throw new ArgumentException
(S._("Xml_NotSameDocument"), "node");
}
RemoveNamedItem(newNode.Name);
if(refNode == null)
{
map.Insert(Count, newNode);
}
else
{
map.Insert(GetItemPosition(refNode), newNode);
}
return newNode;
}
// Prepend a node to this collection.
public virtual XmlAttribute Prepend(XmlAttribute node)
{
return InsertAfter(node, null);
}
// Remove an attribute from this collection.
public virtual XmlAttribute Remove(XmlAttribute node)
{
if(node == null)
{
return null;
}
else
{
return (XmlAttribute)(RemoveNamedItem(node.Name));
}
}
// Remove all attributes from this collection.
public virtual void RemoveAll()
{
map.Clear();
}
// Remove the attribute at a particular index.
public virtual XmlAttribute RemoveAt(int i)
{
if(i < 0 || i >= map.Count)
{
return null;
}
XmlAttribute attr = (XmlAttribute)(map[i]);
map.RemoveAt(i);
return attr;
}
// Set a named item into this node map, after making sure
// that it is indeed an attribute.
public override XmlNode SetNamedItem(XmlNode node)
{
if(node != null && !(node is XmlAttribute))
{
throw new ArgumentException
(S._("Xml_AttrCollectionWrongNode"), "node");
}
return SetOrAppend(node, false);
}
// Implement the ICollection interface.
void ICollection.CopyTo(Array array, int index)
{
int count = Count;
int posn;
for(posn = 0; posn < count; ++posn)
{
array.SetValue(Item(posn), index);
++index;
}
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
Object ICollection.SyncRoot
{
get
{
return this;
}
}
}; // class XmlAttributeCollection
}; // namespace System.Xml
| |
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("Unity.AssetBundleBrowser.Editor.Tests")]
namespace AssetBundleBrowser
{
public class AssetBundleBrowserMain : EditorWindow, IHasCustomMenu, ISerializationCallbackReceiver
{
private static AssetBundleBrowserMain s_instance = null;
internal static AssetBundleBrowserMain instance
{
get
{
if (s_instance == null)
s_instance = GetWindow<AssetBundleBrowserMain>();
return s_instance;
}
}
internal const float kButtonWidth = 150;
enum Mode
{
Browser,
Preprocess,
Builder,
Inspect,
}
[SerializeField]
Mode m_Mode;
[SerializeField]
int m_DataSourceIndex;
[SerializeField]
internal AssetBundleManageTab m_ManageTab;
[SerializeField]
internal AssetBundleBuildTab m_BuildTab;
[SerializeField]
internal AssetBundleInspectTab m_InspectTab;
[SerializeField]
internal ABPreprocessingTab m_PreprocessTab;
private Texture2D m_RefreshTexture;
const float k_ToolbarPadding = 15;
const float k_MenubarPadding = 32;
[MenuItem("Tools/AssetBundle/AssetBundle Browser", priority = 2050)]
static void ShowWindow()
{
s_instance = null;
instance.titleContent = new GUIContent("AssetBundles");
instance.Show();
}
[SerializeField]
internal bool multiDataSource = false;
List<AssetBundleDataSource.ABDataSource> m_DataSourceList = null;
public virtual void AddItemsToMenu(GenericMenu menu)
{
if(menu != null)
menu.AddItem(new GUIContent("Custom Sources"), multiDataSource, FlipDataSource);
}
internal void FlipDataSource()
{
multiDataSource = !multiDataSource;
}
private void OnEnable()
{
Rect subPos = GetSubWindowArea();
if(m_ManageTab == null)
m_ManageTab = new AssetBundleManageTab();
m_ManageTab.OnEnable(subPos, this);
if (m_PreprocessTab == null)
m_PreprocessTab = new ABPreprocessingTab();
m_PreprocessTab.OnEnable(subPos, this);
if (m_BuildTab == null)
m_BuildTab = new AssetBundleBuildTab();
m_BuildTab.OnEnable(this);
if (m_InspectTab == null)
m_InspectTab = new AssetBundleInspectTab();
m_InspectTab.OnEnable(subPos);
m_RefreshTexture = EditorGUIUtility.FindTexture("Refresh");
InitDataSources();
}
private void InitDataSources()
{
//determine if we are "multi source" or not...
multiDataSource = false;
m_DataSourceList = new List<AssetBundleDataSource.ABDataSource>();
foreach (var info in AssetBundleDataSource.ABDataSourceProviderUtility.CustomABDataSourceTypes)
{
m_DataSourceList.AddRange(info.GetMethod("CreateDataSources").Invoke(null, null) as List<AssetBundleDataSource.ABDataSource>);
}
if (m_DataSourceList.Count > 1)
{
multiDataSource = true;
if (m_DataSourceIndex >= m_DataSourceList.Count)
m_DataSourceIndex = 0;
AssetBundleModel.Model.DataSource = m_DataSourceList[m_DataSourceIndex];
}
}
private void OnDisable()
{
if (m_BuildTab != null)
m_BuildTab.OnDisable();
if (m_InspectTab != null)
m_InspectTab.OnDisable();
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
}
private Rect GetSubWindowArea()
{
float padding = k_MenubarPadding;
if (multiDataSource)
padding += k_MenubarPadding * 0.5f;
Rect subPos = new Rect(0, padding, position.width, position.height - padding);
return subPos;
}
private void Update()
{
switch (m_Mode)
{
case Mode.Builder:
break;
case Mode.Inspect:
break;
case Mode.Browser:
default:
m_ManageTab.Update();
break;
}
}
private void OnGUI()
{
ModeToggle();
switch(m_Mode)
{
case Mode.Builder:
m_BuildTab.OnGUI();
break;
case Mode.Inspect:
m_InspectTab.OnGUI(GetSubWindowArea());
break;
case Mode.Preprocess:
m_PreprocessTab.OnGUI(GetSubWindowArea());
break;
case Mode.Browser:
default:
m_ManageTab.OnGUI(GetSubWindowArea());
break;
}
}
void ModeToggle()
{
if (m_RefreshTexture == null) return;
GUILayout.BeginHorizontal();
GUILayout.Space(k_ToolbarPadding);
bool clicked = false;
switch(m_Mode)
{
case Mode.Browser:
clicked = GUILayout.Button(m_RefreshTexture);
if (clicked)
m_ManageTab.ForceReloadData();
break;
case Mode.Preprocess:
clicked = GUILayout.Button(m_RefreshTexture);
if (clicked)
m_PreprocessTab.Refresh();
break;
case Mode.Builder:
GUILayout.Space(m_RefreshTexture.width + k_ToolbarPadding);
break;
case Mode.Inspect:
clicked = GUILayout.Button(m_RefreshTexture);
if (clicked)
m_InspectTab.RefreshBundles();
break;
}
float toolbarWidth = position.width - k_ToolbarPadding * 4 - m_RefreshTexture.width;
//string[] labels = new string[2] { "Configure", "Build"};
string[] labels = new string[4] { "Configure", "Preprocess", "Build", "Inspect" };
m_Mode = (Mode)GUILayout.Toolbar((int)m_Mode, labels, "LargeButton", GUILayout.Width(toolbarWidth) );
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if(multiDataSource)
{
//GUILayout.BeginArea(r);
GUILayout.BeginHorizontal();
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
GUILayout.Label("Bundle Data Source:");
GUILayout.FlexibleSpace();
var c = new GUIContent(string.Format("{0} ({1})", AssetBundleModel.Model.DataSource.Name, AssetBundleModel.Model.DataSource.ProviderName), "Select Asset Bundle Set");
if (GUILayout.Button(c , EditorStyles.toolbarPopup) )
{
GenericMenu menu = new GenericMenu();
for (int index = 0; index < m_DataSourceList.Count; index++)
{
var ds = m_DataSourceList[index];
if (ds == null)
continue;
if (index > 0)
menu.AddSeparator("");
var counter = index;
menu.AddItem(new GUIContent(string.Format("{0} ({1})", ds.Name, ds.ProviderName)), false,
() =>
{
m_DataSourceIndex = counter;
var thisDataSource = ds;
AssetBundleModel.Model.DataSource = thisDataSource;
m_ManageTab.ForceReloadData();
}
);
}
menu.ShowAsContext();
}
GUILayout.FlexibleSpace();
if (AssetBundleModel.Model.DataSource.IsReadOnly())
{
GUIStyle tbLabel = new GUIStyle(EditorStyles.toolbar);
tbLabel.alignment = TextAnchor.MiddleRight;
GUILayout.Label("Read Only", tbLabel);
}
}
GUILayout.EndHorizontal();
//GUILayout.EndArea();
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.DirectoryServices;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.HostedSolution;
namespace WebsitePanel.Import.Enterprise
{
public partial class ApplicationForm : BaseForm
{
private string username;
private string password;
private OrganizationImporter importer;
internal bool ImportStarted = false;
public ApplicationForm()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
public void InitializeForm(string username, string password)
{
this.username = username;
this.password = password;
UserInfo info = UserController.GetUser(username);
SecurityContext.SetThreadPrincipal(info);
importer = new OrganizationImporter();
Assembly assembly = Assembly.GetExecutingAssembly();
this.Text += " v" + assembly.GetName().Version.ToString(3);
UpdateForm();
}
private void OnBrowseSpace(object sender, EventArgs e)
{
SelectSpace();
}
private void SelectSpace()
{
SpaceForm form = new SpaceForm();
form.InitializeForm(username, password);
if (form.ShowDialog(this) == DialogResult.OK)
{
Global.Space = form.SelectedSpace;
txtSpace.Text = Global.Space.PackageName;
LoadSpaceData(Global.Space);
}
}
private void LoadSpaceData(PackageInfo packageInfo)
{
int serviceId = PackageController.GetPackageServiceId(packageInfo.PackageId, ResourceGroups.HostedOrganizations);
ServiceInfo serviceInfo = ServerController.GetServiceInfo(serviceId);
StringDictionary serviceSettings = ServerController.GetServiceSettingsAdmin(serviceId);
Global.RootOU = serviceSettings["RootOU"];
Global.PrimaryDomainController = serviceSettings["PrimaryDomainController"];
Global.TempDomain = serviceSettings["TempDomain"];
ServerInfo serverInfo = ServerController.GetServerById(serviceInfo.ServerId);
Global.ADRootDomain = serverInfo.ADRootDomain;
Global.NetBiosDomain = ActiveDirectoryUtils.GetNETBIOSDomainName(Global.ADRootDomain);
}
private void OnBrowseOU(object sender, EventArgs e)
{
SelectOU();
}
private void SelectOU()
{
if (string.IsNullOrEmpty(txtSpace.Text))
{
ShowWarning("Please select hosting space first.");
return;
}
OUForm form = new OUForm();
form.InitializeForm();
if (form.ShowDialog(this) == DialogResult.OK)
{
Global.OrgDirectoryEntry = form.DirectoryEntry;
string orgId = (string)Global.OrgDirectoryEntry.Properties["name"].Value;
txtOU.Text = form.DirectoryEntry.Path;
Global.OrganizationId = orgId;
LoadOrganizationData(Global.OrgDirectoryEntry);
}
}
private void BindMailboxPlans(string orgId)
{
cbMailboxPlan.Items.Clear();
cbMailboxPlan.Items.Add("<not set>");
cbMailboxPlan.SelectedIndex = 0;
Organization org = OrganizationController.GetOrganizationById(orgId);
if (org == null)
{
List<Organization> orgs = ExchangeServerController.GetExchangeOrganizations(1, false);
if (orgs.Count > 0)
org = orgs[0];
}
if (org != null)
{
int itemId = org.Id;
List<ExchangeMailboxPlan> plans = ExchangeServerController.GetExchangeMailboxPlans(itemId, false);
cbMailboxPlan.Items.AddRange(plans.ToArray());
}
}
private void LoadOrganizationData(DirectoryEntry parent)
{
string orgId = (string)parent.Properties["name"].Value;
txtOrgId.Text = orgId;
Organization org = OrganizationController.GetOrganizationById(orgId);
if (org != null)
{
rbCreateAndImport.Checked = false;
rbImport.Checked = true;
txtOrgName.Text = org.Name;
}
else
{
rbCreateAndImport.Checked = true;
rbImport.Checked = false;
txtOrgName.Text = orgId;
}
BindMailboxPlans(orgId);
LoadOrganizationAccounts(parent);
}
private void LoadOrganizationAccounts(DirectoryEntry ou)
{
lvUsers.Items.Clear();
ListViewItem item = null;
string email;
string type;
string name;
PropertyValueCollection typeProp;
string ouName = (string)ou.Properties["name"].Value;
foreach (DirectoryEntry child in ou.Children)
{
type = null;
email = null;
name = (string)child.Properties["name"].Value;
//account type
typeProp = child.Properties["msExchRecipientDisplayType"];
int typeDetails = 0;
PropertyValueCollection typeDetailsProp = child.Properties["msExchRecipientTypeDetails"];
if (typeDetailsProp != null)
{
if (typeDetailsProp.Value != null)
{
try
{
object adsLargeInteger = typeDetailsProp.Value;
typeDetails = (Int32)adsLargeInteger.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, adsLargeInteger, null);
}
catch { } // just skip
}
}
switch (child.SchemaClassName)
{
case "user":
email = (string)child.Properties["userPrincipalName"].Value;
if (typeDetails == 4)
{
type = "Shared Mailbox";
}
else
{
if (typeProp == null || typeProp.Value == null)
{
type = "User";
}
else
{
int mailboxType = (int)typeProp.Value;
switch (mailboxType)
{
case 1073741824:
type = "User Mailbox";
break;
case 7:
type = "Room Mailbox";
break;
case 8:
type = "Equipment Mailbox";
break;
}
}
}
if (!string.IsNullOrEmpty(type))
{
item = new ListViewItem(name);
item.ImageIndex = 0;
item.Checked = true;
item.Tag = child;
item.SubItems.Add(email);
item.SubItems.Add(type);
lvUsers.Items.Add(item);
}
break;
case "contact":
if (typeProp != null && typeProp.Value != null && 6 == (int)typeProp.Value)
{
type = "Mail Contact";
if (child.Properties["targetAddress"] != null)
{
email = (string)child.Properties["targetAddress"].Value;
if (email != null && email.ToLower().StartsWith("smtp:"))
email = email.Substring(5);
}
}
if (!string.IsNullOrEmpty(type))
{
item = new ListViewItem(name);
item.ImageIndex = 1;
item.Checked = true;
item.Tag = child;
item.SubItems.Add(email);
item.SubItems.Add(type);
lvUsers.Items.Add(item);
}
break;
case "group":
if (child.Properties["mail"] != null)
email = (string)child.Properties["mail"].Value;
bool isDistributionList = false;
if ((typeProp != null) && (typeProp.Value != null) && (1073741833 == (int)typeProp.Value))
isDistributionList = true;
if (typeDetails == 262144)
isDistributionList = true;
if (typeDetails == 0)
isDistributionList = true;
if (isDistributionList)
{
//Universal Security Group
type = "Distribution List";
//email
PropertyValueCollection proxyAddresses = child.Properties["proxyAddresses"];
if (proxyAddresses != null)
{
foreach (string address in proxyAddresses)
{
if (address != null && address.StartsWith("SMTP:"))
{
email = address.Substring(5);
break;
}
}
}
}
if (!string.IsNullOrEmpty(type) && name != ouName)
{
item = new ListViewItem(name);
item.ImageIndex = 2;
item.Checked = true;
item.Tag = child;
item.SubItems.Add(email);
item.SubItems.Add(type);
lvUsers.Items.Add(item);
}
break;
}
}
}
private void OnDataChanged(object sender, EventArgs e)
{
UpdateForm();
}
private void UpdateForm()
{
if (string.IsNullOrEmpty(txtSpace.Text) ||
string.IsNullOrEmpty(txtOU.Text))
{
btnStart.Enabled = false;
}
else
{
btnStart.Enabled = true;
}
}
private void OnImportClick(object sender, EventArgs e)
{
List<DirectoryEntry> accounts = new List<DirectoryEntry>();
foreach (ListViewItem item in lvUsers.Items)
{
if (item.Checked)
{
accounts.Add((DirectoryEntry)item.Tag);
}
}
Global.SelectedAccounts = accounts;
Global.OrganizationName = txtOrgName.Text;
Global.ImportAccountsOnly = rbImport.Checked;
Global.HasErrors = false;
Global.defaultMailboxPlanId = 0;
if (cbMailboxPlan.SelectedItem!=null)
{
ExchangeMailboxPlan plan = cbMailboxPlan.SelectedItem as ExchangeMailboxPlan;
if (plan != null)
Global.defaultMailboxPlanId = plan.MailboxPlanId;
}
importer.Initialize(this.username, this);
importer.Start();
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = ImportStarted;
}
private void OnCheckedChanged(object sender, EventArgs e)
{
txtOrgName.ReadOnly = !rbCreateAndImport.Checked;
}
private void OnSelectAllClick(object sender, EventArgs e)
{
foreach (ListViewItem item in lvUsers.Items)
{
item.Checked = true;
}
}
private void OnDeselectAllClick(object sender, EventArgs e)
{
foreach (ListViewItem item in lvUsers.Items)
{
item.Checked = false;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ReplicationLinkOperationsExtensions
{
/// <summary>
/// Begins failover of the Azure SQL Database Replication Link with the
/// given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static ReplicationLinkFailoverResponse BeginFailover(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).BeginFailoverAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins failover of the Azure SQL Database Replication Link with the
/// given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static Task<ReplicationLinkFailoverResponse> BeginFailoverAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.BeginFailoverAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Begins a forced failover of the Azure SQL Database Replication Link
/// with the given id which may result in data loss.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static ReplicationLinkFailoverResponse BeginFailoverAllowDataLoss(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).BeginFailoverAllowDataLossAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins a forced failover of the Azure SQL Database Replication Link
/// with the given id which may result in data loss.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static Task<ReplicationLinkFailoverResponse> BeginFailoverAllowDataLossAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.BeginFailoverAllowDataLossAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Deletes the Azure SQL Database Replication Link with the given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be dropped.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).DeleteAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the Azure SQL Database Replication Link with the given id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be dropped.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.DeleteAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Fails over the Azure SQL Database Replication Link with the given
/// id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static ReplicationLinkFailoverResponse Failover(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).FailoverAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fails over the Azure SQL Database Replication Link with the given
/// id.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static Task<ReplicationLinkFailoverResponse> FailoverAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.FailoverAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Forces failover of the Azure SQL Database Replication Link with the
/// given id which may result in data loss.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static ReplicationLinkFailoverResponse FailoverAllowDataLoss(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).FailoverAllowDataLossAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Forces failover of the Azure SQL Database Replication Link with the
/// given id which may result in data loss.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database that has the
/// replication link to be failed over.
/// </param>
/// <param name='linkId'>
/// Required. The id of the replication link to be failed over.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static Task<ReplicationLinkFailoverResponse> FailoverAllowDataLossAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.FailoverAllowDataLossAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Replication Link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to get the link for.
/// </param>
/// <param name='linkId'>
/// Required. The replication link id to be retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Replication
/// Link request.
/// </returns>
public static ReplicationLinkGetResponse Get(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).GetAsync(resourceGroupName, serverName, databaseName, linkId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Replication Link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to get the link for.
/// </param>
/// <param name='linkId'>
/// Required. The replication link id to be retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Replication
/// Link request.
/// </returns>
public static Task<ReplicationLinkGetResponse> GetAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName, string linkId)
{
return operations.GetAsync(resourceGroupName, serverName, databaseName, linkId, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure SQL Database replication link failover
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static ReplicationLinkFailoverResponse GetReplicationLinkOperationStatus(this IReplicationLinkOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).GetReplicationLinkOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure SQL Database replication link failover
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database replication failover
/// operations.
/// </returns>
public static Task<ReplicationLinkFailoverResponse> GetReplicationLinkOperationStatusAsync(this IReplicationLinkOperations operations, string operationStatusLink)
{
return operations.GetReplicationLinkOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns information about Azure SQL Database Replication Links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server in which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve links for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database Replication
/// Link request.
/// </returns>
public static ReplicationLinkListResponse List(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IReplicationLinkOperations)s).ListAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about Azure SQL Database Replication Links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IReplicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server in which the Azure SQL
/// Database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to retrieve links for.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Database Replication
/// Link request.
/// </returns>
public static Task<ReplicationLinkListResponse> ListAsync(this IReplicationLinkOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.ListAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Reflection;
using OdeAPI;
using OpenMetaverse;
using Aurora.Framework;
namespace Aurora.Physics.AuroraOpenDynamicsEngine
{
public class AuroraODECharacter : PhysicsCharacter
{
#region Declares
protected readonly CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
protected AuroraODEPhysicsScene _parent_scene;
public float CAPSULE_LENGTH = 2.140599f;
public float CAPSULE_RADIUS = 0.37f;
public float MinimumGroundFlightOffset = 3f;
protected float PID_D;
protected float PID_P;
protected bool ShouldBeWalking = true;
protected bool StartingUnderWater = true;
protected bool WasUnderWater;
public IntPtr Amotor = IntPtr.Zero;
public IntPtr Body = IntPtr.Zero;
public IntPtr Shell = IntPtr.Zero;
protected Vector3 _position;
protected Vector3 _target_velocity;
protected Vector3 _velocity;
protected Vector3 _target_force = Vector3.Zero;
protected Vector3 _target_vel_force = Vector3.Zero;
protected bool _wasZeroFlagFlying;
protected bool _zeroFlag;
protected bool flying;
protected float lastUnderwaterPush;
protected int m_ZeroUpdateSent;
protected bool m_alwaysRun;
protected CollisionCategories m_collisionCategories = (CollisionCategories.Character);
// Default, Collide with Other Geometries, spaces, bodies and characters.
protected const CollisionCategories m_collisionFlags = (CollisionCategories.Geom | CollisionCategories.Space
| CollisionCategories.Body | CollisionCategories.Character | CollisionCategories.Land);
// float m_UpdateTimecntr = 0;
// float m_UpdateFPScntr = 0.05f;
protected bool m_isJumping;
public bool m_isPhysical; // the current physical status
protected bool m_iscolliding;
protected bool m_ispreJumping;
protected Vector3 m_lastAngVelocity;
protected Vector3 m_lastPosition;
protected Vector3 m_lastVelocity;
public uint m_localID;
protected float m_mass = 80f;
protected string m_name = String.Empty;
protected bool m_pidControllerActive = true;
protected int m_preJumpCounter;
protected Vector3 m_preJumpForce = Vector3.Zero;
protected Vector3 m_rotationalVelocity;
protected float m_speedModifier = 1.0f;
protected Quaternion m_taintRotation = Quaternion.Identity;
protected bool m_shouldBePhysical = true;
protected int m_lastForceApplied = 0;
protected Vector3 m_forceAppliedBeforeFalling = Vector3.Zero;
protected ODESpecificAvatar _parent_ref;
// unique UUID of this character object
public UUID m_uuid;
protected bool realFlying;
public override bool IsJumping
{
get { return m_isJumping; }
}
public override bool IsPreJumping
{
get { return m_ispreJumping; }
}
public override float SpeedModifier
{
get { return m_speedModifier; }
set { m_speedModifier = value; }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
#endregion
#region Constructor
public AuroraODECharacter(String avName, AuroraODEPhysicsScene parent_scene, Vector3 pos, Quaternion rotation,
Vector3 size)
{
m_uuid = UUID.Random();
_parent_scene = parent_scene;
m_taintRotation = rotation;
if (pos.IsFinite())
{
if (pos.Z > 9999999f || pos.Z < -90f)
{
pos.Z =
_parent_scene.GetTerrainHeightAtXY(_parent_scene.Region.RegionSizeX * 0.5f,
_parent_scene.Region.RegionSizeY * 0.5f) + 5.0f;
}
_position = pos;
}
else
{
_position.X = _parent_scene.Region.RegionSizeX * 0.5f;
_position.Y = _parent_scene.Region.RegionSizeY * 0.5f;
_position.Z = _parent_scene.GetTerrainHeightAtXY(_position.X, _position.Y) + 10f;
MainConsole.Instance.Warn("[PHYSICS]: Got NaN Position on Character Create");
}
m_isPhysical = false; // current status: no ODE information exists
Size = size;
m_name = avName;
}
public void RebuildAvatar()
{
if (!(Shell == IntPtr.Zero && Body == IntPtr.Zero))
{
MainConsole.Instance.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
+ (Shell != IntPtr.Zero ? "Shell " : "")
+ (Body != IntPtr.Zero ? "Body " : ""));
}
_parent_ref.AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z);
_parent_scene.AddCharacter(this);
m_isPhysical = true;
}
#endregion
#region Properties
public override int PhysicsActorType
{
get { return (int)ActorTypes.Agent; }
}
/// <summary>
/// If this is set, the avatar will move faster
/// </summary>
public override bool SetAlwaysRun
{
get { return m_alwaysRun; }
set { m_alwaysRun = value; }
}
public override uint LocalID
{
get { return m_localID; }
set { m_localID = value; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return m_shouldBePhysical; }
set { m_shouldBePhysical = value; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return realFlying; }
set
{
realFlying = value;
flying = value;
if (!m_isPhysical)
_parent_scene.AddSimulationChange(() => { flying = value; realFlying = value; });
}
}
public override bool IsTruelyColliding { get; set; }
protected int m_colliderfilter;
/// <summary>
/// Returns if the avatar is colliding in general.
/// This includes the ground and objects and avatar.
/// in this and next collision sets there is a general set to false
/// at begin of loop, so a false is 2 sets while a true is a false plus a 1
/// </summary>
public override bool IsColliding
{
get { return m_iscolliding; }
set
{
if (value)
{
m_colliderfilter += 15;
if (m_colliderfilter > 15)
m_colliderfilter = 15;
}
else
{
m_colliderfilter--;
if (m_colliderfilter < 0)
m_colliderfilter = 0;
}
m_iscolliding = m_colliderfilter != 0;
}
}
/// <summary>
/// This 'puts' an avatar somewhere in the physics space.
/// Not really a good choice unless you 'know' it's a good
/// spot otherwise you're likely to orbit the avatar.
/// </summary>
public override Vector3 Position
{
get { return _position; }
set
{
if (value.IsFinite())
{
if (value.Z > 9999999f || value.Z < -90f)
{
value.Z =
_parent_scene.GetTerrainHeightAtXY(_parent_scene.Region.RegionSizeX * 0.5f,
_parent_scene.Region.RegionSizeY * 0.5f) + 5;
}
_position.X = value.X;
_position.Y = value.Y;
_position.Z = value.Z;
_parent_scene.AddSimulationChange(() =>
{
if (!value.ApproxEquals(_position, 0.05f) && Body != null)
_parent_ref.SetPositionLocked(value);
});
}
else
{
MainConsole.Instance.Warn("[PHYSICS]: Got a NaN Position from Scene on a Character");
}
}
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
private Vector3 _lastSetSize = Vector3.Zero;
/// <summary>
/// This property sets the height of the avatar only. We use the height to make sure the avatar stands up straight
/// and use it to offset landings properly
/// </summary>
public override Vector3 Size
{
get { return _lastSetSize; }
set
{
if (value.IsFinite())
{
if (_lastSetSize.Z == value.Z)
{
//It is the same, do not rebuild
MainConsole.Instance.Info(
"[Physics]: Not rebuilding the avatar capsule, as it is the same size as the previous capsule.");
return;
}
_lastSetSize = value;
m_pidControllerActive = true;
CAPSULE_RADIUS = _parent_scene.avCapRadius;
CAPSULE_LENGTH = (_lastSetSize.Z * 1.1f) - CAPSULE_RADIUS * 2.0f;
Velocity = Vector3.Zero;
_parent_scene.AddSimulationChange(() => RebuildAvatar());
}
else
{
MainConsole.Instance.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character");
}
}
}
//
/// <summary>
/// Uses the capped cyllinder volume formula to calculate the avatar's mass.
/// This may be used in calculations in the scene/scenepresence
/// </summary>
public override float Mass
{
get { return m_mass; }
}
public override Vector3 Force
{
get { return _target_velocity; }
set { return; }
}
public override Vector3 Velocity
{
get
{
// There's a problem with Vector3.Zero! Don't Use it Here!
//if (_zeroFlag)
// return Vector3.Zero;
//And definitely don't set this, otherwise, we never stop sending updates!
//m_lastUpdateSent = false;
return _velocity;
}
set
{
if (value.IsFinite())
{
m_pidControllerActive = true;
_target_velocity = value;
}
else
{
MainConsole.Instance.Warn("[PHYSICS]: Got a NaN velocity from Scene in a Character");
}
}
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return m_taintRotation; }
set
{
m_taintRotation = value;
_parent_scene.AddSimulationChange(() =>
{
if (Body != IntPtr.Zero)
_parent_ref.SetRotationLocked(value);
});
}
}
/// <summary>
/// turn the PID controller on or off.
/// The PID Controller will turn on all by itself in many situations
/// </summary>
/// <param name = "status"></param>
public void SetPidStatus(bool status)
{
m_pidControllerActive = status;
}
public override void ForceSetVelocity(Vector3 velocity)
{
_velocity = velocity;
m_lastVelocity = velocity;
}
public override void ForceSetPosition(Vector3 position)
{
_position = position;
m_lastPosition = position;
}
/// <summary>
/// This adds to the force that will be used for moving the avatar in the next physics heartbeat iteration.
/// </summary>
/// <param name = "force"></param>
public override void AddMovementForce(Vector3 force)
{
_target_velocity += force;
}
/// <summary>
/// This sets the force that will be used for moving the avatar in the next physics heartbeat iteration.
/// Note: we do accept Vector3.Zero here as that is an overriding stop for the physics engine.
/// </summary>
/// <param name = "force"></param>
public override void SetMovementForce(Vector3 force)
{
if (_parent_scene.m_allowJump && !Flying && IsColliding && force.Z >= 0.5f)
{
if (_parent_scene.m_usepreJump)
{
if (!m_ispreJumping && !m_isJumping)
{
m_ispreJumping = true;
m_preJumpForce = force;
m_preJumpCounter = 0;
TriggerMovementUpdate();
return;
}
}
else
{
if (!m_isJumping)
{
m_isJumping = true;
m_preJumpCounter = _parent_scene.m_preJumpTime;
TriggerMovementUpdate();
//Leave the / 2, its there so that the jump doesn't go crazy
force.X *= _parent_scene.m_preJumpForceMultiplierX / 2;
force.Y *= _parent_scene.m_preJumpForceMultiplierY / 2;
force.Z *= _parent_scene.m_preJumpForceMultiplierZ;
}
}
}
if (m_ispreJumping || m_isJumping)
{
TriggerMovementUpdate();
return;
}
if (force != Vector3.Zero)
_target_velocity = force;
}
#endregion
#region Methods
#region Move
/// <summary>
/// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
/// </summary>
public void UpdatePositionAndVelocity(float timestep)
{
if (!IsPhysical)
return;
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
Vector3 vec;
try
{
vec = _parent_ref.GetPosition();
}
catch (NullReferenceException)
{
_parent_scene.BadCharacter(this);
vec = new Vector3(_position.X, _position.Y, _position.Z);
base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem!
MainConsole.Instance.WarnFormat("[ODEPLUGIN]: Avatar Null reference for Avatar {0}, physical actor {1}", m_name, m_uuid);
}
// vec is a ptr into internal ode data better not mess with it
_position.X = vec.X;
_position.Y = vec.Y;
_position.Z = vec.Z;
if (!_position.IsFinite())
{
_parent_scene.BadCharacter(this);
base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem!
return;
}
try
{
vec = _parent_ref.GetLinearVelocity();
}
catch (NullReferenceException)
{
vec.X = _velocity.X;
vec.Y = _velocity.Y;
vec.Z = _velocity.Z;
}
Vector3 rvec;
try
{
rvec = _parent_ref.GetAngularVelocity();
}
catch (NullReferenceException)
{
rvec.X = m_rotationalVelocity.X;
rvec.Y = m_rotationalVelocity.Y;
rvec.Z = m_rotationalVelocity.Z;
}
m_rotationalVelocity.X = rvec.X;
m_rotationalVelocity.Y = rvec.Y;
m_rotationalVelocity.Z = rvec.Z;
// vec is a ptr into internal ode data better not mess with it
_velocity.X = vec.X;
_velocity.Y = vec.Y;
_velocity.Z = vec.Z;
if (!_velocity.IsFinite())
{
_parent_scene.BadCharacter(this);
base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem!
return;
}
bool VelIsZero = false;
int vcntr = 0;
if (Math.Abs(_velocity.X) < 0.01)
{
vcntr++;
_velocity.X = 0;
}
if (Math.Abs(_velocity.Y) < 0.01)
{
vcntr++;
_velocity.Y = 0;
}
if (Math.Abs(_velocity.Z) < 0.01)
{
vcntr++;
_velocity.Z = 0;
}
if (vcntr == 3)
VelIsZero = true;
// slow down updates, changed y mind: updates should go at physics fps, acording to movement conditions
/*
m_UpdateTimecntr += timestep;
m_UpdateFPScntr = 2.5f * _parent_scene.StepTime;
if(m_UpdateTimecntr < m_UpdateFPScntr)
return;
m_UpdateTimecntr = 0;
*/
float VELOCITY_TOLERANCE = 0.025f*0.25f;
if (_parent_scene.TimeDilation < 0.5)
{
float percent = (1f - _parent_scene.TimeDilation) * 100;
VELOCITY_TOLERANCE *= percent * 2;
}
//const float ANG_VELOCITY_TOLERANCE = 0.05f;
const float POSITION_TOLERANCE = 5.0f;
bool needSendUpdate = false;
float vlength = (_velocity - m_lastVelocity).LengthSquared();
float plength = (_position - m_lastPosition).LengthSquared();
if ( //!VelIsZero &&
(
vlength > VELOCITY_TOLERANCE ||
plength > POSITION_TOLERANCE
//(anglength > ANG_VELOCITY_TOLERANCE) ||
//true
// (Math.Abs(_lastorientation.X - _orientation.X) > 0.001) ||
// (Math.Abs(_lastorientation.Y - _orientation.Y) > 0.001) ||
// (Math.Abs(_lastorientation.Z - _orientation.Z) > 0.001) ||
// (Math.Abs(_lastorientation.W - _orientation.W) > 0.001)
))
{
needSendUpdate = true;
m_ZeroUpdateSent = 3;
// _lastorientation = Orientation;
// base.RequestPhysicsterseUpdate();
// base.TriggerSignificantMovement();
}
else if (VelIsZero)
{
if (m_ZeroUpdateSent > 0)
{
needSendUpdate = true;
m_ZeroUpdateSent--;
}
}
if (needSendUpdate)
{
m_lastPosition = _position;
// m_lastRotationalVelocity = RotationalVelocity;
m_lastVelocity = _velocity;
m_lastAngVelocity = RotationalVelocity;
base.TriggerSignificantMovement();
//Tell any listeners about the new info
// This is for animations
base.TriggerMovementUpdate();
}
}
#endregion
#region Unused code
/* suspended
private void AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3 movementVector)
{
if (!_parent_scene.IsAvCapsuleTilted)
return;
movementVector.Z = 0f;
if (movementVector == Vector3.Zero)
{
return;
}
// if we change the capsule heading too often, the capsule can fall down
// therefore we snap movement vector to just 1 of 4 predefined directions (ne, nw, se, sw),
// meaning only 4 possible capsule tilt orientations
float sqr2 = 1.41421356f; // square root of 2 lasy to cut extra digits
if (movementVector.X > 0)
{
movementVector.X = sqr2;
// east ?? there is no east above
if (movementVector.Y > 0)
{
// northeast
movementVector.Y = sqr2;
}
else
{
// southeast
movementVector.Y = -sqr2;
}
}
else
{
movementVector.X = -sqr2;
// west
if (movementVector.Y > 0)
{
// northwest
movementVector.Y = sqr2;
}
else
{
// southwest
movementVector.Y = -sqr2;
}
}
// movementVector.Z is zero
// calculate tilt components based on desired amount of tilt and current (snapped) heading.
// the "-" sign is to force the tilt to be OPPOSITE the direction of movement.
float xTiltComponent = -movementVector.X * m_tiltMagnitudeWhenProjectedOnXYPlane;
float yTiltComponent = -movementVector.Y * m_tiltMagnitudeWhenProjectedOnXYPlane;
//MainConsole.Instance.Debug(movementVector.X + " " + movementVector.Y);
//MainConsole.Instance.Debug("[PHYSICS] changing avatar tilt");
d.JointSetAMotorAngle(Amotor, 0, xTiltComponent);
d.JointSetAMotorAngle(Amotor, 1, yTiltComponent);
d.JointSetAMotorAngle(Amotor, 2, 0);
d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, xTiltComponent - 0.001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, xTiltComponent + 0.001f); // must be same as lowstop, else a different, spurious tilt is introduced
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, yTiltComponent - 0.001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, yTiltComponent + 0.001f); // same as lowstop
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, - 0.001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.001f); // same as lowstop
}
*/
// This code is very useful. Written by DanX0r. We're just not using it right now.
// Commented out to prevent a warning.
//
// private void standupStraight()
// {
// // The purpose of this routine here is to quickly stabilize the Body while it's popped up in the air.
// // The amotor needs a few seconds to stabilize so without it, the avatar shoots up sky high when you
// // change appearance and when you enter the simulator
// // After this routine is done, the amotor stabilizes much quicker
// d.Vector3 feet;
// d.Vector3 head;
// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, -1.0f, out feet);
// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, 1.0f, out head);
// float posture = head.Z - feet.Z;
// // restoring force proportional to lack of posture:
// float servo = (2.5f - posture) * POSTURE_SERVO;
// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, servo, 0.0f, 0.0f, 1.0f);
// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, -servo, 0.0f, 0.0f, -1.0f);
// //d.Matrix3 bodyrotation = d.BodyGetRotation(Body);
// //MainConsole.Instance.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22);
// }
#endregion
#region Forces
/// <summary>
/// Adds the force supplied to the Target Velocity
/// The PID controller takes this target velocity and tries to make it a reality
/// </summary>
/// <param name = "force"></param>
public override void AddForce(Vector3 force, bool pushforce)
{
if (force.IsFinite())
{
if (pushforce)
{
m_pidControllerActive = false;
_parent_scene.AddSimulationChange(() =>
{
if (Body != IntPtr.Zero)
_target_force = force;
});
}
else
{
m_pidControllerActive = true;
_target_velocity.X += force.X;
_target_velocity.Y += force.Y;
_target_velocity.Z += force.Z;
}
}
else
{
MainConsole.Instance.Warn("[PHYSICS]: Got a NaN force applied to a Character");
}
//m_lastUpdateSent = false;
}
#endregion
#region Destroy
/// <summary>
/// Cleanup the things we use in the scene.
/// </summary>
public override void Destroy()
{
m_isPhysical = true;
_parent_scene.AddSimulationChange(() =>
{
_parent_scene.RemoveCharacter(this);
// destroy avatar capsule and related ODE data
_parent_ref.DestroyBodyThreadLocked();
m_isPhysical = false;
});
}
#endregion
#endregion
#region Collision events
public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
CollisionEventsThisFrame.addCollider(CollidedWith, contact);
}
public override void SendCollisions()
{
if (!IsPhysical)
return; //Not physical, its not supposed to be here
if (!CollisionEventsThisFrame.Cleared)
{
base.SendCollisionUpdate(CollisionEventsThisFrame.Copy());
CollisionEventsThisFrame.Clear();
}
}
public override bool SubscribedEvents()
{
return true;
}
#endregion
}
}
| |
using System.Diagnostics;
using System.Text;
namespace Lucene.Net.Index
{
using System.Text.RegularExpressions;
/*
* 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.
*/
// TODO: put all files under codec and remove all the static extensions here
/// <summary>
/// this class contains useful constants representing filenames and extensions
/// used by lucene, as well as convenience methods for querying whether a file
/// name matches an extension ({@link #matchesExtension(String, String)
/// matchesExtension}), as well as generating file names from a segment name,
/// generation and extension (
/// <seealso cref="#fileNameFromGeneration(String, String, long) fileNameFromGeneration"/>,
/// <seealso cref="#segmentFileName(String, String, String) segmentFileName"/>).
///
/// <p><b>NOTE</b>: extensions used by codecs are not
/// listed here. You must interact with the <seealso cref="Codec"/>
/// directly.
///
/// @lucene.internal
/// </summary>
public sealed class IndexFileNames
{
/// <summary>
/// No instance </summary>
private IndexFileNames()
{
}
/// <summary>
/// Name of the index segment file </summary>
public const string SEGMENTS = "segments";
/// <summary>
/// Extension of gen file </summary>
public const string GEN_EXTENSION = "gen";
/// <summary>
/// Name of the generation reference file name </summary>
public static readonly string SEGMENTS_GEN = "segments." + GEN_EXTENSION;
/// <summary>
/// Extension of compound file </summary>
public const string COMPOUND_FILE_EXTENSION = "cfs";
/// <summary>
/// Extension of compound file entries </summary>
public const string COMPOUND_FILE_ENTRIES_EXTENSION = "cfe";
/// <summary>
/// this array contains all filename extensions used by
/// Lucene's index files, with one exception, namely the
/// extension made up from <code>.s</code> + a number.
/// Also note that Lucene's <code>segments_N</code> files
/// do not have any filename extension.
/// </summary>
public static readonly string[] INDEX_EXTENSIONS = new string[] { COMPOUND_FILE_EXTENSION, COMPOUND_FILE_ENTRIES_EXTENSION, GEN_EXTENSION };
/// <summary>
/// Computes the full file name from base, extension and generation. If the
/// generation is -1, the file name is null. If it's 0, the file name is
/// <base>.<ext>. If it's > 0, the file name is
/// <base>_<gen>.<ext>.<br>
/// <b>NOTE:</b> .<ext> is added to the name only if <code>ext</code> is
/// not an empty string.
/// </summary>
/// <param name="base"> main part of the file name </param>
/// <param name="ext"> extension of the filename </param>
/// <param name="gen"> generation </param>
public static string FileNameFromGeneration(string @base, string ext, long gen)
{
if (gen == -1)
{
return null;
}
else if (gen == 0)
{
return SegmentFileName(@base, "", ext);
}
else
{
Debug.Assert(gen > 0);
// The '6' part in the length is: 1 for '.', 1 for '_' and 4 as estimate
// to the gen length as string (hopefully an upper limit so SB won't
// expand in the middle.
StringBuilder res = (new StringBuilder(@base.Length + 6 + ext.Length)).Append(@base).Append('_').Append(gen.ToString());
if (ext.Length > 0)
{
res.Append('.').Append(ext);
}
return res.ToString();
}
}
/// <summary>
/// Returns a file name that includes the given segment name, your own custom
/// name and extension. The format of the filename is:
/// <segmentName>(_<name>)(.<ext>).
/// <p>
/// <b>NOTE:</b> .<ext> is added to the result file name only if
/// <code>ext</code> is not empty.
/// <p>
/// <b>NOTE:</b> _<segmentSuffix> is added to the result file name only if
/// it's not the empty string
/// <p>
/// <b>NOTE:</b> all custom files should be named using this method, or
/// otherwise some structures may fail to handle them properly (such as if they
/// are added to compound files).
/// </summary>
public static string SegmentFileName(string segmentName, string segmentSuffix, string ext)
{
if (ext.Length > 0 || segmentSuffix.Length > 0)
{
Debug.Assert(!ext.StartsWith("."));
StringBuilder sb = new StringBuilder(segmentName.Length + 2 + segmentSuffix.Length + ext.Length);
sb.Append(segmentName);
if (segmentSuffix.Length > 0)
{
sb.Append('_').Append(segmentSuffix);
}
if (ext.Length > 0)
{
sb.Append('.').Append(ext);
}
return sb.ToString();
}
else
{
return segmentName;
}
}
/// <summary>
/// Returns true if the given filename ends with the given extension. One
/// should provide a <i>pure</i> extension, without '.'.
/// </summary>
public static bool MatchesExtension(string filename, string ext)
{
// It doesn't make a difference whether we allocate a StringBuilder ourself
// or not, since there's only 1 '+' operator.
return filename.EndsWith("." + ext);
}
/// <summary>
/// locates the boundary of the segment name, or -1 </summary>
private static int IndexOfSegmentName(string filename)
{
// If it is a .del file, there's an '_' after the first character
int idx = filename.IndexOf('_', 1);
if (idx == -1)
{
// If it's not, strip everything that's before the '.'
idx = filename.IndexOf('.');
}
return idx;
}
/// <summary>
/// Strips the segment name out of the given file name. If you used
/// <seealso cref="#segmentFileName"/> or <seealso cref="#fileNameFromGeneration"/> to create your
/// files, then this method simply removes whatever comes before the first '.',
/// or the second '_' (excluding both).
/// </summary>
/// <returns> the filename with the segment name removed, or the given filename
/// if it does not contain a '.' and '_'. </returns>
public static string StripSegmentName(string filename)
{
int idx = IndexOfSegmentName(filename);
if (idx != -1)
{
filename = filename.Substring(idx);
}
return filename;
}
/// <summary>
/// Parses the segment name out of the given file name.
/// </summary>
/// <returns> the segment name only, or filename
/// if it does not contain a '.' and '_'. </returns>
public static string ParseSegmentName(string filename)
{
int idx = IndexOfSegmentName(filename);
if (idx != -1)
{
filename = filename.Substring(0, idx);
}
return filename;
}
/// <summary>
/// Removes the extension (anything after the first '.'),
/// otherwise returns the original filename.
/// </summary>
public static string StripExtension(string filename)
{
int idx = filename.IndexOf('.');
if (idx != -1)
{
filename = filename.Substring(0, idx);
}
return filename;
}
/// <summary>
/// Return the extension (anything after the first '.'),
/// or null if there is no '.' in the file name.
/// </summary>
public static string GetExtension(string filename)
{
int idx = filename.IndexOf('.');
if (idx == -1)
{
return null;
}
else
{
return filename.Substring(idx + 1, filename.Length - (idx + 1));
}
}
/// <summary>
/// All files created by codecs much match this pattern (checked in
/// SegmentInfo).
/// </summary>
public static readonly Regex CODEC_FILE_PATTERN = new Regex("_[a-z0-9]+(_.*)?\\..*", RegexOptions.Compiled);
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// ProvisioningInformation
/// </summary>
[DataContract]
public partial class ProvisioningInformation : IEquatable<ProvisioningInformation>, IValidatableObject
{
public ProvisioningInformation()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="ProvisioningInformation" /> class.
/// </summary>
/// <param name="DefaultConnectionId">DefaultConnectionId.</param>
/// <param name="DefaultPlanId">DefaultPlanId.</param>
/// <param name="DistributorCode">The code that identifies the billing plan groups and plans for the new account..</param>
/// <param name="DistributorPassword">The password for the distributorCode..</param>
/// <param name="PasswordRuleText">PasswordRuleText.</param>
/// <param name="PlanPromotionText">PlanPromotionText.</param>
/// <param name="PurchaseOrderOrPromAllowed">PurchaseOrderOrPromAllowed.</param>
public ProvisioningInformation(string DefaultConnectionId = default(string), string DefaultPlanId = default(string), string DistributorCode = default(string), string DistributorPassword = default(string), string PasswordRuleText = default(string), string PlanPromotionText = default(string), string PurchaseOrderOrPromAllowed = default(string))
{
this.DefaultConnectionId = DefaultConnectionId;
this.DefaultPlanId = DefaultPlanId;
this.DistributorCode = DistributorCode;
this.DistributorPassword = DistributorPassword;
this.PasswordRuleText = PasswordRuleText;
this.PlanPromotionText = PlanPromotionText;
this.PurchaseOrderOrPromAllowed = PurchaseOrderOrPromAllowed;
}
/// <summary>
/// Gets or Sets DefaultConnectionId
/// </summary>
[DataMember(Name="defaultConnectionId", EmitDefaultValue=false)]
public string DefaultConnectionId { get; set; }
/// <summary>
/// Gets or Sets DefaultPlanId
/// </summary>
[DataMember(Name="defaultPlanId", EmitDefaultValue=false)]
public string DefaultPlanId { get; set; }
/// <summary>
/// The code that identifies the billing plan groups and plans for the new account.
/// </summary>
/// <value>The code that identifies the billing plan groups and plans for the new account.</value>
[DataMember(Name="distributorCode", EmitDefaultValue=false)]
public string DistributorCode { get; set; }
/// <summary>
/// The password for the distributorCode.
/// </summary>
/// <value>The password for the distributorCode.</value>
[DataMember(Name="distributorPassword", EmitDefaultValue=false)]
public string DistributorPassword { get; set; }
/// <summary>
/// Gets or Sets PasswordRuleText
/// </summary>
[DataMember(Name="passwordRuleText", EmitDefaultValue=false)]
public string PasswordRuleText { get; set; }
/// <summary>
/// Gets or Sets PlanPromotionText
/// </summary>
[DataMember(Name="planPromotionText", EmitDefaultValue=false)]
public string PlanPromotionText { get; set; }
/// <summary>
/// Gets or Sets PurchaseOrderOrPromAllowed
/// </summary>
[DataMember(Name="purchaseOrderOrPromAllowed", EmitDefaultValue=false)]
public string PurchaseOrderOrPromAllowed { 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 ProvisioningInformation {\n");
sb.Append(" DefaultConnectionId: ").Append(DefaultConnectionId).Append("\n");
sb.Append(" DefaultPlanId: ").Append(DefaultPlanId).Append("\n");
sb.Append(" DistributorCode: ").Append(DistributorCode).Append("\n");
sb.Append(" DistributorPassword: ").Append(DistributorPassword).Append("\n");
sb.Append(" PasswordRuleText: ").Append(PasswordRuleText).Append("\n");
sb.Append(" PlanPromotionText: ").Append(PlanPromotionText).Append("\n");
sb.Append(" PurchaseOrderOrPromAllowed: ").Append(PurchaseOrderOrPromAllowed).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 ProvisioningInformation);
}
/// <summary>
/// Returns true if ProvisioningInformation instances are equal
/// </summary>
/// <param name="other">Instance of ProvisioningInformation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ProvisioningInformation other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DefaultConnectionId == other.DefaultConnectionId ||
this.DefaultConnectionId != null &&
this.DefaultConnectionId.Equals(other.DefaultConnectionId)
) &&
(
this.DefaultPlanId == other.DefaultPlanId ||
this.DefaultPlanId != null &&
this.DefaultPlanId.Equals(other.DefaultPlanId)
) &&
(
this.DistributorCode == other.DistributorCode ||
this.DistributorCode != null &&
this.DistributorCode.Equals(other.DistributorCode)
) &&
(
this.DistributorPassword == other.DistributorPassword ||
this.DistributorPassword != null &&
this.DistributorPassword.Equals(other.DistributorPassword)
) &&
(
this.PasswordRuleText == other.PasswordRuleText ||
this.PasswordRuleText != null &&
this.PasswordRuleText.Equals(other.PasswordRuleText)
) &&
(
this.PlanPromotionText == other.PlanPromotionText ||
this.PlanPromotionText != null &&
this.PlanPromotionText.Equals(other.PlanPromotionText)
) &&
(
this.PurchaseOrderOrPromAllowed == other.PurchaseOrderOrPromAllowed ||
this.PurchaseOrderOrPromAllowed != null &&
this.PurchaseOrderOrPromAllowed.Equals(other.PurchaseOrderOrPromAllowed)
);
}
/// <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.DefaultConnectionId != null)
hash = hash * 59 + this.DefaultConnectionId.GetHashCode();
if (this.DefaultPlanId != null)
hash = hash * 59 + this.DefaultPlanId.GetHashCode();
if (this.DistributorCode != null)
hash = hash * 59 + this.DistributorCode.GetHashCode();
if (this.DistributorPassword != null)
hash = hash * 59 + this.DistributorPassword.GetHashCode();
if (this.PasswordRuleText != null)
hash = hash * 59 + this.PasswordRuleText.GetHashCode();
if (this.PlanPromotionText != null)
hash = hash * 59 + this.PlanPromotionText.GetHashCode();
if (this.PurchaseOrderOrPromAllowed != null)
hash = hash * 59 + this.PurchaseOrderOrPromAllowed.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
#if LOCALTEST
using System.Collections;
using System.Collections.Generic;
namespace System_.Collections.Generic {
#else
namespace System.Collections.Generic {
#endif
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable {
public struct Enumerator : IEnumerator<T>, IDisposable {
private List<T> list;
private int index;
internal Enumerator(List<T> list) {
this.list = list;
this.index = -1;
}
public T Current {
get {
return this.list[this.index];
}
}
public void Dispose() {
}
object IEnumerator.Current {
get {
return this.list[this.index];
}
}
public bool MoveNext() {
this.index++;
return (this.index < this.list.Count);
}
public void Reset() {
this.index = -1;
}
}
private const int defaultCapacity = 4;
private T[] items;
private int size;
public List() : this(defaultCapacity) { }
public List(int capacity) {
if (capacity < 0) {
throw new ArgumentOutOfRangeException("capacity");
}
this.items = new T[capacity];
this.size = 0;
}
public List(IEnumerable<T> collection) {
ICollection<T> iCol = collection as ICollection<T>;
if (iCol != null) {
this.size = iCol.Count;
this.items = new T[this.size];
iCol.CopyTo(this.items, 0);
} else {
this.items = new T[defaultCapacity];
this.size = 0;
foreach (T item in collection) {
this.Add(item);
}
}
}
private void EnsureSpace(int space) {
if (this.size + space > this.items.Length) {
Array.Resize<T>(ref this.items, Math.Max(this.items.Length << 1, 4));
}
}
private void Shift(int index, int count) {
if (count > 0) {
this.EnsureSpace(count);
for (int i = this.size - 1; i >= index; i--) {
this.items[i + count] = this.items[i];
}
} else {
for (int i = index; i < this.size + count; i++) {
this.items[i] = this.items[i - count];
}
}
this.size += count;
}
public void Add(T item) {
this.EnsureSpace(1);
this.items[this.size++] = item;
}
public int Count {
get {
return this.size;
}
}
public int Capacity {
get {
return this.items.Length;
}
set {
throw new NotImplementedException();
}
}
public T this[int index] {
get {
if (index >= this.size || index < 0) {
throw new ArgumentOutOfRangeException("index");
}
return this.items[index];
}
set {
if (index >= this.size || index < 0) {
throw new ArgumentOutOfRangeException("index");
}
this.items[index] = value;
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
public int IndexOf(T item, int start, int count) {
return Array.IndexOf<T>(this.items, item, start, count);
}
public int IndexOf(T item, int start) {
return this.IndexOf(item, start, this.size - start);
}
public void InsertRange(int index, IEnumerable<T> collection) {
if (collection == null) {
throw new ArgumentNullException("collection");
}
if (index < 0 || index > this.size) {
throw new ArgumentOutOfRangeException("index");
}
List<T> toInsert = new List<T>(collection);
this.Shift(index, toInsert.Count);
for (int i = 0; i < toInsert.Count; i++) {
this.items[index + i] = toInsert[i];
}
}
public T[] ToArray() {
T[] array = new T[this.size];
Array.Copy(this.items, array, this.size);
return array;
}
#region Interface Members
public int IndexOf(T item) {
return this.IndexOf(item, 0, size);
}
public void Insert(int index, T item) {
if (index < 0 || index > this.size) {
throw new ArgumentOutOfRangeException("index");
}
this.Shift(index, 1);
this.items[index] = item;
}
public void RemoveAt(int index) {
this.Shift(index, -1);
}
public bool IsReadOnly {
get {
return false;
}
}
public void Clear() {
Array.Clear(this.items, 0, this.items.Length);
this.size = 0;
}
public bool Contains(T item) {
return Array.IndexOf(this.items, item) >= 0;
}
public void CopyTo(T[] array, int arrayIndex) {
Array.Copy(this.items, 0, (Array)array, arrayIndex, this.size);
}
public bool Remove(T item) {
int idx = Array.IndexOf(this.items, item);
if (idx >= 0) {
this.RemoveAt(idx);
return true;
}
return false;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
public bool IsFixedSize {
get {
return false;
}
}
object IList.this[int index] {
get {
return this[index];
}
set {
this[index] = (T)value;
}
}
public int Add(object value) {
this.Add((T)value);
return this.items.Length - 1;
}
public bool Contains(object value) {
return this.Contains((T)value);
}
public int IndexOf(object value) {
return this.IndexOf((T)value);
}
public void Insert(int index, object value) {
this.Insert(index, (T)value);
}
public void Remove(object value) {
this.Remove((T)value);
}
public bool IsSynchronized {
get {
return false;
}
}
public object SyncRoot {
get {
return this;
}
}
public void CopyTo(Array array, int index) {
Array.Copy(this.items, 0, array, index, this.size);
}
#endregion
}
}
| |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace SixLabors.Fonts.Unicode
{
/// <summary>
/// Represents a Unicode value ([ U+0000..U+10FFFF ], inclusive).
/// </summary>
/// <remarks>
/// This type's constructors and conversion operators validate the input, so consumers can call the APIs
/// assuming that the underlying <see cref="CodePoint"/> instance is well-formed.
/// </remarks>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly struct CodePoint : IComparable, IComparable<CodePoint>, IEquatable<CodePoint>
{
// Supplementary plane code points are encoded as 2 UTF-16 code units
private const int MaxUtf16CharsPerCodePoint = 2;
// Supplementary plane code points are encoded as 4 UTF-8 code units
internal const int MaxUtf8BytesPerCodePoint = 4;
private const byte IsWhiteSpaceFlag = 0x80;
private const byte IsLetterOrDigitFlag = 0x40;
private const byte UnicodeCategoryMask = 0x1F;
private readonly uint value;
/// <summary>
/// Initializes a new instance of the <see cref="CodePoint"/> struct.
/// </summary>
/// <param name="value">The char representing the UTF-16 code unit</param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="value"/> represents a UTF-16 surrogate code point
/// U+D800..U+DFFF, inclusive.
/// </exception>
public CodePoint(char value)
{
uint expanded = value;
if (UnicodeUtility.IsSurrogateCodePoint(expanded))
{
ThrowArgumentOutOfRange(expanded, nameof(value), "Must not be in [ U+D800..U+DFFF ], inclusive.");
}
this.value = expanded;
}
/// <summary>
/// Initializes a new instance of the <see cref="CodePoint"/> struct.
/// </summary>
/// <param name="highSurrogate">A char representing a UTF-16 high surrogate code unit.</param>
/// <param name="lowSurrogate">A char representing a UTF-16 low surrogate code unit.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="highSurrogate"/> does not represent a UTF-16 high surrogate code unit
/// or <paramref name="lowSurrogate"/> does not represent a UTF-16 low surrogate code unit.
/// </exception>
public CodePoint(char highSurrogate, char lowSurrogate)
: this((uint)char.ConvertToUtf32(highSurrogate, lowSurrogate), false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodePoint"/> struct.
/// </summary>
/// <param name="value">The value to create the codepoint.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="value"/> does not represent a value Unicode scalar value.
/// </exception>
public CodePoint(int value)
: this((uint)value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodePoint"/> struct.
/// </summary>
/// <param name="value">The value to create the codepoint.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="value"/> does not represent a value Unicode scalar value.
/// </exception>
public CodePoint(uint value)
{
if (!IsValid(value))
{
ThrowArgumentOutOfRange(value, nameof(value), "Must be in [ U+0000..U+10FFFF ], inclusive.");
}
this.value = value;
}
// Non-validating ctor
#pragma warning disable IDE0060 // Remove unused parameter
private CodePoint(uint scalarValue, bool unused)
{
UnicodeUtility.DebugAssertIsValidCodePoint(scalarValue);
this.value = scalarValue;
}
#pragma warning restore IDE0060 // Remove unused parameter
// Contains information about the ASCII character range [ U+0000..U+007F ], with:
// - 0x80 bit if set means 'is whitespace'
// - 0x40 bit if set means 'is letter or digit'
// - 0x20 bit is reserved for future use
// - bottom 5 bits are the UnicodeCategory of the character
private static ReadOnlySpan<byte> AsciiCharInfo => new byte[]
{
0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x8E, 0x8E, 0x8E, 0x8E, 0x8E, 0x0E, 0x0E, // U+0000..U+000F
0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, // U+0010..U+001F
0x8B, 0x18, 0x18, 0x18, 0x1A, 0x18, 0x18, 0x18, 0x14, 0x15, 0x18, 0x19, 0x18, 0x13, 0x18, 0x18, // U+0020..U+002F
0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x18, 0x18, 0x19, 0x19, 0x19, 0x18, // U+0030..U+003F
0x18, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, // U+0040..U+004F
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x14, 0x18, 0x15, 0x1B, 0x12, // U+0050..U+005F
0x1B, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // U+0060..U+006F
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x14, 0x19, 0x15, 0x19, 0x0E, // U+0070..U+007F
};
/// <summary>
/// Gets a value indicating whether this value is ASCII ([ U+0000..U+007F ])
/// and therefore representable by a single UTF-8 code unit.
/// </summary>
public bool IsAscii => UnicodeUtility.IsAsciiCodePoint(this.value);
/// <summary>
/// Gets a value indicating whether this value is within the BMP ([ U+0000..U+FFFF ])
/// and therefore representable by a single UTF-16 code unit.
/// </summary>
public bool IsBmp => UnicodeUtility.IsBmpCodePoint(this.value);
/// <summary>
/// Gets the Unicode plane (0 to 16, inclusive) which contains this scalar.
/// </summary>
public int Plane => UnicodeUtility.GetPlane(this.value);
// Displayed as "'<char>' (U+XXXX)"; e.g., "'e' (U+0065)"
private string DebuggerDisplay => FormattableString.Invariant($"U+{this.value:X4} '{(IsValid(this.value) ? this.ToString() : "\uFFFD")}'");
/// <summary>
/// Gets the Unicode value as an integer.
/// </summary>
public int Value => (int)this.value;
/// <summary>
/// Gets the length in code units (<see cref="char"/>) of the
/// UTF-16 sequence required to represent this scalar value.
/// </summary>
/// <remarks>
/// The return value will be 1 or 2.
/// </remarks>
public int Utf16SequenceLength
{
get
{
int codeUnitCount = UnicodeUtility.GetUtf16SequenceLength(this.value);
Debug.Assert(codeUnitCount is > 0 and <= MaxUtf16CharsPerCodePoint, $"Invalid Utf16SequenceLength {codeUnitCount}.");
return codeUnitCount;
}
}
/// <summary>
/// Gets the length in code units of the
/// UTF-8 sequence required to represent this scalar value.
/// </summary>
/// <remarks>
/// The return value will be 1 through 4, inclusive.
/// </remarks>
public int Utf8SequenceLength
{
get
{
int codeUnitCount = UnicodeUtility.GetUtf8SequenceLength(this.value);
Debug.Assert(codeUnitCount is > 0 and <= MaxUtf8BytesPerCodePoint, $"Invalid Utf8SequenceLength {codeUnitCount}.");
return codeUnitCount;
}
}
/// <summary>
/// Gets a <see cref="CodePoint"/> instance that represents the Unicode replacement character U+FFFD.
/// </summary>
public static CodePoint ReplacementChar { get; } = new CodePoint(0xFFFD);
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
// Operators below are explicit because they may throw.
public static explicit operator CodePoint(char ch) => new(ch);
public static explicit operator CodePoint(uint value) => new(value);
public static explicit operator CodePoint(int value) => new(value);
public static bool operator ==(CodePoint left, CodePoint right) => left.value == right.value;
public static bool operator !=(CodePoint left, CodePoint right) => left.value != right.value;
public static bool operator <(CodePoint left, CodePoint right) => left.value < right.value;
public static bool operator <=(CodePoint left, CodePoint right) => left.value <= right.value;
public static bool operator >(CodePoint left, CodePoint right) => left.value > right.value;
public static bool operator >=(CodePoint left, CodePoint right) => left.value >= right.value;
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
/// <summary>
/// Returns <see langword="true"/> if <paramref name="value"/> is a valid Unicode code
/// point, i.e., is in [ U+0000..U+10FFFF ], inclusive.
/// </summary>
/// <param name="value">The value to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="value"/> represents a valid codepoint; otherwise, <see langword="false"/></returns>
public static bool IsValid(int value) => IsValid((uint)value);
/// <summary>
/// Returns <see langword="true"/> if <paramref name="value"/> is a valid Unicode code
/// point, i.e., is in [ U+0000..U+10FFFF ], inclusive.
/// </summary>
/// <param name="value">The value to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="value"/> represents a valid codepoint; otherwise, <see langword="false"/></returns>
public static bool IsValid(uint value) => UnicodeUtility.IsValidCodePoint(value);
/// <summary>
/// Gets a value indicating whether the given codepoint is white space.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a whitespace character; otherwise, <see langword="false"/></returns>
public static bool IsWhiteSpace(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return (AsciiCharInfo[codePoint.Value] & IsWhiteSpaceFlag) != 0;
}
// Only BMP code points can be white space, so only call into char
// if the incoming value is within the BMP.
return codePoint.IsBmp && char.IsWhiteSpace((char)codePoint.Value);
}
/// <summary>
/// Gets a value indicating whether the given codepoint is a non-breaking space.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a non-breaking space character; otherwise, <see langword="false"/></returns>
public static bool IsNonBreakingSpace(CodePoint codePoint)
=> codePoint.Value == 0x00A0;
/// <summary>
/// Gets a value indicating whether the given codepoint is a zero-width-non-joiner.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a zero-width-non-joiner character; otherwise, <see langword="false"/></returns>
public static bool IsZeroWidthNonJoiner(CodePoint codePoint)
=> codePoint.Value == 0x200C;
/// <summary>
/// Gets a value indicating whether the given codepoint is a zero-width-joiner.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a zero-width-joiner character; otherwise, <see langword="false"/></returns>
public static bool IsZeroWidthJoiner(CodePoint codePoint)
=> codePoint.Value == 0x200D;
/// <summary>
/// Gets a value indicating whether the given codepoint is a variation selector.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a variation selector character; otherwise, <see langword="false"/></returns>
public static bool IsVariationSelector(CodePoint codePoint)
=> (codePoint.Value & 0xFFF0) == 0xFE00; // See https://en.wikipedia.org/wiki/Variation_Selectors_%28Unicode_block%29
/// <summary>
/// Gets a value indicating whether the given codepoint is a control character.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a control character; otherwise, <see langword="false"/></returns>
public static bool IsControl(CodePoint codePoint) =>
// Per the Unicode stability policy, the set of control characters
// is forever fixed at [ U+0000..U+001F ], [ U+007F..U+009F ]. No
// characters will ever be added to or removed from the "control characters"
// group. See https://www.unicode.org/policies/stability_policy.html.
//
// Logic below depends on CodePoint.Value never being -1 (since CodePoint is a validating type)
// 00..1F (+1) => 01..20 (&~80) => 01..20
// 7F..9F (+1) => 80..A0 (&~80) => 00..20
((codePoint.value + 1) & ~0x80u) <= 0x20u;
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a decimal digit.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a decimal digit; otherwise, <see langword="false"/></returns>
public static bool IsDigit(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return UnicodeUtility.IsInRangeInclusive(codePoint.value, '0', '9');
}
else
{
return GetGeneralCategory(codePoint) == UnicodeCategory.DecimalDigitNumber;
}
}
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a letter.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a letter; otherwise, <see langword="false"/></returns>
public static bool IsLetter(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return ((codePoint.value - 'A') & ~0x20u) <= 'Z' - 'A'; // [A-Za-z]
}
else
{
return IsCategoryLetter(GetGeneralCategory(codePoint));
}
}
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a letter or decimal digit.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a letter or decimal digit; otherwise, <see langword="false"/></returns>
public static bool IsLetterOrDigit(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return (AsciiCharInfo[codePoint.Value] & IsLetterOrDigitFlag) != 0;
}
else
{
return IsCategoryLetterOrDecimalDigit(GetGeneralCategory(codePoint));
}
}
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a lowercase letter.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a lowercase letter; otherwise, <see langword="false"/></returns>
public static bool IsLower(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return UnicodeUtility.IsInRangeInclusive(codePoint.value, 'a', 'z');
}
else
{
return GetGeneralCategory(codePoint) == UnicodeCategory.LowercaseLetter;
}
}
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a number.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a number; otherwise, <see langword="false"/></returns>
public static bool IsNumber(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return UnicodeUtility.IsInRangeInclusive(codePoint.value, '0', '9');
}
else
{
return IsCategoryNumber(GetGeneralCategory(codePoint));
}
}
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as punctuation.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is punctuation; otherwise, <see langword="false"/></returns>
public static bool IsPunctuation(CodePoint codePoint)
=> IsCategoryPunctuation(GetGeneralCategory(codePoint));
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a separator.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a separator; otherwise, <see langword="false"/></returns>
public static bool IsSeparator(CodePoint codePoint)
=> IsCategorySeparator(GetGeneralCategory(codePoint));
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a symbol.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a symbol; otherwise, <see langword="false"/></returns>
public static bool IsSymbol(CodePoint codePoint)
=> IsCategorySymbol(GetGeneralCategory(codePoint));
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as a mark.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a symbol; otherwise, <see langword="false"/></returns>
public static bool IsMark(CodePoint codePoint)
=> IsCategoryMark(GetGeneralCategory(codePoint));
/// <summary>
/// Returns a value that indicates whether the specified codepoint is categorized as an uppercase letter.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a uppercase letter; otherwise, <see langword="false"/></returns>
public static bool IsUpper(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return UnicodeUtility.IsInRangeInclusive(codePoint.value, 'A', 'Z');
}
else
{
return GetGeneralCategory(codePoint) == UnicodeCategory.UppercaseLetter;
}
}
/// <summary>
/// Gets a value indicating whether the given codepoint is a tabulation indicator.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a tabulation indicator; otherwise, <see langword="false"/></returns>
public static bool IsTabulation(CodePoint codePoint)
=> codePoint.value == 0x0009;
/// <summary>
/// Gets a value indicating whether the given codepoint is a new line indicator.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns><see langword="true"/> if <paramref name="codePoint"/> is a new line indicator; otherwise, <see langword="false"/></returns>
public static bool IsNewLine(CodePoint codePoint)
{
// See https://www.unicode.org/standard/reports/tr13/tr13-5.html
switch (codePoint.Value)
{
case 0x000A: // LINE FEED (LF)
case 0x000B: // LINE TABULATION (VT)
case 0x000C: // FORM FEED (FF)
case 0x000D: // CARRIAGE RETURN (CR)
case 0x0085: // NEXT LINE (NEL)
case 0x2028: // LINE SEPARATOR (LS)
case 0x2029: // PARAGRAPH SEPARATOR (PS)
return true;
default:
return false;
}
}
/// <summary>
/// Returns the number of codepoints in a given string buffer.
/// </summary>
/// <param name="source">The source buffer to parse.</param>
/// <returns>The <see cref="int"/>.</returns>
public static int GetCodePointCount(ReadOnlySpan<char> source)
{
if (source.IsEmpty)
{
return 0;
}
int count = 0;
var enumerator = new SpanCodePointEnumerator(source);
while (enumerator.MoveNext())
{
count++;
}
return count;
}
/// <summary>
/// Gets the canonical representation of a given codepoint.
/// <see href="http://www.unicode.org/L2/L2013/13123-norm-and-bpa.pdf"/>
/// </summary>
/// <param name="codePoint">The code point to be mapped.</param>
/// <returns>The mapped canonical code point, or the passed <paramref name="codePoint"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static CodePoint GetCanonicalType(CodePoint codePoint)
{
if (codePoint.Value == 0x3008)
{
return new CodePoint(0x2329);
}
if (codePoint.Value == 0x3009)
{
return new CodePoint(0x232A);
}
return codePoint;
}
/// <summary>
/// Gets the <see cref="BidiClass"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="BidiClass"/>.</returns>
public static BidiClass GetBidiClass(CodePoint codePoint)
=> new(codePoint);
/// <summary>
/// Gets the codepoint representing the bidi mirror for this instance.
/// <see href="http://www.unicode.org/reports/tr44/#Bidi_Mirrored"/>
/// </summary>
/// <param name="codePoint">The code point to be mapped.</param>
/// <param name="mirror">
/// When this method returns, contains the codepoint representing the bidi mirror for this instance;
/// otherwise, the default value for the type of the <paramref name="codePoint"/> parameter.
/// This parameter is passed uninitialized.
/// .</param>
/// <returns><see langword="true"/> if this instance has a mirror; otherwise, <see langword="false"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetBidiMirror(CodePoint codePoint, out CodePoint mirror)
{
uint value = UnicodeData.GetBidiMirror(codePoint.Value);
if (value == 0u)
{
mirror = default;
return false;
}
mirror = new CodePoint(value);
return true;
}
/// <summary>
/// Gets the codepoint representing the vertical mirror for this instance.
/// <see href="https://www.unicode.org/reports/tr50/#vertical_alternates"/>
/// </summary>
/// <param name="codePoint">The code point to be mapped.</param>
/// <param name="mirror">
/// When this method returns, contains the codepoint representing the vertical mirror for this instance;
/// otherwise, the default value for the type of the <paramref name="codePoint"/> parameter.
/// This parameter is passed uninitialized.
/// .</param>
/// <returns><see langword="true"/> if this instance has a mirror; otherwise, <see langword="false"/></returns>
public static bool TryGetVerticalMirror(CodePoint codePoint, out CodePoint mirror)
{
uint value = UnicodeUtility.GetVerticalMirror((uint)codePoint.Value);
if (value == 0u)
{
mirror = default;
return false;
}
mirror = new CodePoint(value);
return true;
}
/// <summary>
/// Gets the <see cref="LineBreakClass"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="LineBreakClass"/>.</returns>
public static LineBreakClass GetLineBreakClass(CodePoint codePoint)
=> UnicodeData.GetLineBreakClass(codePoint.Value);
/// <summary>
/// Gets the <see cref="GraphemeClusterClass"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="GraphemeClusterClass"/>.</returns>
public static GraphemeClusterClass GetGraphemeClusterClass(CodePoint codePoint)
=> UnicodeData.GetGraphemeClusterClass(codePoint.Value);
/// <summary>
/// Gets the <see cref="JoiningClass"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="BidiClass"/>.</returns>
internal static JoiningClass GetJoiningClass(CodePoint codePoint)
=> new(codePoint);
/// <summary>
/// Gets the <see cref="ScriptClass"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="ScriptClass"/>.</returns>
internal static ScriptClass GetScriptClass(CodePoint codePoint)
=> UnicodeData.GetScriptClass(codePoint.Value);
/// <summary>
/// Gets the <see cref="UnicodeCategory"/> for the given codepoint.
/// </summary>
/// <param name="codePoint">The codepoint to evaluate.</param>
/// <returns>The <see cref="UnicodeCategory"/>.</returns>
public static UnicodeCategory GetGeneralCategory(CodePoint codePoint)
{
if (codePoint.IsAscii)
{
return (UnicodeCategory)(AsciiCharInfo[codePoint.Value] & UnicodeCategoryMask);
}
return UnicodeData.GetUnicodeCategory(codePoint.Value);
}
/// <summary>
/// Reads the <see cref="CodePoint"/> at specified position.
/// </summary>
/// <param name="text">The text to read from.</param>
/// <param name="index">The index to read at.</param>
/// <param name="charsConsumed">The count of chars consumed reading the buffer.</param>
/// <returns>The <see cref="CodePoint"/>.</returns>
internal static CodePoint ReadAt(string text, int index, out int charsConsumed)
=> DecodeFromUtf16At(text.AsMemory().Span, index, out charsConsumed);
/// <summary>
/// Decodes the <see cref="CodePoint"/> from the provided UTF-16 source buffer at the specified position.
/// </summary>
/// <param name="source">The buffer to read from.</param>
/// <param name="index">The index to read at.</param>
/// <returns>The <see cref="CodePoint"/>.</returns>
internal static CodePoint DecodeFromUtf16At(ReadOnlySpan<char> source, int index)
=> DecodeFromUtf16At(source, index, out int _);
/// <summary>
/// Decodes the <see cref="CodePoint"/> from the provided UTF-16 source buffer at the specified position.
/// </summary>
/// <param name="source">The buffer to read from.</param>
/// <param name="index">The index to read at.</param>
/// <param name="charsConsumed">The count of chars consumed reading the buffer.</param>
/// <returns>The <see cref="CodePoint"/>.</returns>
internal static CodePoint DecodeFromUtf16At(ReadOnlySpan<char> source, int index, out int charsConsumed)
{
if (index >= source.Length)
{
charsConsumed = 0;
return default;
}
// Optimistically assume input is within BMP.
charsConsumed = 1;
uint code = source[index];
// High surrogate
if (UnicodeUtility.IsHighSurrogateCodePoint(code))
{
uint hi, low;
hi = code;
index++;
if (index == source.Length)
{
return ReplacementChar;
}
low = source[index];
if (UnicodeUtility.IsLowSurrogateCodePoint(low))
{
charsConsumed = 2;
return new CodePoint(UnicodeUtility.GetScalarFromUtf16SurrogatePair(hi, low));
}
return ReplacementChar;
}
return new CodePoint(code);
}
/// <inheritdoc cref="IComparable.CompareTo" />
int IComparable.CompareTo(object? obj)
{
if (obj is null)
{
return 1; // non-null ("this") always sorts after null
}
if (obj is CodePoint other)
{
return this.CompareTo(other);
}
throw new ArgumentException("Object must be of type CodePoint.");
}
/// <inheritdoc/>
public int CompareTo(CodePoint other)
// Values don't span entire 32-bit domain so won't integer overflow.
=> this.Value - other.Value;
/// <inheritdoc/>
public override bool Equals(object? obj) => obj is CodePoint point && this.Equals(point);
/// <inheritdoc/>
public bool Equals(CodePoint other) => this.value == other.value;
/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(this.value);
/// <inheritdoc/>
public override string ToString()
{
if (this.IsBmp)
{
return ((char)this.value).ToString();
}
else
{
Span<char> buffer = stackalloc char[MaxUtf16CharsPerCodePoint];
UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneCodePoint(this.value, out buffer[0], out buffer[1]);
return buffer.ToString();
}
}
/// <summary>
/// Returns this instance displayed as "'<char>' (U+XXXX)"; e.g., "'e' (U+0065)"
/// </summary>
/// <returns>The <see cref="string"/>.</returns>
internal string ToDebuggerDisplay() => this.DebuggerDisplay;
// Returns true if this Unicode category represents a letter
private static bool IsCategoryLetter(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.UppercaseLetter, (uint)UnicodeCategory.OtherLetter);
// Returns true if this Unicode category represents a letter or a decimal digit
private static bool IsCategoryLetterOrDecimalDigit(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.UppercaseLetter, (uint)UnicodeCategory.OtherLetter)
|| (category == UnicodeCategory.DecimalDigitNumber);
// Returns true if this Unicode category represents a number
private static bool IsCategoryNumber(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.DecimalDigitNumber, (uint)UnicodeCategory.OtherNumber);
// Returns true if this Unicode category represents a punctuation mark
private static bool IsCategoryPunctuation(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.ConnectorPunctuation, (uint)UnicodeCategory.OtherPunctuation);
// Returns true if this Unicode category represents a separator
private static bool IsCategorySeparator(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.SpaceSeparator, (uint)UnicodeCategory.ParagraphSeparator);
// Returns true if this Unicode category represents a symbol
private static bool IsCategorySymbol(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.MathSymbol, (uint)UnicodeCategory.OtherSymbol);
// Returns true if this Unicode category represents a mark
private static bool IsCategoryMark(UnicodeCategory category)
=> UnicodeUtility.IsInRangeInclusive((uint)category, (uint)UnicodeCategory.NonSpacingMark, (uint)UnicodeCategory.EnclosingMark);
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowArgumentOutOfRange(uint value, string paramName, string message)
=> throw new ArgumentOutOfRangeException(paramName, $"The value {UnicodeUtility.ToHexString(value)} is not a valid Unicode code point value. {message}");
}
}
| |
using System;
using System.Threading;
namespace MonoBrickFirmware.Movement
{
/// <summary>
/// Class for controlling a vehicle
/// </summary>
public class Vehicle{
private MotorSync motorSync = new MotorSync(MotorPort.OutA, MotorPort.OutD);
private MotorPort leftPort;
private MotorPort rightPort;
/// <summary>
/// Initializes a new instance of the Vehicle class.
/// </summary>
/// <param name='left'>
/// The left motor of the vehicle
/// </param>
/// <param name='right'>
/// The right motor of the vehicle
/// </param>
public Vehicle(MotorPort left, MotorPort right){
LeftPort = left;
RightPort = right;
}
/// <summary>
/// Gets or sets the left motor
/// </summary>
/// <value>
/// The left motor
/// </value>
public MotorPort LeftPort{
get{
return leftPort;
}
set{
leftPort = value;
motorSync.BitField = motorSync.MotorPortToBitfield(leftPort) | motorSync.MotorPortToBitfield(rightPort);
}
}
/// <summary>
/// Gets or sets the right motor
/// </summary>
/// <value>
/// The right motor
/// </value>
public MotorPort RightPort{
get{
return rightPort;
}
set{
rightPort = value;
motorSync.BitField = motorSync.MotorPortToBitfield(leftPort) | motorSync.MotorPortToBitfield(rightPort);
}
}
/// <summary>
/// Gets or sets a value indicating whether the left motor is running in reverse direction
/// </summary>
/// <value>
/// <c>true</c> if left motor is reverse; otherwise, <c>false</c>.
/// </value>
public bool ReverseLeft{get; set;}
/// <summary>
/// Gets or sets a value indicating whether the right motor is running in reverse direction
/// </summary>
/// <value>
/// <c>true</c> if right motor is reverse; otherwise, <c>false</c>.
/// </value>
public bool ReverseRight{get;set;}
/// <summary>
/// Run backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void Backward(sbyte speed){
Backward((sbyte)-speed, 0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Run backwards
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle Backward(sbyte speed, UInt32 degrees, bool brake){
return Move((sbyte)-speed, degrees, brake);
}
/// <summary>
/// Run forward
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
public void Forward(sbyte speed){
Forward(speed, 0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Run forward
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle Forward(sbyte speed, UInt32 degrees, bool brake){
return Move(speed,degrees, brake);
}
/// <summary>
/// Spins the vehicle left.
/// </summary>
/// <param name="speed">Speed of the vehicle -100 to 100</param>
public void SpinLeft(sbyte speed){
SpinLeft(speed,0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Spins the left.
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle SpinLeft(sbyte speed, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleSpinLeft(speed, degrees, brake);
}
else{
handle = HandleSpinRight(speed, degrees, brake);
}
return handle;
}
/// <summary>
/// Spins the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed -100 to 100
/// </param>
public void SpinRight(sbyte speed){
SpinRight(speed,0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Spins the vehicle right
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle SpinRight(sbyte speed, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleSpinRight(speed, degrees, brake);
}
else{
handle = HandleSpinLeft(speed, degrees, brake);
}
return handle;
}
/// <summary>
/// Stop moving the vehicle
/// </summary>
public void Off(){
motorSync.Off();
}
/// <summary>
/// Brake the vehicle (the motor is still on but it does not move)
/// </summary>
public void Brake(){
motorSync.Brake();
}
/// <summary>
/// Turns the vehicle right
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent
/// </param>
public void TurnRightForward(sbyte speed, sbyte turnPercent){
TurnRightForward(speed, turnPercent,0,false);
motorSync.CancelPolling();
}
/// <summary>
/// Turns the vehicle right
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="turnPercent">Turn percent.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle TurnRightForward(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleRightForward(speed, turnPercent, degrees, brake);
}
else{
handle = HandleLeftForward(speed,turnPercent, degrees, brake);
}
return handle;
}
/// <summary>
/// Turns the vehicle right while moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnRightReverse(sbyte speed, sbyte turnPercent){
TurnRightReverse(speed,turnPercent,0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Turns the vehicle right while moving backwards
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="turnPercent">Turn percent.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle TurnRightReverse(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleRightReverse(speed, turnPercent, degrees, brake);
}
else{
handle = HandleLeftReverse(speed,turnPercent, degrees, brake);
}
return handle;
}
/// <summary>
/// Turns the vehicle left
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnLeftForward(sbyte speed, sbyte turnPercent){
TurnLeftForward(speed,turnPercent, 0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Turns the vehicle left
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="turnPercent">Turn percent.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle TurnLeftForward(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleLeftForward(speed, turnPercent, degrees, brake);
}
else{
handle = HandleRightForward(speed,turnPercent, degrees, brake);
}
return handle;
}
/// <summary>
/// Turns the vehicle left while moving backwards
/// </summary>
/// <param name='speed'>
/// Speed of the vehicle -100 to 100
/// </param>
/// <param name='turnPercent'>
/// Turn percent.
/// </param>
public void TurnLeftReverse(sbyte speed, sbyte turnPercent){
TurnLeftReverse(speed,turnPercent, 0, false);
motorSync.CancelPolling();
}
/// <summary>
/// Turns the vehicle left while moving backwards
/// </summary>
/// <param name="speed">Speed.</param>
/// <param name="turnPercent">Turn percent.</param>
/// <param name="degrees">Degrees.</param>
/// <param name="brake">If set to <c>true</c> motors will brake when done otherwise off.</param>
public WaitHandle TurnLeftReverse(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle;
if(leftPort < rightPort){
handle = HandleLeftReverse(speed, turnPercent, degrees, brake);
}
else{
handle = HandleRightReverse(speed,turnPercent, degrees, brake);
}
return handle;
}
private WaitHandle HandleLeftForward(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, (short) -turnPercent, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) ((short)-200+ (short)turnPercent), degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, (short) ((short)-200+(short)turnPercent), degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) -turnPercent, degrees, brake);
}
return handle;
}
private WaitHandle HandleRightForward(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, (short) turnPercent, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync(speed, (short) ((short)200- (short)turnPercent), degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) ((short)200-(short)turnPercent), degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) turnPercent, degrees, brake);
}
return handle;
}
private WaitHandle HandleLeftReverse (sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake)
{
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) -turnPercent, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)speed,(short) ( (short)-200+(short)turnPercent), degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) ( (short)-200+(short)turnPercent), degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync(speed, (short) -turnPercent, degrees, brake);
}
return handle;
}
private WaitHandle HandleRightReverse(sbyte speed, sbyte turnPercent, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) turnPercent, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed,(short) ( (short)200-(short)turnPercent), degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)speed, (short) ( (short)200-(short)turnPercent), degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync(speed, (short) turnPercent, degrees, brake);
}
return handle;
}
private WaitHandle HandleSpinRight(sbyte speed, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, 200, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync(speed, (short) 0, degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, 0, degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, 200, degrees, brake);
}
return handle;
}
private WaitHandle HandleSpinLeft(sbyte speed, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, -200, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, (short) 0, degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, 0, degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, -200, degrees, brake);
}
return handle;
}
private WaitHandle Move(sbyte speed, UInt32 degrees, bool brake){
WaitHandle handle = null;
if(!ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, 0, degrees, brake);
}
if(!ReverseLeft && ReverseRight){
handle = motorSync.StepSync(speed, (short) 200, degrees, brake);
}
if(ReverseLeft && !ReverseRight){
handle = motorSync.StepSync(speed, -200, degrees, brake);
}
if(ReverseLeft && ReverseRight){
handle = motorSync.StepSync((sbyte)-speed, 0, degrees, brake);
}
return handle;
}
}
}
| |
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Devtools.Cloudtrace.V1
{
/// <summary>
/// Settings for a <see cref="TraceServiceClient"/>.
/// </summary>
public sealed partial class TraceServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="TraceServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="TraceServiceSettings"/>.
/// </returns>
public static TraceServiceSettings GetDefault() => new TraceServiceSettings();
/// <summary>
/// Constructs a new <see cref="TraceServiceSettings"/> object with default settings.
/// </summary>
public TraceServiceSettings() { }
private TraceServiceSettings(TraceServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
PatchTracesSettings = existing.PatchTracesSettings;
GetTraceSettings = existing.GetTraceSettings;
ListTracesSettings = existing.ListTracesSettings;
}
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 1000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.2</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(1000),
delayMultiplier: 1.2
);
/// <summary>
/// "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Maximum timeout: 30000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(30000),
delayMultiplier: 1.5
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.PatchTraces</c> and <c>TraceServiceClient.PatchTracesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.PatchTraces</c> and
/// <c>TraceServiceClient.PatchTracesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings PatchTracesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.GetTrace</c> and <c>TraceServiceClient.GetTraceAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.GetTrace</c> and
/// <c>TraceServiceClient.GetTraceAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings GetTraceSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.ListTraces</c> and <c>TraceServiceClient.ListTracesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.ListTraces</c> and
/// <c>TraceServiceClient.ListTracesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings ListTracesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="TraceServiceSettings"/> object.</returns>
public TraceServiceSettings Clone() => new TraceServiceSettings(this);
}
/// <summary>
/// TraceService client wrapper, for convenient use.
/// </summary>
public abstract partial class TraceServiceClient
{
/// <summary>
/// The default endpoint for the TraceService service, which is a host of "cloudtrace.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("cloudtrace.googleapis.com", 443);
/// <summary>
/// The default TraceService scopes.
/// </summary>
/// <remarks>
/// The default TraceService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// <item><description>"https://www.googleapis.com/auth/trace.append"</description></item>
/// <item><description>"https://www.googleapis.com/auth/trace.readonly"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/trace.append",
"https://www.googleapis.com/auth/trace.readonly",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="TraceServiceClient"/>.</returns>
public static async Task<TraceServiceClient> CreateAsync(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The created <see cref="TraceServiceClient"/>.</returns>
public static TraceServiceClient Create(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="TraceServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The created <see cref="TraceServiceClient"/>.</returns>
public static TraceServiceClient Create(Channel channel, TraceServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
TraceService.TraceServiceClient grpcClient = new TraceService.TraceServiceClient(channel);
return new TraceServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC TraceService client.
/// </summary>
public virtual TraceService.TraceServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task PatchTracesAsync(
string projectId,
Traces traces,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task PatchTracesAsync(
string projectId,
Traces traces,
CancellationToken cancellationToken) => PatchTracesAsync(
projectId,
traces,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void PatchTraces(
string projectId,
Traces traces,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<Trace> GetTraceAsync(
string projectId,
string traceId,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<Trace> GetTraceAsync(
string projectId,
string traceId,
CancellationToken cancellationToken) => GetTraceAsync(
projectId,
traceId,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual Trace GetTrace(
string projectId,
string traceId,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual IPagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual IPagedEnumerable<ListTracesResponse, Trace> ListTraces(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// TraceService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class TraceServiceClientImpl : TraceServiceClient
{
private readonly ClientHelper _clientHelper;
private readonly ApiCall<PatchTracesRequest, Empty> _callPatchTraces;
private readonly ApiCall<GetTraceRequest, Trace> _callGetTrace;
private readonly ApiCall<ListTracesRequest, ListTracesResponse> _callListTraces;
/// <summary>
/// Constructs a client wrapper for the TraceService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TraceServiceSettings"/> used within this client </param>
public TraceServiceClientImpl(TraceService.TraceServiceClient grpcClient, TraceServiceSettings settings)
{
this.GrpcClient = grpcClient;
TraceServiceSettings effectiveSettings = settings ?? TraceServiceSettings.GetDefault();
_clientHelper = new ClientHelper(effectiveSettings);
_callPatchTraces = _clientHelper.BuildApiCall<PatchTracesRequest, Empty>(
GrpcClient.PatchTracesAsync, GrpcClient.PatchTraces, effectiveSettings.PatchTracesSettings);
_callGetTrace = _clientHelper.BuildApiCall<GetTraceRequest, Trace>(
GrpcClient.GetTraceAsync, GrpcClient.GetTrace, effectiveSettings.GetTraceSettings);
_callListTraces = _clientHelper.BuildApiCall<ListTracesRequest, ListTracesResponse>(
GrpcClient.ListTracesAsync, GrpcClient.ListTraces, effectiveSettings.ListTracesSettings);
}
/// <summary>
/// The underlying gRPC TraceService client.
/// </summary>
public override TraceService.TraceServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_PatchTracesRequest(ref PatchTracesRequest request, ref CallSettings settings);
partial void Modify_GetTraceRequest(ref GetTraceRequest request, ref CallSettings settings);
partial void Modify_ListTracesRequest(ref ListTracesRequest request, ref CallSettings settings);
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task PatchTracesAsync(
string projectId,
Traces traces,
CallSettings callSettings = null)
{
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = projectId,
Traces = traces,
};
Modify_PatchTracesRequest(ref request, ref callSettings);
return _callPatchTraces.Async(request, callSettings);
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override void PatchTraces(
string projectId,
Traces traces,
CallSettings callSettings = null)
{
PatchTracesRequest request = new PatchTracesRequest
{
ProjectId = projectId,
Traces = traces,
};
Modify_PatchTracesRequest(ref request, ref callSettings);
_callPatchTraces.Sync(request, callSettings);
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<Trace> GetTraceAsync(
string projectId,
string traceId,
CallSettings callSettings = null)
{
GetTraceRequest request = new GetTraceRequest
{
ProjectId = projectId,
TraceId = traceId,
};
Modify_GetTraceRequest(ref request, ref callSettings);
return _callGetTrace.Async(request, callSettings);
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override Trace GetTrace(
string projectId,
string traceId,
CallSettings callSettings = null)
{
GetTraceRequest request = new GetTraceRequest
{
ProjectId = projectId,
TraceId = traceId,
};
Modify_GetTraceRequest(ref request, ref callSettings);
return _callGetTrace.Sync(request, callSettings);
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="Trace"/> resources.
/// </returns>
public override IPagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null)
{
ListTracesRequest request = new ListTracesRequest
{
ProjectId = projectId,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
};
Modify_ListTracesRequest(ref request, ref callSettings);
return new PagedAsyncEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings);
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="Trace"/> resources.
/// </returns>
public override IPagedEnumerable<ListTracesResponse, Trace> ListTraces(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null)
{
ListTracesRequest request = new ListTracesRequest
{
ProjectId = projectId,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
};
Modify_ListTracesRequest(ref request, ref callSettings);
return new PagedEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings);
}
}
// Partial classes to enable page-streaming
public partial class ListTracesRequest : IPageRequest { }
public partial class ListTracesResponse : IPageResponse<Trace>
{
/// <summary>
/// Returns an enumerator that iterates through the resources in this response.
/// </summary>
public IEnumerator<Trace> GetEnumerator() => Traces.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ExportLanguageSpecificOptionSerializer(
LanguageNames.CSharp,
OrganizerOptions.FeatureName,
SplitStringLiteralOptions.FeatureName,
AddImportOptions.FeatureName,
CompletionOptions.FeatureName,
CSharpCompletionOptions.FeatureName,
CSharpCodeStyleOptions.FeatureName,
CodeStyleOptions.PerLanguageCodeStyleOption,
SimplificationOptions.PerLanguageFeatureName,
ExtractMethodOptions.FeatureName,
CSharpFormattingOptions.IndentFeatureName,
CSharpFormattingOptions.NewLineFormattingFeatureName,
CSharpFormattingOptions.SpacingFeatureName,
CSharpFormattingOptions.WrappingFeatureName,
FormattingOptions.InternalTabFeatureName,
FeatureOnOffOptions.OptionName,
ServiceFeatureOnOffOptions.OptionName), Shared]
internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer
{
[ImportingConstructor]
public CSharpSettingsManagerOptionSerializer(VisualStudioWorkspaceImpl workspace)
: base(workspace)
{
}
private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators);
private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator);
private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels);
private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft);
private const string Style_QualifyFieldAccess = nameof(AutomationObject.Style_QualifyFieldAccess);
private const string Style_QualifyPropertyAccess = nameof(AutomationObject.Style_QualifyPropertyAccess);
private const string Style_QualifyMethodAccess = nameof(AutomationObject.Style_QualifyMethodAccess);
private const string Style_QualifyEventAccess = nameof(AutomationObject.Style_QualifyEventAccess);
private const string Style_UseImplicitTypeForIntrinsicTypes = nameof(AutomationObject.Style_UseImplicitTypeForIntrinsicTypes);
private const string Style_UseImplicitTypeWhereApparent = nameof(AutomationObject.Style_UseImplicitTypeWhereApparent);
private const string Style_UseImplicitTypeWherePossible = nameof(AutomationObject.Style_UseImplicitTypeWherePossible);
private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo)
{
var value = (IOption)fieldInfo.GetValue(obj: null);
return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value);
}
private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo)
{
return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null));
}
protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap()
{
var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder();
result.AddRange(new[]
{
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnDeletion), CompletionOptions.TriggerOnDeletion),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.ShowCompletionItemFilters), CompletionOptions.ShowCompletionItemFilters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems), CompletionOptions.HighlightMatchingPortionsOfCompletionListItems),
});
Type[] types = new[]
{
typeof(OrganizerOptions),
typeof(AddImportOptions),
typeof(SplitStringLiteralOptions),
typeof(CSharpCompletionOptions),
typeof(SimplificationOptions),
typeof(CSharpCodeStyleOptions),
typeof(ExtractMethodOptions),
typeof(ServiceFeatureOnOffOptions),
typeof(CSharpFormattingOptions),
typeof(CodeStyleOptions)
};
var bindingFlags = BindingFlags.Public | BindingFlags.Static;
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo));
types = new[] { typeof(FeatureOnOffOptions) };
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption));
return result.ToImmutable();
}
protected override string LanguageName { get { return LanguageNames.CSharp; } }
protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } }
protected override string GetStorageKeyForOption(IOption option)
{
var name = option.Name;
if (option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic)
{
// ClosedFileDiagnostics has been deprecated in favor of CSharpClosedFileDiagnostics.
// ClosedFileDiagnostics had a default value of 'true', while CSharpClosedFileDiagnostics has a default value of 'false'.
// We want to ensure that we don't fetch the setting store value for the old flag, as that can cause the default value for this option to change.
name = nameof(AutomationObject.CSharpClosedFileDiagnostics);
}
return SettingStorageRoot + name;
}
protected override bool SupportsOption(IOption option, string languageName)
{
if (option == OrganizerOptions.PlaceSystemNamespaceFirst ||
option == AddImportOptions.SuggestForTypesInReferenceAssemblies ||
option == AddImportOptions.SuggestForTypesInNuGetPackages ||
option.Feature == CodeStyleOptions.PerLanguageCodeStyleOption ||
option.Feature == CSharpCodeStyleOptions.FeatureName ||
option.Feature == CSharpFormattingOptions.WrappingFeatureName ||
option.Feature == CSharpFormattingOptions.IndentFeatureName ||
option.Feature == CSharpFormattingOptions.SpacingFeatureName ||
option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName)
{
return true;
}
else if (languageName == LanguageNames.CSharp)
{
if (option == CompletionOptions.TriggerOnTypingLetters ||
option == CompletionOptions.TriggerOnDeletion ||
option == CompletionOptions.ShowCompletionItemFilters ||
option == CompletionOptions.HighlightMatchingPortionsOfCompletionListItems ||
option == CompletionOptions.EnterKeyBehavior ||
option == CompletionOptions.SnippetsBehavior ||
option.Feature == SimplificationOptions.PerLanguageFeatureName ||
option.Feature == ExtractMethodOptions.FeatureName ||
option.Feature == ServiceFeatureOnOffOptions.OptionName ||
option.Feature == FormattingOptions.InternalTabFeatureName)
{
return true;
}
else if (option.Feature == FeatureOnOffOptions.OptionName)
{
return SupportsOnOffOption(option);
}
}
return false;
}
private bool SupportsOnOffOption(IOption option)
{
return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace ||
option == FeatureOnOffOptions.AutoFormattingOnSemicolon ||
option == FeatureOnOffOptions.LineSeparator ||
option == FeatureOnOffOptions.Outlining ||
option == FeatureOnOffOptions.ReferenceHighlighting ||
option == FeatureOnOffOptions.KeywordHighlighting ||
option == FeatureOnOffOptions.FormatOnPaste ||
option == FeatureOnOffOptions.AutoXmlDocCommentGeneration ||
option == FeatureOnOffOptions.AutoInsertBlockCommentStartString ||
option == FeatureOnOffOptions.RefactoringVerification ||
option == FeatureOnOffOptions.RenameTracking ||
option == FeatureOnOffOptions.RenameTrackingPreview;
}
public override bool TryFetch(OptionKey optionKey, out object value)
{
value = null;
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0);
if (ignoreSpacesAroundBinaryObjectValue.Equals(1))
{
value = BinaryOperatorSpacingOptions.Ignore;
return true;
}
object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1);
if (spaceAroundBinaryOperatorObjectValue.Equals(0))
{
value = BinaryOperatorSpacingOptions.Remove;
return true;
}
value = BinaryOperatorSpacingOptions.Single;
return true;
}
if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0);
if (flushLabelLeftObjectValue.Equals(1))
{
value = LabelPositionOptions.LeftMost;
return true;
}
object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1);
if (unindentLabelsObjectValue.Equals(0))
{
value = LabelPositionOptions.NoIndent;
return true;
}
value = LabelPositionOptions.OneLess;
return true;
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return FetchStyleBool(Style_QualifyFieldAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return FetchStyleBool(Style_QualifyPropertyAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return FetchStyleBool(Style_QualifyMethodAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return FetchStyleBool(Style_QualifyEventAccess, out value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return FetchStyleBool(Style_UseImplicitTypeForIntrinsicTypes, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return FetchStyleBool(Style_UseImplicitTypeWhereApparent, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return FetchStyleBool(Style_UseImplicitTypeWherePossible, out value);
}
if (optionKey.Option == CompletionOptions.EnterKeyBehavior)
{
return FetchEnterKeyBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.SnippetsBehavior)
{
return FetchSnippetsBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.TriggerOnDeletion)
{
return FetchTriggerOnDeletion(optionKey, out value);
}
return base.TryFetch(optionKey, out value);
}
private bool FetchTriggerOnDeletion(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (value == null)
{
// The default behavior for c# is to not trigger completion on deletion.
value = (bool?)false;
}
return true;
}
private bool FetchStyleBool(string settingName, out object value)
{
var typeStyleValue = Manager.GetValueOrDefault<string>(settingName);
return FetchStyleOption<bool>(typeStyleValue, out value);
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchSnippetsBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(SnippetsRule.Default))
{
return true;
}
// if the SnippetsBehavior setting cannot be loaded, then attempt to load and upgrade the legacy setting
#pragma warning disable CS0618 // IncludeSnippets is obsolete
if (base.TryFetch(CSharpCompletionOptions.IncludeSnippets, out value))
#pragma warning restore CS0618
{
if ((bool)value)
{
value = SnippetsRule.AlwaysInclude;
}
else
{
value = SnippetsRule.NeverInclude;
}
return true;
}
value = SnippetsRule.AlwaysInclude;
return true;
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchEnterKeyBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(EnterKeyRule.Default))
{
return true;
}
// if the EnterKeyBehavior setting cannot be loaded, then attempt to load and upgrade the legacy AddNewLineOnEnterAfterFullyTypedWord setting
#pragma warning disable CS0618 // AddNewLineOnEnterAfterFullyTypedWord is obsolete
if (base.TryFetch(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, out value))
#pragma warning restore CS0618
{
int intValue = (int)value;
switch (intValue)
{
case 1:
value = EnterKeyRule.AfterFullyTypedWord;
break;
case 0:
default:
value = EnterKeyRule.Never;
break;
}
return true;
}
value = EnterKeyRule.Never;
return true;
}
public override bool TryPersist(OptionKey optionKey, object value)
{
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
switch ((BinaryOperatorSpacingOptions)value)
{
case BinaryOperatorSpacingOptions.Remove:
{
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Ignore:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Single:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
return true;
}
}
}
else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
switch ((LabelPositionOptions)value)
{
case LabelPositionOptions.LeftMost:
{
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false);
return true;
}
case LabelPositionOptions.NoIndent:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false);
return true;
}
case LabelPositionOptions.OneLess:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
return true;
}
}
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return PersistStyleOption<bool>(Style_QualifyFieldAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return PersistStyleOption<bool>(Style_QualifyPropertyAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return PersistStyleOption<bool>(Style_QualifyMethodAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return PersistStyleOption<bool>(Style_QualifyEventAccess, value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeForIntrinsicTypes, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWhereApparent, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWherePossible, value);
}
return base.TryPersist(optionKey, value);
}
private bool PersistStyleOption<T>(string option, object value)
{
var serializedValue = ((CodeStyleOption<T>)value).ToXElement().ToString();
this.Manager.SetValueAsync(option, value: serializedValue, isMachineLocal: false);
return true;
}
private static bool FetchStyleOption<T>(string typeStyleOptionValue, out object value)
{
if (string.IsNullOrEmpty(typeStyleOptionValue))
{
value = CodeStyleOption<T>.Default;
}
else
{
value = CodeStyleOption<T>.FromXElement(XElement.Parse(typeStyleOptionValue));
}
return true;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.