context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Zoo.Tests
{
/// <summary>
/// The in-memory database set, taken from Microsoft's online example (http://msdn.microsoft.com/en-us/ff714955.aspx)
/// and modified to be based on DbSet instead of ObjectSet.
/// </summary>
/// <typeparam name="T">The type of DbSet.</typeparam>
public class InMemoryDbSet<T> : IDbSet<T> where T : class
{
private Func<IEnumerable<T>, object[], T> _findFunction;
private readonly HashSet<T> _nonStaticData;
/// <summary>
/// The non static backing store data for the InMemoryDbSet.
/// </summary>
private HashSet<T> Data
{
get
{
if (_nonStaticData == null)
{
return _staticData;
}
else
{
return _nonStaticData;
}
}
}
private static readonly HashSet<T> _staticData = new HashSet<T>();
public Func<IEnumerable<T>, object[], T> FindFunction
{
get { return _findFunction; }
set { _findFunction = value; }
}
/// <summary>
/// Creates an instance of the InMemoryDbSet using the default static backing store.This means
/// that data persists between test runs, like it would do with a database unless you
/// cleared it down.
/// </summary>
public InMemoryDbSet()
: this(true)
{
}
/// <summary>
/// This constructor allows you to pass in your own data store, instead of using
/// the static backing store.
/// </summary>
/// <param name="data">A place to store data.</param>
public InMemoryDbSet(HashSet<T> data)
{
_nonStaticData = data;
}
/// <summary>
/// Creates an instance of the InMemoryDbSet using the default static backing store.This means
/// that data persists between test runs, like it would do with a database unless you
/// cleared it down.
/// </summary>
/// <param name="clearDownExistingData"></param>
public InMemoryDbSet(bool clearDownExistingData)
{
if (clearDownExistingData)
{
Clear();
}
}
public void Clear()
{
Data.Clear();
}
public T Add(T entity)
{
Data.Add(entity);
return entity;
}
public T Attach(T entity)
{
Data.Add(entity);
return entity;
}
public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
{
return Activator.CreateInstance<TDerivedEntity>();
}
public T Create()
{
return Activator.CreateInstance<T>();
}
public virtual T Find(params object[] keyValues)
{
if (FindFunction != null)
{
return FindFunction(Data, keyValues);
}
else
{
throw new NotImplementedException("Derive from InMemoryDbSet and override Find, or provide a FindFunction.");
}
}
public ObservableCollection<T> Local
{
get { return new ObservableCollection<T>(Data); }
}
public T Remove(T entity)
{
Data.Remove(entity);
return entity;
}
public IEnumerator<T> GetEnumerator()
{
return Data.GetEnumerator();
}
private IEnumerator GetEnumerator1()
{
return Data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator1();
}
public Type ElementType
{
get { return Data.AsQueryable().ElementType; }
}
public Expression Expression
{
get { return Data.AsQueryable().Expression; }
}
public IQueryProvider Provider
{
get { return Data.AsQueryable().Provider; }
}
}
/// <summary>
/// Provides helper methods for the InMemoryDbSet.
/// </summary>
public class DbSetHelper
{
/// <summary>
/// Increments the provided property as if it was an indentity column in a database.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <typeparam name="TProperty">The type of the primary key property.</typeparam>
/// <param name="primaryKey">A lambda expression which provides the primary key.</param>
/// <param name="entity">The entity set to update.</param>
public static int IncrementPrimaryKey<T>(Expression<Func<T, long>> primaryKey, IDbSet<T> entity) where T : class
{
int newKeys = 0;
long maxId = entity.Count() > 0 ? entity.Max(e => primaryKey.Compile().Invoke(e)) + 1 : 0;
foreach (T item in entity.Where(e => primaryKey.Compile().Invoke(e) <= 0))
{
PropertyInfo propertyInfo = null;
if (primaryKey.Body is MemberExpression)
{
propertyInfo = (primaryKey.Body as MemberExpression).Member as PropertyInfo;
}
else
{
propertyInfo = (((UnaryExpression)primaryKey.Body).Operand as MemberExpression).Member as PropertyInfo;
}
if (propertyInfo.PropertyType == typeof(long))
{
propertyInfo.SetValue(item, maxId, null);
}
else if (propertyInfo.PropertyType == typeof(int))
{
propertyInfo.SetValue(item, (int)maxId, null);
}
newKeys++;
maxId++;
}
return newKeys;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.MathUtils;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Layout
{
public class TestCaseGridContainer : TestCase
{
private Container gridParent;
private GridContainer grid;
[SetUp]
public void Setup() => Schedule(() =>
{
Child = gridParent = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Masking = true,
BorderColour = Color4.White,
BorderThickness = 2,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
},
grid = new GridContainer { RelativeSizeAxes = Axes.Both }
}
};
});
[Test]
public void TestBlankGrid()
{
}
[Test]
public void TestSingleCellDistributedXy()
{
FillBox box = null;
AddStep("set content", () => grid.Content = new[] { new Drawable[] { box = new FillBox() }, });
AddAssert("box is same size as grid", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize));
}
[Test]
public void TestSingleCellAbsoluteXy()
{
const float size = 100;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, size) };
});
AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, new Vector2(size)));
}
[Test]
public void TestSingleCellRelativeXy()
{
const float size = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, size) };
});
AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize * new Vector2(size)));
}
[Test]
public void TestSingleCellRelativeXAbsoluteY()
{
const float absolute_height = 100;
const float relative_width = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = new[] { new Dimension(GridSizeMode.Absolute, absolute_height) };
grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, relative_width) };
});
AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth * relative_width));
AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, absolute_height));
}
[Test]
public void TestSingleCellDistributedXRelativeY()
{
const float height = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = new[] { new Dimension(GridSizeMode.Relative, height) };
});
AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth));
AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, grid.DrawHeight * height));
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXy(bool row)
{
FillBox[] boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }
}, row: row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth / 3f, grid.DrawHeight)));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight / 3f)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyAbsoluteYx(bool row)
{
var sizes = new[] { 50f, 100f, 75f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Absolute, sizes[0]),
new Dimension(GridSizeMode.Absolute, sizes[1]),
new Dimension(GridSizeMode.Absolute, sizes[2])
}, row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local])));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local], grid.DrawHeight)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyRelativeYx(bool row)
{
var sizes = new[] { 0.2f, 0.4f, 0.2f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Relative, sizes[0]),
new Dimension(GridSizeMode.Relative, sizes[1]),
new Dimension(GridSizeMode.Relative, sizes[2])
}, row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local] * grid.DrawHeight)));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local] * grid.DrawWidth, grid.DrawHeight)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyMixedYx(bool row)
{
var sizes = new[] { 0.2f, 75f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Relative, sizes[0]),
new Dimension(GridSizeMode.Absolute, sizes[1]),
new Dimension(),
}, row);
if (row)
{
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(grid.DrawWidth, sizes[0] * grid.DrawHeight)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth, sizes[1])));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight - boxes[0].DrawHeight - boxes[1].DrawHeight)));
}
else
{
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(sizes[0] * grid.DrawWidth, grid.DrawHeight)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(sizes[1], grid.DrawHeight)));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight)));
}
}
[Test]
public void Test3X3GridDistributedXy()
{
var boxes = new FillBox[9];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(grid.DrawSize / 3f, boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridAbsoluteXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Absolute, 75)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size, dimensions[local / 3].Size), boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridRelativeXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Relative, 0.2f),
new Dimension(GridSizeMode.Relative, 0.4f),
new Dimension(GridSizeMode.Relative, 0.2f)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size",
() => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size * grid.DrawWidth, dimensions[local / 3].Size * grid.DrawHeight), boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridMixedXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 50),
new Dimension(GridSizeMode.Relative, 0.2f)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
// Row 1
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(dimensions[0].Size, dimensions[0].Size)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, dimensions[0].Size)));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, dimensions[0].Size)));
// Row 2
AddAssert("box 3 has correct size", () => Precision.AlmostEquals(boxes[3].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight * dimensions[1].Size)));
AddAssert("box 4 has correct size", () => Precision.AlmostEquals(boxes[4].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight * dimensions[1].Size)));
AddAssert("box 5 has correct size",
() => Precision.AlmostEquals(boxes[5].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight * dimensions[1].Size)));
// Row 3
AddAssert("box 6 has correct size", () => Precision.AlmostEquals(boxes[6].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight - boxes[3].DrawHeight - boxes[0].DrawHeight)));
AddAssert("box 7 has correct size",
() => Precision.AlmostEquals(boxes[7].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight - boxes[4].DrawHeight - boxes[1].DrawHeight)));
AddAssert("box 8 has correct size",
() => Precision.AlmostEquals(boxes[8].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight - boxes[5].DrawHeight - boxes[2].DrawHeight)));
}
[Test]
public void TestGridWithNullRowsAndColumns()
{
var boxes = new FillBox[4];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), null, boxes[1] = new FillBox(), null },
null,
new Drawable[] { boxes[2] = new FillBox(), null, boxes[3] = new FillBox(), null },
null
};
});
AddAssert("two extra rows and columns", () =>
{
for (int i = 0; i < 4; i++)
{
if (!Precision.AlmostEquals(boxes[i].DrawSize, grid.DrawSize / 4))
return false;
}
return true;
});
}
[Test]
public void TestNestedGrids()
{
var boxes = new FillBox[4];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), new FillBox(), },
new Drawable[] { new FillBox(), boxes[1] = new FillBox(), },
}
},
new FillBox(),
},
new Drawable[]
{
new FillBox(),
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { boxes[2] = new FillBox(), new FillBox(), },
new Drawable[] { new FillBox(), boxes[3] = new FillBox(), },
}
}
},
};
});
for (int i = 0; i < 4; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, grid.DrawSize / 4));
}
}
[Test]
public void TestGridWithAutoSizingCells()
{
FillBox fillBox = null;
var autoSizingChildren = new Drawable[2];
AddStep("set content", () =>
{
grid.Content = new[]
{
new[]
{
autoSizingChildren[0] = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(50, 10)
},
fillBox = new FillBox(),
},
new[]
{
null,
autoSizingChildren[1] = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(50, 10)
},
},
};
grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) };
grid.RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
};
});
AddAssert("fill box has correct size", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 50, grid.DrawHeight - 10)));
AddStep("rotate boxes", () => autoSizingChildren.ForEach(c => c.RotateTo(90)));
AddAssert("fill box has resized correctly", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 10, grid.DrawHeight - 50)));
}
[TestCase(false)]
[TestCase(true)]
public void TestDimensionsWithMaximumSize(bool row)
{
var boxes = new FillBox[8];
var dimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, maxSize: 100),
new Dimension(),
new Dimension(GridSizeMode.Distributed, maxSize: 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, maxSize: 80),
new Dimension(GridSizeMode.Distributed, maxSize: 150)
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox(),
boxes[2] = new FillBox(),
boxes[3] = new FillBox(),
boxes[4] = new FillBox(),
boxes[5] = new FillBox(),
boxes[6] = new FillBox(),
boxes[7] = new FillBox()
},
}.Invert(), dimensions, row);
AddStep("set size = (0.5, 0.5)", () => gridParent.Size = new Vector2(0.5f));
checkSizes();
AddStep("set size = (0.5f, 0.1f)", () => gridParent.Size = new Vector2(0.5f, 0.1f));
checkSizes();
AddStep("set size = (0.1f, 0.5f)", () => gridParent.Size = new Vector2(0.1f, 0.5f));
checkSizes();
void checkSizes()
{
AddAssert("max size not overflowed", () =>
{
for (int i = 0; i < 8; i++)
{
if (dimensions[i].Mode != GridSizeMode.Distributed)
continue;
if (row && boxes[i].DrawHeight > dimensions[i].MaxSize)
return false;
if (!row && boxes[i].DrawWidth > dimensions[i].MaxSize)
return false;
}
return true;
});
AddAssert("column span total length", () =>
{
return row
? Precision.AlmostEquals(grid.DrawHeight, boxes.Sum(b => b.DrawHeight))
: Precision.AlmostEquals(grid.DrawWidth, boxes.Sum(b => b.DrawWidth));
});
}
}
private void setSingleDimensionContent(Func<Drawable[][]> contentFunc, Dimension[] dimensions = null, bool row = false) => AddStep("set content", () =>
{
var content = contentFunc();
if (!row)
content = content.Invert();
grid.Content = content;
if (dimensions == null)
return;
if (row)
grid.RowDimensions = dimensions;
else
grid.ColumnDimensions = dimensions;
});
private class FillBox : Box
{
public FillBox()
{
RelativeSizeAxes = Axes.Both;
Colour = new Color4(RNG.NextSingle(1), RNG.NextSingle(1), RNG.NextSingle(1), 1);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/test.proto
// Original file comments:
// Copyright 2015-2016, Google 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.
// * Neither the name of Google Inc. 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.
//
// An integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Grpc.Testing {
/// <summary>
/// A simple service to test the various types of RPCs and experiment with
/// performance with various types of payload.
/// </summary>
public static class TestService
{
static readonly string __ServiceName = "grpc.testing.TestService";
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"EmptyCall",
__Marshaller_Empty,
__Marshaller_Empty);
static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.ServerStreaming,
__ServiceName,
"StreamingOutputCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>(
MethodType.ClientStreaming,
__ServiceName,
"StreamingInputCall",
__Marshaller_StreamingInputCallRequest,
__Marshaller_StreamingInputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"FullDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"HalfDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of TestService</summary>
public abstract class TestServiceBase
{
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by one response.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
public virtual global::System.Threading.Tasks.Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
public virtual global::System.Threading.Tasks.Task FullDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
public virtual global::System.Threading.Tasks.Task HalfDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for TestService</summary>
public class TestServiceClient : ClientBase<TestServiceClient>
{
public TestServiceClient(Channel channel) : base(channel)
{
}
public TestServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected TestServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected TestServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCall(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_EmptyCall, null, options, request);
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One empty request followed by one empty response.
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_EmptyCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// </summary>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCall(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// </summary>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingOutputCall(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by a sequence of responses (streamed download).
/// The server returns the payload with client desired type and sizes.
/// </summary>
public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options)
{
return CallInvoker.AsyncServerStreamingCall(__Method_StreamingOutputCall, null, options, request);
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingInputCall(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests followed by one response (streamed upload).
/// The server returns the aggregated size of client payload as the result.
/// </summary>
public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options)
{
return CallInvoker.AsyncClientStreamingCall(__Method_StreamingInputCall, null, options);
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return FullDuplexCall(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests with each request served by the server immediately.
/// As one request could lead to multiple responses, this interface
/// demonstrates the idea of full duplexing.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_FullDuplexCall, null, options);
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return HalfDuplexCall(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A sequence of requests followed by a sequence of responses.
/// The server buffers all the client requests and then serves them in order. A
/// stream of responses are returned to the client when the server starts with
/// first request.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_HalfDuplexCall, null, options);
}
protected override TestServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new TestServiceClient(configuration);
}
}
/// <summary>Creates a new client for TestService</summary>
public static TestServiceClient NewClient(Channel channel)
{
return new TestServiceClient(channel);
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(TestServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall)
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall)
.AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall)
.AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall)
.AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall).Build();
}
}
/// <summary>
/// A simple service NOT implemented at servers so clients can test for
/// that case.
/// </summary>
public static class UnimplementedService
{
static readonly string __ServiceName = "grpc.testing.UnimplementedService";
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"UnimplementedCall",
__Marshaller_Empty,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[1]; }
}
/// <summary>Base class for server-side implementations of UnimplementedService</summary>
public abstract class UnimplementedServiceBase
{
/// <summary>
/// A call that no server should implement
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for UnimplementedService</summary>
public class UnimplementedServiceClient : ClientBase<UnimplementedServiceClient>
{
public UnimplementedServiceClient(Channel channel) : base(channel)
{
}
public UnimplementedServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UnimplementedServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected UnimplementedServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// A call that no server should implement
/// </summary>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCall(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A call that no server should implement
/// </summary>
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request);
}
/// <summary>
/// A call that no server should implement
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A call that no server should implement
/// </summary>
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request);
}
protected override UnimplementedServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new UnimplementedServiceClient(configuration);
}
}
/// <summary>Creates a new client for UnimplementedService</summary>
public static UnimplementedServiceClient NewClient(Channel channel)
{
return new UnimplementedServiceClient(channel);
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(UnimplementedServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build();
}
}
/// <summary>
/// A service used to control reconnect server.
/// </summary>
public static class ReconnectService
{
static readonly string __ServiceName = "grpc.testing.ReconnectService";
static readonly Marshaller<global::Grpc.Testing.ReconnectParams> __Marshaller_ReconnectParams = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectParams.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.ReconnectInfo> __Marshaller_ReconnectInfo = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectInfo.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty> __Method_Start = new Method<global::Grpc.Testing.ReconnectParams, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"Start",
__Marshaller_ReconnectParams,
__Marshaller_Empty);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo> __Method_Stop = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo>(
MethodType.Unary,
__ServiceName,
"Stop",
__Marshaller_Empty,
__Marshaller_ReconnectInfo);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[2]; }
}
/// <summary>Base class for server-side implementations of ReconnectService</summary>
public abstract class ReconnectServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.ReconnectParams request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ReconnectService</summary>
public class ReconnectServiceClient : ClientBase<ReconnectServiceClient>
{
public ReconnectServiceClient(Channel channel) : base(channel)
{
}
public ReconnectServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ReconnectServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected ReconnectServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Start(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.ReconnectParams request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Start, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StartAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.ReconnectParams request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Start, null, options, request);
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Stop(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Stop, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StopAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Stop, null, options, request);
}
protected override ReconnectServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ReconnectServiceClient(configuration);
}
}
/// <summary>Creates a new client for ReconnectService</summary>
public static ReconnectServiceClient NewClient(Channel channel)
{
return new ReconnectServiceClient(channel);
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(ReconnectServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Start, serviceImpl.Start)
.AddMethod(__Method_Stop, serviceImpl.Stop).Build();
}
}
}
#endregion
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.DeviceSystem
{
/// <summary>
///
/// </summary>
public class ColorPalette
{
/// <summary>
///
/// </summary>
protected ushort entries;
/// <summary>
///
/// </summary>
protected Color[] colors;
/// <summary>
/// Initializes a new instance of the <see cref="ColorPalette"/> class.
/// </summary>
/// <param name="entries">The entries.</param>
public ColorPalette(ushort entries)
{
this.entries = entries;
colors = new Color[entries];
for (int i = 0; i < entries; i++)
colors[i] = Color.Transparent;
}
/// <summary>
/// Sets the color.
/// </summary>
/// <param name="colorIndex">Index of the color.</param>
/// <param name="color">The color.</param>
public void SetColor(byte colorIndex, Color color)
{
colors[colorIndex] = color;
}
/// <summary>
/// Sets the color.
/// </summary>
/// <param name="colorIndex">Index of the color.</param>
/// <param name="red">The red.</param>
/// <param name="green">The green.</param>
/// <param name="blue">The blue.</param>
public void SetColor(byte colorIndex, byte red, byte green, byte blue)
{
colors[colorIndex] = new Color(red, green, blue);
}
/// <summary>
/// Gets the color.
/// </summary>
/// <param name="colorIndex">Index of the color.</param>
/// <returns></returns>
public Color GetColor(byte colorIndex)
{
return colors[colorIndex];
}
/// <summary>
/// Finds the closest color match.
/// </summary>
/// <param name="color">The color.</param>
/// <returns></returns>
public byte FindClosestMatch(Color color)
{
byte bestIndex = 0;
int bestDiff = 255 * 255 * 3 + 1;
for (byte i = 0; i < entries; i++)
{
if (colors[i].IsEqual(color))
return i;
// very simple implementation
int dist = (colors[i].Red * color.Red) + (colors[i].Green * color.Green) + (colors[i].Blue * color.Blue);
if (dist < bestDiff)
{
bestIndex = i;
bestDiff = dist;
}
}
return bestIndex;
}
#region Standard Palette
/// <summary>
/// Gets the Standard 16 color palette.
/// </summary>
/// <returns></returns>
static public ColorPalette CreateStandard16ColorPalette()
{
ColorPalette palette = new ColorPalette(16);
palette.SetColor(0, 0, 0, 0);
palette.SetColor(1, 0, 0, 170);
palette.SetColor(2, 0, 170, 0);
palette.SetColor(3, 0, 170, 170);
palette.SetColor(4, 170, 0, 0);
palette.SetColor(5, 170, 0, 170);
palette.SetColor(6, 170, 85, 0);
palette.SetColor(7, 170, 170, 170);
palette.SetColor(8, 85, 85, 85);
palette.SetColor(9, 85, 85, 255);
palette.SetColor(10, 85, 255, 85);
palette.SetColor(11, 85, 255, 255);
palette.SetColor(12, 255, 85, 85);
palette.SetColor(13, 255, 85, 255);
palette.SetColor(14, 255, 255, 85);
palette.SetColor(15, 255, 255, 255);
return palette;
}
/// <summary>
/// Gets the Netscape 256 color palette.
/// </summary>
/// <returns></returns>
static public ColorPalette CreateNetscape256ColorPalette()
{
ColorPalette palette = new ColorPalette(256);
palette.SetColor(0, 255, 255, 255);
palette.SetColor(1, 255, 255, 204);
palette.SetColor(2, 255, 255, 153);
palette.SetColor(3, 255, 255, 102);
palette.SetColor(4, 255, 255, 51);
palette.SetColor(5, 255, 255, 0);
palette.SetColor(6, 255, 204, 255);
palette.SetColor(7, 255, 204, 204);
palette.SetColor(8, 255, 204, 153);
palette.SetColor(9, 255, 204, 102);
palette.SetColor(10, 255, 204, 51);
palette.SetColor(11, 255, 204, 0);
palette.SetColor(12, 255, 153, 255);
palette.SetColor(13, 255, 153, 204);
palette.SetColor(14, 255, 153, 153);
palette.SetColor(15, 255, 153, 102);
palette.SetColor(16, 255, 153, 51);
palette.SetColor(17, 255, 153, 0);
palette.SetColor(18, 255, 102, 255);
palette.SetColor(19, 255, 102, 204);
palette.SetColor(20, 255, 102, 153);
palette.SetColor(21, 255, 102, 102);
palette.SetColor(22, 255, 102, 51);
palette.SetColor(23, 255, 102, 0);
palette.SetColor(24, 255, 51, 255);
palette.SetColor(25, 255, 51, 204);
palette.SetColor(26, 255, 51, 153);
palette.SetColor(27, 255, 51, 102);
palette.SetColor(28, 255, 51, 51);
palette.SetColor(29, 255, 51, 0);
palette.SetColor(30, 255, 0, 255);
palette.SetColor(31, 255, 0, 204);
palette.SetColor(32, 255, 0, 153);
palette.SetColor(33, 255, 0, 102);
palette.SetColor(34, 255, 0, 51);
palette.SetColor(35, 255, 0, 0);
palette.SetColor(36, 204, 255, 255);
palette.SetColor(37, 204, 255, 204);
palette.SetColor(38, 204, 255, 153);
palette.SetColor(39, 204, 255, 102);
palette.SetColor(40, 204, 255, 51);
palette.SetColor(41, 204, 255, 0);
palette.SetColor(42, 204, 204, 255);
palette.SetColor(43, 204, 204, 204);
palette.SetColor(44, 204, 204, 153);
palette.SetColor(45, 204, 204, 102);
palette.SetColor(46, 204, 204, 51);
palette.SetColor(47, 204, 204, 0);
palette.SetColor(48, 204, 153, 255);
palette.SetColor(49, 204, 153, 204);
palette.SetColor(50, 204, 153, 153);
palette.SetColor(51, 204, 153, 102);
palette.SetColor(52, 204, 153, 51);
palette.SetColor(53, 204, 153, 0);
palette.SetColor(54, 204, 102, 255);
palette.SetColor(55, 204, 102, 204);
palette.SetColor(56, 204, 102, 153);
palette.SetColor(57, 204, 102, 102);
palette.SetColor(58, 204, 102, 51);
palette.SetColor(59, 204, 102, 0);
palette.SetColor(60, 204, 51, 255);
palette.SetColor(61, 204, 51, 204);
palette.SetColor(62, 204, 51, 153);
palette.SetColor(63, 204, 51, 102);
palette.SetColor(64, 204, 51, 51);
palette.SetColor(65, 204, 51, 0);
palette.SetColor(66, 204, 0, 255);
palette.SetColor(67, 204, 0, 204);
palette.SetColor(68, 204, 0, 153);
palette.SetColor(69, 204, 0, 102);
palette.SetColor(70, 204, 0, 51);
palette.SetColor(71, 204, 0, 0);
palette.SetColor(72, 153, 255, 255);
palette.SetColor(73, 153, 255, 204);
palette.SetColor(74, 153, 255, 153);
palette.SetColor(75, 153, 255, 102);
palette.SetColor(76, 153, 255, 51);
palette.SetColor(77, 153, 255, 0);
palette.SetColor(78, 153, 204, 255);
palette.SetColor(79, 153, 204, 204);
palette.SetColor(80, 153, 204, 153);
palette.SetColor(81, 153, 204, 102);
palette.SetColor(82, 153, 204, 51);
palette.SetColor(83, 153, 204, 0);
palette.SetColor(84, 153, 153, 255);
palette.SetColor(85, 153, 153, 204);
palette.SetColor(86, 153, 153, 153);
palette.SetColor(87, 153, 153, 102);
palette.SetColor(88, 153, 153, 51);
palette.SetColor(89, 153, 153, 0);
palette.SetColor(90, 153, 102, 255);
palette.SetColor(91, 153, 102, 204);
palette.SetColor(92, 153, 102, 153);
palette.SetColor(93, 153, 102, 102);
palette.SetColor(94, 153, 102, 51);
palette.SetColor(95, 153, 102, 0);
palette.SetColor(96, 153, 51, 255);
palette.SetColor(97, 153, 51, 204);
palette.SetColor(98, 153, 51, 153);
palette.SetColor(99, 153, 51, 102);
palette.SetColor(100, 153, 51, 51);
palette.SetColor(101, 153, 51, 0);
palette.SetColor(102, 153, 0, 255);
palette.SetColor(103, 153, 0, 204);
palette.SetColor(104, 153, 0, 153);
palette.SetColor(105, 153, 0, 102);
palette.SetColor(106, 153, 0, 51);
palette.SetColor(107, 153, 0, 0);
palette.SetColor(108, 102, 255, 255);
palette.SetColor(109, 102, 255, 204);
palette.SetColor(110, 102, 255, 153);
palette.SetColor(111, 102, 255, 102);
palette.SetColor(112, 102, 255, 51);
palette.SetColor(113, 102, 255, 0);
palette.SetColor(114, 102, 204, 255);
palette.SetColor(115, 102, 204, 204);
palette.SetColor(116, 102, 204, 153);
palette.SetColor(117, 102, 204, 102);
palette.SetColor(118, 102, 204, 51);
palette.SetColor(119, 102, 204, 0);
palette.SetColor(120, 102, 153, 255);
palette.SetColor(121, 102, 153, 204);
palette.SetColor(122, 102, 153, 153);
palette.SetColor(123, 102, 153, 102);
palette.SetColor(124, 102, 153, 51);
palette.SetColor(125, 102, 153, 0);
palette.SetColor(126, 102, 102, 255);
palette.SetColor(127, 102, 102, 204);
palette.SetColor(128, 102, 102, 153);
palette.SetColor(129, 102, 102, 102);
palette.SetColor(130, 102, 102, 51);
palette.SetColor(131, 102, 102, 0);
palette.SetColor(132, 102, 51, 255);
palette.SetColor(133, 102, 51, 204);
palette.SetColor(134, 102, 51, 153);
palette.SetColor(135, 102, 51, 102);
palette.SetColor(136, 102, 51, 51);
palette.SetColor(137, 102, 51, 0);
palette.SetColor(138, 102, 0, 255);
palette.SetColor(139, 102, 0, 204);
palette.SetColor(140, 102, 0, 153);
palette.SetColor(141, 102, 0, 102);
palette.SetColor(142, 102, 0, 0);
palette.SetColor(143, 102, 0, 0);
palette.SetColor(144, 51, 255, 255);
palette.SetColor(145, 51, 255, 204);
palette.SetColor(146, 51, 255, 153);
palette.SetColor(147, 51, 255, 102);
palette.SetColor(148, 51, 255, 51);
palette.SetColor(149, 51, 255, 0);
palette.SetColor(150, 51, 204, 255);
palette.SetColor(151, 51, 204, 204);
palette.SetColor(152, 51, 204, 153);
palette.SetColor(153, 51, 204, 102);
palette.SetColor(154, 51, 204, 51);
palette.SetColor(155, 51, 204, 0);
palette.SetColor(156, 51, 153, 255);
palette.SetColor(157, 51, 153, 204);
palette.SetColor(158, 51, 153, 153);
palette.SetColor(159, 51, 153, 102);
palette.SetColor(160, 51, 153, 51);
palette.SetColor(161, 51, 153, 0);
palette.SetColor(162, 51, 102, 255);
palette.SetColor(163, 51, 102, 204);
palette.SetColor(164, 51, 102, 153);
palette.SetColor(165, 51, 102, 102);
palette.SetColor(166, 51, 102, 51);
palette.SetColor(167, 51, 102, 0);
palette.SetColor(168, 51, 51, 255);
palette.SetColor(169, 51, 51, 204);
palette.SetColor(170, 51, 51, 153);
palette.SetColor(171, 51, 51, 102);
palette.SetColor(172, 51, 51, 51);
palette.SetColor(173, 51, 51, 0);
palette.SetColor(174, 51, 0, 255);
palette.SetColor(175, 51, 0, 204);
palette.SetColor(176, 51, 0, 153);
palette.SetColor(177, 51, 0, 102);
palette.SetColor(178, 51, 0, 51);
palette.SetColor(179, 51, 0, 0);
palette.SetColor(180, 0, 255, 255);
palette.SetColor(181, 0, 255, 204);
palette.SetColor(182, 0, 255, 153);
palette.SetColor(183, 0, 255, 102);
palette.SetColor(184, 0, 255, 51);
palette.SetColor(185, 0, 255, 0);
palette.SetColor(186, 0, 204, 255);
palette.SetColor(187, 0, 204, 204);
palette.SetColor(188, 0, 204, 153);
palette.SetColor(189, 0, 204, 102);
palette.SetColor(190, 0, 204, 51);
palette.SetColor(191, 0, 204, 0);
palette.SetColor(192, 0, 153, 255);
palette.SetColor(193, 0, 153, 204);
palette.SetColor(194, 0, 153, 153);
palette.SetColor(195, 0, 153, 102);
palette.SetColor(196, 0, 153, 51);
palette.SetColor(197, 0, 153, 0);
palette.SetColor(198, 0, 102, 255);
palette.SetColor(199, 0, 102, 204);
palette.SetColor(200, 0, 102, 153);
palette.SetColor(201, 0, 102, 102);
palette.SetColor(202, 0, 102, 51);
palette.SetColor(203, 0, 102, 0);
palette.SetColor(204, 0, 51, 255);
palette.SetColor(205, 0, 51, 204);
palette.SetColor(206, 0, 51, 153);
palette.SetColor(207, 0, 51, 102);
palette.SetColor(208, 0, 51, 51);
palette.SetColor(209, 0, 51, 0);
palette.SetColor(210, 0, 0, 255);
palette.SetColor(211, 0, 0, 204);
palette.SetColor(212, 0, 0, 153);
palette.SetColor(213, 0, 0, 102);
palette.SetColor(214, 0, 0, 51);
palette.SetColor(215, 238, 0, 0);
palette.SetColor(216, 221, 0, 0);
palette.SetColor(217, 187, 0, 0);
palette.SetColor(218, 170, 0, 0);
palette.SetColor(219, 136, 0, 0);
palette.SetColor(220, 119, 0, 0);
palette.SetColor(221, 85, 0, 0);
palette.SetColor(222, 68, 0, 0);
palette.SetColor(223, 34, 0, 0);
palette.SetColor(224, 17, 0, 0);
palette.SetColor(225, 0, 238, 0);
palette.SetColor(226, 0, 221, 0);
palette.SetColor(227, 0, 187, 0);
palette.SetColor(228, 0, 170, 0);
palette.SetColor(229, 0, 136, 0);
palette.SetColor(230, 0, 119, 0);
palette.SetColor(231, 0, 85, 0);
palette.SetColor(232, 0, 68, 0);
palette.SetColor(233, 0, 34, 0);
palette.SetColor(234, 0, 17, 0);
palette.SetColor(235, 0, 0, 238);
palette.SetColor(236, 0, 0, 221);
palette.SetColor(237, 0, 0, 187);
palette.SetColor(238, 0, 0, 170);
palette.SetColor(239, 0, 0, 136);
palette.SetColor(240, 0, 0, 119);
palette.SetColor(241, 0, 0, 85);
palette.SetColor(242, 0, 0, 68);
palette.SetColor(243, 0, 0, 34);
palette.SetColor(244, 0, 0, 17);
palette.SetColor(245, 238, 238, 238);
palette.SetColor(246, 221, 221, 221);
palette.SetColor(247, 187, 187, 187);
palette.SetColor(248, 170, 170, 170);
palette.SetColor(249, 136, 136, 136);
palette.SetColor(250, 119, 119, 119);
palette.SetColor(251, 85, 85, 85);
palette.SetColor(252, 68, 68, 68);
palette.SetColor(253, 34, 34, 34);
palette.SetColor(254, 17, 17, 17);
palette.SetColor(255, 0, 0, 0);
return palette;
}
/// <summary>
/// Gets the Standard 256 color palette.
/// </summary>
/// <returns></returns>
static public ColorPalette CreateStandardIBM256ColorPalette()
{
ColorPalette palette = new ColorPalette(256);
palette.SetColor(0, 0, 0, 0);
palette.SetColor(1, 0, 0, 170);
palette.SetColor(2, 0, 170, 0);
palette.SetColor(3, 0, 170, 170);
palette.SetColor(4, 170, 0, 0);
palette.SetColor(5, 170, 0, 170);
palette.SetColor(6, 170, 85, 0);
palette.SetColor(7, 170, 170, 170);
palette.SetColor(8, 85, 85, 85);
palette.SetColor(9, 85, 85, 255);
palette.SetColor(10, 85, 255, 85);
palette.SetColor(11, 85, 255, 255);
palette.SetColor(12, 255, 85, 85);
palette.SetColor(13, 255, 85, 255);
palette.SetColor(14, 255, 255, 85);
palette.SetColor(15, 255, 255, 255);
palette.SetColor(16, 0, 0, 0);
palette.SetColor(17, 17, 17, 17);
palette.SetColor(18, 34, 34, 34);
palette.SetColor(19, 51, 51, 51);
palette.SetColor(20, 68, 68, 68);
palette.SetColor(21, 85, 85, 85);
palette.SetColor(22, 102, 102, 102);
palette.SetColor(23, 119, 119, 119);
palette.SetColor(24, 136, 136, 136);
palette.SetColor(25, 153, 153, 153);
palette.SetColor(26, 170, 170, 170);
palette.SetColor(27, 187, 187, 187);
palette.SetColor(28, 204, 204, 204);
palette.SetColor(29, 221, 221, 221);
palette.SetColor(30, 238, 238, 238);
palette.SetColor(31, 255, 255, 255);
palette.SetColor(32, 0, 0, 0);
palette.SetColor(33, 0, 0, 0);
palette.SetColor(34, 0, 0, 0);
palette.SetColor(35, 0, 0, 0);
palette.SetColor(36, 0, 0, 0);
palette.SetColor(37, 0, 0, 0);
palette.SetColor(38, 0, 0, 0);
palette.SetColor(39, 0, 0, 0);
palette.SetColor(40, 0, 0, 0);
palette.SetColor(41, 0, 0, 51);
palette.SetColor(42, 0, 0, 102);
palette.SetColor(43, 0, 0, 153);
palette.SetColor(44, 0, 0, 204);
palette.SetColor(45, 0, 0, 255);
palette.SetColor(46, 0, 51, 0);
palette.SetColor(47, 0, 51, 51);
palette.SetColor(48, 0, 51, 102);
palette.SetColor(49, 0, 51, 153);
palette.SetColor(50, 0, 51, 204);
palette.SetColor(51, 0, 51, 255);
palette.SetColor(52, 0, 102, 0);
palette.SetColor(53, 0, 102, 51);
palette.SetColor(54, 0, 102, 102);
palette.SetColor(55, 0, 102, 153);
palette.SetColor(56, 0, 102, 204);
palette.SetColor(57, 0, 102, 255);
palette.SetColor(58, 0, 153, 0);
palette.SetColor(59, 0, 153, 51);
palette.SetColor(60, 0, 153, 102);
palette.SetColor(61, 0, 153, 153);
palette.SetColor(62, 0, 153, 204);
palette.SetColor(63, 0, 153, 255);
palette.SetColor(64, 0, 204, 0);
palette.SetColor(65, 0, 204, 51);
palette.SetColor(66, 0, 204, 102);
palette.SetColor(67, 0, 204, 153);
palette.SetColor(68, 0, 204, 204);
palette.SetColor(69, 0, 204, 255);
palette.SetColor(70, 0, 255, 0);
palette.SetColor(71, 0, 255, 51);
palette.SetColor(72, 0, 255, 102);
palette.SetColor(73, 0, 255, 153);
palette.SetColor(74, 0, 255, 204);
palette.SetColor(75, 0, 255, 255);
palette.SetColor(76, 51, 0, 0);
palette.SetColor(77, 51, 0, 51);
palette.SetColor(78, 51, 0, 102);
palette.SetColor(79, 51, 0, 153);
palette.SetColor(80, 51, 0, 204);
palette.SetColor(81, 51, 0, 255);
palette.SetColor(82, 51, 51, 0);
palette.SetColor(83, 51, 51, 51);
palette.SetColor(84, 51, 51, 102);
palette.SetColor(85, 51, 51, 153);
palette.SetColor(86, 51, 51, 204);
palette.SetColor(87, 51, 51, 255);
palette.SetColor(88, 51, 102, 0);
palette.SetColor(89, 51, 102, 51);
palette.SetColor(90, 51, 102, 102);
palette.SetColor(91, 51, 102, 153);
palette.SetColor(92, 51, 102, 204);
palette.SetColor(93, 51, 102, 255);
palette.SetColor(94, 51, 153, 0);
palette.SetColor(95, 51, 153, 51);
palette.SetColor(96, 51, 153, 102);
palette.SetColor(97, 51, 153, 153);
palette.SetColor(98, 51, 153, 204);
palette.SetColor(99, 51, 153, 255);
palette.SetColor(100, 51, 204, 0);
palette.SetColor(101, 51, 204, 51);
palette.SetColor(102, 51, 204, 102);
palette.SetColor(103, 51, 204, 153);
palette.SetColor(104, 51, 204, 204);
palette.SetColor(105, 51, 204, 255);
palette.SetColor(106, 51, 255, 0);
palette.SetColor(107, 51, 255, 51);
palette.SetColor(108, 51, 255, 102);
palette.SetColor(109, 51, 255, 153);
palette.SetColor(110, 51, 255, 204);
palette.SetColor(111, 51, 255, 255);
palette.SetColor(112, 102, 0, 0);
palette.SetColor(113, 102, 0, 51);
palette.SetColor(114, 102, 0, 102);
palette.SetColor(115, 102, 0, 153);
palette.SetColor(116, 102, 0, 204);
palette.SetColor(117, 102, 0, 255);
palette.SetColor(118, 102, 51, 0);
palette.SetColor(119, 102, 51, 51);
palette.SetColor(120, 102, 51, 102);
palette.SetColor(121, 102, 51, 153);
palette.SetColor(122, 102, 51, 204);
palette.SetColor(123, 102, 51, 255);
palette.SetColor(124, 102, 102, 0);
palette.SetColor(125, 102, 102, 51);
palette.SetColor(126, 102, 102, 102);
palette.SetColor(127, 102, 102, 153);
palette.SetColor(128, 102, 102, 204);
palette.SetColor(129, 102, 102, 255);
palette.SetColor(130, 102, 153, 0);
palette.SetColor(131, 102, 153, 51);
palette.SetColor(132, 102, 153, 102);
palette.SetColor(133, 102, 153, 153);
palette.SetColor(134, 102, 153, 204);
palette.SetColor(135, 102, 153, 255);
palette.SetColor(136, 102, 204, 0);
palette.SetColor(137, 102, 204, 51);
palette.SetColor(138, 102, 204, 102);
palette.SetColor(139, 102, 204, 153);
palette.SetColor(140, 102, 204, 204);
palette.SetColor(141, 102, 204, 255);
palette.SetColor(142, 102, 255, 0);
palette.SetColor(143, 102, 255, 51);
palette.SetColor(144, 102, 255, 102);
palette.SetColor(145, 102, 255, 153);
palette.SetColor(146, 102, 255, 204);
palette.SetColor(147, 102, 255, 255);
palette.SetColor(148, 153, 0, 0);
palette.SetColor(149, 153, 0, 51);
palette.SetColor(150, 153, 0, 102);
palette.SetColor(151, 153, 0, 153);
palette.SetColor(152, 153, 0, 204);
palette.SetColor(153, 153, 0, 255);
palette.SetColor(154, 153, 51, 0);
palette.SetColor(155, 153, 51, 51);
palette.SetColor(156, 153, 51, 102);
palette.SetColor(157, 153, 51, 153);
palette.SetColor(158, 153, 51, 204);
palette.SetColor(159, 153, 51, 255);
palette.SetColor(160, 153, 102, 0);
palette.SetColor(161, 153, 102, 51);
palette.SetColor(162, 153, 102, 102);
palette.SetColor(163, 153, 102, 153);
palette.SetColor(164, 153, 102, 204);
palette.SetColor(165, 153, 102, 255);
palette.SetColor(166, 153, 153, 0);
palette.SetColor(167, 153, 153, 51);
palette.SetColor(168, 153, 153, 102);
palette.SetColor(169, 153, 153, 153);
palette.SetColor(170, 153, 153, 204);
palette.SetColor(171, 153, 153, 255);
palette.SetColor(172, 153, 204, 0);
palette.SetColor(173, 153, 204, 51);
palette.SetColor(174, 153, 204, 102);
palette.SetColor(175, 153, 204, 153);
palette.SetColor(176, 153, 204, 204);
palette.SetColor(177, 153, 204, 255);
palette.SetColor(178, 153, 255, 0);
palette.SetColor(179, 153, 255, 51);
palette.SetColor(180, 153, 255, 102);
palette.SetColor(181, 153, 255, 153);
palette.SetColor(182, 153, 255, 204);
palette.SetColor(183, 153, 255, 255);
palette.SetColor(184, 204, 0, 0);
palette.SetColor(185, 204, 0, 51);
palette.SetColor(186, 204, 0, 102);
palette.SetColor(187, 204, 0, 153);
palette.SetColor(188, 204, 0, 204);
palette.SetColor(189, 204, 0, 255);
palette.SetColor(190, 204, 51, 0);
palette.SetColor(191, 204, 51, 51);
palette.SetColor(192, 204, 51, 102);
palette.SetColor(193, 204, 51, 153);
palette.SetColor(194, 204, 51, 204);
palette.SetColor(195, 204, 51, 255);
palette.SetColor(196, 204, 102, 0);
palette.SetColor(197, 204, 102, 51);
palette.SetColor(198, 204, 102, 102);
palette.SetColor(199, 204, 102, 153);
palette.SetColor(200, 204, 102, 204);
palette.SetColor(201, 204, 102, 255);
palette.SetColor(202, 204, 153, 0);
palette.SetColor(203, 204, 153, 51);
palette.SetColor(204, 204, 153, 102);
palette.SetColor(205, 204, 153, 153);
palette.SetColor(206, 204, 153, 204);
palette.SetColor(207, 204, 153, 255);
palette.SetColor(208, 204, 204, 0);
palette.SetColor(209, 204, 204, 51);
palette.SetColor(210, 204, 204, 102);
palette.SetColor(211, 204, 204, 153);
palette.SetColor(212, 204, 204, 204);
palette.SetColor(213, 204, 204, 255);
palette.SetColor(214, 204, 255, 0);
palette.SetColor(215, 204, 255, 51);
palette.SetColor(216, 204, 255, 102);
palette.SetColor(217, 204, 255, 153);
palette.SetColor(218, 204, 255, 204);
palette.SetColor(219, 204, 255, 255);
palette.SetColor(220, 255, 0, 0);
palette.SetColor(221, 255, 0, 51);
palette.SetColor(222, 255, 0, 102);
palette.SetColor(223, 255, 0, 153);
palette.SetColor(224, 255, 0, 204);
palette.SetColor(225, 255, 0, 255);
palette.SetColor(226, 255, 51, 0);
palette.SetColor(227, 255, 51, 51);
palette.SetColor(228, 255, 51, 102);
palette.SetColor(229, 255, 51, 153);
palette.SetColor(230, 255, 51, 204);
palette.SetColor(231, 255, 51, 255);
palette.SetColor(232, 255, 102, 0);
palette.SetColor(233, 255, 102, 51);
palette.SetColor(234, 255, 102, 102);
palette.SetColor(235, 255, 102, 153);
palette.SetColor(236, 255, 102, 204);
palette.SetColor(237, 255, 102, 255);
palette.SetColor(238, 255, 153, 0);
palette.SetColor(239, 255, 153, 51);
palette.SetColor(240, 255, 153, 102);
palette.SetColor(241, 255, 153, 153);
palette.SetColor(242, 255, 153, 204);
palette.SetColor(243, 255, 153, 255);
palette.SetColor(244, 255, 204, 0);
palette.SetColor(245, 255, 204, 51);
palette.SetColor(246, 255, 204, 102);
palette.SetColor(247, 255, 204, 153);
palette.SetColor(248, 255, 204, 204);
palette.SetColor(249, 255, 204, 255);
palette.SetColor(250, 255, 255, 0);
palette.SetColor(251, 255, 255, 51);
palette.SetColor(252, 255, 255, 102);
palette.SetColor(253, 255, 255, 153);
palette.SetColor(254, 255, 255, 204);
palette.SetColor(255, 255, 255, 255);
return palette;
}
#endregion Standard Palette
}
}
| |
using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Rotates a hierarchy of bones to face a target.
/// </summary>
[System.Serializable]
public class IKSolverLookAt : IKSolver {
#region Main Interface
/// <summary>
/// The target Transform.
/// </summary>
public Transform target;
/// <summary>
/// The spine hierarchy.
/// </summary>
public LookAtBone[] spine = new LookAtBone[0];
/// <summary>
/// The head bone.
/// </summary>
public LookAtBone head = new LookAtBone();
/// <summary>
/// The eye bones.
/// </summary>
public LookAtBone[] eyes = new LookAtBone[0];
/// <summary>
/// The body weight.
/// </summary>
[Range(0f, 1f)]
public float bodyWeight = 0.5f;
/// <summary>
/// The head weight.
/// </summary>
[Range(0f, 1f)]
public float headWeight = 0.5f;
/// <summary>
/// The eyes weight.
/// </summary>
[Range(0f, 1f)]
public float eyesWeight = 1f;
/// <summary>
/// Clamp weight for the body.
/// </summary>
[Range(0f, 1f)]
public float clampWeight = 0.5f;
/// <summary>
/// Clamp weight for the head.
/// </summary>
[Range(0f, 1f)]
public float clampWeightHead = 0.5f;
/// <summary>
/// Clamp weight for the eyes.
/// </summary>
[Range(0f, 1f)]
public float clampWeightEyes = 0.5f;
/// <summary>
/// Number of sine smoothing iterations applied on clamping to make the clamping point smoother.
/// </summary>
[Range(0, 2)]
public int clampSmoothing = 2;
/// <summary>
/// Weight distribution between the spine bones.
/// </summary>
public AnimationCurve spineWeightCurve = new AnimationCurve(new Keyframe[2] { new Keyframe(0f, 0.3f), new Keyframe(1f, 1f) });
/// <summary>
/// Sets the look at weight. NOTE: You are welcome edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = this.clampWeight;
this.clampWeightEyes = this.clampWeight;
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight = 0f, float headWeight = 1f, float eyesWeight = 0.5f, float clampWeight = 0.5f, float clampWeightHead = 0.5f, float clampWeightEyes = 0.3f) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = Mathf.Clamp(clampWeightHead, 0f, 1f);
this.clampWeightEyes = Mathf.Clamp(clampWeightEyes, 0f, 1f);
}
public override void StoreDefaultLocalState() {
for (int i = 0; i < spine.Length; i++) spine[i].StoreDefaultLocalState();
for (int i = 0; i < eyes.Length; i++) eyes[i].StoreDefaultLocalState();
if (head != null && head.transform != null) head.StoreDefaultLocalState();
}
public override void FixTransforms() {
for (int i = 0; i < spine.Length; i++) spine[i].FixTransform();
for (int i = 0; i < eyes.Length; i++) eyes[i].FixTransform();
if (head != null && head.transform != null) head.FixTransform();
}
public override bool IsValid (bool log) {
if (!spineIsValid) {
if (log) LogWarning("IKSolverLookAt spine setup is invalid. Can't initiate solver.");
return false;
}
if (!headIsValid) {
if (log) LogWarning("IKSolverLookAt head transform is null. Can't initiate solver.");
return false;
}
if (!eyesIsValid) {
if (log) LogWarning("IKSolverLookAt eyes setup is invalid. Can't initiate solver.");
return false;
}
if (spineIsEmpty && headIsEmpty && eyesIsEmpty) {
if (log) LogWarning("IKSolverLookAt spine, head and eyes are empty. There is nothing for the solver to solve.");
return false;
}
Transform spineDuplicate = ContainsDuplicateBone(spine);
if (spineDuplicate != null) {
if (log) LogWarning(spineDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.");
return false;
}
Transform eyeDuplicate = ContainsDuplicateBone(eyes);
if (eyeDuplicate != null) {
if (log) LogWarning(eyeDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.");
return false;
}
return true;
}
public override IKSolver.Point[] GetPoints() {
IKSolver.Point[] allPoints = new IKSolver.Point[spine.Length + eyes.Length + (head.transform != null? 1: 0)];
for (int i = 0; i < spine.Length; i++) allPoints[i] = spine[i] as IKSolver.Point;
int eye = 0;
for (int i = spine.Length; i < allPoints.Length; i++) {
allPoints[i] = eyes[eye] as IKSolver.Point;
eye ++;
}
if (head.transform != null) allPoints[allPoints.Length - 1] = head as IKSolver.Point;
return allPoints;
}
public override IKSolver.Point GetPoint(Transform transform) {
foreach (IKSolverLookAt.LookAtBone b in spine) if (b.transform == transform) return b as IKSolver.Point;
foreach (IKSolverLookAt.LookAtBone b in eyes) if (b.transform == transform) return b as IKSolver.Point;
if (head.transform == transform) return head as IKSolver.Point;
return null;
}
/// <summary>
/// Look At bone class.
/// </summary>
[System.Serializable]
public class LookAtBone: IKSolver.Bone {
#region Public methods
public LookAtBone() {}
/*
* Custom constructor
* */
public LookAtBone(Transform transform) {
this.transform = transform;
}
/*
* Initiates the bone, precalculates values.
* */
public void Initiate(Transform root) {
if (transform == null) return;
axis = Quaternion.Inverse(transform.rotation) * root.forward;
}
/*
* Rotates the bone to look at a world direction.
* */
public void LookAt(Vector3 direction, float weight) {
Quaternion fromTo = Quaternion.FromToRotation(forward, direction);
Quaternion r = transform.rotation;
transform.rotation = Quaternion.Lerp(r, fromTo * r, weight);
}
/*
* Gets the local axis to goal in world space.
* */
public Vector3 forward {
get {
return transform.rotation * axis;
}
}
#endregion Public methods
}
/// <summary>
/// Reinitiate the solver with new bone Transforms.
/// </summary>
/// <returns>
/// Returns true if the new chain is valid.
/// </returns>
public bool SetChain(Transform[] spine, Transform head, Transform[] eyes, Transform root) {
// Spine
SetBones(spine, ref this.spine);
// Head
this.head = new LookAtBone(head);
// Eyes
SetBones(eyes, ref this.eyes);
Initiate(root);
return initiated;
}
#endregion Main Interface
private Vector3[] spineForwards = new Vector3[0];
private Vector3[] headForwards = new Vector3[1];
private Vector3[] eyeForward = new Vector3[1];
protected override void OnInitiate() {
// Set IKPosition to default value
if (firstInitiation || !Application.isPlaying) {
if (spine.Length > 0) IKPosition = spine[spine.Length - 1].transform.position + root.forward * 3f;
else if (head.transform != null) IKPosition = head.transform.position + root.forward * 3f;
else if (eyes.Length > 0 && eyes[0].transform != null) IKPosition = eyes[0].transform.position + root.forward * 3f;
}
// Initiating the bones
foreach (LookAtBone s in spine) s.Initiate(root);
if (head != null) head.Initiate(root);
foreach (LookAtBone eye in eyes) eye.Initiate(root);
if (spineForwards == null || spineForwards.Length != spine.Length) spineForwards = new Vector3[spine.Length];
if (headForwards == null) headForwards = new Vector3[1];
if (eyeForward == null) eyeForward = new Vector3[1];
}
protected override void OnUpdate() {
if (IKPositionWeight <= 0) return;
IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f);
if (target != null) IKPosition = target.position;
// Solving the hierarchies
SolveSpine();
SolveHead();
SolveEyes();
}
private bool spineIsValid {
get {
if (spine == null) return false;
if (spine.Length == 0) return true;
for (int i = 0; i < spine.Length; i++) if (spine[i] == null || spine[i].transform == null) return false;
return true;
}
}
private bool spineIsEmpty { get { return spine.Length == 0; }}
// Solving the spine hierarchy
private void SolveSpine() {
if (bodyWeight <= 0) return;
if (spineIsEmpty) return;
// Get the look at vectors for each bone
//Vector3 targetForward = Vector3.Lerp(spine[0].forward, (IKPosition - spine[spine.Length - 1].transform.position).normalized, bodyWeight * IKPositionWeight).normalized;
Vector3 targetForward = (IKPosition - spine[spine.Length - 1].transform.position).normalized;
GetForwards(ref spineForwards, spine[0].forward, targetForward, spine.Length, clampWeight);
// Rotate each bone to face their look at vectors
for (int i = 0; i < spine.Length; i++) {
spine[i].LookAt(spineForwards[i], bodyWeight * IKPositionWeight);
}
}
private bool headIsValid {
get {
if (head == null) return false;
return true;
}
}
private bool headIsEmpty { get { return head.transform == null; }}
// Solving the head rotation
private void SolveHead() {
if (headWeight <= 0) return;
if (headIsEmpty) return;
// Get the look at vector for the head
Vector3 baseForward = spine.Length > 0 && spine[spine.Length - 1].transform != null? spine[spine.Length - 1].forward: head.forward;
Vector3 targetForward = Vector3.Lerp(baseForward, (IKPosition - head.transform.position).normalized, headWeight * IKPositionWeight).normalized;
GetForwards(ref headForwards, baseForward, targetForward, 1, clampWeightHead);
// Rotate the head to face its look at vector
head.LookAt(headForwards[0], headWeight * IKPositionWeight);
}
private bool eyesIsValid {
get {
if (eyes == null) return false;
if (eyes.Length == 0) return true;
for (int i = 0; i < eyes.Length; i++) if (eyes[i] == null || eyes[i].transform == null) return false;
return true;
}
}
private bool eyesIsEmpty { get { return eyes.Length == 0; }}
// Solving the eye rotations
private void SolveEyes() {
if (eyesWeight <= 0) return;
if (eyesIsEmpty) return;
for (int i = 0; i < eyes.Length; i++) {
// Get the look at vector for the eye
Vector3 baseForward = head.transform != null? head.forward: eyes[i].forward;
GetForwards(ref eyeForward, baseForward, (IKPosition - eyes[i].transform.position).normalized, 1, clampWeightEyes);
// Rotate the eye to face its look at vector
eyes[i].LookAt(eyeForward[0], eyesWeight * IKPositionWeight);
}
}
/*
* Returns forwards for a number of bones rotating from baseForward to targetForward.
* NB! Make sure baseForward and targetForward are normalized.
* */
private Vector3[] GetForwards(ref Vector3[] forwards, Vector3 baseForward, Vector3 targetForward, int bones, float clamp) {
// If clamp >= 1 make all the forwards match the base
if (clamp >= 1 || IKPositionWeight <= 0) {
for (int i = 0; i < forwards.Length; i++) forwards[i] = baseForward;
return forwards;
}
// Get normalized dot product.
float angle = Vector3.Angle(baseForward, targetForward);
float dot = 1f - (angle / 180f);
// Clamping the targetForward so it doesn't exceed clamp
float targetClampMlp = clamp > 0? Mathf.Clamp(1f - ((clamp - dot) / (1f - dot)), 0f, 1f): 1f;
// Calculating the clamp multiplier
float clampMlp = clamp > 0? Mathf.Clamp(dot / clamp, 0f, 1f): 1f;
for (int i = 0; i < clampSmoothing; i++) {
float sinF = clampMlp * Mathf.PI * 0.5f;
clampMlp = Mathf.Sin(sinF);
}
// Rotation amount for 1 bone
if (forwards.Length == 1) {
forwards[0] = Vector3.Slerp(baseForward, targetForward, clampMlp * targetClampMlp);
} else {
float step = 1f / (float)(forwards.Length - 1);
// Calculate the forward for each bone
for (int i = 0; i < forwards.Length; i++) {
forwards[i] = Vector3.Slerp(baseForward, targetForward, spineWeightCurve.Evaluate(step * i) * clampMlp * targetClampMlp);
}
}
return forwards;
}
/*
* Build LookAtBone[] array of a Transform array
* */
private void SetBones(Transform[] array, ref LookAtBone[] bones) {
if (array == null) {
bones = new LookAtBone[0];
return;
}
if (bones.Length != array.Length) bones = new LookAtBone[array.Length];
for (int i = 0; i < array.Length; i++) {
if (bones[i] == null) bones[i] = new LookAtBone(array[i]);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using GameDataEditor;
public class GDESaveHook : UnityEditor.AssetModificationProcessor
{
public static string[] OnWillSaveAssets(string[] paths)
{
if (GDEItemManager.ItemsNeedSave || GDEItemManager.SchemasNeedSave)
GDEItemManager.Save();
return paths;
}
}
public abstract class GDEManagerWindowBase : EditorWindow {
protected HashSet<string> entryFoldoutState = new HashSet<string>();
protected HashSet<string> listFieldFoldoutState = new HashSet<string>();
protected HashSet<string> previewState = new HashSet<string>();
protected bool currentFoldoutAllState = false;
protected Dictionary<string, int> newListCountDict = new Dictionary<string, int>();
protected string filterText = string.Empty;
protected string newFilterText = string.Empty;
protected Vector2 verticalScrollbarPosition;
protected float scrollViewHeight = 0;
protected float scrollViewY = 0;
protected bool shouldRecalculateHeights = true;
protected float currentGroupHeightTotal = 0;
protected Dictionary<string, float> groupHeights = new Dictionary<string, float>();
protected Dictionary<string, float> groupHeightBySchema = new Dictionary<string, float>();
protected bool shouldRebuildEntriesList = true;
protected Dictionary<string, Dictionary<string, object>> entriesToDraw;
protected List<string> deleteEntries = new List<string>();
protected List<string> cloneEntries = new List<string>();
protected GUIStyle foldoutStyle = null;
protected GUIStyle labelStyle = null;
protected GUIStyle saveButtonStyle = null;
protected GUIStyle loadButtonStyle = null;
protected GUIStyle linkStyle = null;
protected GUIStyle rateBoxStyle = null;
protected GUIStyle audioPreviewStyle = null;
protected GUIStyle searchStyle = null;
protected GUIStyle searchCancelStyle = null;
protected GUIStyle searchCancelEmptyStyle = null;
static GameObject _audioSampler = null;
protected static GameObject AudioSampler
{
get
{
if (_audioSampler == null)
{
_audioSampler = new GameObject("GDE Audio Sampler", typeof(AudioSource));
_audioSampler.hideFlags = HideFlags.HideAndDontSave;
}
return _audioSampler;
}
}
static AudioSource _audioSource = null;
protected static AudioSource AudioSamplerAS
{
get
{
if (_audioSource == null)
_audioSource = AudioSampler.GetComponent<AudioSource>();
return _audioSource;
}
}
protected Vector2 size = Vector2.zero;
GUIContent _content;
protected GUIContent content
{
get
{
if (_content == null)
_content = new GUIContent();
return _content;
}
}
protected string highlightContent;
protected float highlightStartTime;
protected Color32 highlightColorStart;
protected Color32 highlightColorEnd;
protected Color32 newhighlightColor;
protected string newhighlightColorStr;
protected float lerpColorProgress;
GDEDrawHelper _drawHelper;
protected GDEDrawHelper drawHelper
{
get {
if (_drawHelper == null)
_drawHelper = new GDEDrawHelper(this);
return _drawHelper;
}
}
protected string saveButtonText = GDEConstants.SaveBtn;
protected Color headerColor = Color.red;
protected string mainHeaderText = "Oops";
protected float buttonHeightMultiplier = 1.5f;
protected float buttonWidth = 60f;
protected string highlightColor;
protected string SearchCancelContent = string.Empty;
protected double lastClickTime = 0;
protected string lastClickedKey = string.Empty;
protected HashSet<string> editingFields = new HashSet<string>();
protected Dictionary<string, string> editFieldTextDict = new Dictionary<string, string>();
protected delegate bool DoRenameDelgate(string oldValue, string newValue, Dictionary<string, object> data, out string errorMsg);
void OnFocus()
{
if (GDEItemManager.AllItems.Count.Equals(0) && GDEItemManager.AllSchemas.Count.Equals(0) && !GDEItemManager.ItemsNeedSave && !GDEItemManager.SchemasNeedSave)
GDEItemManager.Load();
}
void SetStyles()
{
if (labelStyle.IsNullOrEmpty())
{
labelStyle = new GUIStyle(GUI.skin.label);
labelStyle.richText = true;
}
if (saveButtonStyle.IsNullOrEmpty())
{
saveButtonStyle = new GUIStyle(GUI.skin.button);
saveButtonStyle.fontSize = 14;
}
if (loadButtonStyle.IsNullOrEmpty())
{
loadButtonStyle = new GUIStyle(GUI.skin.button);
loadButtonStyle.fontSize = 14;
}
if (foldoutStyle.IsNullOrEmpty())
{
foldoutStyle = new GUIStyle(EditorStyles.foldout);
foldoutStyle.richText = true;
}
if (linkStyle.IsNullOrEmpty())
{
linkStyle = new GUIStyle(GUI.skin.label);
linkStyle.fontSize = 16;
linkStyle.alignment = TextAnchor.MiddleCenter;
linkStyle.normal.textColor = Color.blue;
}
if (rateBoxStyle.IsNullOrEmpty())
{
rateBoxStyle = new GUIStyle(GUI.skin.box);
rateBoxStyle.normal.background = (Texture2D)AssetDatabase.LoadAssetAtPath(GDESettings.RelativeRootDir + Path.DirectorySeparatorChar +
GDEConstants.BorderTexturePath, typeof(Texture2D));
rateBoxStyle.border = new RectOffset(2, 2, 2, 2);
}
if (audioPreviewStyle.IsNullOrEmpty())
{
audioPreviewStyle = new GUIStyle(EditorStyles.foldout);
}
if (searchStyle.IsNullOrEmpty())
{
var style = GUI.skin.FindStyle("ToolbarSeachTextField");
if (!style.IsNullOrEmpty())
searchStyle = new GUIStyle(style);
else
searchStyle = new GUIStyle(EditorStyles.textField);
searchStyle.fixedWidth = 200f;
searchStyle.fontSize = 12;
searchStyle.fixedHeight = 16;
searchStyle.contentOffset = new Vector2(0, -1);
}
if (searchCancelStyle.IsNullOrEmpty())
{
var style = GUI.skin.FindStyle("ToolbarSeachCancelButton");
if (!style.IsNullOrEmpty())
searchCancelStyle = new GUIStyle(style);
else
{
searchCancelStyle = new GUIStyle(GUI.skin.button);
SearchCancelContent = "X";
}
searchCancelStyle.fixedHeight = 16;
}
if (searchCancelEmptyStyle.IsNullOrEmpty())
{
var style = GUI.skin.FindStyle("ToolbarSeachCancelButtonEmpty");
if (!style.IsNullOrEmpty())
searchCancelEmptyStyle = new GUIStyle(style);
else
searchCancelEmptyStyle = new GUIStyle();
searchCancelEmptyStyle.fixedHeight = 16;
}
}
protected virtual void Update()
{
if (string.IsNullOrEmpty(highlightContent))
return;
float timeElapsed = Time.realtimeSinceStartup - highlightStartTime;
// Flip the colors
if (lerpColorProgress >= 1f)
{
if (highlightColorEnd.NearlyEqual(GDEConstants.NewHighlightStart.ToColor32()))
{
highlightColorEnd = GDEConstants.NewHighlightEnd.ToColor32();
highlightColorStart = GDEConstants.NewHighlightStart.ToColor32();
}
else
{
highlightColorEnd = GDEConstants.NewHighlightStart.ToColor32();
highlightColorStart = GDEConstants.NewHighlightEnd.ToColor32();
}
lerpColorProgress = 0f;
}
if (timeElapsed >= GDEConstants.NewHighlightDuration)
{
highlightContent = string.Empty;
highlightStartTime = 0;
lerpColorProgress = 0;
}
else if ((timeElapsed%GDEConstants.NewHighlightRate).NearlyEqual(0f))
{
// Update the color
newhighlightColor = Color32.Lerp(highlightColorStart, highlightColorEnd, lerpColorProgress/GDEConstants.NewHightlightPeriod);
newhighlightColorStr = newhighlightColor.ToHexString();
lerpColorProgress += GDEConstants.NewHighlightRate;
}
}
void OnInspectorUpdate()
{
Repaint();
}
#region OnGUI and DrawHeader Methods
protected virtual void OnGUI()
{
SetStyles();
highlightColor = GDESettings.Instance.HighlightColor;
drawHelper.ResetToTop();
// Process page up/down press & home/end press
if (Event.current.isKey)
{
if (Event.current.keyCode == KeyCode.PageDown)
{
verticalScrollbarPosition.y += scrollViewHeight/2f;
Event.current.Use();
}
else if (Event.current.keyCode == KeyCode.PageUp)
{
verticalScrollbarPosition.y -= scrollViewHeight/2f;
Event.current.Use();
}
else if (Event.current.keyCode == KeyCode.Home)
{
verticalScrollbarPosition.y = 0;
Event.current.Use();
}
else if (Event.current.keyCode == KeyCode.End)
{
verticalScrollbarPosition.y = CalculateGroupHeightsTotal()-GDEConstants.LineHeight-scrollViewY;
Event.current.Use();
}
}
drawHelper.DrawMainHeaderLabel(mainHeaderText, headerColor, GDEConstants.SizeEditorHeaderKey);
DrawHeader();
DrawCreateSection();
}
protected virtual void DrawHeader()
{
size.x = 60;
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()*buttonHeightMultiplier), GDEConstants.LoadBtn, loadButtonStyle))
{
Load();
GUI.FocusControl(string.Empty);
}
drawHelper.CurrentLinePosition += (size.x + 2);
content.text = FilePath();
drawHelper.TryGetCachedSize(GDEConstants.SizeFileLblKey, content, EditorStyles.label, out size);
EditorGUI.SelectableLabel(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), drawHelper.WidthLeftOnCurrentLine(), size.y), content.text);
drawHelper.CurrentLinePosition += (size.x + 2);
drawHelper.NewLine(buttonHeightMultiplier+.1f);
if (NeedToSave())
{
size.x = 110;
saveButtonStyle.normal.textColor = Color.red;
saveButtonStyle.fontStyle = FontStyle.Bold;
saveButtonText = GDEConstants.SaveNeededBtn;
}
else
{
size.x = 60;
saveButtonStyle.normal.textColor = GUI.skin.button.normal.textColor;
saveButtonStyle.fontStyle = FontStyle.Normal;
saveButtonText = GDEConstants.SaveBtn;
}
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()*buttonHeightMultiplier), saveButtonText, saveButtonStyle))
Save();
drawHelper.NewLine(buttonHeightMultiplier+.5f);
drawHelper.DrawSectionSeparator();
DrawSpreadsheetSection();
drawHelper.NewLine(.5f);
if (DrawFilterSection())
ClearSearch();
drawHelper.DrawSectionSeparator();
}
protected virtual void DrawRateBox(float left, float top, float width, float height)
{
GUI.Box(new Rect(left, top, 2f, height), string.Empty, rateBoxStyle);
GUI.Box(new Rect(left, top, width, 2f), string.Empty, rateBoxStyle);
GUI.Box(new Rect(left, top+height, width+2, 2f), string.Empty, rateBoxStyle);
GUI.Box(new Rect(left+width, top, 2f, height), string.Empty, rateBoxStyle);
}
void DrawSpreadsheetSection()
{
GDESettings settings = GDESettings.Instance;
drawHelper.NewLine(0.75f);
drawHelper.DrawSubHeader(GDEConstants.SpreadsheetSectionHeader, headerColor, GDEConstants.SizeSpreadsheetSectionHeaderKey, false);
drawHelper.CurrentLinePosition += 5f;
float pos = drawHelper.CurrentLinePosition;
// Import Button
content.text = GDEConstants.ImportBtn;
if (!drawHelper.SizeCache.ContainsKey(GDEConstants.SizeImportBtnKey))
{
size.x = buttonWidth;
size.y = loadButtonStyle.CalcHeight(content, size.x);
drawHelper.SizeCache.Add(GDEConstants.SizeImportBtnKey, new Vector2(size.x, size.y));
}
else
size = drawHelper.SizeCache[GDEConstants.SizeImportBtnKey];
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()*buttonHeightMultiplier), content, loadButtonStyle))
{
GDEExcelManager.DoImport();
}
drawHelper.CurrentLinePosition += size.x + 4f;
// Import label
string path;
if (!settings.ImportType.Equals(ImportExportType.None))
{
if (settings.ImportType.Equals(ImportExportType.Google))
{
content.text = string.Format(GDEConstants.ImportSource, GDEConstants.GoogleDrive);
path = settings.ImportedGoogleSpreadsheetName;
}
else
{
content.text = string.Format(GDEConstants.ImportSource, string.Empty);
path = settings.ImportedLocalSpreadsheetName;
}
size = labelStyle.CalcSize(content);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+drawHelper.LineHeight*(buttonHeightMultiplier-1)/2f, size.x, size.y), content, labelStyle);
drawHelper.CurrentLinePosition += (size.x + 2f);
content.text = path;
size = labelStyle.CalcSize(content);
drawHelper.TryGetCachedSize(content.text, content, labelStyle, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+drawHelper.LineHeight*(buttonHeightMultiplier-1)/2f, size.x, size.y), content, labelStyle);
drawHelper.CurrentLinePosition += (size.x + 2f);
}
drawHelper.NewLine(buttonHeightMultiplier);
drawHelper.CurrentLinePosition = pos;
// Export Button
content.text = GDEConstants.ExportBtn;
if (!drawHelper.SizeCache.ContainsKey(GDEConstants.SizeExportBtnKey))
{
size.x = buttonWidth;
size.y = loadButtonStyle.CalcHeight(content, size.x);
drawHelper.SizeCache.Add(GDEConstants.SizeExportBtnKey, new Vector2(size.x, size.y));
}
else
size = drawHelper.SizeCache[GDEConstants.SizeExportBtnKey];
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()*buttonHeightMultiplier), content, loadButtonStyle))
{
GDEExcelManager.DoExport();
}
drawHelper.CurrentLinePosition += size.x + 4f;
// Export label
if (!settings.ExportType.Equals(ImportExportType.None))
{
if (settings.ExportType.Equals(ImportExportType.Google))
{
content.text = string.Format(GDEConstants.ExportDest, GDEConstants.GoogleDrive);
path = settings.ExportedGoogleSpreadsheetPath;
}
else
{
content.text = string.Format(GDEConstants.ExportDest, string.Empty);
path = settings.ExportedLocalSpreadsheetName;
}
size = labelStyle.CalcSize(content);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+drawHelper.LineHeight*(buttonHeightMultiplier-1)/2f, size.x, size.y), content, labelStyle);
drawHelper.CurrentLinePosition += (size.x + 2f);
content.text = path;
size = labelStyle.CalcSize(content);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+drawHelper.LineHeight*(buttonHeightMultiplier-1)/2f, size.x, size.y), content, labelStyle);
drawHelper.CurrentLinePosition += (size.x + 2f);
}
drawHelper.NewLine(buttonHeightMultiplier+.25f);
drawHelper.DrawSectionSeparator();
}
protected virtual void DrawEntryFooter(string cloneLbl, string cloneSizeKey, string entryKey)
{
content.text = cloneLbl;
drawHelper.TryGetCachedSize(cloneSizeKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
cloneEntries.Add(entryKey);
drawHelper.CurrentLinePosition += (size.x + 2f);
content.text = GDEConstants.DeleteBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeDeleteBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
deleteEntries.Add(entryKey);
drawHelper.NewLine();
drawHelper.DrawSectionSeparator();
drawHelper.NewLine(0.25f);
}
#endregion
#region GUI Position Methods
protected virtual void SetGroupHeight(string forKey, float height)
{
groupHeights[forKey] = height;
}
#endregion
#region Foldout Methods
protected virtual void DrawEditableLabel(string editableLabel, string editFieldKey, DoRenameDelgate doRename)
{
DrawEditableLabel(editableLabel, editFieldKey, doRename, null);
}
protected virtual void DrawEditableLabel(string editableLabel, string editFieldKey, DoRenameDelgate doRename, Dictionary<string, object> data)
{
if (!editingFields.Contains(editFieldKey))
{
if (editableLabel.Equals(highlightContent))
content.text = editableLabel.HighlightSubstring(highlightContent, newhighlightColorStr);
else
content.text = editableLabel.HighlightSubstring(filterText, highlightColor);
drawHelper.TryGetCachedSize(editFieldKey, content, labelStyle, out size);
size.x = Math.Max(size.x, GDEConstants.MinLabelWidth);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content, labelStyle))
{
if (EditorApplication.timeSinceStartup - lastClickTime < GDEConstants.DoubleClickTime && lastClickedKey.Equals(editFieldKey))
{
lastClickedKey = string.Empty;
editingFields.Add(editFieldKey);
}
else
{
lastClickedKey = editFieldKey;
editingFields.Remove(editFieldKey);
}
lastClickTime = EditorApplication.timeSinceStartup;
}
drawHelper.CurrentLinePosition += (size.x + 2);
}
else
{
string editFieldText;
if (!editFieldTextDict.TryGetValue(editFieldKey, out editFieldText))
editFieldText = editableLabel;
string newValue = DrawResizableTextBox(editFieldText);
editFieldTextDict.TryAddOrUpdateValue(editFieldKey, newValue);
if (!newValue.Equals(editableLabel))
{
content.text = GDEConstants.RenameBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeRenameBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content) && doRename != null)
{
string error;
if (doRename(editableLabel, newValue, data, out error))
{
editingFields.Remove(editFieldKey);
editFieldTextDict.Remove(editFieldKey);
GUI.FocusControl(string.Empty);
// Clear the current component size so its recalculated next draw cycle
drawHelper.SizeCache.Remove(editFieldKey);
}
else
EditorUtility.DisplayDialog(GDEConstants.ErrorLbl, string.Format(GDEConstants.CouldNotRenameFormat, editableLabel, newValue, error), GDEConstants.OkLbl);
}
drawHelper.CurrentLinePosition += (size.x + 2);
content.text = GDEConstants.CancelBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeCancelBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
editingFields.Remove(editFieldKey);
editFieldTextDict.Remove(editFieldKey);
GUI.FocusControl(string.Empty);
}
drawHelper.CurrentLinePosition += (size.x + 2);
}
else
{
content.text = GDEConstants.CancelBtn;
drawHelper.TryGetCachedSize(GDEConstants.SizeCancelBtnKey, content, GUI.skin.button, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content))
{
editingFields.Remove(editFieldKey);
editFieldTextDict.Remove(editFieldKey);
GUI.FocusControl(string.Empty);
}
drawHelper.CurrentLinePosition += (size.x + 2);
}
}
}
protected virtual bool DrawFoldout(string foldoutLabel, string key, string editableLabel, string editFieldKey, DoRenameDelgate doRename)
{
bool currentFoldoutState = entryFoldoutState.Contains(key);
content.text = foldoutLabel;
drawHelper.TryGetCachedSize(foldoutLabel+GDEConstants.LblSuffix, content, foldoutStyle, out size);
bool newFoldoutState = EditorGUI.Foldout(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), currentFoldoutState,
foldoutLabel.HighlightSubstring(filterText, highlightColor), foldoutStyle);
drawHelper.CurrentLinePosition += (size.x + 2);
if (doRename != null)
DrawEditableLabel(editableLabel, editFieldKey, doRename);
SetFoldout(newFoldoutState, key);
return newFoldoutState;
}
protected virtual void DrawExpandCollapseAllFoldout(string[] forKeys, string headerText)
{
drawHelper.DrawSubHeader(headerText, headerColor, GDEConstants.SizeListSubHeaderKey);
string key;
if (currentFoldoutAllState)
{
content.text = GDEConstants.CollapseAllLbl;
key = GDEConstants.SizeCollapseAllLblKey;
}
else
{
content.text = GDEConstants.ExpandAllLbl;
key = GDEConstants.SizeExpandAllLblKey;
}
drawHelper.TryGetCachedSize(key, content, EditorStyles.foldout, out size);
bool newFoldAllState = EditorGUI.Foldout(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), currentFoldoutAllState, content.text);
if (newFoldAllState != currentFoldoutAllState)
{
SetAllFoldouts(newFoldAllState, forKeys);
currentFoldoutAllState = newFoldAllState;
// Reset scrollbar if we just collapsed everything
if (!newFoldAllState)
verticalScrollbarPosition.y = 0;
shouldRecalculateHeights = true;
}
drawHelper.NewLine();
}
protected virtual void SetAllFoldouts(bool state, string[] forKeys)
{
foreach(string key in forKeys)
SetFoldout(state, key);
}
protected virtual void SetFoldout(bool state, string forKey)
{
if (state)
entryFoldoutState.Add(forKey);
else
entryFoldoutState.Remove(forKey);
}
#endregion
#region Draw Field Methods
protected virtual void DrawBool(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object currentValue;
bool newValue;
string key = fieldName;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 50;
newValue = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), Convert.ToBoolean(currentValue));
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != Convert.ToBoolean(currentValue))
{
data[key] = newValue;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListBool(GUIContent label, int index, bool value, IList boolList)
{
try
{
bool newValue;
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 30;
newValue = EditorGUI.Toggle(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), value);
drawHelper.CurrentLinePosition += (size.x + 2);
if (value != newValue)
{
boolList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawInt(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object currentValue;
int newValue;
string key = fieldName;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 50;
newValue = EditorGUI.IntField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), Convert.ToInt32(currentValue));
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != Convert.ToInt32(currentValue))
{
data[key] = newValue;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListInt(GUIContent label, int index, int value, IList intList)
{
try
{
int newValue;
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 50;
newValue = EditorGUI.IntField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), value);
drawHelper.CurrentLinePosition += (size.x + 2);
if (value != newValue)
{
intList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawFloat(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object currentValue;
float newValue;
string key = fieldName;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 50;
newValue = EditorGUI.FloatField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), Convert.ToSingle(currentValue));
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != Convert.ToSingle(currentValue))
{
data[key] = newValue;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListFloat(GUIContent label, int index, float value, IList floatList)
{
try
{
float newValue;
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 50;
newValue = EditorGUI.FloatField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), value);
drawHelper.CurrentLinePosition += (size.x + 2);
if (value != newValue)
{
floatList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawString(string fieldName, Dictionary<string, object> data, string label)
{
try
{
string key = fieldName;
object currentValue;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
string newValue = DrawResizableTextBox(currentValue as string);
if (newValue != (string)currentValue)
{
data[key] = newValue;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual string DrawResizableTextBox(string text)
{
content.text = text;
size = GUI.skin.textField.CalcSize(content);
size.x = Math.Min(Math.Max(size.x, GDEConstants.MinTextAreaWidth), drawHelper.WidthLeftOnCurrentLine() - 62);
size.y = Math.Max(size.y, drawHelper.StandardHeight());
string newValue = EditorGUI.TextArea(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content.text);
drawHelper.CurrentLinePosition += (size.x + 2);
float tempLinePosition = drawHelper.CurrentLinePosition;
drawHelper.NewLine(size.y/GDEConstants.LineHeight - 1);
drawHelper.CurrentLinePosition = tempLinePosition;
return newValue;
}
protected virtual void DrawListString(GUIContent label, int index, string value, IList stringList)
{
try
{
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
string newValue = DrawResizableTextBox(value);
if (!value.Equals(newValue))
{
stringList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawVector2(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object temp = null;
Dictionary<string, object> vectDict = null;
Vector2 currentValue = Vector2.zero;
Vector2 newValue;
string key = fieldName;
if (data.TryGetValue(key, out temp))
{
vectDict = temp as Dictionary<string, object>;
currentValue.x = Convert.ToSingle(vectDict["x"]);
currentValue.y = Convert.ToSingle(vectDict["y"]);
}
size.x = 136;
newValue = EditorGUI.Vector2Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
vectDict["x"] = newValue.x;
vectDict["y"] = newValue.y;
data[key] = vectDict;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListVector2(GUIContent label, int index, Dictionary<string, object> value, IList vectorList)
{
try
{
Vector2 newValue;
Vector2 currentValue = Vector2.zero;
currentValue.x = Convert.ToSingle(value["x"]);
currentValue.y = Convert.ToSingle(value["y"]);
size.x = 136;
newValue = EditorGUI.Vector2Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label.text, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
value["x"] = newValue.x;
value["y"] = newValue.y;
vectorList[index] = value;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawVector3(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object temp = null;
Dictionary<string, object> vectDict = null;
Vector3 currentValue = Vector3.zero;
Vector3 newValue;
string key = fieldName;
if (data.TryGetValue(key, out temp))
{
vectDict = temp as Dictionary<string, object>;
currentValue.x = Convert.ToSingle(vectDict["x"]);
currentValue.y = Convert.ToSingle(vectDict["y"]);
currentValue.z = Convert.ToSingle(vectDict["z"]);
}
size.x = 200;
newValue = EditorGUI.Vector3Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
vectDict["x"] = newValue.x;
vectDict["y"] = newValue.y;
vectDict["z"] = newValue.z;
data[key] = vectDict;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListVector3(GUIContent label, int index, Dictionary<string, object> value, IList vectorList)
{
try
{
Vector3 newValue;
Vector3 currentValue = Vector3.zero;
currentValue.x = Convert.ToSingle(value["x"]);
currentValue.y = Convert.ToSingle(value["y"]);
currentValue.z = Convert.ToSingle(value["z"]);
size.x = 200;
newValue = EditorGUI.Vector3Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label.text, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
value["x"] = newValue.x;
value["y"] = newValue.y;
value["z"] = newValue.z;
vectorList[index] = value;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawVector4(string fieldName, Dictionary<string, object> data, string label)
{
try
{
object temp = null;
Dictionary<string, object> vectDict = null;
Vector4 currentValue = Vector4.zero;
Vector4 newValue;
string key = fieldName;
if (data.TryGetValue(key, out temp))
{
vectDict = temp as Dictionary<string, object>;
currentValue.x = Convert.ToSingle(vectDict["x"]);
currentValue.y = Convert.ToSingle(vectDict["y"]);
currentValue.z = Convert.ToSingle(vectDict["z"]);
currentValue.w = Convert.ToSingle(vectDict["w"]);
}
size.x = 228;
newValue = EditorGUI.Vector4Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
vectDict["x"] = newValue.x;
vectDict["y"] = newValue.y;
vectDict["z"] = newValue.z;
vectDict["w"] = newValue.w;
data[key] = vectDict;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListVector4(GUIContent label, int index, Dictionary<string, object> value, IList vectorList)
{
try
{
Vector4 newValue;
Vector4 currentValue = Vector4.zero;
currentValue.x = Convert.ToSingle(value["x"]);
currentValue.y = Convert.ToSingle(value["y"]);
currentValue.z = Convert.ToSingle(value["z"]);
currentValue.w = Convert.ToSingle(value["w"]);
size.x = 228;
newValue = EditorGUI.Vector4Field(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.VectorFieldHeight()), label.text, currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
value["x"] = newValue.x;
value["y"] = newValue.y;
value["z"] = newValue.z;
value["w"] = newValue.w;
vectorList[index] = value;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawColor(string fieldName, Dictionary<string, object> data, string label)
{
try
{
Color newValue;
Color currentValue = Color.white;
object temp;
Dictionary<string, object> colorDict = new Dictionary<string, object>();
if (data.TryGetValue(fieldName, out temp))
{
colorDict = temp as Dictionary<string, object>;
colorDict.TryGetFloat("r", out currentValue.r);
colorDict.TryGetFloat("g", out currentValue.g);
colorDict.TryGetFloat("b", out currentValue.b);
colorDict.TryGetFloat("a", out currentValue.a);
}
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230 - size.x;
newValue = EditorGUI.ColorField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
colorDict.TryAddOrUpdateValue("r", newValue.r);
colorDict.TryAddOrUpdateValue("g", newValue.g);
colorDict.TryAddOrUpdateValue("b", newValue.b);
colorDict.TryAddOrUpdateValue("a", newValue.a);
SetNeedToSave(true);
}
}
catch(Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawListColor(GUIContent label, int index, Dictionary<string, object> value, IList colorList)
{
try
{
Color newValue;
Color currentValue = Color.white;
value.TryGetFloat("r", out currentValue.r);
value.TryGetFloat("g", out currentValue.g);
value.TryGetFloat("b", out currentValue.b);
value.TryGetFloat("a", out currentValue.a);
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230 - size.x;
newValue = EditorGUI.ColorField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, drawHelper.StandardHeight()), currentValue);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newValue != currentValue)
{
value.TryAddOrUpdateValue("r", newValue.r);
value.TryAddOrUpdateValue("g", newValue.g);
value.TryAddOrUpdateValue("b", newValue.b);
value.TryAddOrUpdateValue("a", newValue.a);
colorList[index] = value;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawAudio(string fieldKey, string fieldName, Dictionary<string, object> data, string label)
{
try
{
string key = fieldName;
object currentValue;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230f - size.x;
AudioClip newClip = EditorGUI.ObjectField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), currentValue as AudioClip, typeof(AudioClip), false) as AudioClip;
drawHelper.CurrentLinePosition += (size.x + 2);
DrawAudioPreview(fieldKey, newClip);
if (newClip != currentValue)
{
data[key] = newClip;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawListAudio(string fieldKey, GUIContent label, int index, AudioClip value, IList goList)
{
try
{
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230f - size.x;
AudioClip newValue = EditorGUI.ObjectField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), value, typeof(AudioClip), false) as AudioClip;
drawHelper.CurrentLinePosition += (size.x + 2);
DrawAudioPreview(fieldKey, newValue);
if (newValue != value)
{
goList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawAudioPreview(string fieldKey, AudioClip clip)
{
if (clip != null)
{
bool isPlayingThisClip = false;
if (AudioSamplerAS.isPlaying && AudioSamplerAS.clip.Equals(clip))
{
isPlayingThisClip = true;
audioPreviewStyle.normal = EditorStyles.foldout.focused;
}
else
{
audioPreviewStyle.normal = EditorStyles.foldout.active;
}
content.text = string.Empty;
drawHelper.TryGetCachedSize(GDEConstants.SizePreviewAudioLblKey, content, audioPreviewStyle, out size);
if (GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), string.Empty, audioPreviewStyle))
{
if (isPlayingThisClip)
{
AudioSamplerAS.Stop();
}
else
{
AudioSamplerAS.clip = clip;
AudioSamplerAS.Play();
}
}
drawHelper.CurrentLinePosition += (size.x + 2);
}
}
protected virtual void DrawObject<T>(string fieldKey, string fieldName, Dictionary<string, object> data, string label) where T : UnityEngine.Object
{
try
{
string key = fieldName;
object currentValue;
data.TryGetValue(key, out currentValue);
content.text = label;
drawHelper.TryGetCachedSize(label, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230f - size.x;
T newValue = EditorGUI.ObjectField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), currentValue as T, typeof(T), false) as T;
drawHelper.CurrentLinePosition += (size.x + 2);
DrawPreview<T>(fieldKey, newValue);
if (newValue != currentValue)
{
data[key] = newValue;
SetNeedToSave(true);
}
}
catch(Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawListObject<T>(string fieldKey, GUIContent label, int index, T value, IList goList) where T : UnityEngine.Object
{
try
{
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 230f - size.x;
T newValue = EditorGUI.ObjectField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), value, typeof(T), false) as T;
drawHelper.CurrentLinePosition += (size.x + 2);
DrawPreview<T>(fieldKey, newValue);
if (newValue != value)
{
goList[index] = newValue;
SetNeedToSave(true);
}
}
catch (Exception ex)
{
// Don't log ExitGUIException here. This is a unity bug with ObjectField and ColorField.
if (!(ex is ExitGUIException))
Debug.LogError(ex);
}
}
protected virtual void DrawPreview<T>(string fieldKey, T newValue) where T : UnityEngine.Object
{
Texture2D preview = null;
if (newValue != null)
preview = AssetPreview.GetAssetPreview(newValue);
if (preview != null)
{
content.text = GDEConstants.PreviewLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizePreviewLblKey, content, EditorStyles.foldout, out size);
bool curFoldoutState = previewState.Contains(fieldKey);
bool newFoldoutState = EditorGUI.Foldout(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), curFoldoutState, content);
drawHelper.CurrentLinePosition += (size.x + 2);
if (newFoldoutState != curFoldoutState)
{
if (newFoldoutState)
previewState.Add(fieldKey);
else
previewState.Remove(fieldKey);
}
if (newFoldoutState)
{
EditorGUI.DrawPreviewTexture(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), preview.width, preview.height), preview);
drawHelper.CurrentLinePosition += (preview.width + 2);
drawHelper.NewLine(preview.height/drawHelper.LineHeight);
}
}
}
protected virtual void DrawCustom(string fieldName, Dictionary<string, object> data, bool canEdit, List<string> possibleValues = null)
{
try
{
object currentValue;
int newIndex;
int currentIndex;
string key = fieldName;
data.TryGetValue(key, out currentValue);
if (canEdit && possibleValues != null)
{
currentIndex = possibleValues.IndexOf(currentValue as string);
content.text = GDEConstants.ValueLbl;
drawHelper.TryGetCachedSize(GDEConstants.SizeValueLblKey, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 80;
newIndex = EditorGUI.Popup(new Rect(drawHelper.CurrentLinePosition, drawHelper.PopupTop(), size.x, drawHelper.StandardHeight()), currentIndex, possibleValues.ToArray());
drawHelper.CurrentLinePosition += (size.x + 2);
if (newIndex != currentIndex)
{
data[key] = possibleValues[newIndex];
SetNeedToSave(true);
}
}
else
{
content.text = GDEConstants.DefaultValueLbl + " null";
drawHelper.TryGetCachedSize(GDEConstants.SizeDefaultValueLblKey, content, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), content);
drawHelper.CurrentLinePosition += (size.x + 4);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void DrawListCustom(GUIContent label, int index, string value, IList customList, bool canEdit, List<string> possibleValues = null)
{
try
{
int newIndex;
int currentIndex;
if (canEdit && possibleValues != null)
{
currentIndex = possibleValues.IndexOf(value);
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
size.x = 80;
newIndex = EditorGUI.Popup(new Rect(drawHelper.CurrentLinePosition, drawHelper.PopupTop(), size.x, drawHelper.StandardHeight()), currentIndex, possibleValues.ToArray());
drawHelper.CurrentLinePosition += (size.x + 2);
if (newIndex != currentIndex)
{
customList[index] = possibleValues[newIndex];
SetNeedToSave(true);
}
}
else
{
label.text += " null";
drawHelper.TryGetCachedSize(label.text, label, EditorStyles.label, out size);
EditorGUI.LabelField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine(), size.x, size.y), label);
drawHelper.CurrentLinePosition += (size.x + 2);
}
}
catch(Exception ex)
{
Debug.LogError(ex);
}
}
protected virtual void HighlightNew(string content)
{
highlightContent = content;
highlightStartTime = Time.realtimeSinceStartup;
lerpColorProgress = 0f;
newhighlightColor = GDEConstants.NewHighlightStart.ToColor32();
highlightColorStart = GDEConstants.NewHighlightStart.ToColor32();
highlightColorEnd = GDEConstants.NewHighlightEnd.ToColor32();
}
#endregion
#region Filter/Sorting Methods
protected virtual bool DrawFilterSection()
{
content.text = GDEConstants.SearchHeader;
size = drawHelper.DrawSubHeader(content.text, headerColor, GDEConstants.SizeSearchHeaderKey, false);
drawHelper.NewLine(.1f);
drawHelper.CurrentLinePosition += (size.x + 4f);
// Text search
size.x = searchStyle.fixedWidth;
newFilterText = EditorGUI.TextField(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+GDEConstants.LineHeight/4f-2f, size.x, drawHelper.StandardHeight()), newFilterText, searchStyle);
drawHelper.CurrentLinePosition += (size.x);
if (!newFilterText.Equals(filterText))
{
filterText = newFilterText;
shouldRecalculateHeights = true;
shouldRebuildEntriesList = true;
}
GUIStyle cancelStyle;
string cancelKey;
content.text = SearchCancelContent;
if(string.IsNullOrEmpty(newFilterText))
{
cancelStyle = searchCancelEmptyStyle;
cancelKey = GDEConstants.SizeClearSearchEmptyKey;
content.text = string.Empty;
}
else
{
cancelStyle = searchCancelStyle;
cancelKey = GDEConstants.SizeClearSearchBtnKey;
}
drawHelper.TryGetCachedSize(cancelKey, content, cancelStyle, out size);
bool clearSearch = GUI.Button(new Rect(drawHelper.CurrentLinePosition, drawHelper.TopOfLine()+GDEConstants.LineHeight/4f-2f, size.x, size.y), content, cancelStyle);
drawHelper.CurrentLinePosition += (size.x + 2);
return clearSearch;
}
protected virtual int NumberOfItemsBeingShown()
{
if (entriesToDraw != null)
return entriesToDraw.Count;
return 0;
}
protected virtual void ClearSearch()
{
newFilterText = string.Empty;
filterText = string.Empty;
GUI.FocusControl(string.Empty);
shouldRebuildEntriesList = true;
shouldRecalculateHeights = true;
}
protected Dictionary<string, Dictionary<string, object>> GetEntriesToDraw(Dictionary<string, Dictionary<string, object>> source)
{
Dictionary<string, Dictionary<string, object>> entries = new Dictionary<string, Dictionary<string, object>>();
foreach(var entry in source)
{
if (!ShouldFilter(entry.Key, entry.Value))
entries.Add(entry.Key, entry.Value);
}
return entries;
}
#endregion
#region List Helper Methods
protected virtual void ResizeList(IList list, int size, object defaultValue)
{
// Remove from the end until the size matches what we want
if (list.Count > size)
{
while(list.Count > size)
list.RemoveAt(list.Count-1);
SetNeedToSave(true);
}
else if (list.Count < size)
{
// Add entries with the default value until the size is what we want
for (int i = list.Count; i < size; i++)
list.Add(defaultValue.DeepCopyCollection());
SetNeedToSave(true);
}
}
#endregion
#region Save/Load methods
protected virtual void Load()
{
GDEItemManager.Load();
entryFoldoutState.Clear();
listFieldFoldoutState.Clear();
currentFoldoutAllState = false;
newListCountDict.Clear();
filterText = string.Empty;
groupHeights.Clear();
groupHeightBySchema.Clear();
editingFields.Clear();
editFieldTextDict.Clear();
deleteEntries.Clear();
cloneEntries.Clear();
drawHelper.SizeCache.Clear();
shouldRecalculateHeights = true;
shouldRebuildEntriesList = true;
}
protected virtual void Save()
{
GDEItemManager.Save();
}
#endregion
#region Abstract methods
protected abstract bool Create(object data);
protected abstract void Remove(string key);
protected abstract bool Clone(string key);
protected abstract void DrawEntry(string key, Dictionary<string, object> data);
protected abstract void DrawCreateSection();
protected abstract bool ShouldFilter(string key, Dictionary<string, object> data);
protected abstract bool NeedToSave();
protected abstract void SetNeedToSave(bool shouldSave);
protected abstract string FilePath();
protected abstract float CalculateGroupHeightsTotal();
#endregion
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public partial class AutomationManagementClient : ServiceClient<AutomationManagementClient>, IAutomationManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _resourceNamespace;
/// <summary>
/// Gets or sets the resource namespace.
/// </summary>
public string ResourceNamespace
{
get { return this._resourceNamespace; }
set { this._resourceNamespace = value; }
}
private IActivityOperations _activities;
/// <summary>
/// Service operation for automation activities. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
public virtual IActivityOperations Activities
{
get { return this._activities; }
}
private IAgentRegistrationOperation _agentRegistrationInformation;
/// <summary>
/// Service operation for automation agent registration information.
/// (see http://aka.ms/azureautomationsdk/agentregistrationoperations
/// for more information)
/// </summary>
public virtual IAgentRegistrationOperation AgentRegistrationInformation
{
get { return this._agentRegistrationInformation; }
}
private IAutomationAccountOperations _automationAccounts;
/// <summary>
/// Service operation for automation accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
public virtual IAutomationAccountOperations AutomationAccounts
{
get { return this._automationAccounts; }
}
private ICertificateOperations _certificates;
/// <summary>
/// Service operation for automation certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
public virtual ICertificateOperations Certificates
{
get { return this._certificates; }
}
private IConnectionOperations _connections;
/// <summary>
/// Service operation for automation connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
public virtual IConnectionOperations Connections
{
get { return this._connections; }
}
private IConnectionTypeOperations _connectionTypes;
/// <summary>
/// Service operation for automation connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
public virtual IConnectionTypeOperations ConnectionTypes
{
get { return this._connectionTypes; }
}
private ICredentialOperations _psCredentials;
/// <summary>
/// Service operation for automation credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
public virtual ICredentialOperations PsCredentials
{
get { return this._psCredentials; }
}
private IDscCompilationJobOperations _compilationJobs;
/// <summary>
/// Service operation for automation dsc configuration compile jobs.
/// (see
/// http://aka.ms/azureautomationsdk/dscccompilationjoboperations for
/// more information)
/// </summary>
public virtual IDscCompilationJobOperations CompilationJobs
{
get { return this._compilationJobs; }
}
private IDscConfigurationOperations _configurations;
/// <summary>
/// Service operation for configurations. (see
/// http://aka.ms/azureautomationsdk/configurationoperations for more
/// information)
/// </summary>
public virtual IDscConfigurationOperations Configurations
{
get { return this._configurations; }
}
private IDscNodeConfigurationOperations _nodeConfigurations;
/// <summary>
/// Service operation for automation dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
public virtual IDscNodeConfigurationOperations NodeConfigurations
{
get { return this._nodeConfigurations; }
}
private IDscNodeOperations _nodes;
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
public virtual IDscNodeOperations Nodes
{
get { return this._nodes; }
}
private IDscNodeReportsOperations _nodeReports;
/// <summary>
/// Service operation for node reports. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
public virtual IDscNodeReportsOperations NodeReports
{
get { return this._nodeReports; }
}
private IHybridRunbookWorkerGroupOperations _hybridRunbookWorkerGroups;
/// <summary>
/// Service operation for automation hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
public virtual IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroups
{
get { return this._hybridRunbookWorkerGroups; }
}
private IJobOperations _jobs;
/// <summary>
/// Service operation for automation jobs. (see
/// http://aka.ms/azureautomationsdk/joboperations for more
/// information)
/// </summary>
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
private IJobScheduleOperations _jobSchedules;
/// <summary>
/// Service operation for automation job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
public virtual IJobScheduleOperations JobSchedules
{
get { return this._jobSchedules; }
}
private IJobStreamOperations _jobStreams;
/// <summary>
/// Service operation for automation job streams. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations for more
/// information)
/// </summary>
public virtual IJobStreamOperations JobStreams
{
get { return this._jobStreams; }
}
private IModuleOperations _modules;
/// <summary>
/// Service operation for automation modules. (see
/// http://aka.ms/azureautomationsdk/moduleoperations for more
/// information)
/// </summary>
public virtual IModuleOperations Modules
{
get { return this._modules; }
}
private IRunbookDraftOperations _runbookDraft;
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
public virtual IRunbookDraftOperations RunbookDraft
{
get { return this._runbookDraft; }
}
private IRunbookOperations _runbooks;
/// <summary>
/// Service operation for automation runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
public virtual IRunbookOperations Runbooks
{
get { return this._runbooks; }
}
private IScheduleOperations _schedules;
/// <summary>
/// Service operation for automation schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
public virtual IScheduleOperations Schedules
{
get { return this._schedules; }
}
private ITestJobOperations _testJobs;
/// <summary>
/// Service operation for automation test jobs. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
public virtual ITestJobOperations TestJobs
{
get { return this._testJobs; }
}
private IVariableOperations _variables;
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
public virtual IVariableOperations Variables
{
get { return this._variables; }
}
private IWebhookOperations _webhooks;
/// <summary>
/// Service operation for automation webhook. (see
/// http://aka.ms/azureautomationsdk/webhookoperations for more
/// information)
/// </summary>
public virtual IWebhookOperations Webhooks
{
get { return this._webhooks; }
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
public AutomationManagementClient()
: base()
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._modules = new ModuleOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._testJobs = new TestJobOperations(this);
this._variables = new VariableOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._modules = new ModuleOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._testJobs = new TestJobOperations(this);
this._variables = new VariableOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AutomationManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of AutomationManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<AutomationManagementClient> client)
{
base.Clone(client);
if (client is AutomationManagementClient)
{
AutomationManagementClient clonedClient = ((AutomationManagementClient)client);
clonedClient._resourceNamespace = this._resourceNamespace;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> GetOperationResultStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetOperationResultStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
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
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.BadRequest)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.NotFound)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified operation. After calling an asynchronous operation,
/// you can call Get Operation Status to determine whether the
/// operation has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </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 async Task<LongRunningOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.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
LongRunningOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LongRunningOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
LongRunningOperationStatusResponse.ErrorDetails errorInstance = new LongRunningOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
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();
}
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Renders the nested states from <see cref="ScopeContext"/> like a callstack
/// </summary>
[LayoutRenderer("scopenested")]
public sealed class ScopeContextNestedStatesLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Gets or sets the number of top stack frames to be rendered.
/// </summary>
/// <docgen category='Layout Options' order='100' />
public int TopFrames { get; set; } = -1;
/// <summary>
/// Gets or sets the number of bottom stack frames to be rendered.
/// </summary>
/// <docgen category='Layout Options' order='100' />
public int BottomFrames { get; set; } = -1;
/// <summary>
/// Gets or sets the separator to be used for concatenating nested logical context output.
/// </summary>
/// <docgen category='Layout Options' order='100' />
public string Separator { get => _separator?.OriginalText; set => _separator = new SimpleLayout(value ?? string.Empty); }
private SimpleLayout _separator = new SimpleLayout(" ");
/// <summary>
/// Gets or sets how to format each nested state. Ex. like JSON = @
/// </summary>
/// <docgen category='Layout Options' order='50' />
public string Format { get; set; }
/// <summary>
/// Gets or sets the culture used for rendering.
/// </summary>
/// <docgen category='Layout Options' order='100' />
public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture;
/// <inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (TopFrames == 1)
{
// Allows fast rendering of topframes=1
var topFrame = ScopeContext.PeekNestedState();
if (topFrame != null)
builder.AppendFormattedValue(topFrame, Format, GetFormatProvider(logEvent, Culture), ValueFormatter);
return;
}
var messages = ScopeContext.GetAllNestedStates();
if (messages.Length == 0)
return;
int startPos = 0;
int endPos = messages.Length;
if (TopFrames != -1)
{
endPos = Math.Min(TopFrames, messages.Length);
}
else if (BottomFrames != -1)
{
startPos = messages.Length - Math.Min(BottomFrames, messages.Length);
}
AppendNestedStates(builder, messages, startPos, endPos, logEvent);
}
private void AppendNestedStates(StringBuilder builder, object[] messages, int startPos, int endPos, LogEventInfo logEvent)
{
bool formatAsJson = MessageTemplates.ValueFormatter.FormatAsJson.Equals(Format, StringComparison.Ordinal);
var formatProvider = GetFormatProvider(logEvent, Culture);
string separator = null;
string itemSeparator = null;
if (formatAsJson)
{
separator = _separator?.Render(logEvent) ?? string.Empty;
builder.Append('[');
builder.Append(separator);
itemSeparator = "," + separator;
}
try
{
string currentSeparator = null;
for (int i = endPos - 1; i >= startPos; --i)
{
builder.Append(currentSeparator);
if (formatAsJson)
AppendJsonFormattedValue(messages[i], formatProvider, builder, separator, itemSeparator);
else if (messages[i] is IEnumerable<KeyValuePair<string, object>>)
builder.Append(Convert.ToString(messages[i])); // Special support for Microsoft Extension Logging ILogger.BeginScope
else
builder.AppendFormattedValue(messages[i], Format, formatProvider, ValueFormatter);
currentSeparator = itemSeparator ?? _separator?.Render(logEvent) ?? string.Empty;
}
}
finally
{
if (formatAsJson)
{
builder.Append(separator);
builder.Append(']');
}
}
}
private void AppendJsonFormattedValue(object nestedState, IFormatProvider formatProvider, StringBuilder builder, string separator, string itemSeparator)
{
if (nestedState is IEnumerable<KeyValuePair<string, object>> propertyList && HasUniqueCollectionKeys(propertyList))
{
// Special support for Microsoft Extension Logging ILogger.BeginScope where property-states are rendered as expando-objects
builder.Append('{');
builder.Append(separator);
string currentSeparator = string.Empty;
using (var scopeEnumerator = new ScopeContextPropertyEnumerator<object>(propertyList))
{
while (scopeEnumerator.MoveNext())
{
var property = scopeEnumerator.Current;
int orgLength = builder.Length;
if (!AppendJsonProperty(property.Key, property.Value, builder, currentSeparator))
{
builder.Length = orgLength;
continue;
}
currentSeparator = itemSeparator;
}
}
builder.Append(separator);
builder.Append('}');
}
else
{
builder.AppendFormattedValue(nestedState, Format, formatProvider, ValueFormatter);
}
}
bool AppendJsonProperty(string propertyName, object propertyValue, StringBuilder builder, string itemSeparator)
{
if (string.IsNullOrEmpty(propertyName))
return false;
builder.Append(itemSeparator);
if (!ValueFormatter.FormatValue(propertyName, null, MessageTemplates.CaptureType.Serialize, null, builder))
{
return false;
}
builder.Append(": ");
if (!ValueFormatter.FormatValue(propertyValue, null, MessageTemplates.CaptureType.Serialize, null, builder))
{
return false;
}
return true;
}
bool HasUniqueCollectionKeys(IEnumerable<KeyValuePair<string, object>> propertyList)
{
if (propertyList is IDictionary<string, object>)
{
return true;
}
#if !NET35
else if (propertyList is IReadOnlyDictionary<string, object>)
{
return true;
}
else if (propertyList is IReadOnlyCollection<KeyValuePair<string, object>> propertyCollection)
{
if (propertyCollection.Count <= 1)
return true;
else if (propertyCollection.Count > 10)
return false; // Too many combinations
}
#endif
return ScopeContextPropertyEnumerator<object>.HasUniqueCollectionKeys(propertyList, StringComparer.Ordinal);
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonEditor.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
// MenuItems and in-Editor scripts for PhotonNetwork.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ExitGames.Client.Photon;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
public class PunWizardText
{
public string WindowTitle = "PUN Wizard";
public string SetupWizardWarningTitle = "Warning";
public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking.";
public string MainMenuButton = "Main Menu";
public string SetupWizardTitle = "PUN Setup";
public string SetupWizardInfo = "Thanks for importing Photon Unity Networking.\nThis window should set you up.\n\n<b>-</b> To use an existing Photon Cloud App, enter your AppId.\n<b>-</b> To register an account or access an existing one, enter the account's mail address.\n<b>-</b> To use Photon OnPremise, skip this step.";
public string EmailOrAppIdLabel = "AppId or Email";
public string AlreadyRegisteredInfo = "The email is registered so we can't fetch your AppId (without password).\n\nPlease login online to get your AppId and paste it above.";
public string SkipRegistrationInfo = "Skipping? No problem:\nEdit your server settings in the PhotonServerSettings file.";
public string RegisteredNewAccountInfo = "We created a (free) account and fetched you an AppId.\nWelcome. Your PUN project is setup.";
public string AppliedToSettingsInfo = "Your AppId is now applied to this project.";
public string SetupCompleteInfo = "<b>Done!</b>\nAll connection settings can be edited in the <b>PhotonServerSettings</b> now.\nHave a look.";
public string CloseWindowButton = "Close";
public string SkipButton = "Skip";
public string SetupButton = "Setup Project";
public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile or use Unity 5.";
public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android.";
public string CancelButton = "Cancel";
public string PUNWizardLabel = "PUN Wizard";
public string SettingsButton = "Settings";
public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud.";
public string WarningPhotonDisconnect = "";
public string StartButton = "Start";
public string LocateSettingsButton = "Locate PhotonServerSettings";
public string SettingsHighlightLabel = "Highlights the used photon settings file in the project.";
public string DocumentationLabel = "Documentation";
public string OpenPDFText = "Reference PDF";
public string OpenPDFTooltip = "Opens the local documentation pdf.";
public string OpenDevNetText = "DevNet / Manual";
public string OpenDevNetTooltip = "Online documentation for Photon.";
public string OpenCloudDashboardText = "Cloud Dashboard Login";
public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics.";
public string OpenForumText = "Open Forum";
public string OpenForumTooltip = "Online support for Photon.";
public string OkButton = "Ok";
public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'.";
public string ComparisonPageButton = "Cloud versus OnPremise";
public string ConnectionTitle = "Connecting";
public string ConnectionInfo = "Connecting to the account service...";
public string ErrorTextTitle = "Error";
public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!";
public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings().";
public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs";
public string FullRPCListTitle = "Warning: RPC-list is full!";
public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings().";
public string SkipRPCListUpdateLabel = "Skip RPC-list update";
public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility";
public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients.";
public string RPCListCleared = "Clear RPC-list";
public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings().";
public string RpcFoundMessage = "Some code uses the obsolete RPC attribute. PUN now requires the PunRPC attribute to mark remote-callable methods.\nThe Editor can search and replace that code which will modify your source.";
public string RpcFoundDialogTitle = "RPC Attribute Outdated";
public string RpcReplaceButton = "Replace. I got a backup.";
public string RpcSkipReplace = "Not now.";
public string WizardMainWindowInfo = "This window should help you find important settings for PUN, as well as documentation.";
}
[InitializeOnLoad]
public class PhotonEditor : EditorWindow
{
protected static Type WindowType = typeof (PhotonEditor);
protected Vector2 scrollPos = Vector2.zero;
private readonly Vector2 preferredSize = new Vector2(350, 400);
private static Texture2D BackgroundImage;
public static PunWizardText CurrentLang = new PunWizardText();
protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun;
protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf";
protected static string UrlFreeLicense = "https://www.photonengine.com/dashboard/OnPremise";
protected static string UrlDevNet = "http://doc.photonengine.com/en/pun/current";
protected static string UrlForum = "http://forum.exitgames.com";
protected static string UrlCompare = "http://doc.photonengine.com/en/realtime/current/getting-started/onpremise-or-saas";
protected static string UrlHowToSetup = "http://doc.photonengine.com/en/onpremise/current/getting-started/photon-server-in-5min";
protected static string UrlAppIDExplained = "http://doc.photonengine.com/en/realtime/current/getting-started/obtain-your-app-id";
protected static string UrlAccountPage = "https://www.photonengine.com/Account/SignIn?email="; // opened in browser
protected static string UrlCloudDashboard = "https://www.photonengine.com/dashboard?email=";
private enum PhotonSetupStates
{
MainUi,
RegisterForPhotonCloud,
EmailAlreadyRegistered,
GoEditPhotonServerSettings
}
private bool isSetupWizard = false;
private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
private bool minimumInput = false;
private bool useMail = false;
private bool useAppId = false;
private bool useSkip = false;
private bool highlightedSettings = false;
private bool close = false;
private string mailOrAppId = string.Empty;
private static double lastWarning = 0;
private static bool postCompileActionsDone;
private static bool isPunPlus;
private static bool androidLibExists;
private static bool iphoneLibExists;
// setup once on load
static PhotonEditor()
{
EditorApplication.projectWindowChanged += EditorUpdate;
EditorApplication.hierarchyWindowChanged += EditorUpdate;
EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
EditorApplication.update += OnUpdate;
// detect optional packages
PhotonEditor.CheckPunPlus();
}
// setup per window
public PhotonEditor()
{
minSize = this.preferredSize;
}
[MenuItem("Window/Photon Unity Networking/PUN Wizard &p", false, 0)]
protected static void MenuItemOpenWizard()
{
PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor;
win.photonSetupState = PhotonSetupStates.MainUi;
win.isSetupWizard = false;
}
[MenuItem("Window/Photon Unity Networking/Highlight Server Settings %#&p", false, 1)]
protected static void MenuItemHighlightSettings()
{
HighlightSettings();
}
/// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary>
protected static void ShowRegistrationWizard()
{
PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor;
win.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
win.isSetupWizard = true;
}
// called 100 times / sec
private static void OnUpdate()
{
// after a compile, check RPCs to create a cache-list
if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonNetwork.PhotonServerSettings != null)
{
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 || UNITY_5_3_AND_NEWER
if (EditorApplication.isUpdating)
{
return;
}
#endif
PhotonEditor.UpdateRpcList();
postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything)
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 || UNITY_5_3_AND_NEWER
PhotonEditor.ImportWin8Support();
#endif
}
}
// called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues)
private static void EditorUpdate()
{
if (PhotonNetwork.PhotonServerSettings == null)
{
PhotonNetwork.CreateSettings();
}
if (PhotonNetwork.PhotonServerSettings == null)
{
return;
}
// serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set
if (!PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard && PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet)
{
ShowRegistrationWizard();
PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard = true;
PhotonEditor.SaveSettings();
}
// Workaround for TCP crash. Plus this surpresses any other recompile errors.
if (EditorApplication.isCompiling)
{
if (PhotonNetwork.connected)
{
if (lastWarning > EditorApplication.timeSinceStartup - 3)
{
// Prevent error spam
Debug.LogWarning(CurrentLang.WarningPhotonDisconnect);
lastWarning = EditorApplication.timeSinceStartup;
}
PhotonNetwork.Disconnect();
}
}
}
// called in editor on change of play-mode (used to show a message popup that connection settings are incomplete)
private static void PlaymodeStateChanged()
{
if (EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet)
{
EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton);
}
}
#region GUI and Wizard
// Window Update() callback. On-demand, when Window is open
protected void Update()
{
if (this.close)
{
Close();
}
}
protected virtual void OnGUI()
{
if (BackgroundImage == null)
{
BackgroundImage = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/background.jpg", typeof(Texture2D)) as Texture2D;
}
PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed.
GUI.SetNextControlName("");
this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
if (this.photonSetupState == PhotonSetupStates.MainUi)
{
UiMainWizard();
}
else
{
UiSetupApp();
}
GUILayout.EndScrollView();
if (oldGuiState != this.photonSetupState)
{
GUI.FocusControl("");
}
}
protected virtual void UiSetupApp()
{
GUI.skin.label.wordWrap = true;
if (!this.isSetupWizard)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false)))
{
this.photonSetupState = PhotonSetupStates.MainUi;
}
GUILayout.EndHorizontal();
}
// setup header
UiTitleBox(CurrentLang.SetupWizardTitle, BackgroundImage);
// setup info text
GUI.skin.label.richText = true;
GUILayout.Label(CurrentLang.SetupWizardInfo);
// input of appid or mail
EditorGUILayout.Separator();
GUILayout.Label(CurrentLang.EmailOrAppIdLabel);
this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId).Trim(); // note: we trim all input
if (this.mailOrAppId.Contains("@"))
{
// this should be a mail address
this.minimumInput = (this.mailOrAppId.Length >= 5 && this.mailOrAppId.Contains("."));
this.useMail = this.minimumInput;
this.useAppId = false;
}
else
{
// this should be an appId
this.minimumInput = ServerSettings.IsAppId(this.mailOrAppId);
this.useMail = false;
this.useAppId = this.minimumInput;
}
// button to skip setup
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100)))
{
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
this.useSkip = true;
this.useMail = false;
this.useAppId = false;
}
// SETUP button
EditorGUI.BeginDisabledGroup(!this.minimumInput);
if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100)))
{
this.useSkip = false;
GUIUtility.keyboardControl = 0;
if (this.useMail)
{
RegisterWithEmail(this.mailOrAppId); // sets state
}
if (this.useAppId)
{
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN");
PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId);
PhotonEditor.SaveSettings();
}
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
// existing account needs to fetch AppId online
if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered)
{
// button to open dashboard and get the AppId
GUILayout.Space(15);
GUILayout.Label(CurrentLang.AlreadyRegisteredInfo);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205)))
{
Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
this.mailOrAppId = "";
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings)
{
if (!this.highlightedSettings)
{
this.highlightedSettings = true;
HighlightSettings();
}
GUILayout.Space(15);
if (this.useSkip)
{
GUILayout.Label(CurrentLang.SkipRegistrationInfo);
}
else if (this.useMail)
{
GUILayout.Label(CurrentLang.RegisteredNewAccountInfo);
}
else if (this.useAppId)
{
GUILayout.Label(CurrentLang.AppliedToSettingsInfo);
}
// setup-complete info
GUILayout.Space(15);
GUILayout.Label(CurrentLang.SetupCompleteInfo);
// close window (done)
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205)))
{
this.close = true;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUI.skin.label.richText = false;
}
private void UiTitleBox(string title, Texture2D bgIcon)
{
GUIStyle bgStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
bgStyle.normal.background = bgIcon;
bgStyle.fontSize = 22;
bgStyle.fontStyle = FontStyle.Bold;
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
Rect scale = GUILayoutUtility.GetLastRect();
scale.height = 30;
GUI.Label(scale, title, bgStyle);
GUILayout.Space(scale.height+5);
}
protected virtual void UiMainWizard()
{
GUILayout.Space(15);
// title
UiTitleBox(CurrentLang.PUNWizardLabel, BackgroundImage);
// wizard info text
GUILayout.Label(CurrentLang.WizardMainWindowInfo);
GUILayout.Space(15);
// pun+ info
if (isPunPlus)
{
GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel);
GUILayout.Space(15);
}
#if !(UNITY_5_0 || UNITY_5 || UNITY_5_3_AND_NEWER)
else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone))
{
GUILayout.Label(CurrentLang.MobileExportNoteLabel);
GUILayout.Space(15);
}
#endif
// settings button
GUILayout.BeginHorizontal();
GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100));
GUILayout.BeginVertical();
if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel)))
{
HighlightSettings();
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip)))
{
Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
}
if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel)))
{
this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.Space(15);
EditorGUILayout.Separator();
// documentation
GUILayout.BeginHorizontal();
GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100));
GUILayout.BeginVertical();
if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip)))
{
EditorUtility.OpenWithDefaultApp(DocumentationLocation);
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip)))
{
Application.OpenURL(UrlDevNet);
}
GUI.skin.label.wordWrap = true;
GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel);
if (GUILayout.Button(CurrentLang.ComparisonPageButton))
{
Application.OpenURL(UrlCompare);
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip)))
{
Application.OpenURL(UrlForum);
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
#endregion
protected virtual void RegisterWithEmail(string email)
{
EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f);
string accountServiceType = string.Empty;
if (PhotonEditorUtils.HasVoice)
{
accountServiceType = "voice";
}
AccountService client = new AccountService();
client.RegisterByEmail(email, RegisterOrigin, accountServiceType); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client
EditorUtility.ClearProgressBar();
if (client.ReturnCode == 0)
{
this.mailOrAppId = client.AppId;
PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId, 0);
if (PhotonEditorUtils.HasVoice)
{
PhotonNetwork.PhotonServerSettings.VoiceAppID = client.AppId2;
}
PhotonEditor.SaveSettings();
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
}
else
{
PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.PhotonCloud;
PhotonEditor.SaveSettings();
Debug.LogWarning(client.Message + " ReturnCode: " + client.ReturnCode);
if (client.Message.Contains("registered"))
{
this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered;
}
else
{
EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton);
this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
}
}
}
protected internal static bool CheckPunPlus()
{
androidLibExists = File.Exists("Assets/Plugins/Android/armeabi-v7a/libPhotonSocketPlugin.so") &&
File.Exists("Assets/Plugins/Android/x86/libPhotonSocketPlugin.so");
iphoneLibExists = File.Exists("Assets/Plugins/IOS/libPhotonSocketPlugin.a");
isPunPlus = androidLibExists || iphoneLibExists;
return isPunPlus;
}
private static void ImportWin8Support()
{
if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode)
{
return; // don't import while compiling
}
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 || UNITY_5_3_AND_NEWER
const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage";
bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll");
if (!win8LibsExist && File.Exists(win8Package))
{
AssetDatabase.ImportPackage(win8Package, false);
}
#endif
}
// Pings PhotonServerSettings and makes it selected (show in Inspector)
private static void HighlightSettings()
{
Selection.objects = new UnityEngine.Object[] { PhotonNetwork.PhotonServerSettings };
EditorGUIUtility.PingObject(PhotonNetwork.PhotonServerSettings);
}
// Marks settings object as dirty, so it gets saved.
// unity 5.3 changes the usecase for SetDirty(). but here we don't modify a scene object! so it's ok to use
private static void SaveSettings()
{
EditorUtility.SetDirty(PhotonNetwork.PhotonServerSettings);
}
#region RPC List Handling
public static void UpdateRpcList()
{
List<string> additionalRpcs = new List<string>();
HashSet<string> currentRpcs = new HashSet<string>();
var types = GetAllSubTypesInScripts(typeof(MonoBehaviour));
int countOldRpcs = 0;
foreach (var mono in types)
{
MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MethodInfo method in methods)
{
bool isOldRpc = false;
#pragma warning disable 618
// we let the Editor check for outdated RPC attributes in code. that should not cause a compile warning
if (method.IsDefined(typeof (RPC), false))
{
countOldRpcs++;
isOldRpc = true;
}
#pragma warning restore 618
if (isOldRpc || method.IsDefined(typeof(PunRPC), false))
{
currentRpcs.Add(method.Name);
if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name))
{
additionalRpcs.Add(method.Name);
}
}
}
}
if (additionalRpcs.Count > 0)
{
// LIMITS RPC COUNT
if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue)
{
if (currentRpcs.Count <= byte.MaxValue)
{
bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton);
if (clearList)
{
PhotonNetwork.PhotonServerSettings.RpcList.Clear();
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs);
}
else
{
return;
}
}
else
{
EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel);
return;
}
}
additionalRpcs.Sort();
Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list");
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs);
PhotonEditor.SaveSettings();
}
if (countOldRpcs > 0)
{
bool convertRPCs = EditorUtility.DisplayDialog(CurrentLang.RpcFoundDialogTitle, CurrentLang.RpcFoundMessage, CurrentLang.RpcReplaceButton, CurrentLang.RpcSkipReplace);
if (convertRPCs)
{
PhotonConverter.ConvertRpcAttribute("");
}
}
}
public static void ClearRpcList()
{
bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton);
if (clearList)
{
PhotonNetwork.PhotonServerSettings.RpcList.Clear();
Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning);
}
}
public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass)
{
var result = new System.Collections.Generic.List<System.Type>();
System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var A in AS)
{
// this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project
if (!A.FullName.StartsWith("Assembly-"))
{
// Debug.Log("Skipping Assembly: " + A);
continue;
}
//Debug.Log("Assembly: " + A.FullName);
System.Type[] types = A.GetTypes();
foreach (var T in types)
{
if (T.IsSubclassOf(aBaseClass))
{
result.Add(T);
}
}
}
return result.ToArray();
}
#endregion
}
| |
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.model.Model.Validators;
using DevExpress.Web.Mvc;
using EIDSS;
using eidss.avr.mweb.Utils;
using eidss.avr.mweb.Utils.Localization;
using eidss.model.Core;
using eidss.model.Resources;
using MvcContrib;
using MvcContrib.UI.InputBuilder;
using eidss.web.common.Utils;
namespace eidss.avr.mweb
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
//routes.IgnoreRoute("Content/Images/{*pathInfo}");
routes.MapRoute(
"Start",
"",
new {controller = "Account", action = "Login"}
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Login",
"Account/Login",
new {controller = "Account", action = "Login"}
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Report",
"Account/Layout",
new { controller = "Account", action = "Layout" }
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Error",
"Error/HttpError",
new { controller = "Error", action = "HttpError" }
);
routes.MapRoute(
"Errors",
"Error/{page}",
new { controller = "Error", action = "Http404" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller = "Account", action = "Login", id = UrlParameter.Optional} // Parameter defaults
);
AreaRegistration.RegisterAllAreas();
foreach (Route r in routes)
{
if (r.RouteHandler is SingleCultureMvcRouteHandler || r.RouteHandler is StopRoutingHandler)
{
continue;
}
r.RouteHandler = new MultiCultureMvcRouteHandler();
r.Url = "{culture}/" + r.Url;
//Adding default culture
if (r.Defaults == null)
{
r.Defaults = new RouteValueDictionary();
}
//Adding constraint for culture param
if (r.Constraints == null)
{
r.Constraints = new RouteValueDictionary();
}
if (!r.Constraints.Contains(typeof (CultureConstraint)))
{
r.Constraints.Add("culture", new CultureConstraint(Cultures.Available));
}
}
}
protected void Application_Start()
{
var connectionCredentials = new ConnectionCredentials();
DbManagerFactory.SetSqlFactory(connectionCredentials.ConnectionString);
EidssUserContext.Init();
CustomCultureHelper.CurrentCountry = EidssSiteContext.Instance.CountryID;
EIDSS_LookupCacheHelper.Init();
LookupCacheListener.Cleanup();
LookupCacheListener.Listen();
ClassLoader.Init("eidss_db.dll", bv.common.Core.Utils.GetDesktopExecutingPath());
//AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
InputBuilder.BootStrap();
BaseFieldValidator.FieldCaptions = EidssFields.Instance;
ModelBinders.Binders.DefaultBinder = new DevExpressEditorsBinder();
SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
XtraWebLocalizer.Activate();
}
protected void Application_End()
{
LookupCacheListener.Stop();
}
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Application[HttpContext.Current.Request.UserHostAddress] = ex;
LogError(ex);
HttpContext.Current.ClearError();
ProcessError(ex);
}
private void ProcessError(Exception ex)
{
var error = ex as HttpException;
int statusCode = error == null ? 500 : error.GetHttpCode();
string culture = Cultures.GetCulture(ModelUserContext.CurrentLanguage);
switch (statusCode)
{
case 404:
Response.Redirect("~/" + culture + "/Error/Http404");
break;
default:
Response.Redirect("~/" + culture + "/Error/HttpError");
break;
}
}
private void LogError(Exception ex)
{
string path = Config.GetSetting("ErrorLogPath");
if (!String.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch
{
return;
}
}
string filename = String.Format("ErrorLog{0}{1}{2}.txt", DateTime.Today.Month, DateTime.Today.Day, DateTime.Today.Year);
try
{
using (StreamWriter stream = File.AppendText(Path.Combine(path, filename)))
{
//var connectionCredentials = new ConnectionCredentials();
//stream.WriteLine("ConnectionString: " + connectionCredentials.ConnectionString);
stream.Write("{0} {1}\r\n {2}\r\n", DateTime.Now.ToString("MM/dd/yyyy hh:mm"), ex.Message, ex.StackTrace);
stream.WriteLine("--------------------------------------------------\r\n");
stream.Flush();
}
}
catch
{
// todo: process error
}
}
}
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
DevExpressHelper.Theme = GeneralSettings.Theme;
}
#region session handlers
protected void Session_Start()
{
var ms = new ModelStorage(Session.SessionID);
Session["ModelStorage"] = ms;
}
protected void Session_End()
{
var ms = Session["ModelStorage"] as ModelStorage;
if (ms != null)
{
Session.Remove("ModelStorage");
ms.Dispose();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using AutoMapper;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the ContentType Service, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public class ContentTypeService : ContentTypeServiceBase, IContentTypeService
{
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public ContentTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IContentService contentService, IMediaService mediaService)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
if (contentService == null) throw new ArgumentNullException("contentService");
if (mediaService == null) throw new ArgumentNullException("mediaService");
_contentService = contentService;
_mediaService = mediaService;
}
#region Containers
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingContentTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedContentTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.MediaTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingMediaTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedMediaTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingContentTypeContainer, SavedContentTypeContainer,
container, Constants.ObjectTypes.DocumentTypeContainerGuid, "document type", userId);
}
public Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingMediaTypeContainer, SavedMediaTypeContainer,
container, Constants.ObjectTypes.MediaTypeContainerGuid, "media type", userId);
}
private Attempt<OperationStatus> SaveContainer(
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savingEvent,
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savedEvent,
EntityContainer container,
Guid containerObjectType,
string objectTypeName, int userId)
{
var evtMsgs = EventMessagesFactory.Get();
if (container.ContainedObjectType != containerObjectType)
{
var ex = new InvalidOperationException("Not a " + objectTypeName + " container.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (container.HasIdentity && container.IsPropertyDirty("ParentId"))
{
var ex = new InvalidOperationException("Cannot save a container with a modified parent, move the container instead.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (savingEvent.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return OperationStatus.Cancelled(evtMsgs);
}
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
repo.AddOrUpdate(container);
uow.Commit();
}
savedEvent.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return OperationStatus.Success(evtMsgs);
}
public EntityContainer GetContentTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeContainerGuid);
}
public EntityContainer GetMediaTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeContainerGuid);
}
private EntityContainer GetContainer(int containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType)
{
var ancestorIds = mediaType.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != mediaType.Id)
.ToArray();
return GetMediaTypeContainers(ancestorIds);
}
public EntityContainer GetContentTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeContainerGuid);
}
public IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType)
{
var ancestorIds = contentType.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != contentType.Id)
.ToArray();
return GetContentTypeContainers(ancestorIds);
}
public EntityContainer GetMediaTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeContainerGuid);
}
private EntityContainer GetContainer(Guid containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingContentTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedContentTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
public Attempt<OperationStatus> DeleteMediaTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingMediaTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedMediaTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
#endregion
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllPropertyTypeAliases();
}
}
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
public IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllContentTypeAliases(objectTypes);
}
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, int parentId = -1)
{
IContentType parent = null;
if (parentId > 0)
{
parent = GetContentType(parentId);
if (parent == null)
{
throw new InvalidOperationException("Could not find content type with id " + parentId);
}
}
return Copy(original, alias, name, parent);
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to, default is null (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, IContentType parent)
{
Mandate.ParameterNotNull(original, "original");
Mandate.ParameterNotNullOrEmpty(alias, "alias");
if (parent != null)
{
Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity"));
}
var clone = original.DeepCloneWithResetIdentities(alias);
clone.Name = name;
var compositionAliases = clone.CompositionAliases().Except(new[] { alias }).ToList();
//remove all composition that is not it's current alias
foreach (var a in compositionAliases)
{
clone.RemoveContentType(a);
}
//if a parent is specified set it's composition and parent
if (parent != null)
{
//add a new parent composition
clone.AddContentType(parent);
clone.ParentId = parent.Id;
}
else
{
//set to root
clone.ParentId = -1;
}
Save(clone);
return clone;
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return Enumerable.Empty<IContentType>();
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return false;
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
/// </summary>
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
}
public int CountContentTypes()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IContentType>.Builder);
}
}
public int CountMediaTypes()
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IMediaType>.Builder);
}
}
/// <summary>
/// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned
/// </summary>
/// <param name="compo"></param>
/// <returns></returns>
public Attempt<string[]> ValidateComposition(IContentTypeComposition compo)
{
using (new WriteLock(Locker))
{
try
{
ValidateLocked(compo);
return Attempt<string[]>.Succeed();
}
catch (InvalidCompositionException ex)
{
return Attempt.Fail(ex.PropertyTypeAliases, ex);
}
}
}
protected void ValidateLocked(IContentTypeComposition compositionContentType)
{
// performs business-level validation of the composition
// should ensure that it is absolutely safe to save the composition
// eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
// but that cannot be used (conflict with descendants)
var contentType = compositionContentType as IContentType;
var mediaType = compositionContentType as IMediaType;
var memberType = compositionContentType as IMemberType; // should NOT do it here but... v8!
IContentTypeComposition[] allContentTypes;
if (contentType != null)
allContentTypes = GetAllContentTypes().Cast<IContentTypeComposition>().ToArray();
else if (mediaType != null)
allContentTypes = GetAllMediaTypes().Cast<IContentTypeComposition>().ToArray();
else if (memberType != null)
return; // no compositions on members, always validate
else
throw new Exception("Composition is neither IContentType nor IMediaType nor IMemberType?");
var compositionAliases = compositionContentType.CompositionAliases();
var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
var indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
var comparer = new DelegateEqualityComparer<IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
var dependencies = new HashSet<IContentTypeComposition>(compositions, comparer);
var stack = new Stack<IContentTypeComposition>();
indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
while (stack.Count > 0)
{
var indirectReference = stack.Pop();
dependencies.Add(indirectReference);
//Get all compositions for the current indirect reference
var directReferences = indirectReference.ContentTypeComposition;
foreach (var directReference in directReferences)
{
if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue;
dependencies.Add(directReference);
//A direct reference has compositions of its own - these also need to be taken into account
var directReferenceGraph = directReference.CompositionAliases();
allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
}
//Recursive lookup of indirect references
allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
}
foreach (var dependency in dependencies)
{
if (dependency.Id == compositionContentType.Id) continue;
var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
if (contentTypeDependency == null) continue;
var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
if (intersect.Length == 0) continue;
throw new InvalidCompositionException(compositionContentType.Alias, intersect.ToArray());
}
}
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IContentType contentType, int userId = 0)
{
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
ValidateLocked(contentType); // throws if invalid
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType);
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(contentType, false), this);
Audit(AuditType.Save, string.Format("Save ContentType performed by user"), userId, contentType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var contentType in asArray)
{
ValidateLocked(contentType); // throws if invalid
}
foreach (var contentType in asArray)
{
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save ContentTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
//TODO: This needs to change, if we are deleting a content type, we should just delete the data,
// this method will recursively go lookup every content item, check if any of it's descendants are
// of a different type, move them to the recycle bin, then permanently delete the content items.
// The main problem with this is that for every content item being deleted, events are raised...
// which we need for many things like keeping caches in sync, but we can surely do this MUCH better.
var deletedContentTypes = new List<IContentType>() {contentType};
deletedContentTypes.AddRange(contentType.Descendants().OfType<IContentType>());
foreach (var deletedContentType in deletedContentTypes)
{
_contentService.DeleteContentOfType(deletedContentType.Id);
}
repository.Delete(contentType);
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects.
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>
/// Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/>
/// </remarks>
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
var deletedContentTypes = new List<IContentType>();
deletedContentTypes.AddRange(asArray);
foreach (var contentType in asArray)
{
deletedContentTypes.AddRange(contentType.Descendants().OfType<IContentType>());
}
foreach (var deletedContentType in deletedContentTypes)
{
_contentService.DeleteContentOfType(deletedContentType.Id);
}
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return Enumerable.Empty<IMediaType>();
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return false;
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
public Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
if (MovingMediaType.IsRaisedEventCancelled(
new MoveEventArgs<IMediaType>(evtMsgs, new MoveEventInfo<IMediaType>(toMove, toMove.Path, containerId)),
this))
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(
MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var moveInfo = new List<MoveEventInfo<IMediaType>>();
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
try
{
EntityContainer container = null;
if (containerId > 0)
{
container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
moveInfo.AddRange(repository.Move(toMove, container));
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
}
MovedMediaType.RaiseEvent(new MoveEventArgs<IMediaType>(false, evtMsgs, moveInfo.ToArray()), this);
return Attempt.Succeed(
new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<MoveOperationStatusType>> MoveContentType(IContentType toMove, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
if (MovingContentType.IsRaisedEventCancelled(
new MoveEventArgs<IContentType>(evtMsgs, new MoveEventInfo<IContentType>(toMove, toMove.Path, containerId)),
this))
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(
MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var moveInfo = new List<MoveEventInfo<IContentType>>();
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
try
{
EntityContainer container = null;
if (containerId > 0)
{
container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
moveInfo.AddRange(repository.Move(toMove, container));
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
}
MovedContentType.RaiseEvent(new MoveEventArgs<IContentType>(false, evtMsgs, moveInfo.ToArray()), this);
return Attempt.Succeed(
new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<IMediaType, MoveOperationStatusType>> CopyMediaType(IMediaType toCopy, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
IMediaType copy;
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
try
{
if (containerId > 0)
{
var container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
var alias = repository.GetUniqueAlias(toCopy.Alias);
copy = toCopy.DeepCloneWithResetIdentities(alias);
copy.Name = copy.Name + " (copy)"; // might not be unique
// if it has a parent, and the parent is a content type, unplug composition
// all other compositions remain in place in the copied content type
if (copy.ParentId > 0)
{
var parent = repository.Get(copy.ParentId);
if (parent != null)
copy.RemoveContentType(parent.Alias);
}
copy.ParentId = containerId;
repository.AddOrUpdate(copy);
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(new OperationStatus<IMediaType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
}
return Attempt.Succeed(new OperationStatus<IMediaType, MoveOperationStatusType>(copy, MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<IContentType, MoveOperationStatusType>> CopyContentType(IContentType toCopy, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
IContentType copy;
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
try
{
if (containerId > 0)
{
var container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
var alias = repository.GetUniqueAlias(toCopy.Alias);
copy = toCopy.DeepCloneWithResetIdentities(alias);
copy.Name = copy.Name + " (copy)"; // might not be unique
// if it has a parent, and the parent is a content type, unplug composition
// all other compositions remain in place in the copied content type
if (copy.ParentId > 0)
{
var parent = repository.Get(copy.ParentId);
if (parent != null)
copy.RemoveContentType(parent.Alias);
}
copy.ParentId = containerId;
repository.AddOrUpdate(copy);
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(new OperationStatus<IContentType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
}
return Attempt.Succeed(new OperationStatus<IContentType, MoveOperationStatusType>(copy, MoveOperationStatusType.Success, evtMsgs));
}
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user saving the MediaType</param>
public void Save(IMediaType mediaType, int userId = 0)
{
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
ValidateLocked(mediaType); // throws if invalid
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
uow.Commit();
}
UpdateContentXmlStructure(mediaType);
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(mediaType, false), this);
Audit(AuditType.Save, string.Format("Save MediaType performed by user"), userId, mediaType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user savging the MediaTypes</param>
public void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var mediaType in asArray)
{
ValidateLocked(mediaType); // throws if invalid
}
foreach (var mediaType in asArray)
{
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save MediaTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <param name="userId">Optional Id of the user deleting the MediaType</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IMediaType mediaType, int userId = 0)
{
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
_mediaService.DeleteMediaOfType(mediaType.Id, userId);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
var deletedMediaTypes = new List<IMediaType>() {mediaType};
deletedMediaTypes.AddRange(mediaType.Descendants().OfType<IMediaType>());
repository.Delete(mediaType);
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaType performed by user"), userId, mediaType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <param name="userId"></param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var mediaType in asArray)
{
_mediaService.DeleteMediaOfType(mediaType.Id);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
var deletedMediaTypes = new List<IMediaType>();
deletedMediaTypes.AddRange(asArray);
foreach (var mediaType in asArray)
{
deletedMediaTypes.AddRange(mediaType.Descendants().OfType<IMediaType>());
repository.Delete(mediaType);
}
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetDtd()
{
var dtd = new StringBuilder();
dtd.AppendLine("<!DOCTYPE root [ ");
dtd.AppendLine(GetContentTypesDtd());
dtd.AppendLine("]>");
return dtd.ToString();
}
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetContentTypesDtd()
{
var dtd = new StringBuilder();
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
dtd.AppendLine("<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>");
}
else
{
try
{
var strictSchemaBuilder = new StringBuilder();
var contentTypes = GetAllContentTypes();
foreach (ContentType contentType in contentTypes)
{
string safeAlias = contentType.Alias.ToUmbracoAlias();
if (safeAlias != null)
{
strictSchemaBuilder.AppendLine(String.Format("<!ELEMENT {0} ANY>", safeAlias));
strictSchemaBuilder.AppendLine(String.Format("<!ATTLIST {0} id ID #REQUIRED>", safeAlias));
}
}
// Only commit the strong schema to the container if we didn't generate an error building it
dtd.Append(strictSchemaBuilder);
}
catch (Exception exception)
{
LogHelper.Error<ContentTypeService>("Error while trying to build DTD for Xml schema; is Umbraco installed correctly and the connection string configured?", exception);
}
}
return dtd.ToString();
}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = UowProvider.GetUnitOfWork();
using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#region Event Handlers
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavingContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavedContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletingContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletedContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavingMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavedMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletingMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletedMediaTypeContainer;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletingContentType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletedContentType;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletingMediaType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletedMediaType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavingContentType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavedContentType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavingMediaType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavedMediaType;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IMediaType>> MovingMediaType;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IMediaType>> MovedMediaType;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IContentType>> MovingContentType;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IContentType>> MovedContentType;
#endregion
}
}
| |
//#define DEBUG_RENDERING_FEEDBACK
//-----------------------------------------------------------------------
// <copyright file="StrokeNode.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Media;
using System.Windows.Input;
using System.Diagnostics;
namespace MS.Internal.Ink
{
#region StrokeNode
/// <summary>
/// StrokeNode represents a single segment on a stroke spine.
/// It's used in enumerating through basic geometries making a stroke contour.
/// </summary>
internal struct StrokeNode
{
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="operations">StrokeNodeOperations object created for particular rendering</param>
/// <param name="index">Index of the node on the stroke spine</param>
/// <param name="nodeData">StrokeNodeData for this node</param>
/// <param name="lastNodeData">StrokeNodeData for the precedeng node</param>
/// <param name="isLastNode">Whether the current node is the last node</param>
internal StrokeNode(
StrokeNodeOperations operations,
int index,
StrokeNodeData nodeData,
StrokeNodeData lastNodeData,
bool isLastNode)
{
System.Diagnostics.Debug.Assert(operations != null);
System.Diagnostics.Debug.Assert((nodeData.IsEmpty == false) && (index >= 0));
_operations = operations;
_index = index;
_thisNode = nodeData;
_lastNode = lastNodeData;
_isQuadCached = lastNodeData.IsEmpty;
_connectingQuad = Quad.Empty;
_isLastNode = isLastNode;
}
#endregion
#region Public API
/// <summary>
/// Position of the node on the stroke spine.
/// </summary>
/// <value></value>
internal Point Position { get { return _thisNode.Position; } }
/// <summary>
/// Position of the previous StrokeNode
/// </summary>
/// <value></value>
internal Point PreviousPosition { get { return _lastNode.Position; } }
/// <summary>
/// PressureFactor of the node on the stroke spine.
/// </summary>
/// <value></value>
internal float PressureFactor { get { return _thisNode.PressureFactor; } }
/// <summary>
/// PressureFactor of the previous StrokeNode
/// </summary>
/// <value></value>
internal float PreviousPressureFactor { get { return _lastNode.PressureFactor; } }
/// <summary>
/// Tells whether the node shape (the stylus shape used in the rendering)
/// is elliptical or polygonal. If the shape is an ellipse, GetContourPoints
/// returns the control points for the quadratic Bezier that defines the ellipse.
/// </summary>
/// <value>true if the shape is ellipse, false otherwise</value>
internal bool IsEllipse { get { return IsValid && _operations.IsNodeShapeEllipse; } }
/// <summary>
/// Returns true if this is the last node in the enumerator
/// </summary>
internal bool IsLastNode { get { return _isLastNode; } }
/// <summary>
/// Returns the bounds of the node shape w/o connecting quadrangle
/// </summary>
/// <returns></returns>
internal Rect GetBounds()
{
return IsValid ? _operations.GetNodeBounds(_thisNode) : Rect.Empty;
}
/// <summary>
/// Returns the bounds of the node shape and connecting quadrangle
/// </summary>
/// <returns></returns>
internal Rect GetBoundsConnected()
{
return IsValid ? Rect.Union(_operations.GetNodeBounds(_thisNode), ConnectingQuad.Bounds) : Rect.Empty;
}
/// <summary>
/// Returns the points that make up the stroke node shape (minus the connecting quad)
/// </summary>
internal void GetContourPoints(List<Point> pointBuffer)
{
if (IsValid)
{
_operations.GetNodeContourPoints(_thisNode, pointBuffer);
}
}
/// <summary>
/// Returns the points that make up the stroke node shape (minus the connecting quad)
/// </summary>
internal void GetPreviousContourPoints(List<Point> pointBuffer)
{
if (IsValid)
{
_operations.GetNodeContourPoints(_lastNode, pointBuffer);
}
}
/// <summary>
/// Returns the connecting quad
/// </summary>
internal Quad GetConnectingQuad()
{
if (IsValid)
{
return ConnectingQuad;
}
return Quad.Empty;
}
///// <summary>
///// IsPointWithinRectOrEllipse
///// </summary>
//internal bool IsPointWithinRectOrEllipse(Point point, double xRadiusOrHalfWidth, double yRadiusOrHalfHeight, Point center, bool isEllipse)
//{
// if (isEllipse)
// {
// //determine what delta is required to move the rect to be
// //centered at 0,0
// double xDelta = center.X + xRadiusOrHalfWidth;
// double yDelta = center.Y + yRadiusOrHalfHeight;
// //offset the point by that delta
// point.X -= xDelta;
// point.Y -= yDelta;
// //formula for ellipse is x^2/a^2 + y^2/b^2 = 1
// double a = xRadiusOrHalfWidth;
// double b = yRadiusOrHalfHeight;
// double res = (((point.X * point.X) / (a * a)) +
// ((point.Y * point.Y) / (b * b)));
// if (res <= 1)
// {
// return true;
// }
// return false;
// }
// else
// {
// if (point.X >= (center.X - xRadiusOrHalfWidth) &&
// point.X <= (center.X + xRadiusOrHalfWidth) &&
// point.Y >= (center.Y - yRadiusOrHalfHeight) &&
// point.Y <= (center.Y + yRadiusOrHalfHeight))
// {
// return true;
// }
// return false;
// }
//}
/// <summary>
/// GetPointsAtStartOfSegment
/// </summary>
internal void GetPointsAtStartOfSegment(List<Point> abPoints,
List<Point> dcPoints
#if DEBUG_RENDERING_FEEDBACK
, DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
)
{
if (IsValid)
{
Quad quad = ConnectingQuad;
if (IsEllipse)
{
Rect startNodeBounds = _operations.GetNodeBounds(_lastNode);
//add instructions to arc from D to A
abPoints.Add(quad.D);
abPoints.Add(StrokeRenderer.ArcToMarker);
abPoints.Add(new Point(startNodeBounds.Width, startNodeBounds.Height));
abPoints.Add(quad.A);
//simply start at D
dcPoints.Add(quad.D);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _lastNode.Position, startNodeBounds.Width / 2, startNodeBounds.Height / 2);
debugDC.DrawEllipse(Brushes.Red, null, quad.A, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Blue, null, quad.D, feedbackSize, feedbackSize);
}
#endif
}
else
{
//we're interested in the A, D points as well as the
//nodecountour points between them
Rect endNodeRect = _operations.GetNodeBounds(_thisNode);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), _operations.GetNodeBounds(_lastNode));
}
#endif
Vector[] vertices = _operations.GetVertices();
double pressureFactor = _lastNode.PressureFactor;
int maxCount = vertices.Length * 2;
int i = 0;
bool dIsInEndNode = true;
for (; i < maxCount; i++)
{
//look for the d point first
Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
if (point == quad.D)
{
//ab always starts with the D position (only add if it's not in endNode's bounds)
if (!endNodeRect.Contains(quad.D))
{
dIsInEndNode = false;
abPoints.Add(quad.D);
dcPoints.Add(quad.D);
}
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Blue, null, quad.D, feedbackSize, feedbackSize);
}
#endif
break;
}
}
if (i == maxCount)
{
Debug.Assert(false, "StrokeNodeOperations.GetPointsAtStartOfSegment failed to find the D position");
//we didn't find the d point, return
return;
}
//now look for the A position
//advance i
i++;
for (int j = 0; i < maxCount && j < vertices.Length; i++, j++)
{
//look for the A point now
Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
//add everything in between to ab as long as it's not already in endNode's bounds
if (!endNodeRect.Contains(point))
{
abPoints.Add(point);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Wheat, null, point, feedbackSize, feedbackSize);
}
#endif
}
if (dIsInEndNode)
{
Debug.Assert(!endNodeRect.Contains(point));
//add the first point after d, clockwise
dIsInEndNode = false;
dcPoints.Add(point);
}
if (point == quad.A)
{
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Red, null, point, feedbackSize, feedbackSize);
}
#endif
break;
}
}
}
}
}
/// <summary>
/// GetPointsAtEndOfSegment
/// </summary>
internal void GetPointsAtEndOfSegment( List<Point> abPoints,
List<Point> dcPoints
#if DEBUG_RENDERING_FEEDBACK
, DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
)
{
if (IsValid)
{
Quad quad = ConnectingQuad;
if (IsEllipse)
{
Rect bounds = GetBounds();
//add instructions to arc from D to A
abPoints.Add(quad.B);
abPoints.Add(StrokeRenderer.ArcToMarker);
abPoints.Add(new Point(bounds.Width, bounds.Height));
abPoints.Add(quad.C);
//don't add to the dc points
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _thisNode.Position, bounds.Width / 2, bounds.Height / 2);
debugDC.DrawEllipse(Brushes.Green, null, quad.B, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Yellow, null, quad.C, feedbackSize, feedbackSize);
}
#endif
}
else
{
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), GetBounds());
}
#endif
//we're interested in the B, C points as well as the
//nodecountour points between them
double pressureFactor = _thisNode.PressureFactor;
Vector[] vertices = _operations.GetVertices();
int maxCount = vertices.Length * 2;
int i = 0;
for (; i < maxCount; i++)
{
//look for the d point first
Point point = _thisNode.Position + (vertices[i % vertices.Length] * pressureFactor);
if (point == quad.B)
{
abPoints.Add(quad.B);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, point, feedbackSize, feedbackSize);
}
#endif
break;
}
}
if (i == maxCount)
{
Debug.Assert(false, "StrokeNodeOperations.GetPointsAtEndOfSegment failed to find the B position");
//we didn't find the d point, return
return;
}
//now look for the C position
//advance i
i++;
for (int j = 0; i < maxCount && j < vertices.Length; i++, j++)
{
//look for the c point last
Point point = _thisNode.Position + (vertices[i % vertices.Length] * pressureFactor);
if (point == quad.C)
{
break;
}
//only add to ab if we didn't find C
abPoints.Add(point);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Wheat, null, quad.C, feedbackSize, feedbackSize);
}
#endif
}
//finally, add the D point
dcPoints.Add(quad.C);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Yellow, null, quad.C, feedbackSize, feedbackSize);
}
#endif
}
}
}
/// <summary>
/// GetPointsAtMiddleSegment
/// </summary>
internal void GetPointsAtMiddleSegment( StrokeNode previous,
double angleBetweenNodes,
List<Point> abPoints,
List<Point> dcPoints,
out bool missingIntersection
#if DEBUG_RENDERING_FEEDBACK
, DrawingContext debugDC, double feedbackSize, bool showFeedback
#endif
)
{
missingIntersection = false;
if (IsValid && previous.IsValid)
{
Quad quad1 = previous.ConnectingQuad;
if (!quad1.IsEmpty)
{
Quad quad2 = ConnectingQuad;
if (!quad2.IsEmpty)
{
if (IsEllipse)
{
Rect node1Bounds = _operations.GetNodeBounds(previous._lastNode);
Rect node2Bounds = _operations.GetNodeBounds(_lastNode);
Rect node3Bounds = _operations.GetNodeBounds(_thisNode);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(null, new Pen(Brushes.Pink, feedbackSize / 2), _lastNode.Position, node2Bounds.Width / 2, node2Bounds.Height / 2);
}
#endif
if (angleBetweenNodes == 0.0d || ((quad1.B == quad2.A) && (quad1.C == quad2.D)))
{
//quads connections are the same, just add them
abPoints.Add(quad1.B);
dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
}
#endif
}
else if (angleBetweenNodes > 0.0)
{
//the stroke angled towards the AB side
//this part is easy
if (quad1.B == quad2.A)
{
abPoints.Add(quad1.B);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
}
#endif
}
else
{
Point intersection = GetIntersection(quad1.A, quad1.B, quad2.A, quad2.B);
Rect union = Rect.Union(node1Bounds, node2Bounds);
union.Inflate(1.0, 1.0);
//make sure we're not off in space
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize * 1.5, feedbackSize * 1.5);
debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
}
#endif
if (union.Contains(intersection))
{
abPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize);
}
#endif
}
else
{
//if we missed the intersection we'll need to close the stroke segment
//this work is done in StrokeRenderer
missingIntersection = true;
return; //we're done.
}
}
if (quad1.C == quad2.D)
{
dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
}
#endif
}
else
{
//add instructions to arc from quad1.C to quad2.D in reverse order (since we walk this array backwards to render)
dcPoints.Add(quad1.C);
dcPoints.Add(new Point(node2Bounds.Width, node2Bounds.Height));
dcPoints.Add(StrokeRenderer.ArcToMarker);
dcPoints.Add(quad2.D);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
}
#endif
}
}
else
{
//the stroke angled towards the CD side
//this part is easy
if (quad1.C == quad2.D)
{
dcPoints.Add(quad1.C);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
}
#endif
}
else
{
Point intersection = GetIntersection(quad1.D, quad1.C, quad2.D, quad2.C);
Rect union = Rect.Union(node1Bounds, node2Bounds);
union.Inflate(1.0, 1.0);
//make sure we're not off in space
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize * 1.5, feedbackSize * 1.5);
debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
}
#endif
if (union.Contains(intersection))
{
dcPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize);
}
#endif
}
else
{
//if we missed the intersection we'll need to close the stroke segment
//this work is done in StrokeRenderer
missingIntersection = true;
return; //we're done.
}
}
if (quad1.B == quad2.A)
{
abPoints.Add(quad1.B);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
}
#endif
}
else
{
//we need to arc between quad1.B and quad2.A along node2
abPoints.Add(quad1.B);
abPoints.Add(StrokeRenderer.ArcToMarker);
abPoints.Add(new Point(node2Bounds.Width, node2Bounds.Height));
abPoints.Add(quad2.A);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
}
#endif
}
}
}
else
{
//rectangle
int indexA = -1;
int indexB = -1;
int indexC = -1;
int indexD = -1;
Vector[] vertices = _operations.GetVertices();
double pressureFactor = _lastNode.PressureFactor;
for (int i = 0; i < vertices.Length; i++)
{
Point point = _lastNode.Position + (vertices[i % vertices.Length] * pressureFactor);
if (point == quad2.A)
{
indexA = i;
}
if (point == quad1.B)
{
indexB = i;
}
if (point == quad1.C)
{
indexC = i;
}
if (point == quad2.D)
{
indexD = i;
}
}
if (indexA == -1 || indexB == -1 || indexC == -1 || indexD == -1)
{
Debug.Assert(false, "Couldn't find all 4 indexes in StrokeNodeOperations.GetPointsAtMiddleSegment");
return;
}
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawRectangle(null, new Pen(Brushes.Pink, feedbackSize / 2), _operations.GetNodeBounds(_lastNode));
debugDC.DrawEllipse(Brushes.Red, null, quad2.A, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Green, null, quad1.B, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Yellow, null, quad1.C, feedbackSize, feedbackSize);
debugDC.DrawEllipse(Brushes.Blue, null, quad2.D, feedbackSize, feedbackSize);
}
#endif
Rect node3Rect = _operations.GetNodeBounds(_thisNode);
//take care of a-b first
if (indexA == indexB)
{
//quad connection is the same, just add it
if (!node3Rect.Contains(quad1.B))
{
abPoints.Add(quad1.B);
}
}
else if ((indexA == 0 && indexB == 3) || ((indexA != 3 || indexB != 0) && (indexA > indexB)))
{
if (!node3Rect.Contains(quad1.B))
{
abPoints.Add(quad1.B);
}
if (!node3Rect.Contains(quad2.A))
{
abPoints.Add(quad2.A);
}
}
else
{
Point intersection = GetIntersection(quad1.A, quad1.B, quad2.A, quad2.B);
Rect node12 = Rect.Union(_operations.GetNodeBounds(previous._lastNode), _operations.GetNodeBounds(_lastNode));
node12.Inflate(1.0, 1.0);
//make sure we're not off in space
if (node12.Contains(intersection))
{
abPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize * 1.5);
}
#endif
}
else
{
//if we missed the intersection we'll need to close the stroke segment
//this work is done in StrokeRenderer.
missingIntersection = true;
return; //we're done.
}
}
// now take care of c-d.
if (indexC == indexD)
{
//quad connection is the same, just add it
if (!node3Rect.Contains(quad1.C))
{
dcPoints.Add(quad1.C);
}
}
else if ((indexC == 0 && indexD == 3) || ((indexC != 3 || indexD != 0) && (indexC > indexD)))
{
if (!node3Rect.Contains(quad1.C))
{
dcPoints.Add(quad1.C);
}
if (!node3Rect.Contains(quad2.D))
{
dcPoints.Add(quad2.D);
}
}
else
{
Point intersection = GetIntersection(quad1.D, quad1.C, quad2.D, quad2.C);
Rect node12 = Rect.Union(_operations.GetNodeBounds(previous._lastNode), _operations.GetNodeBounds(_lastNode));
node12.Inflate(1.0, 1.0);
//make sure we're not off in space
if (node12.Contains(intersection))
{
dcPoints.Add(intersection);
#if DEBUG_RENDERING_FEEDBACK
if (showFeedback)
{
debugDC.DrawEllipse(Brushes.Orange, null, intersection, feedbackSize, feedbackSize * 1.5);
}
#endif
}
else
{
//if we missed the intersection we'll need to close the stroke segment
//this work is done in StrokeRenderer.
missingIntersection = true;
return; //we're done.
}
}
}
}
}
}
}
/// <summary>
/// Returns the intersection between two lines. This code assumes there is an intersection
/// and should only be called if that assumption is valid
/// </summary>
/// <returns></returns>
internal static Point GetIntersection(Point line1Start, Point line1End, Point line2Start, Point line2End)
{
double a1 = line1End.Y - line1Start.Y;
double b1 = line1Start.X - line1End.X;
double c1 = (line1End.X * line1Start.Y) - (line1Start.X * line1End.Y);
double a2 = line2End.Y - line2Start.Y;
double b2 = line2Start.X - line2End.X;
double c2 = (line2End.X * line2Start.Y) - (line2Start.X * line2End.Y);
double d = (a1 * b2) - (a2 * b1);
if (d != 0.0)
{
double x = ((b1 * c2) - (b2 * c1)) / d;
double y = ((a2 * c1) - (a1 * c2)) / d;
//capture the min and max points
double line1XMin, line1XMax, line1YMin, line1YMax, line2XMin, line2XMax, line2YMin, line2YMax;
if (line1Start.X < line1End.X)
{
line1XMin = Math.Floor(line1Start.X);
line1XMax = Math.Ceiling(line1End.X);
}
else
{
line1XMin = Math.Floor(line1End.X);
line1XMax = Math.Ceiling(line1Start.X);
}
if (line2Start.X < line2End.X)
{
line2XMin = Math.Floor(line2Start.X);
line2XMax = Math.Ceiling(line2End.X);
}
else
{
line2XMin = Math.Floor(line2End.X);
line2XMax = Math.Ceiling(line2Start.X);
}
if (line1Start.Y < line1End.Y)
{
line1YMin = Math.Floor(line1Start.Y);
line1YMax = Math.Ceiling(line1End.Y);
}
else
{
line1YMin = Math.Floor(line1End.Y);
line1YMax = Math.Ceiling(line1Start.Y);
}
if (line2Start.Y < line2End.Y)
{
line2YMin = Math.Floor(line2Start.Y);
line2YMax = Math.Ceiling(line2End.Y);
}
else
{
line2YMin = Math.Floor(line2End.Y);
line2YMax = Math.Ceiling(line2Start.Y);
}
// now see if we have an intersection between the lines
// and not just the projection of the lines
if ((line1XMin <= x && x <= line1XMax) &&
(line1YMin <= y && y <= line1YMax) &&
(line2XMin <= x && x <= line2XMax) &&
(line2YMin <= y && y <= line2YMax))
{
return new Point(x, y);
}
}
if ((long)line1End.X == (long)line2Start.X &&
(long)line1End.Y == (long)line2Start.Y)
{
return new Point(line1End.X, line1End.Y);
}
return new Point(Double.NaN, Double.NaN);
}
/// <summary>
/// This method tells whether the contour of a given stroke node
/// intersects with the contour of this node. The contours of both nodes
/// include their connecting quadrangles.
/// </summary>
/// <param name="hitNode"></param>
/// <returns></returns>
internal bool HitTest(StrokeNode hitNode)
{
if (!IsValid || !hitNode.IsValid)
{
return false;
}
IEnumerable<ContourSegment> hittingContour = hitNode.GetContourSegments();
return _operations.HitTest(_lastNode, _thisNode, ConnectingQuad, hittingContour);
}
/// <summary>
/// Finds out if a given node intersects with this one,
/// and returns findices of the intersection.
/// </summary>
/// <param name="hitNode"></param>
/// <returns></returns>
internal StrokeFIndices CutTest(StrokeNode hitNode)
{
if ((IsValid == false) || (hitNode.IsValid == false))
{
return StrokeFIndices.Empty;
}
IEnumerable<ContourSegment> hittingContour = hitNode.GetContourSegments();
// If the node contours intersect, the result is a pair of findices
// this segment should be cut at to let the hitNode's contour through it.
StrokeFIndices cutAt = _operations.CutTest(_lastNode, _thisNode, ConnectingQuad, hittingContour);
return (_index == 0) ? cutAt : BindFIndices(cutAt);
}
/// <summary>
/// Finds out if a given linear segment intersects with the contour of this node
/// (including connecting quadrangle), and returns findices of the intersection.
/// </summary>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <returns></returns>
internal StrokeFIndices CutTest(Point begin, Point end)
{
if (IsValid == false)
{
return StrokeFIndices.Empty;
}
// If the node contours intersect, the result is a pair of findices
// this segment should be cut at to let the hitNode's contour through it.
StrokeFIndices cutAt = _operations.CutTest(_lastNode, _thisNode, ConnectingQuad, begin, end);
System.Diagnostics.Debug.Assert(!double.IsNaN(cutAt.BeginFIndex) && !double.IsNaN(cutAt.EndFIndex));
// Bind the found findices to the node and return the result
return BindFIndicesForLassoHitTest(cutAt);
}
#endregion
#region Private helpers
/// <summary>
/// Binds a local fragment to this node by setting the integer part of the
/// fragment findices equal to the index of the previous node
/// </summary>
/// <param name="fragment"></param>
/// <returns></returns>
private StrokeFIndices BindFIndices(StrokeFIndices fragment)
{
System.Diagnostics.Debug.Assert(IsValid && (_index >= 0));
if (fragment.IsEmpty == false)
{
// Adjust only findices which are on this segment of thew spine (i.e. between 0 and 1)
if (!DoubleUtil.AreClose(fragment.BeginFIndex, StrokeFIndices.BeforeFirst))
{
System.Diagnostics.Debug.Assert(fragment.BeginFIndex >= 0 && fragment.BeginFIndex <= 1);
fragment.BeginFIndex += _index - 1;
}
if (!DoubleUtil.AreClose(fragment.EndFIndex, StrokeFIndices.AfterLast))
{
System.Diagnostics.Debug.Assert(fragment.EndFIndex >= 0 && fragment.EndFIndex <= 1);
fragment.EndFIndex += _index - 1;
}
}
return fragment;
}
internal int Index
{
get { return _index; }
}
/// <summary>
/// Bind the StrokeFIndices for lasso hit test results.
/// </summary>
/// <param name="fragment"></param>
/// <returns></returns>
private StrokeFIndices BindFIndicesForLassoHitTest(StrokeFIndices fragment)
{
System.Diagnostics.Debug.Assert(IsValid);
if (!fragment.IsEmpty)
{
// Adjust BeginFIndex
if (DoubleUtil.AreClose(fragment.BeginFIndex, StrokeFIndices.BeforeFirst))
{
// set it to be the index of the previous node, indicating intersection start from previous node
fragment.BeginFIndex = (_index == 0 ? StrokeFIndices.BeforeFirst:_index - 1);
}
else
{
// Adjust findices which are on this segment of the spine (i.e. between 0 and 1)
System.Diagnostics.Debug.Assert(DoubleUtil.GreaterThanOrClose(fragment.BeginFIndex, 0f));
System.Diagnostics.Debug.Assert(DoubleUtil.LessThanOrClose(fragment.BeginFIndex, 1f));
// Adjust the value to consider index, say from 0.75 to 3.75 (for _index = 4)
fragment.BeginFIndex += _index - 1;
}
//Adjust EndFIndex
if (DoubleUtil.AreClose(fragment.EndFIndex, StrokeFIndices.AfterLast))
{
// set it to be the index of the current node, indicating the intersection cover the end of the node
fragment.EndFIndex = (_isLastNode ? StrokeFIndices.AfterLast:_index);
}
else
{
System.Diagnostics.Debug.Assert(DoubleUtil.GreaterThanOrClose(fragment.EndFIndex, 0f));
System.Diagnostics.Debug.Assert(DoubleUtil.LessThanOrClose(fragment.EndFIndex, 1f));
// Ajust the value to consider the index
fragment.EndFIndex += _index - 1;
}
}
return fragment;
}
/// <summary>
/// Tells whether the StrokeNode instance is valid or not (created via the default ctor)
/// </summary>
internal bool IsValid { get { return _operations != null; } }
/// <summary>
/// The quadrangle that connects this and the previous node.
/// Can be empty if this node is the first one or if one of the nodes is
/// completely inside the other.
/// The type Quad is supposed to be internal even if we surface StrokeNode.
/// External users of StrokeNode should use GetConnectionPoints instead.
/// </summary>
private Quad ConnectingQuad
{
get
{
System.Diagnostics.Debug.Assert(IsValid);
if (_isQuadCached == false)
{
_connectingQuad = _operations.GetConnectingQuad(_lastNode, _thisNode);
_isQuadCached = true;
}
return _connectingQuad;
}
}
/// <summary>
/// Returns an enumerator for edges of the contour comprised by the node
/// and connecting quadrangle (_lastNode is excluded)
/// Used for hit-testing a stroke against an other stroke (stroke and point erasing)
/// </summary>
private IEnumerable<ContourSegment> GetContourSegments()
{
System.Diagnostics.Debug.Assert(IsValid);
// Calls thru to the StrokeNodeOperations object
if (IsEllipse)
{
// ISSUE-2004/06/15- temporary workaround to avoid hit-testing with ellipses
return _operations.GetNonBezierContourSegments(_lastNode, _thisNode);
}
return _operations.GetContourSegments(_thisNode, ConnectingQuad);
}
/// <summary>
/// Returns the spine point that corresponds to the given findex.
/// </summary>
/// <param name="findex">A local findex between the previous index and this one (ex: between 2.0 and 3.0)</param>
/// <returns>Point on the spine</returns>
internal Point GetPointAt(double findex)
{
System.Diagnostics.Debug.Assert(IsValid);
if (_lastNode.IsEmpty)
{
System.Diagnostics.Debug.Assert(findex == 0);
return _thisNode.Position;
}
System.Diagnostics.Debug.Assert((findex >= _index - 1) && (findex <= _index));
if (DoubleUtil.AreClose(findex, (double)_index))
{
//
// we're being asked for this exact point
// if we don't return it here, our algorithm
// below doesn't work
//
return _thisNode.Position;
}
//
// get the spare change to the left of the decimal point
// eg turn 2.75 into .75
//
double floor = Math.Floor(findex);
findex = findex - floor;
double xDiff = (_thisNode.Position.X - _lastNode.Position.X) * findex;
double yDiff = (_thisNode.Position.Y - _lastNode.Position.Y) * findex;
//
// return the previous point plus the delta's
//
return new Point( _lastNode.Position.X + xDiff,
_lastNode.Position.Y + yDiff);
}
#endregion
#region Fields
// Internal objects created for particular rendering
private StrokeNodeOperations _operations;
// Node's index on the stroke spine
private int _index;
// This and the previous node data that used by the StrokeNodeOperations object to build
// and/or hit-test the contour of the node/segment
private StrokeNodeData _thisNode;
private StrokeNodeData _lastNode;
// Calculating of the connecting quadrangle is not a cheap operations, therefore,
// first, it's computed only by request, and second, once computed it's cached in the StrokeNode
private bool _isQuadCached;
private Quad _connectingQuad;
// Is the current stroke node the last node?
private bool _isLastNode;
#endregion
}
#endregion
}
| |
using System;
using System.Windows.Forms;
using PCSUtils.Utils;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSComUtils.Admin.BO;
//using PCSComUtils.Admin.DS;
namespace PCSUtils.Admin
{
/// <summary>
/// Summary description for UpdatePassword.
/// </summary>
public class UpdatePassword : System.Windows.Forms.Form
{
#region Declaration
#region System Generated
private System.Windows.Forms.TextBox txtOldPassword;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.TextBox txtNewPassword;
private System.Windows.Forms.TextBox txtConfirmPassword;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Label lblOldPass;
private System.Windows.Forms.Label lblNewPass;
private System.Windows.Forms.Label lblConfirmPass;
#endregion System Generated
const string THIS = "PCSUtils.Admin.UpdatePassword";
private string strUserName;
#endregion Declaration
#region Constructor, Destructor
public UpdatePassword()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion Constructor, Destructor
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(UpdatePassword));
this.lblOldPass = new System.Windows.Forms.Label();
this.txtOldPassword = new System.Windows.Forms.TextBox();
this.lblNewPass = new System.Windows.Forms.Label();
this.txtNewPassword = new System.Windows.Forms.TextBox();
this.lblConfirmPass = new System.Windows.Forms.Label();
this.txtConfirmPassword = new System.Windows.Forms.TextBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblOldPass
//
this.lblOldPass.AccessibleDescription = resources.GetString("lblOldPass.AccessibleDescription");
this.lblOldPass.AccessibleName = resources.GetString("lblOldPass.AccessibleName");
this.lblOldPass.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblOldPass.Anchor")));
this.lblOldPass.AutoSize = ((bool)(resources.GetObject("lblOldPass.AutoSize")));
this.lblOldPass.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblOldPass.Dock")));
this.lblOldPass.Enabled = ((bool)(resources.GetObject("lblOldPass.Enabled")));
this.lblOldPass.Font = ((System.Drawing.Font)(resources.GetObject("lblOldPass.Font")));
this.lblOldPass.ForeColor = System.Drawing.Color.Maroon;
this.lblOldPass.Image = ((System.Drawing.Image)(resources.GetObject("lblOldPass.Image")));
this.lblOldPass.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblOldPass.ImageAlign")));
this.lblOldPass.ImageIndex = ((int)(resources.GetObject("lblOldPass.ImageIndex")));
this.lblOldPass.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblOldPass.ImeMode")));
this.lblOldPass.Location = ((System.Drawing.Point)(resources.GetObject("lblOldPass.Location")));
this.lblOldPass.Name = "lblOldPass";
this.lblOldPass.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblOldPass.RightToLeft")));
this.lblOldPass.Size = ((System.Drawing.Size)(resources.GetObject("lblOldPass.Size")));
this.lblOldPass.TabIndex = ((int)(resources.GetObject("lblOldPass.TabIndex")));
this.lblOldPass.Text = resources.GetString("lblOldPass.Text");
this.lblOldPass.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblOldPass.TextAlign")));
this.lblOldPass.Visible = ((bool)(resources.GetObject("lblOldPass.Visible")));
//
// txtOldPassword
//
this.txtOldPassword.AccessibleDescription = resources.GetString("txtOldPassword.AccessibleDescription");
this.txtOldPassword.AccessibleName = resources.GetString("txtOldPassword.AccessibleName");
this.txtOldPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtOldPassword.Anchor")));
this.txtOldPassword.AutoSize = ((bool)(resources.GetObject("txtOldPassword.AutoSize")));
this.txtOldPassword.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtOldPassword.BackgroundImage")));
this.txtOldPassword.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtOldPassword.Dock")));
this.txtOldPassword.Enabled = ((bool)(resources.GetObject("txtOldPassword.Enabled")));
this.txtOldPassword.Font = ((System.Drawing.Font)(resources.GetObject("txtOldPassword.Font")));
this.txtOldPassword.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtOldPassword.ImeMode")));
this.txtOldPassword.Location = ((System.Drawing.Point)(resources.GetObject("txtOldPassword.Location")));
this.txtOldPassword.MaxLength = ((int)(resources.GetObject("txtOldPassword.MaxLength")));
this.txtOldPassword.Multiline = ((bool)(resources.GetObject("txtOldPassword.Multiline")));
this.txtOldPassword.Name = "txtOldPassword";
this.txtOldPassword.PasswordChar = ((char)(resources.GetObject("txtOldPassword.PasswordChar")));
this.txtOldPassword.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtOldPassword.RightToLeft")));
this.txtOldPassword.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtOldPassword.ScrollBars")));
this.txtOldPassword.Size = ((System.Drawing.Size)(resources.GetObject("txtOldPassword.Size")));
this.txtOldPassword.TabIndex = ((int)(resources.GetObject("txtOldPassword.TabIndex")));
this.txtOldPassword.Text = resources.GetString("txtOldPassword.Text");
this.txtOldPassword.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtOldPassword.TextAlign")));
this.txtOldPassword.Visible = ((bool)(resources.GetObject("txtOldPassword.Visible")));
this.txtOldPassword.WordWrap = ((bool)(resources.GetObject("txtOldPassword.WordWrap")));
this.txtOldPassword.Leave += new System.EventHandler(this.OnLeaveControl);
this.txtOldPassword.Enter += new System.EventHandler(this.OnEnterControl);
//
// lblNewPass
//
this.lblNewPass.AccessibleDescription = resources.GetString("lblNewPass.AccessibleDescription");
this.lblNewPass.AccessibleName = resources.GetString("lblNewPass.AccessibleName");
this.lblNewPass.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblNewPass.Anchor")));
this.lblNewPass.AutoSize = ((bool)(resources.GetObject("lblNewPass.AutoSize")));
this.lblNewPass.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblNewPass.Dock")));
this.lblNewPass.Enabled = ((bool)(resources.GetObject("lblNewPass.Enabled")));
this.lblNewPass.Font = ((System.Drawing.Font)(resources.GetObject("lblNewPass.Font")));
this.lblNewPass.ForeColor = System.Drawing.Color.Maroon;
this.lblNewPass.Image = ((System.Drawing.Image)(resources.GetObject("lblNewPass.Image")));
this.lblNewPass.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblNewPass.ImageAlign")));
this.lblNewPass.ImageIndex = ((int)(resources.GetObject("lblNewPass.ImageIndex")));
this.lblNewPass.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblNewPass.ImeMode")));
this.lblNewPass.Location = ((System.Drawing.Point)(resources.GetObject("lblNewPass.Location")));
this.lblNewPass.Name = "lblNewPass";
this.lblNewPass.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblNewPass.RightToLeft")));
this.lblNewPass.Size = ((System.Drawing.Size)(resources.GetObject("lblNewPass.Size")));
this.lblNewPass.TabIndex = ((int)(resources.GetObject("lblNewPass.TabIndex")));
this.lblNewPass.Text = resources.GetString("lblNewPass.Text");
this.lblNewPass.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblNewPass.TextAlign")));
this.lblNewPass.Visible = ((bool)(resources.GetObject("lblNewPass.Visible")));
//
// txtNewPassword
//
this.txtNewPassword.AccessibleDescription = resources.GetString("txtNewPassword.AccessibleDescription");
this.txtNewPassword.AccessibleName = resources.GetString("txtNewPassword.AccessibleName");
this.txtNewPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtNewPassword.Anchor")));
this.txtNewPassword.AutoSize = ((bool)(resources.GetObject("txtNewPassword.AutoSize")));
this.txtNewPassword.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtNewPassword.BackgroundImage")));
this.txtNewPassword.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtNewPassword.Dock")));
this.txtNewPassword.Enabled = ((bool)(resources.GetObject("txtNewPassword.Enabled")));
this.txtNewPassword.Font = ((System.Drawing.Font)(resources.GetObject("txtNewPassword.Font")));
this.txtNewPassword.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtNewPassword.ImeMode")));
this.txtNewPassword.Location = ((System.Drawing.Point)(resources.GetObject("txtNewPassword.Location")));
this.txtNewPassword.MaxLength = ((int)(resources.GetObject("txtNewPassword.MaxLength")));
this.txtNewPassword.Multiline = ((bool)(resources.GetObject("txtNewPassword.Multiline")));
this.txtNewPassword.Name = "txtNewPassword";
this.txtNewPassword.PasswordChar = ((char)(resources.GetObject("txtNewPassword.PasswordChar")));
this.txtNewPassword.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtNewPassword.RightToLeft")));
this.txtNewPassword.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtNewPassword.ScrollBars")));
this.txtNewPassword.Size = ((System.Drawing.Size)(resources.GetObject("txtNewPassword.Size")));
this.txtNewPassword.TabIndex = ((int)(resources.GetObject("txtNewPassword.TabIndex")));
this.txtNewPassword.Text = resources.GetString("txtNewPassword.Text");
this.txtNewPassword.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtNewPassword.TextAlign")));
this.txtNewPassword.Visible = ((bool)(resources.GetObject("txtNewPassword.Visible")));
this.txtNewPassword.WordWrap = ((bool)(resources.GetObject("txtNewPassword.WordWrap")));
this.txtNewPassword.Leave += new System.EventHandler(this.OnLeaveControl);
this.txtNewPassword.Enter += new System.EventHandler(this.OnEnterControl);
//
// lblConfirmPass
//
this.lblConfirmPass.AccessibleDescription = resources.GetString("lblConfirmPass.AccessibleDescription");
this.lblConfirmPass.AccessibleName = resources.GetString("lblConfirmPass.AccessibleName");
this.lblConfirmPass.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblConfirmPass.Anchor")));
this.lblConfirmPass.AutoSize = ((bool)(resources.GetObject("lblConfirmPass.AutoSize")));
this.lblConfirmPass.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblConfirmPass.Dock")));
this.lblConfirmPass.Enabled = ((bool)(resources.GetObject("lblConfirmPass.Enabled")));
this.lblConfirmPass.Font = ((System.Drawing.Font)(resources.GetObject("lblConfirmPass.Font")));
this.lblConfirmPass.ForeColor = System.Drawing.Color.Maroon;
this.lblConfirmPass.Image = ((System.Drawing.Image)(resources.GetObject("lblConfirmPass.Image")));
this.lblConfirmPass.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblConfirmPass.ImageAlign")));
this.lblConfirmPass.ImageIndex = ((int)(resources.GetObject("lblConfirmPass.ImageIndex")));
this.lblConfirmPass.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblConfirmPass.ImeMode")));
this.lblConfirmPass.Location = ((System.Drawing.Point)(resources.GetObject("lblConfirmPass.Location")));
this.lblConfirmPass.Name = "lblConfirmPass";
this.lblConfirmPass.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblConfirmPass.RightToLeft")));
this.lblConfirmPass.Size = ((System.Drawing.Size)(resources.GetObject("lblConfirmPass.Size")));
this.lblConfirmPass.TabIndex = ((int)(resources.GetObject("lblConfirmPass.TabIndex")));
this.lblConfirmPass.Text = resources.GetString("lblConfirmPass.Text");
this.lblConfirmPass.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblConfirmPass.TextAlign")));
this.lblConfirmPass.Visible = ((bool)(resources.GetObject("lblConfirmPass.Visible")));
//
// txtConfirmPassword
//
this.txtConfirmPassword.AccessibleDescription = resources.GetString("txtConfirmPassword.AccessibleDescription");
this.txtConfirmPassword.AccessibleName = resources.GetString("txtConfirmPassword.AccessibleName");
this.txtConfirmPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtConfirmPassword.Anchor")));
this.txtConfirmPassword.AutoSize = ((bool)(resources.GetObject("txtConfirmPassword.AutoSize")));
this.txtConfirmPassword.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtConfirmPassword.BackgroundImage")));
this.txtConfirmPassword.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtConfirmPassword.Dock")));
this.txtConfirmPassword.Enabled = ((bool)(resources.GetObject("txtConfirmPassword.Enabled")));
this.txtConfirmPassword.Font = ((System.Drawing.Font)(resources.GetObject("txtConfirmPassword.Font")));
this.txtConfirmPassword.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtConfirmPassword.ImeMode")));
this.txtConfirmPassword.Location = ((System.Drawing.Point)(resources.GetObject("txtConfirmPassword.Location")));
this.txtConfirmPassword.MaxLength = ((int)(resources.GetObject("txtConfirmPassword.MaxLength")));
this.txtConfirmPassword.Multiline = ((bool)(resources.GetObject("txtConfirmPassword.Multiline")));
this.txtConfirmPassword.Name = "txtConfirmPassword";
this.txtConfirmPassword.PasswordChar = ((char)(resources.GetObject("txtConfirmPassword.PasswordChar")));
this.txtConfirmPassword.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtConfirmPassword.RightToLeft")));
this.txtConfirmPassword.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtConfirmPassword.ScrollBars")));
this.txtConfirmPassword.Size = ((System.Drawing.Size)(resources.GetObject("txtConfirmPassword.Size")));
this.txtConfirmPassword.TabIndex = ((int)(resources.GetObject("txtConfirmPassword.TabIndex")));
this.txtConfirmPassword.Text = resources.GetString("txtConfirmPassword.Text");
this.txtConfirmPassword.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtConfirmPassword.TextAlign")));
this.txtConfirmPassword.Visible = ((bool)(resources.GetObject("txtConfirmPassword.Visible")));
this.txtConfirmPassword.WordWrap = ((bool)(resources.GetObject("txtConfirmPassword.WordWrap")));
this.txtConfirmPassword.Leave += new System.EventHandler(this.OnLeaveControl);
this.txtConfirmPassword.Enter += new System.EventHandler(this.OnEnterControl);
//
// btnCancel
//
this.btnCancel.AccessibleDescription = resources.GetString("btnCancel.AccessibleDescription");
this.btnCancel.AccessibleName = resources.GetString("btnCancel.AccessibleName");
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnCancel.Anchor")));
this.btnCancel.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnCancel.BackgroundImage")));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnCancel.Dock")));
this.btnCancel.Enabled = ((bool)(resources.GetObject("btnCancel.Enabled")));
this.btnCancel.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnCancel.FlatStyle")));
this.btnCancel.Font = ((System.Drawing.Font)(resources.GetObject("btnCancel.Font")));
this.btnCancel.Image = ((System.Drawing.Image)(resources.GetObject("btnCancel.Image")));
this.btnCancel.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnCancel.ImageAlign")));
this.btnCancel.ImageIndex = ((int)(resources.GetObject("btnCancel.ImageIndex")));
this.btnCancel.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnCancel.ImeMode")));
this.btnCancel.Location = ((System.Drawing.Point)(resources.GetObject("btnCancel.Location")));
this.btnCancel.Name = "btnCancel";
this.btnCancel.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnCancel.RightToLeft")));
this.btnCancel.Size = ((System.Drawing.Size)(resources.GetObject("btnCancel.Size")));
this.btnCancel.TabIndex = ((int)(resources.GetObject("btnCancel.TabIndex")));
this.btnCancel.Text = resources.GetString("btnCancel.Text");
this.btnCancel.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnCancel.TextAlign")));
this.btnCancel.Visible = ((bool)(resources.GetObject("btnCancel.Visible")));
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOK
//
this.btnOK.AccessibleDescription = resources.GetString("btnOK.AccessibleDescription");
this.btnOK.AccessibleName = resources.GetString("btnOK.AccessibleName");
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnOK.Anchor")));
this.btnOK.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnOK.BackgroundImage")));
this.btnOK.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnOK.Dock")));
this.btnOK.Enabled = ((bool)(resources.GetObject("btnOK.Enabled")));
this.btnOK.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnOK.FlatStyle")));
this.btnOK.Font = ((System.Drawing.Font)(resources.GetObject("btnOK.Font")));
this.btnOK.Image = ((System.Drawing.Image)(resources.GetObject("btnOK.Image")));
this.btnOK.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnOK.ImageAlign")));
this.btnOK.ImageIndex = ((int)(resources.GetObject("btnOK.ImageIndex")));
this.btnOK.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnOK.ImeMode")));
this.btnOK.Location = ((System.Drawing.Point)(resources.GetObject("btnOK.Location")));
this.btnOK.Name = "btnOK";
this.btnOK.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnOK.RightToLeft")));
this.btnOK.Size = ((System.Drawing.Size)(resources.GetObject("btnOK.Size")));
this.btnOK.TabIndex = ((int)(resources.GetObject("btnOK.TabIndex")));
this.btnOK.Text = resources.GetString("btnOK.Text");
this.btnOK.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnOK.TextAlign")));
this.btnOK.Visible = ((bool)(resources.GetObject("btnOK.Visible")));
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnHelp
//
this.btnHelp.AccessibleDescription = resources.GetString("btnHelp.AccessibleDescription");
this.btnHelp.AccessibleName = resources.GetString("btnHelp.AccessibleName");
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnHelp.Anchor")));
this.btnHelp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHelp.BackgroundImage")));
this.btnHelp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnHelp.Dock")));
this.btnHelp.Enabled = ((bool)(resources.GetObject("btnHelp.Enabled")));
this.btnHelp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnHelp.FlatStyle")));
this.btnHelp.Font = ((System.Drawing.Font)(resources.GetObject("btnHelp.Font")));
this.btnHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnHelp.Image")));
this.btnHelp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.ImageAlign")));
this.btnHelp.ImageIndex = ((int)(resources.GetObject("btnHelp.ImageIndex")));
this.btnHelp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnHelp.ImeMode")));
this.btnHelp.Location = ((System.Drawing.Point)(resources.GetObject("btnHelp.Location")));
this.btnHelp.Name = "btnHelp";
this.btnHelp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnHelp.RightToLeft")));
this.btnHelp.Size = ((System.Drawing.Size)(resources.GetObject("btnHelp.Size")));
this.btnHelp.TabIndex = ((int)(resources.GetObject("btnHelp.TabIndex")));
this.btnHelp.Text = resources.GetString("btnHelp.Text");
this.btnHelp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.TextAlign")));
this.btnHelp.Visible = ((bool)(resources.GetObject("btnHelp.Visible")));
//
// UpdatePassword
//
this.AcceptButton = this.btnOK;
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.CancelButton = this.btnCancel;
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.txtConfirmPassword);
this.Controls.Add(this.txtNewPassword);
this.Controls.Add(this.txtOldPassword);
this.Controls.Add(this.lblConfirmPass);
this.Controls.Add(this.lblNewPass);
this.Controls.Add(this.lblOldPass);
this.Controls.Add(this.btnHelp);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximizeBox = false;
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "UpdatePassword";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.Load += new System.EventHandler(this.UpdatePassword_Load);
this.ResumeLayout(false);
}
#endregion
#region Class's Method And Properties
/// <summary>
/// This method uses to validate data on this form
/// </summary>
/// <returns></returns>
/// <author> Son HT, Dec 13, 2004</author>
private bool IsValidated()
{
const string METHOD_NAME = THIS + ".IsValidated()";
bool blnIsCorrect = true;
try
{
CommonBO boCommon = new CommonBO();
//blnIsCorrect = boCommon.IsCorrectedPassword(strUserName,txtOldPassword.Text);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
// if incorrect old password
if(!blnIsCorrect)
{
PCSMessageBox.Show(ErrorCode.INVALID_PASSWORD, MessageBoxIcon.Error);
txtOldPassword.Focus();
txtOldPassword.Select(0,txtOldPassword.Text.Length);
return false;
}
// if new password != confirm password
if(txtNewPassword.Text != txtConfirmPassword.Text)
{
PCSMessageBox.Show(ErrorCode.NEWPASSWORD_DIFFERENT_CONFIRMPASSWORD, MessageBoxIcon.Error);
txtNewPassword.Focus();
txtNewPassword.Select(0,txtNewPassword.Text.Length);
return false;
}
return true;
}
/// <summary>
/// Check mandatory of a specific control
/// </summary>
/// <param name="pobjControl"></param>
/// <returns></returns>
/// <author> Son HT, Jan 20, 2005</author>
public bool CheckMandatory(Control pobjControl)
{
if (pobjControl.Text == string.Empty)
{
return true;
}
return false;
}
/// <summary>
/// Make this button act like btnSearchProductCode_Click
/// HACKED: Thachnn
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Son HT, Jan 20, 2005</author>
private void OnEnterControl(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ". OnEnterControl()";
try
{
FormControlComponents.OnEnterControl(sender, e);
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Process onleave control event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Son HT, Jan 20, 2005</author>
private void OnLeaveControl(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".txtCode_Leave()";
//Only use when users use this to search for existing product
try
{
FormControlComponents.OnLeaveControl(sender, e);
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
/// ENDHACKED: Thachnn
#endregion Class's Method And Properties
#region Event Processing
/// <summary>
/// Processing Load event on this form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Son HT, Dec 13, 2004</author>
private void UpdatePassword_Load(object sender, System.EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".UpdatePassword_Load()";
try
{
//Set authorization for user
Security objSecurity = new Security();
this.Name = THIS;
if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW ,MessageBoxIcon.Warning);
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
strUserName = SystemProperty.UserName;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Processing click event on Cancel button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Son HT, Dec 13, 2004</author>
private void btnCancel_Click(object sender, System.EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
Close();
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <summary>
/// Processing click event on OK button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Son HT, Dec 13, 2004</author>
private void btnOK_Click(object sender, System.EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".btnOK_Click()";
try
{
// check mandatory old password
if(CheckMandatory(txtOldPassword))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
txtOldPassword.Focus();
txtOldPassword.SelectAll();
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
// check mandatory new password
if(CheckMandatory(txtNewPassword))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
txtNewPassword.Focus();
txtNewPassword.SelectAll();
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
// check mandatory confirm password
if(CheckMandatory(txtConfirmPassword))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
txtConfirmPassword.Focus();
txtConfirmPassword.SelectAll();
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
return;
}
if(IsValidated())
{
// Update password
CommonBO boCommon = new CommonBO();
boCommon.UpdateNewPassword(strUserName,txtNewPassword.Text);
PCSMessageBox.Show(ErrorCode.PASSWORD_UPDATE_SUCCESSFUL);
Close();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
#endregion Event Processing
}
}
| |
using System;
using ClosedXML.Excel;
namespace ClosedXML_Examples.Misc
{
public class DataTypes : IXLExample
{
#region Variables
// Public
// Private
#endregion
#region Properties
// Public
// Private
// Override
#endregion
#region Events
// Public
// Private
// Override
#endregion
#region Methods
// Public
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.Worksheets.Add("Data Types");
var co = 2;
var ro = 1;
ws.Cell(++ro, co).Value = "Plain Text:";
ws.Cell(ro, co + 1).Value = "Hello World.";
ws.Cell(++ro, co).Value = "Plain Date:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(++ro, co).Value = "Plain DateTime:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2, 13, 45, 22);
ws.Cell(++ro, co).Value = "Plain Boolean:";
ws.Cell(ro, co + 1).Value = true;
ws.Cell(++ro, co).Value = "Plain Number:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(++ro, co).Value = "TimeSpan:";
ws.Cell(ro, co + 1).Value = new TimeSpan(33, 45, 22);
ro++;
ws.Cell(++ro, co).Value = "Decimal Number:";
ws.Cell(ro, co + 1).Value = 123.45m;
ws.Cell(++ro, co).Value = "Float Number:";
ws.Cell(ro, co + 1).Value = 123.45f;
ws.Cell(++ro, co).Value = "Double Number:";
ws.Cell(ro, co + 1).Value = 123.45d;
ws.Cell(++ro, co).Value = "Large Double Number:";
ws.Cell(ro, co + 1).Value = 9.999E307d;
ro++;
ws.Cell(++ro, co).Value = "Explicit Text:";
ws.Cell(ro, co + 1).Value = "'Hello World.";
ws.Cell(++ro, co).Value = "Date as Text:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2).ToString();
ws.Cell(++ro, co).Value = "DateTime as Text:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2, 13, 45, 22).ToString();
ws.Cell(++ro, co).Value = "Boolean as Text:";
ws.Cell(ro, co + 1).Value = "'" + true.ToString();
ws.Cell(++ro, co).Value = "Number as Text:";
ws.Cell(ro, co + 1).Value = "'123.45";
ws.Cell(++ro, co).Value = "Number with @ format:";
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(++ro, co).Value = "Format number with @:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(++ro, co).Value = "TimeSpan as Text:";
ws.Cell(ro, co + 1).Value = "'" + new TimeSpan(33, 45, 22).ToString();
ro++;
ws.Cell(++ro, co).Value = "Changing Data Types:";
ro++;
ws.Cell(++ro, co).Value = "Date to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "DateTime to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2, 13, 45, 22);
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "Boolean to Text:";
ws.Cell(ro, co + 1).Value = true;
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "Number to Text:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "TimeSpan to Text:";
ws.Cell(ro, co + 1).Value = new TimeSpan(33, 45, 22);
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "Text to Date:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2).ToString();
ws.Cell(ro, co + 1).DataType = XLDataType.DateTime;
ws.Cell(++ro, co).Value = "Text to DateTime:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2, 13, 45, 22).ToString();
ws.Cell(ro, co + 1).DataType = XLDataType.DateTime;
ws.Cell(++ro, co).Value = "Text to Boolean:";
ws.Cell(ro, co + 1).Value = "'" + true.ToString();
ws.Cell(ro, co + 1).DataType = XLDataType.Boolean;
ws.Cell(++ro, co).Value = "Text to Number:";
ws.Cell(ro, co + 1).Value = "'123.45";
ws.Cell(ro, co + 1).DataType = XLDataType.Number;
ws.Cell(++ro, co).Value = "Percentage Text to Number:";
ws.Cell(ro, co + 1).Value = "'55.12%";
ws.Cell(ro, co + 1).Style.NumberFormat.SetNumberFormatId((int)XLPredefinedFormat.Number.PercentPrecision2);
ws.Cell(ro, co + 1).DataType = XLDataType.Number;
ws.Cell(++ro, co).Value = "@ format to Number:";
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).DataType = XLDataType.Number;
ws.Cell(++ro, co).Value = "Text to TimeSpan:";
ws.Cell(ro, co + 1).Value = "'" + new TimeSpan(33, 45, 22).ToString();
ws.Cell(ro, co + 1).DataType = XLDataType.TimeSpan;
ro++;
ws.Cell(++ro, co).Value = "Formatted Date to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(ro, co + 1).Style.DateFormat.Format = "yyyy-MM-dd";
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(++ro, co).Value = "Formatted Number to Text:";
ws.Cell(ro, co + 1).Value = 12345.6789;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "#,##0.00";
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ro++;
ws.Cell(++ro, co).Value = "Blank Text:";
ws.Cell(ro, co + 1).Value = 12345.6789;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "#,##0.00";
ws.Cell(ro, co + 1).DataType = XLDataType.Text;
ws.Cell(ro, co + 1).Value = "";
ro++;
// Using inline strings (few users will ever need to use this feature)
//
// By default all strings are stored as shared so one block of text
// can be reference by multiple cells.
// You can override this by setting the .ShareString property to false
ws.Cell(++ro, co).Value = "Inline String:";
var cell = ws.Cell(ro, co + 1);
cell.Value = "Not Shared";
cell.ShareString = false;
// To view all shared strings (all texts in the workbook actually), use the following:
// workbook.GetSharedStrings()
ws.Cell(++ro, co)
.SetDataType(XLDataType.Text)
.SetDataType(XLDataType.Boolean)
.SetDataType(XLDataType.DateTime)
.SetDataType(XLDataType.Number)
.SetDataType(XLDataType.TimeSpan)
.SetDataType(XLDataType.Text)
.SetDataType(XLDataType.TimeSpan)
.SetDataType(XLDataType.Number)
.SetDataType(XLDataType.DateTime)
.SetDataType(XLDataType.Boolean)
.SetDataType(XLDataType.Text);
ws.Columns(2, 3).AdjustToContents();
workbook.SaveAs(filePath);
}
// Private
// Override
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// this file contains the data structures for the in memory database
// containing display and formatting information
using System.Collections.Generic;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
#region Table View Definitions
/// <summary>
/// Alignment values
/// NOTE: we do not use an enum because this will have to be
/// serialized and ERS/serialization do not support enumerations.
/// </summary>
internal static class TextAlignment
{
internal const int Undefined = 0;
internal const int Left = 1;
internal const int Center = 2;
internal const int Right = 3;
}
/// <summary>
/// Definition of a table control.
/// </summary>
internal sealed class TableControlBody : ControlBody
{
/// <summary>
/// Optional, if not present, use data off the default table row definition.
/// </summary>
internal TableHeaderDefinition header = new TableHeaderDefinition();
/// <summary>
/// Default row definition
/// It's mandatory.
/// </summary>
internal TableRowDefinition defaultDefinition;
/// <summary>
/// Optional list of row definition overrides. It can be empty if there are no overrides.
/// </summary>
internal List<TableRowDefinition> optionalDefinitionList = new List<TableRowDefinition>();
internal override ControlBase Copy()
{
TableControlBody result = new TableControlBody
{
autosize = this.autosize,
header = this.header.Copy()
};
if (defaultDefinition != null)
{
result.defaultDefinition = this.defaultDefinition.Copy();
}
foreach (TableRowDefinition trd in this.optionalDefinitionList)
{
result.optionalDefinitionList.Add(trd);
}
return result;
}
}
/// <summary>
/// Information about the table header
/// NOTE: if an instance of this class is present, the list must not be empty.
/// </summary>
internal sealed class TableHeaderDefinition
{
/// <summary>
/// If true, direct the outputter to suppress table header printing.
/// </summary>
internal bool hideHeader;
/// <summary>
/// Mandatory list of column header definitions.
/// </summary>
internal List<TableColumnHeaderDefinition> columnHeaderDefinitionList =
new List<TableColumnHeaderDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableHeaderDefinition Copy()
{
TableHeaderDefinition result = new TableHeaderDefinition { hideHeader = this.hideHeader };
foreach (TableColumnHeaderDefinition tchd in this.columnHeaderDefinitionList)
{
result.columnHeaderDefinitionList.Add(tchd);
}
return result;
}
}
internal sealed class TableColumnHeaderDefinition
{
/// <summary>
/// Optional label
/// If not present, use the name of the property from the matching
/// mandatory row description.
/// </summary>
internal TextToken label = null;
/// <summary>
/// General alignment for the column
/// If not present, either use the one from the row definition
/// or the data driven heuristics.
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// Width of the column.
/// </summary>
internal int width = 0; // undefined
}
/// <summary>
/// Definition of the data to be displayed in a table row.
/// </summary>
internal sealed class TableRowDefinition
{
/// <summary>
/// Applicability clause
/// Only valid if not the default definition.
/// </summary>
internal AppliesTo appliesTo;
/// <summary>
/// If true, the current table row should be allowed
/// to wrap to multiple lines, else truncated.
/// </summary>
internal bool multiLine;
/// <summary>
/// Mandatory list of column items.
/// It cannot be empty.
/// </summary>
internal List<TableRowItemDefinition> rowItemDefinitionList = new List<TableRowItemDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableRowDefinition Copy()
{
TableRowDefinition result = new TableRowDefinition
{
appliesTo = this.appliesTo,
multiLine = this.multiLine
};
foreach (TableRowItemDefinition trid in this.rowItemDefinitionList)
{
result.rowItemDefinitionList.Add(trid);
}
return result;
}
}
/// <summary>
/// Cell definition inside a row.
/// </summary>
internal sealed class TableRowItemDefinition
{
/// <summary>
/// Optional alignment to override the default one at the header level.
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// Format directive body telling how to format the cell
/// RULE: the body can only contain
/// * TextToken
/// * PropertyToken
/// * NOTHING (provide an empty cell)
/// </summary>
internal List<FormatToken> formatTokenList = new List<FormatToken>();
}
#endregion
}
namespace System.Management.Automation
{
/// <summary>
/// Defines a table control.
/// </summary>
public sealed class TableControl : PSControl
{
/// <summary>Collection of column header definitions for this table control</summary>
public List<TableControlColumnHeader> Headers { get; set; }
/// <summary>Collection of row definitions for this table control</summary>
public List<TableControlRow> Rows { get; set; }
/// <summary>When true, column widths are calculated based on more than the first object.</summary>
public bool AutoSize { get; set; }
/// <summary>When true, table headers are not displayed</summary>
public bool HideTableHeaders { get; set; }
/// <summary>Create a default TableControl</summary>
public static TableControlBuilder Create(bool outOfBand = false, bool autoSize = false, bool hideTableHeaders = false)
{
var table = new TableControl { OutOfBand = outOfBand, AutoSize = autoSize, HideTableHeaders = hideTableHeaders };
return new TableControlBuilder(table);
}
/// <summary>Public default constructor for TableControl</summary>
public TableControl()
{
Headers = new List<TableControlColumnHeader>();
Rows = new List<TableControlRow>();
}
internal override void WriteToXml(FormatXmlWriter writer)
{
writer.WriteTableControl(this);
}
/// <summary>
/// Determines if this object is safe to be written.
/// </summary>
/// <returns>True if safe, false otherwise.</returns>
internal override bool SafeForExport()
{
if (!base.SafeForExport())
return false;
foreach (var row in Rows)
{
if (!row.SafeForExport())
return false;
}
return true;
}
internal override bool CompatibleWithOldPowerShell()
{
if (!base.CompatibleWithOldPowerShell())
return false;
foreach (var row in Rows)
{
if (!row.CompatibleWithOldPowerShell())
return false;
}
return true;
}
internal TableControl(TableControlBody tcb, ViewDefinition viewDefinition) : this()
{
this.OutOfBand = viewDefinition.outOfBand;
this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy);
this.AutoSize = tcb.autosize.HasValue && tcb.autosize.Value;
this.HideTableHeaders = tcb.header.hideHeader;
TableControlRow row = new TableControlRow(tcb.defaultDefinition);
Rows.Add(row);
foreach (TableRowDefinition rd in tcb.optionalDefinitionList)
{
row = new TableControlRow(rd);
Rows.Add(row);
}
foreach (TableColumnHeaderDefinition hd in tcb.header.columnHeaderDefinitionList)
{
TableControlColumnHeader header = new TableControlColumnHeader(hd);
Headers.Add(header);
}
}
/// <summary>
/// Public constructor for TableControl that only takes 'tableControlRows'.
/// </summary>
/// <param name="tableControlRow"></param>
public TableControl(TableControlRow tableControlRow) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
this.Rows.Add(tableControlRow);
}
/// <summary>
/// Public constructor for TableControl that takes both 'tableControlRows' and 'tableControlColumnHeaders'.
/// </summary>
/// <param name="tableControlRow"></param>
/// <param name="tableControlColumnHeaders"></param>
public TableControl(TableControlRow tableControlRow, IEnumerable<TableControlColumnHeader> tableControlColumnHeaders) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
if (tableControlColumnHeaders == null)
throw PSTraceSource.NewArgumentNullException("tableControlColumnHeaders");
this.Rows.Add(tableControlRow);
foreach (TableControlColumnHeader header in tableControlColumnHeaders)
{
this.Headers.Add(header);
}
}
}
/// <summary>
/// Defines the header for a particular column in a table control.
/// </summary>
public sealed class TableControlColumnHeader
{
/// <summary>Label for the column</summary>
public string Label { get; set; }
/// <summary>Alignment of the string within the column</summary>
public Alignment Alignment { get; set; }
/// <summary>Width of the column - in number of display cells</summary>
public int Width { get; set; }
internal TableControlColumnHeader(TableColumnHeaderDefinition colheaderdefinition)
{
if (colheaderdefinition.label != null)
{
Label = colheaderdefinition.label.text;
}
Alignment = (Alignment)colheaderdefinition.alignment;
Width = colheaderdefinition.width;
}
/// <summary>Default constructor</summary>
public TableControlColumnHeader()
{
}
/// <summary>
/// Public constructor for TableControlColumnHeader.
/// </summary>
/// <param name="label">Could be null if no label to specify.</param>
/// <param name="width">The Value should be non-negative.</param>
/// <param name="alignment">The default value is Alignment.Undefined.</param>
public TableControlColumnHeader(string label, int width, Alignment alignment)
{
if (width < 0)
throw PSTraceSource.NewArgumentOutOfRangeException("width", width);
this.Label = label;
this.Width = width;
this.Alignment = alignment;
}
}
/// <summary>
/// Defines a particular column within a row
/// in a table control.
/// </summary>
public sealed class TableControlColumn
{
/// <summary>Alignment of the particular column</summary>
public Alignment Alignment { get; set; }
/// <summary>Display Entry</summary>
public DisplayEntry DisplayEntry { get; set; }
/// <summary>Format string to apply</summary>
public string FormatString { get; internal set; }
/// <summary>
/// Returns the value of the entry.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return DisplayEntry.Value;
}
/// <summary>Default constructor</summary>
public TableControlColumn()
{
}
internal TableControlColumn(string text, int alignment, bool isscriptblock, string formatString)
{
Alignment = (Alignment)alignment;
DisplayEntry = new DisplayEntry(text, isscriptblock ? DisplayEntryValueType.ScriptBlock : DisplayEntryValueType.Property);
FormatString = formatString;
}
/// <summary>
/// Public constructor for TableControlColumn.
/// </summary>
/// <param name="alignment"></param>
/// <param name="entry"></param>
public TableControlColumn(Alignment alignment, DisplayEntry entry)
{
this.Alignment = alignment;
this.DisplayEntry = entry;
}
internal bool SafeForExport()
{
return DisplayEntry.SafeForExport();
}
}
/// <summary>
/// Defines a single row in a table control.
/// </summary>
public sealed class TableControlRow
{
/// <summary>Collection of column definitions for this row</summary>
public List<TableControlColumn> Columns { get; set; }
/// <summary>List of typenames which select this entry</summary>
public EntrySelectedBy SelectedBy { get; internal set; }
/// <summary>When true, instead of truncating to the column width, use multiple lines.</summary>
public bool Wrap { get; set; }
/// <summary>Public constructor for TableControlRow</summary>
public TableControlRow()
{
Columns = new List<TableControlColumn>();
}
internal TableControlRow(TableRowDefinition rowdefinition) : this()
{
Wrap = rowdefinition.multiLine;
if (rowdefinition.appliesTo != null)
{
SelectedBy = EntrySelectedBy.Get(rowdefinition.appliesTo.referenceList);
}
foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList)
{
FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken;
TableControlColumn column;
if (fpt != null)
{
column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment,
fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString);
}
else
{
column = new TableControlColumn();
}
Columns.Add(column);
}
}
/// <summary>Public constructor for TableControlRow.</summary>
public TableControlRow(IEnumerable<TableControlColumn> columns) : this()
{
if (columns == null)
throw PSTraceSource.NewArgumentNullException("columns");
foreach (TableControlColumn column in columns)
{
Columns.Add(column);
}
}
internal bool SafeForExport()
{
foreach (var column in Columns)
{
if (!column.SafeForExport())
return false;
}
return SelectedBy != null && SelectedBy.SafeForExport();
}
internal bool CompatibleWithOldPowerShell()
{
// Old versions of PowerShell don't support multiple row definitions.
return SelectedBy == null;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableRowDefinitionBuilder
{
internal readonly TableControlBuilder _tcb;
internal readonly TableControlRow _tcr;
internal TableRowDefinitionBuilder(TableControlBuilder tcb, TableControlRow tcr)
{
_tcb = tcb;
_tcr = tcr;
}
private TableRowDefinitionBuilder AddItem(string value, DisplayEntryValueType entryType, Alignment alignment, string format)
{
if (string.IsNullOrEmpty(value))
throw PSTraceSource.NewArgumentException("value");
var tableControlColumn = new TableControlColumn(alignment, new DisplayEntry(value, entryType))
{
FormatString = format
};
_tcr.Columns.Add(tableControlColumn);
return this;
}
/// <summary>
/// Add a column to the current row definition that calls a script block.
/// </summary>
public TableRowDefinitionBuilder AddScriptBlockColumn(string scriptBlock, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(scriptBlock, DisplayEntryValueType.ScriptBlock, alignment, format);
}
/// <summary>
/// Add a column to the current row definition that references a property.
/// </summary>
public TableRowDefinitionBuilder AddPropertyColumn(string propertyName, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(propertyName, DisplayEntryValueType.Property, alignment, format);
}
/// <summary>
/// Complete a row definition.
/// </summary>
public TableControlBuilder EndRowDefinition()
{
return _tcb;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableControlBuilder
{
internal readonly TableControl _table;
internal TableControlBuilder(TableControl table)
{
_table = table;
}
/// <summary>Group instances by the property name with an optional label.</summary>
public TableControlBuilder GroupByProperty(string property, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(property, DisplayEntryValueType.Property),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Group instances by the script block expression with an optional label.</summary>
public TableControlBuilder GroupByScriptBlock(string scriptBlock, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Add a header</summary>
public TableControlBuilder AddHeader(Alignment alignment = Alignment.Undefined, int width = 0, string label = null)
{
_table.Headers.Add(new TableControlColumnHeader(label, width, alignment));
return this;
}
/// <summary>Add a header</summary>
public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null)
{
var row = new TableControlRow { Wrap = wrap };
if (entrySelectedByType != null || entrySelectedByCondition != null)
{
row.SelectedBy = new EntrySelectedBy();
if (entrySelectedByType != null)
{
row.SelectedBy.TypeNames = new List<string>(entrySelectedByType);
}
if (entrySelectedByCondition != null)
{
row.SelectedBy.SelectionCondition = new List<DisplayEntry>(entrySelectedByCondition);
}
}
_table.Rows.Add(row);
return new TableRowDefinitionBuilder(this, row);
}
/// <summary>Complete a table definition</summary>
public TableControl EndTable()
{
return _table;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules
{
public class CloudModule : ICloudModule
{
// private static readonly log4net.ILog m_log
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private int m_frameUpdateRate = 1000;
private Random m_rndnums = new Random(Environment.TickCount);
private Scene m_scene = null;
private bool m_ready = false;
private bool m_enabled = false;
private float m_cloudDensity = 1.0F;
private float[] cloudCover = new float[16 * 16];
public void Initialize(Scene scene, IConfigSource config)
{
IConfig cloudConfig = config.Configs["Cloud"];
if (cloudConfig != null)
{
m_enabled = cloudConfig.GetBoolean("enabled", false);
m_cloudDensity = cloudConfig.GetFloat("density", 0.5F);
m_frameUpdateRate = cloudConfig.GetInt("cloud_update_rate", 1000);
}
if (m_enabled)
{
m_scene = scene;
scene.EventManager.OnNewClient += CloudsToClient;
scene.RegisterModuleInterface<ICloudModule>(this);
scene.EventManager.OnFrame += CloudUpdate;
GenerateCloudCover();
m_ready = true;
}
}
public void PostInitialize()
{
}
public void Close()
{
if (m_enabled)
{
m_ready = false;
// Remove our hooks
m_scene.EventManager.OnNewClient -= CloudsToClient;
m_scene.EventManager.OnFrame -= CloudUpdate;
}
}
public string Name
{
get { return "CloudModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
public float CloudCover(int x, int y, int z)
{
float cover = 0f;
x /= 16;
y /= 16;
if (x < 0) x = 0;
if (x > 15) x = 15;
if (y < 0) y = 0;
if (y > 15) y = 15;
if (cloudCover != null)
{
cover = cloudCover[y * 16 + x];
}
return cover;
}
private void UpdateCloudCover()
{
float[] newCover = new float[16 * 16];
int rowAbove = new int();
int rowBelow = new int();
int columnLeft = new int();
int columnRight = new int();
for (int x = 0; x < 16; x++)
{
if (x == 0)
{
columnRight = x + 1;
columnLeft = 15;
}
else if (x == 15)
{
columnRight = 0;
columnLeft = x - 1;
}
else
{
columnRight = x + 1;
columnLeft = x - 1;
}
for (int y = 0; y< 16; y++)
{
if (y == 0)
{
rowAbove = y + 1;
rowBelow = 15;
}
else if (y == 15)
{
rowAbove = 0;
rowBelow = y - 1;
}
else
{
rowAbove = y + 1;
rowBelow = y - 1;
}
float neighborAverage = (cloudCover[rowBelow * 16 + columnLeft] +
cloudCover[y * 16 + columnLeft] +
cloudCover[rowAbove * 16 + columnLeft] +
cloudCover[rowBelow * 16 + x] +
cloudCover[rowAbove * 16 + x] +
cloudCover[rowBelow * 16 + columnRight] +
cloudCover[y * 16 + columnRight] +
cloudCover[rowAbove * 16 + columnRight] +
cloudCover[y * 16 + x]) / 9;
newCover[y * 16 + x] = ((neighborAverage / m_cloudDensity) + 0.175f) % 1.0f;
newCover[y * 16 + x] *= m_cloudDensity;
}
}
Array.Copy(newCover, cloudCover, 16 * 16);
}
private void CloudUpdate()
{
if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready || (m_cloudDensity == 0))
{
return;
}
UpdateCloudCover();
}
public void CloudsToClient(IClientAPI client)
{
if (m_ready)
{
client.SendCloudData(cloudCover);
}
}
/// <summary>
/// Calculate the cloud cover over the region.
/// </summary>
private void GenerateCloudCover()
{
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
cloudCover[y * 16 + x] = (float)(m_rndnums.NextDouble()); // 0 to 1
cloudCover[y * 16 + x] *= m_cloudDensity;
}
}
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtStaticStarfield))]
public class SgtStaticStarfield_Editor : SgtQuads_Editor<SgtStaticStarfield>
{
protected override void OnInspector()
{
var updateMaterial = false;
var updateMeshesAndModels = false;
DrawMaterial(ref updateMaterial);
Separator();
DrawAtlas(ref updateMaterial, ref updateMeshesAndModels);
Separator();
DrawDefault("Seed", ref updateMeshesAndModels);
BeginError(Any(t => t.Radius <= 0.0f));
DrawDefault("Radius", ref updateMeshesAndModels);
EndError();
DrawDefault("Symmetry", ref updateMeshesAndModels);
Separator();
BeginError(Any(t => t.StarCount < 0));
DrawDefault("StarCount", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.StarRadiusMin < 0.0f || t.StarRadiusMin > t.StarRadiusMax));
DrawDefault("StarRadiusMin", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.StarRadiusMax < 0.0f || t.StarRadiusMin > t.StarRadiusMax));
DrawDefault("StarRadiusMax", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.StarRadiusBias < 1.0f));
DrawDefault("StarRadiusBias", ref updateMeshesAndModels);
EndError();
DrawDefault("StarColors", ref updateMeshesAndModels);
RequireObserver();
if (updateMaterial == true) DirtyEach(t => t.UpdateMaterial ());
if (updateMeshesAndModels == true) DirtyEach(t => t.UpdateMeshesAndModels());
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Static Starfield")]
public class SgtStaticStarfield : SgtQuads
{
[Tooltip("The random seed used when generating the stars")]
[SgtSeed]
public int Seed;
[Tooltip("The radius of the starfield")]
public float Radius = 1.0f;
[Tooltip("Should more stars be placed near the horizon?")]
[Range(0.0f, 1.0f)]
public float Symmetry = 1.0f;
[Tooltip("The amount of stars that will be generated in the starfield")]
public int StarCount = 1000;
[Tooltip("The minimum radius of stars in the starfield")]
public float StarRadiusMin = 0.0f;
[Tooltip("The maximum radius of stars in the starfield")]
public float StarRadiusMax = 0.05f;
[Tooltip("How likely the size picking will pick smaller stars over larger ones (1 = default/linear)")]
public float StarRadiusBias = 1.0f;
[Tooltip("Each star is given a random color from this gradient")]
public Gradient StarColors;
protected override string ShaderName
{
get
{
return SgtHelper.ShaderNamePrefix + "StaticStarfield";
}
}
public static SgtStaticStarfield CreateStaticStarfield(int layer = 0, Transform parent = null)
{
return CreateStaticStarfield(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtStaticStarfield CreateStaticStarfield(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Static Starfield", layer, parent, localPosition, localRotation, localScale);
var starfield = gameObject.AddComponent<SgtStaticStarfield>();
return starfield;
}
#if UNITY_EDITOR
[MenuItem(SgtHelper.GameObjectMenuPrefix + "Static Starfield", false, 10)]
private static void CreateStaticStarfieldMenuItem()
{
var parent = SgtHelper.GetSelectedParent();
var starfield = CreateStaticStarfield(parent != null ? parent.gameObject.layer : 0, parent);
SgtHelper.SelectAndPing(starfield);
}
#endif
protected override void OnEnable()
{
base.OnEnable();
Camera.onPreCull += CameraPreCull;
Camera.onPreRender += CameraPreRender;
Camera.onPostRender += CameraPostRender;
}
protected override void OnDisable()
{
base.OnDisable();
Camera.onPreCull -= CameraPreCull;
Camera.onPreRender -= CameraPreRender;
Camera.onPostRender -= CameraPostRender;
}
protected override int BeginQuads()
{
SgtHelper.BeginRandomSeed(Seed);
return StarCount;
}
protected virtual void NextQuad(ref SgtStaticStar quad, int starIndex)
{
var position = Random.insideUnitSphere;
position.y *= Symmetry;
quad.Variant = Random.Range(int.MinValue, int.MaxValue);
quad.Radius = Mathf.Lerp(StarRadiusMin, StarRadiusMax, Mathf.Pow(Random.value, StarRadiusBias));
quad.Position = position.normalized * Radius;
if (StarColors != null)
{
quad.Color = StarColors.Evaluate(Random.value);
}
else
{
quad.Color = Color.white;
}
}
protected override void EndQuads()
{
SgtHelper.EndRandomSeed();
}
protected override void BuildMesh(Mesh mesh, int starIndex, int starCount)
{
var positions = new Vector3[starCount * 4];
var colors = new Color[starCount * 4];
var coords1 = new Vector2[starCount * 4];
var indices = new int[starCount * 6];
var minMaxSet = false;
var min = default(Vector3);
var max = default(Vector3);
for (var i = 0; i < starCount; i++)
{
NextQuad(ref SgtStaticStar.Temp, starIndex + i);
var offV = i * 4;
var offI = i * 6;
var radius = SgtStaticStar.Temp.Radius;
var uv = tempCoords[SgtHelper.Mod(SgtStaticStar.Temp.Variant, tempCoords.Count)];
var rotation = Quaternion.FromToRotation(Vector3.back, SgtStaticStar.Temp.Position);
var up = rotation * Vector3.up * radius;
var right = rotation * Vector3.right * radius;
ExpandBounds(ref minMaxSet, ref min, ref max, SgtStaticStar.Temp.Position, radius);
positions[offV + 0] = SgtStaticStar.Temp.Position - up - right;
positions[offV + 1] = SgtStaticStar.Temp.Position - up + right;
positions[offV + 2] = SgtStaticStar.Temp.Position + up - right;
positions[offV + 3] = SgtStaticStar.Temp.Position + up + right;
colors[offV + 0] =
colors[offV + 1] =
colors[offV + 2] =
colors[offV + 3] = SgtStaticStar.Temp.Color;
coords1[offV + 0] = new Vector2(uv.x, uv.y);
coords1[offV + 1] = new Vector2(uv.z, uv.y);
coords1[offV + 2] = new Vector2(uv.x, uv.w);
coords1[offV + 3] = new Vector2(uv.z, uv.w);
indices[offI + 0] = offV + 0;
indices[offI + 1] = offV + 1;
indices[offI + 2] = offV + 2;
indices[offI + 3] = offV + 3;
indices[offI + 4] = offV + 2;
indices[offI + 5] = offV + 1;
}
mesh.vertices = positions;
mesh.colors = colors;
mesh.uv = coords1;
mesh.triangles = indices;
mesh.bounds = SgtHelper.NewBoundsFromMinMax(min, max);
}
protected virtual void CameraPreCull(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
{
model.transform.position = camera.transform.position;
}
model.Save(camera);
}
}
}
}
protected void CameraPreRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Restore(camera);
}
}
}
}
protected void CameraPostRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
}
}
}
}
}
| |
// 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.Text;
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System
{
// TimeSpan represents a duration of time. A TimeSpan can be negative
// or positive.
//
// TimeSpan is internally represented as a number of milliseconds. While
// this maps well into units of time such as hours and days, any
// periods longer than that aren't representable in a nice fashion.
// For instance, a month can be between 28 and 31 days, while a year
// can contain 365 or 364 days. A decade can have between 1 and 3 leapyears,
// depending on when you map the TimeSpan into the calendar. This is why
// we do not provide Years() or Months().
//
// Note: System.TimeSpan needs to interop with the WinRT structure
// type Windows::Foundation:TimeSpan. These types are currently binary-compatible in
// memory so no custom marshalling is required. If at any point the implementation
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
[System.Runtime.InteropServices.ComVisible(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
public const long TicksPerMillisecond = 10000;
private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond;
public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000
private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000
private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9
public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000
private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11
public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000
private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60; // 60,000
private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000
private const int MillisPerDay = MillisPerHour * 24; // 86,400,000
internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond;
internal const long MinSeconds = Int64.MinValue / TicksPerSecond;
internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond;
internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond;
internal const long TicksPerTenthSecond = TicksPerMillisecond * 100;
public static readonly TimeSpan Zero = new TimeSpan(0);
public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue);
public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue);
// internal so that DateTime doesn't have to call an extra get
// method for some arithmetic operations.
internal long _ticks;
public TimeSpan(long ticks)
{
this._ticks = ticks;
}
public TimeSpan(int hours, int minutes, int seconds)
{
_ticks = TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
: this(days, hours, minutes, seconds, 0)
{
}
public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
{
Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds;
if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds)
throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
_ticks = (long)totalMilliSeconds * TicksPerMillisecond;
}
public long Ticks
{
get { return _ticks; }
}
public int Days
{
get { return (int)(_ticks / TicksPerDay); }
}
public int Hours
{
get { return (int)((_ticks / TicksPerHour) % 24); }
}
public int Milliseconds
{
get { return (int)((_ticks / TicksPerMillisecond) % 1000); }
}
public int Minutes
{
get { return (int)((_ticks / TicksPerMinute) % 60); }
}
public int Seconds
{
get { return (int)((_ticks / TicksPerSecond) % 60); }
}
public double TotalDays
{
get { return ((double)_ticks) * DaysPerTick; }
}
public double TotalHours
{
get { return (double)_ticks * HoursPerTick; }
}
public double TotalMilliseconds
{
get
{
double temp = (double)_ticks * MillisecondsPerTick;
if (temp > MaxMilliSeconds)
return (double)MaxMilliSeconds;
if (temp < MinMilliSeconds)
return (double)MinMilliSeconds;
return temp;
}
}
public double TotalMinutes
{
get { return (double)_ticks * MinutesPerTick; }
}
public double TotalSeconds
{
get { return (double)_ticks * SecondsPerTick; }
}
public TimeSpan Add(TimeSpan ts)
{
long result = _ticks + ts._ticks;
// Overflow if signs of operands was identical and result's
// sign was opposite.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
// Compares two TimeSpan values, returning an integer that indicates their
// relationship.
//
public static int Compare(TimeSpan t1, TimeSpan t2)
{
if (t1._ticks > t2._ticks) return 1;
if (t1._ticks < t2._ticks) return -1;
return 0;
}
// Returns a value less than zero if this object
int IComparable.CompareTo(Object value)
{
if (value == null) return 1;
if (!(value is TimeSpan))
throw new ArgumentException(SR.Arg_MustBeTimeSpan);
long t = ((TimeSpan)value)._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public int CompareTo(TimeSpan value)
{
long t = value._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public static TimeSpan FromDays(double value)
{
return Interval(value, MillisPerDay);
}
public TimeSpan Duration()
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_Duration);
Contract.EndContractBlock();
return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks);
}
public override bool Equals(Object value)
{
if (value is TimeSpan)
{
return _ticks == ((TimeSpan)value)._ticks;
}
return false;
}
public bool Equals(TimeSpan obj)
{
return _ticks == obj._ticks;
}
public static bool Equals(TimeSpan t1, TimeSpan t2)
{
return t1._ticks == t2._ticks;
}
public override int GetHashCode()
{
return (int)_ticks ^ (int)(_ticks >> 32);
}
public static TimeSpan FromHours(double value)
{
return Interval(value, MillisPerHour);
}
private static TimeSpan Interval(double value, int scale)
{
if (Double.IsNaN(value))
throw new ArgumentException(SR.Arg_CannotBeNaN);
Contract.EndContractBlock();
double tmp = value * scale;
double millis = tmp + (value >= 0 ? 0.5 : -0.5);
if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan((long)millis * TicksPerMillisecond);
}
public static TimeSpan FromMilliseconds(double value)
{
return Interval(value, 1);
}
public static TimeSpan FromMinutes(double value)
{
return Interval(value, MillisPerMinute);
}
public TimeSpan Negate()
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return new TimeSpan(-_ticks);
}
public static TimeSpan FromSeconds(double value)
{
return Interval(value, MillisPerSecond);
}
public TimeSpan Subtract(TimeSpan ts)
{
long result = _ticks - ts._ticks;
// Overflow if signs of operands was different and result's
// sign was opposite from the first argument's sign.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
public static TimeSpan FromTicks(long value)
{
return new TimeSpan(value);
}
internal static long TimeToTicks(int hour, int minute, int second)
{
// totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31,
// which is less than 2^44, meaning we won't overflow totalSeconds.
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
return totalSeconds * TicksPerSecond;
}
// See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat
#region ParseAndFormat
private static void ValidateStyles(TimeSpanStyles style, String parameterName)
{
if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative)
throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName);
}
public static TimeSpan Parse(String s)
{
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
return FormatProvider.ParseTimeSpan(s, null);
}
public static TimeSpan Parse(String input, IFormatProvider formatProvider)
{
return FormatProvider.ParseTimeSpan(input, formatProvider);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider)
{
return FormatProvider.ParseTimeSpanExact(input, format, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider)
{
return FormatProvider.ParseTimeSpanExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, "styles");
return FormatProvider.ParseTimeSpanExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, "styles");
return FormatProvider.ParseTimeSpanExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result)
{
return FormatProvider.TryParseTimeSpan(s, null, out result);
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result)
{
return FormatProvider.TryParseTimeSpan(input, formatProvider, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result)
{
return FormatProvider.TryParseTimeSpanExact(input, format, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result)
{
return FormatProvider.TryParseTimeSpanExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, "styles");
return FormatProvider.TryParseTimeSpanExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, "styles");
return FormatProvider.TryParseTimeSpanExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString()
{
return FormatProvider.FormatTimeSpan(this, null, null);
}
public String ToString(String format)
{
return FormatProvider.FormatTimeSpan(this, format, null);
}
public String ToString(String format, IFormatProvider formatProvider)
{
return FormatProvider.FormatTimeSpan(this, format, formatProvider);
}
#endregion
public static TimeSpan operator -(TimeSpan t)
{
if (t._ticks == TimeSpan.MinValue._ticks)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
return new TimeSpan(-t._ticks);
}
public static TimeSpan operator -(TimeSpan t1, TimeSpan t2)
{
return t1.Subtract(t2);
}
public static TimeSpan operator +(TimeSpan t)
{
return t;
}
public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)
{
return t1.Add(t2);
}
public static bool operator ==(TimeSpan t1, TimeSpan t2)
{
return t1._ticks == t2._ticks;
}
public static bool operator !=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks != t2._ticks;
}
public static bool operator <(TimeSpan t1, TimeSpan t2)
{
return t1._ticks < t2._ticks;
}
public static bool operator <=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks <= t2._ticks;
}
public static bool operator >(TimeSpan t1, TimeSpan t2)
{
return t1._ticks > t2._ticks;
}
public static bool operator >=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks >= t2._ticks;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using DowUtils;
namespace Factotum{
public class EGridProcedure : IEntity
{
public static event EventHandler<EntityChangedEventArgs> Changed;
public static event EventHandler GridProcedureOutageAssignmentsChanged;
protected virtual void OnChanged(Guid? ID)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<EntityChangedEventArgs> temp = Changed;
if (temp != null)
temp(this, new EntityChangedEventArgs(ID));
}
protected virtual void OnGridProcedureOutageAssignmentsChanged()
{
EventHandler temp = GridProcedureOutageAssignmentsChanged;
if (temp != null)
temp(this, new EventArgs());
}
// Mapped database columns
// Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not).
// Use int?, decimal?, etc for nullable numbers
// Strings, images, etc, are reference types already
private Guid? GrpDBid;
private string GrpName;
private string GrpDescription;
private short? GrpDsDiameters;
private bool GrpIsLclChg;
private bool GrpUsedInOutage;
private bool GrpIsActive;
// This is used by ListWithAssignmentsForOutage() to indicate whether or not
// the current grid procedure is assigned to the specified outage.
private bool isAssignedToYourOutage;
// Textbox limits
public static int GrpNameCharLimit = 50;
public static int GrpDescriptionCharLimit = 255;
public static int GrpDsDiametersCharLimit = 6;
// Field-specific error message strings (normally just needed for textbox data)
private string GrpNameErrMsg;
private string GrpDescriptionErrMsg;
private string GrpDsDiametersErrMsg;
// Form level validation message
private string GrpErrMsg;
//--------------------------------------------------------
// Field Properties
//--------------------------------------------------------
// Primary key accessor
public Guid? ID
{
get { return GrpDBid; }
}
public string GridProcedureName
{
get { return GrpName; }
set { GrpName = Util.NullifyEmpty(value); }
}
public string GridProcedureDescription
{
get { return GrpDescription; }
set { GrpDescription = Util.NullifyEmpty(value); }
}
public short? GridProcedureDsDiameters
{
get { return GrpDsDiameters; }
set { GrpDsDiameters = value; }
}
public bool GridProcedureIsLclChg
{
get { return GrpIsLclChg; }
set { GrpIsLclChg = value; }
}
public bool GridProcedureUsedInOutage
{
get { return GrpUsedInOutage; }
set { GrpUsedInOutage = value; }
}
public bool GridProcedureIsActive
{
get { return GrpIsActive; }
set { GrpIsActive = value; }
}
// This is used by ListWithAssignmentsForOutage() to indicate whether or not
// the current grid procedure is assigned to the specified outage.
public bool IsAssignedToYourOutage
{
get { return isAssignedToYourOutage; }
set { isAssignedToYourOutage = value; }
}
//-----------------------------------------------------------------
// Field Level Error Messages.
// Include one for every text column
// In cases where we need to ensure data consistency, we may need
// them for other types.
//-----------------------------------------------------------------
public string GridProcedureNameErrMsg
{
get { return GrpNameErrMsg; }
}
public string GridProcedureDescriptionErrMsg
{
get { return GrpDescriptionErrMsg; }
}
public string GridProcedureDsDiametersErrMsg
{
get { return GrpDsDiametersErrMsg; }
}
//--------------------------------------
// Form level Error Message
//--------------------------------------
public string GridProcedureErrMsg
{
get { return GrpErrMsg; }
set { GrpErrMsg = Util.NullifyEmpty(value); }
}
//--------------------------------------
// Textbox Name Length Validation
//--------------------------------------
public bool GridProcedureNameLengthOk(string s)
{
if (s == null) return true;
if (s.Length > GrpNameCharLimit)
{
GrpNameErrMsg = string.Format("Grid Procedure Names cannot exceed {0} characters", GrpNameCharLimit);
return false;
}
else
{
GrpNameErrMsg = null;
return true;
}
}
public bool GridProcedureDescriptionLengthOk(string s)
{
if (s == null) return true;
if (s.Length > GrpDescriptionCharLimit)
{
GrpDescriptionErrMsg = string.Format("Grid Procedure Descriptions cannot exceed {0} characters", GrpDescriptionCharLimit);
return false;
}
else
{
GrpDescriptionErrMsg = null;
return true;
}
}
public bool GridProcedureDsDiametersLengthOk(string s)
{
if (s == null) return true;
if (s.Length > GrpDsDiametersCharLimit)
{
GrpDsDiametersErrMsg = string.Format("Grid Procedure D/S Diameters cannot exceed {0} characters", GrpDsDiametersCharLimit);
return false;
}
else
{
GrpDsDiametersErrMsg = null;
return true;
}
}
//--------------------------------------
// Field-Specific Validation
// sets and clears error messages
//--------------------------------------
public bool GridProcedureNameValid(string name)
{
bool existingIsInactive;
if (!GridProcedureNameLengthOk(name)) return false;
// KEEP, MODIFY OR REMOVE THIS AS REQUIRED
// YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC..
if (NameExists(name, GrpDBid, out existingIsInactive))
{
GrpNameErrMsg = existingIsInactive ?
"A Grid Procedure with that Name exists but its status has been set to inactive." :
"That Grid Procedure Name is already in use.";
return false;
}
GrpNameErrMsg = null;
return true;
}
public bool GridProcedureDescriptionValid(string value)
{
if (!GridProcedureDescriptionLengthOk(value)) return false;
GrpNameErrMsg = null;
return true;
}
public bool GridProcedureDsDiametersValid(string value)
{
// Add some real validation here if needed.
short result;
if (Util.IsNullOrEmpty(value))
{
GrpDsDiametersErrMsg = null;
return true;
}
if (short.TryParse(value, out result) && result > 0 && result < 100)
{
GrpDsDiametersErrMsg = null;
return true;
}
GrpDsDiametersErrMsg = string.Format("Please enter a positive number less than 100");
return false;
}
//--------------------------------------
// Constructors
//--------------------------------------
// Default constructor. Field defaults must be set here.
// Any defaults set by the database will be overridden.
public EGridProcedure()
{
this.GrpIsLclChg = false;
this.GrpUsedInOutage = false;
this.GrpIsActive = true;
}
// Constructor which loads itself from the supplied id.
// If the id is null, this gives the same result as using the default constructor.
public EGridProcedure(Guid? id) : this()
{
Load(id);
}
//--------------------------------------
// Public Methods
//--------------------------------------
//----------------------------------------------------
// Load the object from the database given a Guid?
//----------------------------------------------------
public void Load(Guid? id)
{
if (id == null) return;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
SqlCeDataReader dr;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Select
GrpDBid,
GrpName,
GrpDescription,
GrpDsDiameters,
GrpIsLclChg,
GrpUsedInOutage,
GrpIsActive
from GridProcedures
where GrpDBid = @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// The query should return one record.
// If it doesn't return anything (no match) the object is not affected
if (dr.Read())
{
// For nullable foreign keys, set field to null for dbNull case
// For other nullable values, replace dbNull with null
GrpDBid = (Guid?)dr[0];
GrpName = (string)dr[1];
GrpDescription = (string)Util.NullForDbNull(dr[2]);
GrpDsDiameters = (short?)Util.NullForDbNull(dr[3]);
GrpIsLclChg = (bool)dr[4];
GrpUsedInOutage = (bool)dr[5];
GrpIsActive = (bool)dr[6];
}
dr.Close();
}
//--------------------------------------
// Save the current record if it's valid
//--------------------------------------
public Guid? Save()
{
if (!Valid())
{
// Note: We're returning null if we fail,
// so don't just assume you're going to get your id back
// and set your id to the result of this function call.
return null;
}
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
if (ID == null)
{
// we are inserting a new record
// If this is not a master db, set the local change flag to true.
if (!Globals.IsMasterDB) GrpIsLclChg = true;
// first ask the database for a new Guid
cmd.CommandText = "Select Newid()";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
GrpDBid = (Guid?)(cmd.ExecuteScalar());
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", GrpDBid),
new SqlCeParameter("@p1", GrpName),
new SqlCeParameter("@p2", Util.DbNullForNull(GrpDescription)),
new SqlCeParameter("@p3", Util.DbNullForNull(GrpDsDiameters)),
new SqlCeParameter("@p4", GrpIsLclChg),
new SqlCeParameter("@p5", GrpUsedInOutage),
new SqlCeParameter("@p6", GrpIsActive)
});
cmd.CommandText = @"Insert Into GridProcedures (
GrpDBid,
GrpName,
GrpDescription,
GrpDsDiameters,
GrpIsLclChg,
GrpUsedInOutage,
GrpIsActive
) values (@p0,@p1,@p2,@p3,@p4,@p5,@p6)";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert Grid Procedures row");
}
}
else
{
// we are updating an existing record
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", GrpDBid),
new SqlCeParameter("@p1", GrpName),
new SqlCeParameter("@p2", Util.DbNullForNull(GrpDescription)),
new SqlCeParameter("@p3", Util.DbNullForNull(GrpDsDiameters)),
new SqlCeParameter("@p4", GrpIsLclChg),
new SqlCeParameter("@p5", GrpUsedInOutage),
new SqlCeParameter("@p6", GrpIsActive)});
cmd.CommandText =
@"Update GridProcedures
set
GrpName = @p1,
GrpDescription = @p2,
GrpDsDiameters = @p3,
GrpIsLclChg = @p4,
GrpUsedInOutage = @p5,
GrpIsActive = @p6
Where GrpDBid = @p0";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to update grid procedures row");
}
}
OnChanged(ID);
return ID;
}
//--------------------------------------
// Validate the current record
//--------------------------------------
// Make this public so that the UI can check validation itself
// if it chooses to do so. This is also called by the Save function.
public bool Valid()
{
// First check each field to see if it's valid from the UI perspective
if (!GridProcedureNameValid(GridProcedureName)) return false;
if (!GridProcedureDescriptionValid(GridProcedureDescription)) return false;
// Check form to make sure all required fields have been filled in
if (!RequiredFieldsFilled()) return false;
// Check for incorrect field interactions...
return true;
}
//--------------------------------------
// Delete the current record
//--------------------------------------
public bool Delete(bool promptUser)
{
// If the current object doesn't reference a database record, there's nothing to do.
if (GrpDBid == null)
{
GridProcedureErrMsg = "Unable to delete. Record not found.";
return false;
}
if (GrpUsedInOutage)
{
GridProcedureErrMsg = "Unable to delete because this Grid Procedure has been used in past outages.\r\nYou may wish to inactivate it instead.";
return false;
}
if (!GrpIsLclChg && !Globals.IsMasterDB)
{
GridProcedureErrMsg = "Unable to delete this Grid Procedure because it was not added during this outage.\r\nYou may wish to inactivate it instead.";
return false;
}
if (HasInspectedComponents())
{
GridProcedureErrMsg = "Unable to delete because this Grid Procedure is referenced by one or more Component Reports.";
return false;
}
if (HasOutages())
{
GridProcedureErrMsg = "Unable to delete because this Grid Procedure is referenced by one or more outages.";
return false;
}
DialogResult rslt = DialogResult.None;
if (promptUser)
{
rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
}
if (!promptUser || rslt == DialogResult.OK)
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Delete from GridProcedures
where GrpDBid = @p0";
cmd.Parameters.Add("@p0", GrpDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
// Todo: figure out how I really want to do this.
// Is there a problem with letting the database try to do cascading deletes?
// How should the user be notified of the problem??
if (rowsAffected < 1)
{
GridProcedureErrMsg = "Unable to delete. Please try again later.";
return false;
}
else
{
GridProcedureErrMsg = null;
OnChanged(ID);
return true;
}
}
else
{
return false;
}
}
private bool HasInspectedComponents()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select IscDBid from InspectedComponents
where IscGrpID = @p0";
cmd.Parameters.Add("@p0", GrpDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
return result != null;
}
private bool HasOutages()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select OgpOtgID from OutageGridProcedures
where OgpGrpID = @p0";
cmd.Parameters.Add("@p0", GrpDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
return result != null;
}
//--------------------------------------------------------------------
// Static listing methods which return collections of gridprocedures
//--------------------------------------------------------------------
// This helper function builds the collection for you based on the flags you send it
// I originally had a flag that would let you indicate inactive items by appending '(inactive)'
// to the name. This was a bad idea, because sometimes the objects in this collection
// will get modified and saved back to the database -- with the extra text appended to the name.
public static EGridProcedureCollection ListByName(
bool showactive, bool showinactive, bool addNoSelection)
{
EGridProcedure gridprocedure;
EGridProcedureCollection gridprocedures = new EGridProcedureCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
GrpDBid,
GrpName,
GrpDescription,
GrpDsDiameters,
GrpIsLclChg,
GrpUsedInOutage,
GrpIsActive
from GridProcedures";
if (showactive && !showinactive)
qry += " where GrpIsActive = 1";
else if (!showactive && showinactive)
qry += " where GrpIsActive = 0";
qry += " order by GrpName";
cmd.CommandText = qry;
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
gridprocedure = new EGridProcedure();
gridprocedure.GrpName = "<No Selection>";
gridprocedures.Add(gridprocedure);
}
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
gridprocedure = new EGridProcedure((Guid?)dr[0]);
gridprocedure.GrpName = (string)(dr[1]);
gridprocedure.GrpDescription = (string)Util.NullForDbNull(dr[2]);
gridprocedure.GrpDsDiameters = (short?)(dr[3]);
gridprocedure.GrpIsLclChg = (bool)(dr[4]);
gridprocedure.GrpUsedInOutage = (bool)(dr[5]);
gridprocedure.GrpIsActive = (bool)(dr[6]);
gridprocedures.Add(gridprocedure);
}
// Finish up
dr.Close();
return gridprocedures;
}
// This helper function builds the collection for you based on the flags you send it
// I originally had a flag that would let you indicate inactive items by appending '(inactive)'
// to the name. This was a bad idea, because sometimes the objects in this collection
// will get modified and saved back to the database -- with the extra text appended to the name.
public static EGridProcedureCollection ListForOutage(Guid outageID,
bool showinactive, bool addNoSelection)
{
EGridProcedure gridprocedure;
EGridProcedureCollection gridprocedures = new EGridProcedureCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
GrpDBid,
GrpName,
GrpDescription,
GrpDsDiameters,
GrpIsLclChg,
GrpUsedInOutage,
GrpIsActive
from GridProcedures
left outer join OutageGridProcedures
on GrpDBid = OgpGrpID";
qry += " where OgpOtgID = @p1";
if (!showinactive)
qry += " and GrpIsActive = 1";
qry += " order by GrpName";
cmd.CommandText = qry;
cmd.Parameters.Add("@p1", outageID);
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
gridprocedure = new EGridProcedure();
gridprocedure.GrpName = "<No Selection>";
gridprocedures.Add(gridprocedure);
}
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
gridprocedure = new EGridProcedure((Guid?)dr[0]);
gridprocedure.GrpName = (string)(dr[1]);
gridprocedure.GrpDescription = (string)Util.NullForDbNull(dr[2]);
gridprocedure.GrpDsDiameters = (short?)Util.NullForDbNull(dr[3]);
gridprocedure.GrpIsLclChg = (bool)(dr[4]);
gridprocedure.GrpUsedInOutage = (bool)(dr[5]);
gridprocedure.GrpIsActive = (bool)(dr[6]);
gridprocedures.Add(gridprocedure);
}
// Finish up
dr.Close();
return gridprocedures;
}
// This helper function builds the collection for you based on the flags you send it
// To fill a checked listbox you may want to set 'includeUnassigned'
// To fill a treeview, you probably don't.
public static EGridProcedureCollection ListWithAssignmentsForOutage(Guid? OutageID,
bool showactive, bool showinactive)
{
EGridProcedure grp;
EGridProcedureCollection grps = new EGridProcedureCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry =
@"
Select
GrpDBid,
GrpName,
GrpDescription,
GrpDsDiameters,
GrpIsLclChg,
GrpUsedInOutage,
GrpIsActive,
Max(Case OutageGridProcedures.OgpOtgID
when @p1 then 1
else 0
end) as IsAssigned
From GridProcedures
left outer join OutageGridProcedures
on GridProcedures.GrpDBid = OutageGridProcedures.OgpGrpID";
if (showactive && !showinactive)
qry +=
@"
where GrpIsActive = 1";
else if (!showactive && showinactive)
qry +=
@" where GrpIsActive = 0";
qry +=
@"
Group by GrpName, GrpDBid, GrpDescription,
GrpDsDiameters, GrpIsLclChg, GrpUsedInOutage,
GrpIsActive";
cmd.CommandText = qry;
cmd.Parameters.Add("@p1", OutageID == null ? Guid.Empty : OutageID);
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
grp = new EGridProcedure((Guid?)dr[0]);
grp.GridProcedureName = (string)dr[1];
grp.GridProcedureDescription = (string)Util.NullForDbNull(dr[2]);
grp.GridProcedureDsDiameters = (short?)Util.NullForDbNull(dr[3]);
grp.GridProcedureIsLclChg = (bool)dr[4];
grp.GridProcedureUsedInOutage = (bool)dr[5];
grp.GridProcedureIsActive = (bool)dr[6];
grp.IsAssignedToYourOutage = Convert.ToBoolean(dr[7]);
grps.Add(grp);
}
// Finish up
dr.Close();
return grps;
}
public static void UpdateAssignmentsToOutage(Guid? OutageID, EGridProcedureCollection grps)
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
// First delete any existing grid procedure assignments (except those that are
// used in reports)
cmd.CommandText =
@"Delete from OutageGridProcedures
where OgpOtgID = @p1
and not exists(
select IscDBid from InspectedComponents
where IscGrpID = OgpGrpID)";
cmd.Parameters.Add("@p1", OutageID);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
cmd.ExecuteNonQuery();
cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select OgpOtgID from OutageGridProcedures
where OgpOtgID = @p1 and OgpGrpID = @p2";
cmd.Parameters.Add("@p1", OutageID);
cmd.Parameters.Add("@p2", "");
SqlCeCommand cmd2 = Globals.cnn.CreateCommand();
cmd2.CommandText =
@"Insert Into OutageGridProcedures (OgpOtgID, OgpGrpID)
values (@p1, @p2)";
cmd2.Parameters.Add("@p1", OutageID);
cmd2.Parameters.Add("@p2", "");
// Now insert the current grid procedure assignments (except those that are
// used in reports)
foreach (EGridProcedure grp in grps)
{
if (grp.isAssignedToYourOutage)
{
cmd.Parameters["@p2"].Value = grp.ID;
cmd2.Parameters["@p2"].Value = grp.ID;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteScalar() == null)
{
if (cmd2.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert Outage Grid Procedures row");
}
}
}
}
// Just throw one event for all
EGridProcedure gridproc = new EGridProcedure();
gridproc.OnGridProcedureOutageAssignmentsChanged();
}
// Get a Default data view with all columns that a user would likely want to see.
// You can bind this view to a DataGridView, hide the columns you don't need, filter, etc.
// I decided not to indicate inactive in the names of inactive items. The 'user'
// can always show the inactive column if they wish.
// Pass a null outage id if you don't want to limit to the current outage.
public static DataView GetDefaultDataView(Guid? OutageID)
{
DataSet ds = new DataSet();
DataView dv;
SqlCeDataAdapter da = new SqlCeDataAdapter();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
// Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and
// makes the column sortable.
// You'll likely want to modify this query further, joining in other tables, etc.
string qry = @"Select
GrpDBid as ID,
GrpName as GridProcedureName,
GrpDsDiameters as GridProcedureDsDiameters,
GrpDescription as GridProcedureDescription,
CASE
WHEN GrpIsLclChg = 0 THEN 'No'
ELSE 'Yes'
END as GridProcedureIsLclChg,
CASE
WHEN GrpUsedInOutage = 0 THEN 'No'
ELSE 'Yes'
END as GridProcedureUsedInOutage,
CASE
WHEN GrpIsActive = 0 THEN 'No'
ELSE 'Yes'
END as GridProcedureIsActive
from GridProcedures";
if (OutageID != null)
{
qry +=
@" Inner join OutageGridProcedures on GrpDBid = OgpGrpID
where OgpOtgID = @p1";
cmd.Parameters.Add("@p1", OutageID);
}
cmd.CommandText = qry;
da.SelectCommand = cmd;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
da.Fill(ds);
dv = new DataView(ds.Tables[0]);
return dv;
}
// Check if the name exists for any records besides the current one
// This is used to show an error when the user tabs away from the field.
// We don't want to show an error if the user has left the field blank.
// If it's a required field, we'll catch it when the user hits save.
private bool NameExists(string name, Guid? id, out bool existingIsInactive)
{
existingIsInactive = false;
if (Util.IsNullOrEmpty(name)) return false;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlCeParameter("@p1", name));
if (id == null)
{
cmd.CommandText = "Select GrpIsActive from GridProcedures where GrpName = @p1";
}
else
{
cmd.CommandText = "Select GrpIsActive from GridProcedures where GrpName = @p1 and GrpDBid != @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
}
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object val = cmd.ExecuteScalar();
bool exists = (val != null);
if (exists) existingIsInactive = !(bool)val;
return exists;
}
// Check for required fields, setting the individual error messages
private bool RequiredFieldsFilled()
{
bool allFilled = true;
if (GridProcedureName == null)
{
GrpNameErrMsg = "A unique Grid Procedure Name is required";
allFilled = false;
}
else
{
GrpNameErrMsg = null;
}
return allFilled;
}
}
//--------------------------------------
// GridProcedure Collection class
//--------------------------------------
public class EGridProcedureCollection : CollectionBase
{
//this event is fired when the collection's items have changed
public event EventHandler Changed;
//this is the constructor of the collection.
public EGridProcedureCollection()
{ }
//the indexer of the collection
public EGridProcedure this[int index]
{
get
{
return (EGridProcedure)this.List[index];
}
}
//this method fires the Changed event.
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
public bool ContainsID(Guid? ID)
{
if (ID == null) return false;
foreach (EGridProcedure gridprocedure in InnerList)
{
if (gridprocedure.ID == ID)
return true;
}
return false;
}
//returns the index of an item in the collection
public int IndexOf(EGridProcedure item)
{
return InnerList.IndexOf(item);
}
//adds an item to the collection
public void Add(EGridProcedure item)
{
this.List.Add(item);
OnChanged(EventArgs.Empty);
}
//inserts an item in the collection at a specified index
public void Insert(int index, EGridProcedure item)
{
this.List.Insert(index, item);
OnChanged(EventArgs.Empty);
}
//removes an item from the collection.
public void Remove(EGridProcedure item)
{
this.List.Remove(item);
OnChanged(EventArgs.Empty);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Threading
{
using System;
using System.Security;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM,
// to schedule all managed timers in the AppDomain.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
internal class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
private static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
//
// We need to keep our notion of time synchronized with the calls to SleepEx that drive
// the underlying native timer. In Win8, SleepEx does not count the time the machine spends
// sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time,
// so we will get out of sync with SleepEx if we use that method.
//
// So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent
// in sleep/hibernate mode.
//
private static int TickCount
{
get
{
#if !FEATURE_PAL
if (Environment.IsWindows8OrAbove)
{
ulong time100ns;
bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns);
if (!result)
throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
// convert to 100ns to milliseconds, and truncate to 32 bits.
return (int)(uint)(time100ns / 10000);
}
else
#endif
{
return Environment.TickCount;
}
}
}
//
// We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
//
private class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public AppDomainTimerSafeHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return DeleteAppDomainTimer(handle);
}
}
private AppDomainTimerSafeHandle m_appDomainTimer;
private bool m_isAppDomainTimerScheduled;
private int m_currentAppDomainTimerStartTicks;
private uint m_currentAppDomainTimerDuration;
private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (m_isAppDomainTimerScheduled)
{
uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks);
if (elapsed >= m_currentAppDomainTimerDuration)
return true; //the timer's about to fire
uint remainingDuration = m_currentAppDomainTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return true; //the timer will fire earlier than this request
}
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if (m_pauseTicks != 0)
{
Debug.Assert(!m_isAppDomainTimerScheduled);
Debug.Assert(m_appDomainTimer == null);
return true;
}
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
Debug.Assert(!m_isAppDomainTimerScheduled);
m_appDomainTimer = CreateAppDomainTimer(actualDuration);
if (!m_appDomainTimer.IsInvalid)
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
else
{
if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration))
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
}
//
// The VM calls this when the native timer fires.
//
internal static void AppDomainTimerCallback()
{
Instance.FireNextTimers();
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool DeleteAppDomainTimer(IntPtr handle);
#endregion
#region Firing timers
//
// The list of timers
//
private TimerQueueTimer m_timers;
private volatile int m_pauseTicks = 0; // Time when Pause was called
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
lock (this)
{
// prevent ThreadAbort while updating state
try { }
finally
{
//
// since we got here, that means our previous timer has fired.
//
m_isAppDomainTimerScheduled = false;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timeout.UnsignedInfinite)
{
timer.m_startTicks = nowTicks;
timer.m_dueTime = timer.m_period;
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timeout.UnsignedInfinite)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = m_timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
m_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period;
timer.m_startTicks = TickCount;
return EnsureAppDomainTimerFiresBy(dueTime);
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timeout.UnsignedInfinite)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (m_timers == timer)
m_timers = timer.m_next;
timer.m_dueTime = Timeout.UnsignedInfinite;
timer.m_period = Timeout.UnsignedInfinite;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
internal sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
private readonly TimerCallback m_timerCallback;
private readonly Object m_state;
private readonly ExecutionContext m_executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set m_canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
private int m_callbacksRunning;
private volatile bool m_canceled;
private volatile WaitHandle m_notifyWhenNoCallbacksRunning;
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timeout.UnsignedInfinite;
m_period = Timeout.UnsignedInfinite;
m_executionContext = ExecutionContext.Capture();
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timeout.UnsignedInfinite)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (TimerQueue.Instance)
{
if (m_canceled)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
// prevent ThreadAbort while updating state
try { }
finally
{
m_period = period;
if (dueTime == Timeout.UnsignedInfinite)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true);
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
}
return success;
}
public void Close()
{
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
}
public bool Close(WaitHandle toSignal)
{
bool success;
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (m_canceled)
{
success = false;
}
else
{
m_canceled = true;
m_notifyWhenNoCallbacksRunning = toSignal;
TimerQueue.Instance.DeleteTimer(this);
if (m_callbacksRunning == 0)
shouldSignal = true;
success = true;
}
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
return success;
}
internal void Fire()
{
bool canceled = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
canceled = m_canceled;
if (!canceled)
m_callbacksRunning++;
}
}
if (canceled)
return;
CallCallback();
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
m_callbacksRunning--;
if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null)
shouldSignal = true;
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
}
internal void SignalNoCallbacksRunning()
{
Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle);
}
internal void CallCallback()
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty);
// call directly if EC flow is suppressed
if (m_executionContext == null)
{
m_timerCallback(m_state);
}
else
{
ExecutionContext.Run(m_executionContext, s_callCallbackInContext, this);
}
}
private static readonly ContextCallback s_callCallbackInContext = state =>
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
};
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
internal sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run in this AppDomain.
//
if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload())
return;
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
public bool Close(WaitHandle notifyObject)
{
bool result = m_timer.Close(notifyObject);
GC.SuppressFinalize(this);
return result;
}
}
public sealed class Timer : MarshalByRefObject, IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder m_timer;
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException(nameof(dueTm), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTm), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm);
}
[CLSCompliant(false)]
public Timer(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
TimerSetup(callback, state, dueTime, period);
}
public Timer(TimerCallback callback,
Object state,
long dueTime,
long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period);
}
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
public bool Change(int dueTime, int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
[CLSCompliant(false)]
public bool Change(UInt32 dueTime, UInt32 period)
{
return m_timer.m_timer.Change(dueTime, period);
}
public bool Change(long dueTime, long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject == null)
throw new ArgumentNullException(nameof(notifyObject));
Contract.EndContractBlock();
return m_timer.Close(notifyObject);
}
public void Dispose()
{
m_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(m_timer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ModestTree;
using Assert=ModestTree.Assert;
using Zenject;
#if ZEN_SIGNALS_ADD_UNIRX
using UniRx;
#endif
namespace ZenjectSignalsAndSignals.Tests
{
[TestFixture]
public class TestSignals2 : ZenjectIntegrationTestFixture
{
[SetUp]
public void CommonInstall()
{
Container.BindInterfacesAndSelfTo<SignalManager>().AsSingle();
}
[Test]
public void TestToSingle1()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.Bind<Bar>().AsSingle();
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsSingle();
Initialize();
Container.Resolve<Bar>();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.IsEqual(Bar.InstanceCount, 1);
Assert.IsEqual(Bar.TriggeredCount, 0);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 1);
Assert.IsEqual(Bar.TriggeredCount, 1);
}
[Test]
[ValidateOnly]
public void TestValidationFailure()
{
Container.Bind<Qux>().AsSingle();
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).FromResolve();
Assert.Throws(() => Initialize());
}
[Test]
[ValidateOnly]
public void TestValidationSuccess()
{
Container.Bind<Qux>().AsSingle();
Container.Bind<Bar>().AsSingle();
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).FromResolve();
Initialize();
}
[Test]
public void TestToCached1()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.Bind<Bar>().AsCached();
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsCached();
Initialize();
Container.Resolve<Bar>();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.IsEqual(Bar.InstanceCount, 1);
Assert.IsEqual(Bar.TriggeredCount, 0);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 1);
Assert.IsEqual(Bar.InstanceCount, 2);
cmd.Fire();
Assert.IsEqual(Bar.InstanceCount, 2);
Assert.IsEqual(Bar.TriggeredCount, 2);
}
[Test]
public void TestNoHandlerDefault()
{
Container.DeclareSignal<DoSomethingSignal>();
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
cmd.Fire();
}
[Test]
public void TestNoHandlerRequiredFailure()
{
Container.DeclareSignal<DoSomethingSignal>().RequireHandler();
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.Throws(() => cmd.Fire());
}
[Test]
public void TestNoHandlerRequiredSuccess()
{
Container.DeclareSignal<DoSomethingSignal>().RequireHandler();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsCached();
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
cmd.Fire();
}
[Test]
public void TestHandlerRequiredEventStyle()
{
Container.DeclareSignal<DoSomethingSignal>().RequireHandler();
Initialize();
var signal = Container.Resolve<DoSomethingSignal>();
Assert.Throws(() => signal.Fire());
bool received = false;
Action receiveSignal = () => received = true;
signal += receiveSignal;
Assert.That(!received);
signal.Fire();
Assert.That(received);
signal -= receiveSignal;
Assert.Throws(() => signal.Fire());
}
#if ZEN_SIGNALS_ADD_UNIRX
[Test]
public void TestHandlerRequiredUniRxStyle()
{
Container.DeclareSignal<DoSomethingSignal>().RequireHandler();
Initialize();
var signal = Container.Resolve<DoSomethingSignal>();
Assert.Throws(() => signal.Fire());
bool received = false;
var subscription = signal.AsObservable.Subscribe((x) => received = true);
Assert.That(!received);
signal.Fire();
Assert.That(received);
subscription.Dispose();
Assert.Throws(() => signal.Fire());
}
#endif
[Test]
public void TestToMethod()
{
bool wasCalled = false;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To(() => wasCalled = true);
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.That(!wasCalled);
cmd.Fire();
Assert.That(wasCalled);
}
[Test]
public void TestMultipleHandlers()
{
bool wasCalled1 = false;
bool wasCalled2 = false;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To(() => wasCalled1 = true);
Container.BindSignal<DoSomethingSignal>()
.To(() => wasCalled2 = true);
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.That(!wasCalled1);
Assert.That(!wasCalled2);
cmd.Fire();
Assert.That(wasCalled1);
Assert.That(wasCalled2);
}
[Test]
public void TestFromNewTransient()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsTransient();
Initialize();
TestBarHandlerTransient();
}
[Test]
public void TestFromNewCached()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsCached();
Initialize();
TestBarHandlerCached();
}
[Test]
public void TestFromNewSingle()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).AsSingle();
Initialize();
TestBarHandlerCached();
}
[Test]
public void TestFromMethod()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).FromMethod(_ => new Bar());
Initialize();
TestBarHandlerTransient();
}
[Test]
public void TestFromMethodMultiple()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).FromMethodMultiple(_ => new[] { new Bar(), new Bar() });
Initialize();
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.IsEqual(Bar.TriggeredCount, 0);
Assert.IsEqual(Bar.InstanceCount, 0);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 2);
Assert.IsEqual(Bar.InstanceCount, 2);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 4);
Assert.IsEqual(Bar.InstanceCount, 4);
}
[Test]
public void TestFromMethodMultipleEmpty()
{
Bar.TriggeredCount = 0;
Bar.InstanceCount = 0;
Container.DeclareSignal<DoSomethingSignal>();
Container.BindSignal<DoSomethingSignal>()
.To<Bar>(x => x.Execute).FromMethodMultiple(_ => new Bar[] {});
Initialize();
var signal = Container.Resolve<DoSomethingSignal>();
Assert.Throws(() => signal.Fire());
}
void TestBarHandlerTransient()
{
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.IsEqual(Bar.TriggeredCount, 0);
Assert.IsEqual(Bar.InstanceCount, 0);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 1);
Assert.IsEqual(Bar.InstanceCount, 1);
cmd.Fire();
Assert.IsEqual(Bar.InstanceCount, 2);
Assert.IsEqual(Bar.TriggeredCount, 2);
}
void TestBarHandlerCached()
{
var cmd = Container.Resolve<DoSomethingSignal>();
Assert.IsEqual(Bar.TriggeredCount, 0);
Assert.IsEqual(Bar.InstanceCount, 0);
cmd.Fire();
Assert.IsEqual(Bar.TriggeredCount, 1);
Assert.IsEqual(Bar.InstanceCount, 1);
cmd.Fire();
Assert.IsEqual(Bar.InstanceCount, 1);
Assert.IsEqual(Bar.TriggeredCount, 2);
}
public class DoSomethingSignal : Signal<DoSomethingSignal>
{
}
public class Qux
{
public Qux(Bar bar)
{
}
}
public class Bar
{
public static int InstanceCount = 0;
public Bar()
{
InstanceCount++;
}
public static int TriggeredCount
{
get;
set;
}
public void Execute()
{
TriggeredCount++;
}
}
}
}
| |
using System;
/// <summary>
/// System.Enum.IConvertibleToUint32(System.Type,IFormatProvider )
/// </summary>
public class EnumIConvertibleToUint32
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert an enum of zero to Uint32");
try
{
color c1 = color.blue;
IConvertible i1 = c1 as IConvertible;
UInt32 u1 = i1.ToUInt32(null);
if (u1 != 0)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Test a system defined enum type");
try
{
Enum e2 = System.StringComparison.OrdinalIgnoreCase;
UInt32 l2 = (e2 as IConvertible).ToUInt32(null);
if (l2 != 5)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an enum of Uint32.maxvalue to Uint32");
try
{
color c1 = color.white;
IConvertible i1 = c1 as IConvertible;
UInt32 u1 = i1.ToUInt32(null);
if (u1 != UInt32.MaxValue)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an enum of negative zero to Uint32 ");
try
{
color c1 = color.red;
IConvertible i1 = c1 as IConvertible;
UInt32 u1 = i1.ToUInt32(null);
if (u1 != 0)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an enum of negative value to Uint32");
try
{
e_test e1 = e_test.itemA;
IConvertible i1 = e1 as IConvertible;
UInt32 u1 = i1.ToUInt32(null);
TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: Convert an enum of the value which is bigger than uint32.maxvalue to Uint32");
try
{
e_test e1 = e_test.itemB;
IConvertible i1 = e1 as IConvertible;
UInt32 u1 = i1.ToUInt32(null);
TestLibrary.TestFramework.LogError("103", "The OverflowException was not thrown as expected");
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
EnumIConvertibleToUint32 test = new EnumIConvertibleToUint32();
TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToUint32");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
enum color : uint
{
blue = 0,
white = UInt32.MaxValue,
red = -0,
}
enum e_test : long
{
itemA = -123,
itemB = Int64.MaxValue,
itemC = Int64.MaxValue,
itemD = -0,
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Text;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.IO;
namespace PdfSharp.Pdf
{
/// <summary>
/// Represents a PDF array object.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay}")]
public class PdfArray : PdfObject, IEnumerable<PdfItem>
{
/// <summary>
/// Initializes a new instance of the <see cref="PdfArray"/> class.
/// </summary>
public PdfArray()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="PdfArray"/> class.
/// </summary>
/// <param name="document">The document.</param>
public PdfArray(PdfDocument document)
: base(document)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="PdfArray"/> class.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="items">The items.</param>
public PdfArray(PdfDocument document, params PdfItem[] items)
: base(document)
{
foreach (PdfItem item in items)
Elements.Add(item);
}
/// <summary>
/// Initializes a new instance from an existing dictionary. Used for object type transformation.
/// </summary>
/// <param name="array">The array.</param>
protected PdfArray(PdfArray array)
: base(array)
{
if (array._elements != null)
array._elements.ChangeOwner(this);
}
/// <summary>
/// Creates a copy of this array. Direct elements are deep copied.
/// Indirect references are not modified.
/// </summary>
public new PdfArray Clone()
{
return (PdfArray)Copy();
}
/// <summary>
/// Implements the copy mechanism.
/// </summary>
protected override object Copy()
{
PdfArray array = (PdfArray)base.Copy();
if (array._elements != null)
{
array._elements = array._elements.Clone();
int count = array._elements.Count;
for (int idx = 0; idx < count; idx++)
{
PdfItem item = array._elements[idx];
if (item is PdfObject)
array._elements[idx] = item.Clone();
}
}
return array;
}
/// <summary>
/// Gets the collection containing the elements of this object.
/// </summary>
public ArrayElements Elements
{
get { return _elements ?? (_elements = new ArrayElements(this)); }
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
public virtual IEnumerator<PdfItem> GetEnumerator()
{
return Elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Returns a string with the content of this object in a readable form. Useful for debugging purposes only.
/// </summary>
public override string ToString()
{
StringBuilder pdf = new StringBuilder();
pdf.Append("[ ");
int count = Elements.Count;
for (int idx = 0; idx < count; idx++)
pdf.Append(Elements[idx] + " ");
pdf.Append("]");
return pdf.ToString();
}
internal override void WriteObject(PdfWriter writer)
{
writer.WriteBeginObject(this);
int count = Elements.Count;
for (int idx = 0; idx < count; idx++)
{
PdfItem value = Elements[idx];
value.WriteObject(writer);
}
writer.WriteEndObject();
}
/// <summary>
/// Represents the elements of an PdfArray.
/// </summary>
public sealed class ArrayElements : IList<PdfItem>, ICloneable
{
internal ArrayElements(PdfArray array)
{
_elements = new List<PdfItem>();
_ownerArray = array;
}
object ICloneable.Clone()
{
ArrayElements elements = (ArrayElements)MemberwiseClone();
elements._elements = new List<PdfItem>(elements._elements);
elements._ownerArray = null;
return elements;
}
/// <summary>
/// Creates a shallow copy of this object.
/// </summary>
public ArrayElements Clone()
{
return (ArrayElements)((ICloneable)this).Clone();
}
/// <summary>
/// Moves this instance to another array during object type transformation.
/// </summary>
internal void ChangeOwner(PdfArray array)
{
if (_ownerArray != null)
{
// ???
}
// Set new owner.
_ownerArray = array;
// Set owners elements to this.
array._elements = this;
}
/// <summary>
/// Converts the specified value to boolean.
/// If the value does not exist, the function returns false.
/// If the value is not convertible, the function throws an InvalidCastException.
/// If the index is out of range, the function throws an ArgumentOutOfRangeException.
/// </summary>
public bool GetBoolean(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
object obj = this[index];
if (obj == null)
return false;
PdfBoolean boolean = obj as PdfBoolean;
if (boolean != null)
return boolean.Value;
PdfBooleanObject booleanObject = obj as PdfBooleanObject;
if (booleanObject != null)
return booleanObject.Value;
throw new InvalidCastException("GetBoolean: Object is not a boolean.");
}
/// <summary>
/// Converts the specified value to integer.
/// If the value does not exist, the function returns 0.
/// If the value is not convertible, the function throws an InvalidCastException.
/// If the index is out of range, the function throws an ArgumentOutOfRangeException.
/// </summary>
public int GetInteger(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
object obj = this[index];
if (obj == null)
return 0;
PdfInteger integer = obj as PdfInteger;
if (integer != null)
return integer.Value;
PdfIntegerObject integerObject = obj as PdfIntegerObject;
if (integerObject != null)
return integerObject.Value;
throw new InvalidCastException("GetInteger: Object is not an integer.");
}
/// <summary>
/// Converts the specified value to double.
/// If the value does not exist, the function returns 0.
/// If the value is not convertible, the function throws an InvalidCastException.
/// If the index is out of range, the function throws an ArgumentOutOfRangeException.
/// </summary>
public double GetReal(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
object obj = this[index];
if (obj == null)
return 0;
PdfReal real = obj as PdfReal;
if (real != null)
return real.Value;
PdfRealObject realObject = obj as PdfRealObject;
if (realObject != null)
return realObject.Value;
PdfInteger integer = obj as PdfInteger;
if (integer != null)
return integer.Value;
PdfIntegerObject integerObject = obj as PdfIntegerObject;
if (integerObject != null)
return integerObject.Value;
throw new InvalidCastException("GetReal: Object is not a number.");
}
/// <summary>
/// Converts the specified value to string.
/// If the value does not exist, the function returns the empty string.
/// If the value is not convertible, the function throws an InvalidCastException.
/// If the index is out of range, the function throws an ArgumentOutOfRangeException.
/// </summary>
public string GetString(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
object obj = this[index];
if (obj == null)
return String.Empty;
PdfString str = obj as PdfString;
if (str != null)
return str.Value;
PdfStringObject strObject = obj as PdfStringObject;
if (strObject != null)
return strObject.Value;
throw new InvalidCastException("GetString: Object is not a string.");
}
/// <summary>
/// Converts the specified value to a name.
/// If the value does not exist, the function returns the empty string.
/// If the value is not convertible, the function throws an InvalidCastException.
/// If the index is out of range, the function throws an ArgumentOutOfRangeException.
/// </summary>
public string GetName(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
object obj = this[index];
if (obj == null)
return String.Empty;
PdfName name = obj as PdfName;
if (name != null)
return name.Value;
PdfNameObject nameObject = obj as PdfNameObject;
if (nameObject != null)
return nameObject.Value;
throw new InvalidCastException("GetName: Object is not a name.");
}
/// <summary>
/// Returns the indirect object if the value at the specified index is a PdfReference.
/// </summary>
[Obsolete("Use GetObject, GetDictionary, GetArray, or GetReference")]
public PdfObject GetIndirectObject(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
PdfReference reference = this[index] as PdfReference;
if (reference != null)
return reference.Value;
return null;
}
/// <summary>
/// Gets the PdfObject with the specified index, or null, if no such object exists. If the index refers to
/// a reference, the referenced PdfObject is returned.
/// </summary>
public PdfObject GetObject(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.IndexOutOfRange);
PdfItem item = this[index];
PdfReference reference = item as PdfReference;
if (reference != null)
return reference.Value;
return item as PdfObject;
}
/// <summary>
/// Gets the PdfArray with the specified index, or null, if no such object exists. If the index refers to
/// a reference, the referenced PdfArray is returned.
/// </summary>
public PdfDictionary GetDictionary(int index)
{
return GetObject(index) as PdfDictionary;
}
/// <summary>
/// Gets the PdfArray with the specified index, or null, if no such object exists. If the index refers to
/// a reference, the referenced PdfArray is returned.
/// </summary>
public PdfArray GetArray(int index)
{
return GetObject(index) as PdfArray;
}
/// <summary>
/// Gets the PdfReference with the specified index, or null, if no such object exists.
/// </summary>
public PdfReference GetReference(int index)
{
PdfItem item = this[index];
return item as PdfReference;
}
/// <summary>
/// Gets all items of this array.
/// </summary>
public PdfItem[] Items
{
get { return _elements.ToArray(); }
}
#region IList Members
/// <summary>
/// Returns false.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets or sets an item at the specified index.
/// </summary>
/// <value></value>
public PdfItem this[int index]
{
get { return _elements[index]; }
set
{
if (value == null)
throw new ArgumentNullException("value");
_elements[index] = value;
}
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
public void RemoveAt(int index)
{
_elements.RemoveAt(index);
}
/// <summary>
/// Removes the first occurrence of a specific object from the array/>.
/// </summary>
public bool Remove(PdfItem item)
{
return _elements.Remove(item);
}
/// <summary>
/// Inserts the item the specified index.
/// </summary>
public void Insert(int index, PdfItem value)
{
_elements.Insert(index, value);
}
/// <summary>
/// Determines whether the specified value is in the array.
/// </summary>
public bool Contains(PdfItem value)
{
return _elements.Contains(value);
}
/// <summary>
/// Removes all items from the array.
/// </summary>
public void Clear()
{
_elements.Clear();
}
/// <summary>
/// Gets the index of the specified item.
/// </summary>
public int IndexOf(PdfItem value)
{
return _elements.IndexOf(value);
}
/// <summary>
/// Appends the specified object to the array.
/// </summary>
public void Add(PdfItem value)
{
// TODO: ???
//Debug.Assert((value is PdfObject && ((PdfObject)value).Reference == null) | !(value is PdfObject),
// "You try to set an indirect object directly into an array.");
PdfObject obj = value as PdfObject;
if (obj != null && obj.IsIndirect)
_elements.Add(obj.Reference);
else
_elements.Add(value);
}
/// <summary>
/// Returns false.
/// </summary>
public bool IsFixedSize
{
get { return false; }
}
#endregion
#region ICollection Members
/// <summary>
/// Returns false.
/// </summary>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets the number of elements in the array.
/// </summary>
public int Count
{
get { return _elements.Count; }
}
/// <summary>
/// Copies the elements of the array to the specified array.
/// </summary>
public void CopyTo(PdfItem[] array, int index)
{
_elements.CopyTo(array, index);
}
/// <summary>
/// The current implementation return null.
/// </summary>
public object SyncRoot
{
get { return null; }
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the array.
/// </summary>
public IEnumerator<PdfItem> GetEnumerator()
{
return _elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _elements.GetEnumerator();
}
/// <summary>
/// The elements of the array.
/// </summary>
List<PdfItem> _elements;
/// <summary>
/// The array this objects belongs to.
/// </summary>
PdfArray _ownerArray;
}
ArrayElements _elements;
/// <summary>
/// Gets the DebuggerDisplayAttribute text.
/// </summary>
// ReSharper disable UnusedMember.Local
string DebuggerDisplay
// ReSharper restore UnusedMember.Local
{
get
{
#if true
return String.Format(CultureInfo.InvariantCulture, "array({0},[{1}])", ObjectID.DebuggerDisplay, _elements == null ? 0 : _elements.Count);
#else
return String.Format(CultureInfo.InvariantCulture, "array({0},[{1}])", ObjectID.DebuggerDisplay, _elements == null ? 0 : _elements.Count);
#endif
}
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class XInventoryServicesConnector : IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private object m_Lock = new object();
public XInventoryServicesConnector()
{
}
public XInventoryServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public XInventoryServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["InventoryService"];
if (assetConfig == null)
{
m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
throw new Exception("Inventory connector init error");
}
string serviceURI = assetConfig.GetString("InventoryServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService");
throw new Exception("Inventory connector init error");
}
m_ServerURI = serviceURI;
}
private bool CheckReturn(Dictionary<string, object> ret)
{
if (ret == null)
return false;
if (ret.Count == 0)
return false;
if (ret.ContainsKey("RESULT"))
{
if (ret["RESULT"] is string)
{
bool result;
if (bool.TryParse((string)ret["RESULT"], out result))
return result;
return false;
}
}
return true;
}
public bool CreateUserInventory(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("CREATEUSERINVENTORY",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
return CheckReturn(ret);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETINVENTORYSKELETON",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> folders = (Dictionary<string, object>)ret["FOLDERS"];
List<InventoryFolderBase> fldrs = new List<InventoryFolderBase>();
try
{
foreach (Object o in folders.Values)
fldrs.Add(BuildFolder((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception unwrapping folder list: ", e);
}
return fldrs;
}
public InventoryFolderBase GetRootFolder(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETROOTFOLDER",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERFORTYPE",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "TYPE", ((int)type).ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
inventory.UserID = principalID;
try
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERCONTENT",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string,object> folders =
(Dictionary<string,object>)ret["FOLDERS"];
Dictionary<string,object> items =
(Dictionary<string,object>)ret["ITEMS"];
foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i
inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o));
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
inventory.Items.Add(BuildItem((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolderContent: {0}", e.Message);
}
return inventory;
}
public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> items = (Dictionary<string, object>)ret["ITEMS"];
List<InventoryItemBase> fitems = new List<InventoryItemBase>();
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
fitems.Add(BuildItem((Dictionary<string, object>)o));
return fitems;
}
public bool AddFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("ADDFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("UPDATEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool MoveFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("MOVEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "ID", folder.ID.ToString() },
{ "PRINCIPAL", folder.Owner.ToString() }
});
return CheckReturn(ret);
}
public bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in folderIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEFOLDERS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDERS", slist }
});
return CheckReturn(ret);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("PURGEFOLDER",
new Dictionary<string,object> {
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool AddItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("ADDITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("UPDATEITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
List<string> idlist = new List<string>();
List<string> destlist = new List<string>();
foreach (InventoryItemBase item in items)
{
idlist.Add(item.ID.ToString());
destlist.Add(item.Folder.ToString());
}
Dictionary<string,object> ret = MakeRequest("MOVEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "IDLIST", idlist },
{ "DESTLIST", destlist }
});
return CheckReturn(ret);
}
public bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in itemIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "ITEMS", slist }
});
return CheckReturn(ret);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETITEM",
new Dictionary<string, object> {
{ "ID", item.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildItem((Dictionary<string, object>)ret["item"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetItem: ", e);
}
return null;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETFOLDER",
new Dictionary<string, object> {
{ "ID", folder.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolder: ", e);
}
return null;
}
public List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETACTIVEGESTURES",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
List<InventoryItemBase> items = new List<InventoryItemBase>();
foreach (Object o in ((Dictionary<string,object>)ret["ITEMS"]).Values)
items.Add(BuildItem((Dictionary<string, object>)o));
return items;
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
Dictionary<string,object> ret = MakeRequest("GETASSETPERMISSIONS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "ASSET", assetID.ToString() }
});
// We cannot use CheckReturn() here because valid values for RESULT are "false" (in the case of request failure) or an int
if (ret == null)
return 0;
if (ret.ContainsKey("RESULT"))
{
if (ret["RESULT"] is string)
{
int intResult;
if (int.TryParse ((string)ret["RESULT"], out intResult))
return intResult;
}
}
return 0;
}
public InventoryCollection GetUserInventory(UUID principalID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
inventory.UserID = principalID;
try
{
Dictionary<string, object> ret = MakeRequest("GETUSERINVENTORY",
new Dictionary<string, object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> folders =
(Dictionary<string, object>)ret["FOLDERS"];
Dictionary<string, object> items =
(Dictionary<string, object>)ret["ITEMS"];
foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i
inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o));
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
inventory.Items.Add(BuildItem((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetUserInventory: ", e);
}
return inventory;
}
public void GetUserInventory(UUID principalID, InventoryReceiptCallback callback)
{
}
public bool HasInventoryForUser(UUID principalID)
{
return false;
}
// Helpers
//
private Dictionary<string,object> MakeRequest(string method,
Dictionary<string,object> sendData)
{
sendData["METHOD"] = method;
string reply = string.Empty;
lock (m_Lock)
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/xinventory",
ServerUtils.BuildQueryString(sendData));
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(
reply);
return replyData;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
try
{
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception building folder: ", e);
}
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
try
{
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
if (data.ContainsKey("CreatorData"))
item.CreatorData = data["CreatorData"].ToString();
else
item.CreatorData = String.Empty;
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY CONNECTOR]: Exception building item: ", e);
}
return item;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFiltersOperations operations.
/// </summary>
internal partial class RouteFiltersOperations : IServiceOperations<NetworkManagementClient>, IRouteFiltersOperations
{
/// <summary>
/// Initializes a new instance of the RouteFiltersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteFiltersOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilter>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilter> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteFilter>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilter> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (routeFilterParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("routeFilterParameters", routeFilterParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilter>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (routeFilterParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeFilterName", routeFilterName);
tracingParameters.Add("routeFilterParameters", routeFilterParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeFilterParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteFilter>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilter>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteFilter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteFilter>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilter>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.Net;
using System.Net.Http.Headers;
using FluentAssertions;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Serialization.Objects;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ContentNegotiation;
public sealed class AcceptHeaderTests : IClassFixture<IntegrationTestContext<TestableStartup<PolicyDbContext>, PolicyDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<PolicyDbContext>, PolicyDbContext> _testContext;
public AcceptHeaderTests(IntegrationTestContext<TestableStartup<PolicyDbContext>, PolicyDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
testContext.UseController<PoliciesController>();
}
[Fact]
public async Task Permits_no_Accept_headers()
{
// Arrange
const string route = "/policies";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Permits_no_Accept_headers_at_operations_endpoint()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "policies",
attributes = new
{
name = "some"
}
}
}
}
};
const string route = "/operations";
const string contentType = HeaderConstants.AtomicOperationsMediaType;
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecutePostAsync<Document>(route, requestBody, contentType);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Permits_global_wildcard_in_Accept_headers()
{
// Arrange
const string route = "/policies";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/html"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("*/*"));
};
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<Document>(route, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Permits_application_wildcard_in_Accept_headers()
{
// Arrange
const string route = "/policies";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/html;q=0.8"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/*;q=0.2"));
};
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<Document>(route, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Permits_JsonApi_without_parameters_in_Accept_headers()
{
// Arrange
const string route = "/policies";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/html"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; profile=some"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; ext=other"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; unknown=unexpected"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; q=0.3"));
};
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<Document>(route, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Permits_JsonApi_with_AtomicOperations_extension_in_Accept_headers_at_operations_endpoint()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "policies",
attributes = new
{
name = "some"
}
}
}
}
};
const string route = "/operations";
const string contentType = HeaderConstants.AtomicOperationsMediaType;
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/html"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; profile=some"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(HeaderConstants.MediaType));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; unknown=unexpected"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType};ext=\"https://jsonapi.org/ext/atomic\"; q=0.2"));
};
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecutePostAsync<Document>(route, requestBody, contentType, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Denies_JsonApi_with_parameters_in_Accept_headers()
{
// Arrange
const string route = "/policies";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/html"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; profile=some"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; ext=other"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse($"{HeaderConstants.MediaType}; unknown=unexpected"));
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(HeaderConstants.AtomicOperationsMediaType));
};
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotAcceptable);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
error.Title.Should().Be("The specified Accept header value does not contain any supported media types.");
error.Detail.Should().Be("Please include 'application/vnd.api+json' in the Accept header values.");
error.Source.ShouldNotBeNull();
error.Source.Header.Should().Be("Accept");
}
[Fact]
public async Task Denies_JsonApi_in_Accept_headers_at_operations_endpoint()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "add",
data = new
{
type = "policies",
attributes = new
{
name = "some"
}
}
}
}
};
const string route = "/operations";
const string contentType = HeaderConstants.AtomicOperationsMediaType;
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(HeaderConstants.MediaType));
};
// Act
(HttpResponseMessage httpResponse, Document responseDocument) =
await _testContext.ExecutePostAsync<Document>(route, requestBody, contentType, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotAcceptable);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
error.Title.Should().Be("The specified Accept header value does not contain any supported media types.");
error.Detail.Should().Be("Please include 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"' in the Accept header values.");
error.Source.ShouldNotBeNull();
error.Source.Header.Should().Be("Accept");
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Build.Evaluation;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using Clipboard = System.Windows.Forms.Clipboard;
using Task = System.Threading.Tasks.Task;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using VsMenus = Microsoft.VisualStudioTools.Project.VsMenus;
namespace Microsoft.PythonTools.Project {
/// <summary>
/// Represents an interpreter as a node in the Solution Explorer.
/// </summary>
[ComVisible(true)]
internal class InterpretersNode : HierarchyNode {
private readonly IInterpreterRegistryService _interpreterService;
internal readonly IPythonInterpreterFactory _factory;
private readonly bool _isReference;
private readonly bool _canDelete, _canRemove;
private readonly string _captionSuffix;
private readonly FileSystemWatcher _fileWatcher;
private readonly Timer _timer;
private bool _checkedItems, _checkingItems, _disposed;
internal readonly bool _isGlobalDefault;
public static readonly object InstallPackageLockMoniker = new object();
public InterpretersNode(
PythonProjectNode project,
IPythonInterpreterFactory factory,
bool isInterpreterReference,
bool canDelete,
bool isGlobalDefault = false
)
: base(project, MakeElement(project)) {
ExcludeNodeFromScc = true;
_interpreterService = project.Site.GetComponentModel().GetService<IInterpreterRegistryService>();
_factory = factory;
_isReference = isInterpreterReference;
_canDelete = canDelete;
_isGlobalDefault = isGlobalDefault;
_canRemove = !isGlobalDefault;
_captionSuffix = isGlobalDefault ? Strings.GlobalDefaultSuffix : "";
if (Directory.Exists(_factory.Configuration.LibraryPath)) {
// TODO: Need to handle watching for creation
try {
_fileWatcher = new FileSystemWatcher(_factory.Configuration.LibraryPath);
} catch (ArgumentException) {
// Path was not actually valid, despite Directory.Exists
// returning true.
}
if (_fileWatcher != null) {
try {
_fileWatcher.IncludeSubdirectories = true;
_fileWatcher.Deleted += PackagesChanged;
_fileWatcher.Created += PackagesChanged;
_fileWatcher.EnableRaisingEvents = true;
// Only create the timer if the file watcher is running.
_timer = new Timer(CheckPackages);
} catch (IOException) {
// Raced with directory deletion
_fileWatcher.Dispose();
_fileWatcher = null;
}
}
}
}
public override int MenuCommandId {
get { return PythonConstants.EnvironmentMenuId; }
}
public override Guid MenuGroupId {
get { return GuidList.guidPythonToolsCmdSet; }
}
private static ProjectElement MakeElement(PythonProjectNode project) {
return new VirtualProjectElement(project);
}
public override void Close() {
if (!_disposed && _fileWatcher != null) {
_fileWatcher.Dispose();
_timer.Dispose();
}
_disposed = true;
base.Close();
}
/// <summary>
/// Disables the file watcher. This function may be called as many times
/// as you like, but it only requires one call to
/// <see cref="ResumeWatching"/> to re-enable the watcher.
/// </summary>
public void StopWatching() {
if (!_disposed && _fileWatcher != null) {
try {
_fileWatcher.EnableRaisingEvents = false;
} catch (IOException) {
} catch (ObjectDisposedException) {
}
}
}
/// <summary>
/// Enables the file watcher, regardless of how many times
/// <see cref="StopWatching"/> was called. If the file watcher was
/// enabled successfully, the list of packages is updated.
/// </summary>
public void ResumeWatching() {
if (!_disposed && _fileWatcher != null) {
try {
_fileWatcher.EnableRaisingEvents = true;
CheckPackages(null);
} catch (IOException) {
} catch (ObjectDisposedException) {
}
}
}
private void PackagesChanged(object sender, FileSystemEventArgs e) {
// have a delay before refreshing because there's probably more than one write,
// so we wait until things have been quiet for a second.
_timer.Change(1000, Timeout.Infinite);
}
private void CheckPackages(object arg) {
ProjectMgr.Site.GetUIThread().InvokeTask(() => CheckPackagesAsync())
.HandleAllExceptions(ProjectMgr.Site, GetType())
.DoNotWait();
}
private async Task CheckPackagesAsync() {
var uiThread = ProjectMgr.Site.GetUIThread();
uiThread.MustBeCalledFromUIThreadOrThrow();
bool prevChecked = _checkedItems;
// Use _checkingItems to prevent the expanded state from
// disappearing too quickly.
_checkingItems = true;
_checkedItems = true;
if (!Directory.Exists(_factory.Configuration.LibraryPath)) {
_checkingItems = false;
ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Expandable, 0);
return;
}
HashSet<string> lines;
bool anyChanges = false;
try {
lines = await Pip.List(_factory).ConfigureAwait(true);
} catch (MissingInterpreterException) {
return;
} catch (NoInterpretersException) {
return;
} catch (FileNotFoundException) {
return;
}
// Ensure we are back on the UI thread
uiThread.MustBeCalledFromUIThread();
if (ProjectMgr == null || ProjectMgr.IsClosed) {
return;
}
var existing = AllChildren.ToDictionary(c => c.Url);
// remove the nodes which were uninstalled.
foreach (var keyValue in existing) {
if (!lines.Contains(keyValue.Key)) {
RemoveChild(keyValue.Value);
anyChanges = true;
}
}
// remove already existing nodes so we don't add them a 2nd time
lines.ExceptWith(existing.Keys);
// add the new nodes
foreach (var line in lines) {
AddChild(new InterpretersPackageNode(ProjectMgr, line));
anyChanges = true;
var packageInfo = PythonProjectNode.FindRequirementRegex.Match(line.ToLower());
if (packageInfo.Groups["name"].Success) {
//Log the details of the Installation
var packageDetails = new Logging.PackageInstallDetails(
packageInfo.Groups["name"].Value,
packageInfo.Groups["ver"].Success ? packageInfo.Groups["ver"].Value : String.Empty,
_factory.GetType().Name,
_factory.Configuration.Version.ToString(),
_factory.Configuration.Architecture.ToString(),
"Existing", //Installer if we tracked it
false, //Installer was not run elevated
0); //The installation already existed
ProjectMgr.Site.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.PackageInstalled, packageDetails);
}
}
_checkingItems = false;
ProjectMgr.OnInvalidateItems(this);
if (!prevChecked) {
if (anyChanges) {
ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Expandable, 0);
}
if (ProjectMgr.ParentHierarchy != null) {
ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder);
}
}
if (prevChecked && anyChanges) {
var withDb = _factory as IPythonInterpreterFactoryWithDatabase;
if (withDb != null) {
withDb.GenerateDatabase(GenerateDatabaseOptions.SkipUnchanged);
}
}
}
public override Guid ItemTypeGuid {
get { return PythonConstants.InterpreterItemTypeGuid; }
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case CommonConstants.OpenFolderInExplorerCmdId:
Process.Start(new ProcessStartInfo {
FileName = _factory.Configuration.PrefixPath,
Verb = "open",
UseShellExecute = true
});
return VSConstants.S_OK;
}
}
if (cmdGroup == ProjectMgr.SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.OpenCommandPromptHere:
var pyProj = ProjectMgr as PythonProjectNode;
if (pyProj != null && _factory != null && _factory.Configuration != null) {
return pyProj.OpenCommandPrompt(
_factory.Configuration.PrefixPath,
_factory.Configuration,
_factory.Configuration.FullDescription
);
}
break;
case SharedCommands.CopyFullPath:
Clipboard.SetText(_factory.Configuration.InterpreterPath);
return VSConstants.S_OK;
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
public new PythonProjectNode ProjectMgr {
get {
return (PythonProjectNode)base.ProjectMgr;
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (_interpreterService.IsInterpreterLocked(_factory, InstallPackageLockMoniker)) {
// Prevent the environment from being deleted while installing.
return false;
}
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) {
// Interpreter and InterpreterReference can both be removed from
// the project, but the default environment cannot
return _canRemove;
} else if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
// Only Interpreter can be deleted.
return _canDelete;
}
return false;
}
public override bool Remove(bool removeFromStorage) {
// If _canDelete, a prompt has already been shown by VS.
return Remove(removeFromStorage, !_canDelete);
}
private bool Remove(bool removeFromStorage, bool showPrompt) {
if (!_canRemove || (removeFromStorage && !_canDelete)) {
// Prevent the environment from being deleted or removed if not
// supported.
throw new NotSupportedException();
}
if (_interpreterService.IsInterpreterLocked(_factory, InstallPackageLockMoniker)) {
// Prevent the environment from being deleted while installing.
// This situation should not occur through the UI, but might be
// invocable through DTE.
return false;
}
if (showPrompt && !Utilities.IsInAutomationFunction(ProjectMgr.Site)) {
string message = (removeFromStorage ?
Strings.EnvironmentDeleteConfirmation :
Strings.EnvironmentRemoveConfirmation
).FormatUI(
Caption,
_factory.Configuration.PrefixPath
);
int res = VsShellUtilities.ShowMessageBox(
ProjectMgr.Site,
string.Empty,
message,
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
if (res != 1) {
return false;
}
}
//Make sure we can edit the project file
if (!ProjectMgr.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
ProjectMgr.RemoveInterpreter(_factory, !_isReference && removeFromStorage && _canDelete);
return true;
}
/// <summary>
/// Show interpreter display (description and version).
/// </summary>
public override string Caption {
get {
return _factory.Configuration.FullDescription + _captionSuffix;
}
}
/// <summary>
/// Prevent editing the description
/// </summary>
public override string GetEditLabel() {
return null;
}
protected override VSOVERLAYICON OverlayIconIndex {
get {
if (!Directory.Exists(Url)) {
return (VSOVERLAYICON)__VSOVERLAYICON2.OVERLAYICON_NOTONDISK;
} else if (_isReference) {
return VSOVERLAYICON.OVERLAYICON_SHORTCUT;
}
return base.OverlayIconIndex;
}
}
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
if (!_factory.Configuration.IsAvailable()) {
// TODO: Find a better icon
return KnownMonikers.DocumentWarning;
} else if (ProjectMgr.ActiveInterpreter == _factory) {
return KnownMonikers.ActiveEnvironment;
}
// TODO: Change to PYEnvironment
return KnownMonikers.DockPanel;
}
/// <summary>
/// Interpreter node cannot be dragged.
/// </summary>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
/// <summary>
/// Disable Copy/Cut/Paste commands on interpreter node.
/// </summary>
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case CommonConstants.OpenFolderInExplorerCmdId:
result = QueryStatusResult.SUPPORTED;
if (_factory != null && Directory.Exists(_factory.Configuration.PrefixPath)) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
if (cmdGroup == GuidList.guidPythonToolsCmdSet) {
switch (cmd) {
case PythonConstants.ActivateEnvironment:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable() &&
ProjectMgr.ActiveInterpreter != _factory &&
Directory.Exists(_factory.Configuration.PrefixPath)
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.InstallPythonPackage:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.PrefixPath)
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.InstallRequirementsTxt:
result |= QueryStatusResult.SUPPORTED;
if (File.Exists(PathUtils.GetAbsoluteFilePath(ProjectMgr.ProjectHome, "requirements.txt"))) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.GenerateRequirementsTxt:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable()) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.OpenInteractiveForEnvironment:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable() &&
File.Exists(_factory.Configuration.InterpreterPath)
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
if (cmdGroup == ProjectMgr.SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.OpenCommandPromptHere:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.PrefixPath) &&
File.Exists(_factory.Configuration.InterpreterPath)) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case SharedCommands.CopyFullPath:
result |= QueryStatusResult.SUPPORTED;
if (_factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.PrefixPath) &&
File.Exists(_factory.Configuration.InterpreterPath)) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
public override string Url {
get {
if (!PathUtils.IsValidPath(_factory.Configuration.PrefixPath)) {
return string.Format("UnknownInterpreter\\{0}", _factory.Configuration.Id);
}
return _factory.Configuration.PrefixPath;
}
}
/// <summary>
/// Defines whether this node is valid node for painting the interpreter
/// icon.
/// </summary>
protected override bool CanShowDefaultIcon() {
return true;
}
public override bool CanAddFiles {
get {
return false;
}
}
protected override NodeProperties CreatePropertiesObject() {
if (_factory is DerivedInterpreterFactory) {
return new InterpretersNodeWithBaseInterpreterProperties(this);
} else {
return new InterpretersNodeProperties(this);
}
}
public override object GetProperty(int propId) {
if (propId == (int)__VSHPROPID.VSHPROPID_Expandable) {
if (!_checkedItems) {
// We haven't checked if we have files on disk yet, report
// that we can expand until we do.
// We do this lazily so we don't need to spawn a process for
// each interpreter on project load.
ThreadPool.QueueUserWorkItem(CheckPackages);
return true;
} else if (_checkingItems) {
// Still checking, so keep reporting true.
return true;
}
}
return base.GetProperty(propId);
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using static Interop.Advapi32;
namespace System.ServiceProcess
{
/// <devdoc>
/// <para>Provides a base class for a service that will exist as part of a service application. <see cref='System.ServiceProcess.ServiceBase'/>
/// must be derived when creating a new service class.</para>
/// </devdoc>
public class ServiceBase : Component
{
private SERVICE_STATUS _status = new SERVICE_STATUS();
private IntPtr _statusHandle;
private ServiceControlCallback _commandCallback;
private ServiceControlCallbackEx _commandCallbackEx;
private ServiceMainCallback _mainCallback;
private IntPtr _handleName;
private ManualResetEvent _startCompletedSignal;
private int _acceptedCommands;
private string _serviceName;
private bool _nameFrozen; // set to true once we've started running and ServiceName can't be changed any more.
private bool _commandPropsFrozen; // set to true once we've use the Can... properties.
private bool _disposed;
private bool _initialized;
private EventLog _eventLog;
/// <devdoc>
/// <para>
/// Indicates the maximum size for a service name.
/// </para>
/// </devdoc>
public const int MaxNameLength = 80;
/// <devdoc>
/// <para>Creates a new instance of the <see cref='System.ServiceProcess.ServiceBase()'/> class.</para>
/// </devdoc>
public ServiceBase()
{
_acceptedCommands = AcceptOptions.ACCEPT_STOP;
ServiceName = "";
AutoLog = true;
}
/// <devdoc>
/// When this method is called from OnStart, OnStop, OnPause or OnContinue,
/// the specified wait hint is passed to the
/// Service Control Manager to avoid having the service marked as hung.
/// </devdoc>
public unsafe void RequestAdditionalTime(int milliseconds)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
if (_status.currentState != ServiceControlStatus.STATE_CONTINUE_PENDING &&
_status.currentState != ServiceControlStatus.STATE_START_PENDING &&
_status.currentState != ServiceControlStatus.STATE_STOP_PENDING &&
_status.currentState != ServiceControlStatus.STATE_PAUSE_PENDING)
{
throw new InvalidOperationException(SR.NotInPendingState);
}
_status.waitHint = milliseconds;
_status.checkPoint++;
SetServiceStatus(_statusHandle, pStatus);
}
}
/// <devdoc>
/// Indicates whether to report Start, Stop, Pause, and Continue commands in the event
/// </devdoc>
[DefaultValue(true)]
public bool AutoLog { get; set; }
/// <devdoc>
/// The termination code for the service. Set this to a non-zero value before
/// stopping to indicate an error to the Service Control Manager.
/// </devdoc>
public int ExitCode
{
get
{
return _status.win32ExitCode;
}
set
{
_status.win32ExitCode = value;
}
}
/// <devdoc>
/// Indicates whether the service can be handle notifications on
/// computer power status changes.
/// </devdoc>
[DefaultValue(false)]
public bool CanHandlePowerEvent
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_POWEREVENT) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_POWEREVENT;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_POWEREVENT;
}
}
}
/// <devdoc>
/// Indicates whether the service can handle Terminal Server session change events.
/// </devdoc>
[DefaultValue(false)]
public bool CanHandleSessionChangeEvent
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_SESSIONCHANGE) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_SESSIONCHANGE;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_SESSIONCHANGE;
}
}
}
/// <devdoc>
/// <para> Indicates whether the service can be paused
/// and resumed.</para>
/// </devdoc>
[DefaultValue(false)]
public bool CanPauseAndContinue
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_PAUSE_CONTINUE;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_PAUSE_CONTINUE;
}
}
}
/// <devdoc>
/// <para> Indicates whether the service should be notified when
/// the system is shutting down.</para>
/// </devdoc>
[DefaultValue(false)]
public bool CanShutdown
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_SHUTDOWN) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_SHUTDOWN;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_SHUTDOWN;
}
}
}
/// <devdoc>
/// <para> Indicates whether the service can be
/// stopped once it has started.</para>
/// </devdoc>
[DefaultValue(true)]
public bool CanStop
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_STOP) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_STOP;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_STOP;
}
}
}
/// <devdoc>
/// can be used to write notification of service command calls, such as Start and Stop, to the Application event log. This property is read-only.
/// </devdoc>
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public virtual EventLog EventLog
{
get
{
if (_eventLog == null)
{
_eventLog = new EventLog("Application");
_eventLog.Source = ServiceName;
}
return _eventLog;
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected IntPtr ServiceHandle
{
get
{
return _statusHandle;
}
}
/// <devdoc>
/// <para> Indicates the short name used to identify the service to the system.</para>
/// </devdoc>
public string ServiceName
{
get
{
return _serviceName;
}
set
{
if (_nameFrozen)
throw new InvalidOperationException(SR.CannotChangeName);
// For component properties, "" is a special case.
if (value != "" && !ValidServiceName(value))
throw new ArgumentException(SR.Format(SR.ServiceName, value, ServiceBase.MaxNameLength.ToString(CultureInfo.CurrentCulture)));
_serviceName = value;
}
}
internal static bool ValidServiceName(string serviceName)
{
if (serviceName == null)
return false;
// not too long and check for empty name as well.
if (serviceName.Length > ServiceBase.MaxNameLength || serviceName.Length == 0)
return false;
// no slashes or backslash allowed
foreach (char c in serviceName)
{
if ((c == '\\') || (c == '/'))
return false;
}
return true;
}
/// <devdoc>
/// <para>Disposes of the resources (other than memory ) used by
/// the <see cref='System.ServiceProcess.ServiceBase'/>.</para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (_handleName != (IntPtr)0)
{
Marshal.FreeHGlobal(_handleName);
_handleName = (IntPtr)0;
}
_nameFrozen = false;
_commandPropsFrozen = false;
_disposed = true;
base.Dispose(disposing);
}
/// <devdoc>
/// <para> When implemented in a
/// derived class,
/// executes when a Continue command is sent to the service
/// by the
/// Service Control Manager. Specifies the actions to take when a
/// service resumes normal functioning after being paused.</para>
/// </devdoc>
protected virtual void OnContinue()
{
}
/// <devdoc>
/// <para> When implemented in a
/// derived class, executes when a Pause command is sent
/// to
/// the service by the Service Control Manager. Specifies the
/// actions to take when a service pauses.</para>
/// </devdoc>
protected virtual void OnPause()
{
}
/// <devdoc>
/// <para>
/// When implemented in a derived class, executes when the computer's
/// power status has changed.
/// </para>
/// </devdoc>
protected virtual bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return true;
}
/// <devdoc>
/// <para>When implemented in a derived class,
/// executes when a Terminal Server session change event is received.</para>
/// </devdoc>
protected virtual void OnSessionChange(SessionChangeDescription changeDescription)
{
}
/// <devdoc>
/// <para>When implemented in a derived class,
/// executes when the system is shutting down.
/// Specifies what should
/// happen just prior
/// to the system shutting down.</para>
/// </devdoc>
protected virtual void OnShutdown()
{
}
/// <devdoc>
/// <para> When implemented in a
/// derived class, executes when a Start command is sent
/// to the service by the Service
/// Control Manager. Specifies the actions to take when the service starts.</para>
/// <note type="rnotes">
/// Tech review note:
/// except that the SCM does not allow passing arguments, so this overload will
/// never be called by the SCM in the current version. Question: Is this true even
/// when the string array is empty? What should we say, then. Can
/// a ServiceBase derived class only be called programmatically? Will
/// OnStart never be called if you use the SCM to start the service? What about
/// services that start automatically at boot-up?
/// </note>
/// </devdoc>
protected virtual void OnStart(string[] args)
{
}
/// <devdoc>
/// <para> When implemented in a
/// derived class, executes when a Stop command is sent to the
/// service by the Service Control Manager. Specifies the actions to take when a
/// service stops
/// running.</para>
/// </devdoc>
protected virtual void OnStop()
{
}
private unsafe void DeferredContinue()
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
try
{
OnContinue();
WriteLogEntry(SR.ContinueSuccessful);
_status.currentState = ServiceControlStatus.STATE_RUNNING;
}
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_PAUSED;
WriteLogEntry(SR.Format(SR.ContinueFailed, e.ToString()), true);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
finally
{
SetServiceStatus(_statusHandle, pStatus);
}
}
}
private void DeferredCustomCommand(int command)
{
try
{
OnCustomCommand(command);
WriteLogEntry(SR.CommandSuccessful);
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.CommandFailed, e.ToString()), true);
// We should re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
private unsafe void DeferredPause()
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
try
{
OnPause();
WriteLogEntry(SR.PauseSuccessful);
_status.currentState = ServiceControlStatus.STATE_PAUSED;
}
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_RUNNING;
WriteLogEntry(SR.Format(SR.PauseFailed, e.ToString()), true);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
finally
{
SetServiceStatus(_statusHandle, pStatus);
}
}
}
private void DeferredPowerEvent(int eventType, IntPtr eventData)
{
// Note: The eventData pointer might point to an invalid location
// This might happen because, between the time the eventData ptr was
// captured and the time this deferred code runs, the ptr might have
// already been freed.
try
{
PowerBroadcastStatus status = (PowerBroadcastStatus)eventType;
bool statusResult = OnPowerEvent(status);
WriteLogEntry(SR.PowerEventOK);
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.PowerEventFailed, e.ToString()), true);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
private void DeferredSessionChange(int eventType, int sessionId)
{
try
{
OnSessionChange(new SessionChangeDescription((SessionChangeReason)eventType, sessionId));
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.SessionChangeFailed, e.ToString()), true);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
// We mustn't call OnStop directly from the command callback, as this will
// tie up the command thread for the duration of the OnStop, which can be lengthy.
// This is a problem when multiple services are hosted in a single process.
private unsafe void DeferredStop()
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
int previousState = _status.currentState;
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_STOP_PENDING;
SetServiceStatus(_statusHandle, pStatus);
try
{
OnStop();
WriteLogEntry(SR.StopSuccessful);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
catch (Exception e)
{
_status.currentState = previousState;
SetServiceStatus(_statusHandle, pStatus);
WriteLogEntry(SR.Format(SR.StopFailed, e.ToString()), true);
throw;
}
}
}
private unsafe void DeferredShutdown()
{
try
{
OnShutdown();
WriteLogEntry(SR.Format(SR.ShutdownOK));
if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
}
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.ShutdownFailed, e.ToString()), true);
throw;
}
}
/// <devdoc>
/// <para>When implemented in a derived class, <see cref='System.ServiceProcess.ServiceBase.OnCustomCommand'/>
/// executes when a custom command is passed to
/// the service. Specifies the actions to take when
/// a command with the specified parameter value occurs.</para>
/// <note type="rnotes">
/// Previously had "Passed to the
/// service by
/// the SCM", but the SCM doesn't pass custom commands. Do we want to indicate an
/// agent here? Would it be the ServiceController, or is there another way to pass
/// the int into the service? I thought that the SCM did pass it in, but
/// otherwise ignored it since it was an int it doesn't recognize. I was under the
/// impression that the difference was that the SCM didn't have default processing, so
/// it transmitted it without examining it or trying to performs its own
/// default behavior on it. Please correct where my understanding is wrong in the
/// second paragraph below--what, if any, contact does the SCM have with a
/// custom command?
/// </note>
/// </devdoc>
protected virtual void OnCustomCommand(int command)
{
}
/// <devdoc>
/// <para>Provides the main entry point for an executable that
/// contains multiple associated services. Loads the specified services into memory so they can be
/// started.</para>
/// </devdoc>
public static void Run(ServiceBase[] services)
{
if (services == null || services.Length == 0)
throw new ArgumentException(SR.NoServices);
IntPtr entriesPointer = Marshal.AllocHGlobal((IntPtr)((services.Length + 1) * Marshal.SizeOf(typeof(SERVICE_TABLE_ENTRY))));
SERVICE_TABLE_ENTRY[] entries = new SERVICE_TABLE_ENTRY[services.Length];
bool multipleServices = services.Length > 1;
IntPtr structPtr = (IntPtr)0;
for (int index = 0; index < services.Length; ++index)
{
services[index].Initialize(multipleServices);
entries[index] = services[index].GetEntry();
structPtr = (IntPtr)((long)entriesPointer + Marshal.SizeOf(typeof(SERVICE_TABLE_ENTRY)) * index);
Marshal.StructureToPtr(entries[index], structPtr, true);
}
SERVICE_TABLE_ENTRY lastEntry = new SERVICE_TABLE_ENTRY();
lastEntry.callback = null;
lastEntry.name = (IntPtr)0;
structPtr = (IntPtr)((long)entriesPointer + Marshal.SizeOf(typeof(SERVICE_TABLE_ENTRY)) * services.Length);
Marshal.StructureToPtr(lastEntry, structPtr, true);
// While the service is running, this function will never return. It will return when the service
// is stopped.
bool res = StartServiceCtrlDispatcher(entriesPointer);
string errorMessage = "";
if (!res)
{
errorMessage = new Win32Exception().Message;
Console.WriteLine(SR.CantStartFromCommandLine);
}
foreach (ServiceBase service in services)
{
service.Dispose();
if (!res)
{
service.WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), true);
}
}
}
/// <devdoc>
/// <para>Provides the main
/// entry point for an executable that contains a single
/// service. Loads the service into memory so it can be
/// started.</para>
/// </devdoc>
public static void Run(ServiceBase service)
{
if (service == null)
throw new ArgumentException(SR.NoServices);
Run(new ServiceBase[] { service });
}
public void Stop()
{
DeferredStop();
}
private void Initialize(bool multipleServices)
{
if (!_initialized)
{
//Cannot register the service with NT service manatger if the object has been disposed, since finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!multipleServices)
{
_status.serviceType = ServiceTypeOptions.SERVICE_TYPE_WIN32_OWN_PROCESS;
}
else
{
_status.serviceType = ServiceTypeOptions.SERVICE_TYPE_WIN32_SHARE_PROCESS;
}
_status.currentState = ServiceControlStatus.STATE_START_PENDING;
_status.controlsAccepted = 0;
_status.win32ExitCode = 0;
_status.serviceSpecificExitCode = 0;
_status.checkPoint = 0;
_status.waitHint = 0;
_mainCallback = new ServiceMainCallback(this.ServiceMainCallback);
_commandCallback = new ServiceControlCallback(this.ServiceCommandCallback);
_commandCallbackEx = new ServiceControlCallbackEx(this.ServiceCommandCallbackEx);
_handleName = Marshal.StringToHGlobalUni(this.ServiceName);
_initialized = true;
}
}
private SERVICE_TABLE_ENTRY GetEntry()
{
SERVICE_TABLE_ENTRY entry = new SERVICE_TABLE_ENTRY();
_nameFrozen = true;
entry.callback = (Delegate)_mainCallback;
entry.name = _handleName;
return entry;
}
private int ServiceCommandCallbackEx(int command, int eventType, IntPtr eventData, IntPtr eventContext)
{
switch (command)
{
case ControlOptions.CONTROL_POWEREVENT:
{
ThreadPool.QueueUserWorkItem(_ => DeferredPowerEvent(eventType, eventData));
break;
}
case ControlOptions.CONTROL_SESSIONCHANGE:
{
// The eventData pointer can be released between now and when the DeferredDelegate gets called.
// So we capture the session id at this point
WTSSESSION_NOTIFICATION sessionNotification = new WTSSESSION_NOTIFICATION();
Marshal.PtrToStructure(eventData, sessionNotification);
ThreadPool.QueueUserWorkItem(_ => DeferredSessionChange(eventType, sessionNotification.sessionId));
break;
}
default:
{
ServiceCommandCallback(command);
break;
}
}
return 0;
}
/// <devdoc>
/// Command Handler callback is called by NT .
/// Need to take specific action in response to each
/// command message. There is usually no need to override this method.
/// Instead, override OnStart, OnStop, OnCustomCommand, etc.
/// </devdoc>
/// <internalonly/>
private unsafe void ServiceCommandCallback(int command)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
if (command == ControlOptions.CONTROL_INTERROGATE)
SetServiceStatus(_statusHandle, pStatus);
else if (_status.currentState != ServiceControlStatus.STATE_CONTINUE_PENDING &&
_status.currentState != ServiceControlStatus.STATE_START_PENDING &&
_status.currentState != ServiceControlStatus.STATE_STOP_PENDING &&
_status.currentState != ServiceControlStatus.STATE_PAUSE_PENDING)
{
switch (command)
{
case ControlOptions.CONTROL_CONTINUE:
if (_status.currentState == ServiceControlStatus.STATE_PAUSED)
{
_status.currentState = ServiceControlStatus.STATE_CONTINUE_PENDING;
SetServiceStatus(_statusHandle, pStatus);
ThreadPool.QueueUserWorkItem(_ => DeferredContinue());
}
break;
case ControlOptions.CONTROL_PAUSE:
if (_status.currentState == ServiceControlStatus.STATE_RUNNING)
{
_status.currentState = ServiceControlStatus.STATE_PAUSE_PENDING;
SetServiceStatus(_statusHandle, pStatus);
ThreadPool.QueueUserWorkItem(_ => DeferredPause());
}
break;
case ControlOptions.CONTROL_STOP:
int previousState = _status.currentState;
//
// Can't perform all of the service shutdown logic from within the command callback.
// This is because there is a single ScDispatcherLoop for the entire process. Instead, we queue up an
// asynchronous call to "DeferredStop", and return immediately. This is crucial for the multiple service
// per process scenario, such as the new managed service host model.
//
if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING)
{
_status.currentState = ServiceControlStatus.STATE_STOP_PENDING;
SetServiceStatus(_statusHandle, pStatus);
// Set our copy of the state back to the previous so that the deferred stop routine
// can also save the previous state.
_status.currentState = previousState;
ThreadPool.QueueUserWorkItem(_ => DeferredStop());
}
break;
case ControlOptions.CONTROL_SHUTDOWN:
//
// Same goes for shutdown -- this needs to be very responsive, so we can't have one service tying up the
// dispatcher loop.
//
ThreadPool.QueueUserWorkItem(_ => DeferredShutdown());
break;
default:
ThreadPool.QueueUserWorkItem(_ => DeferredCustomCommand(command));
break;
}
}
}
}
// Need to execute the start method on a thread pool thread.
// Most applications will start asynchronous operations in the
// OnStart method. If such a method is executed in MainCallback
// thread, the async operations might get canceled immediately.
private void ServiceQueuedMainCallback(object state)
{
string[] args = (string[])state;
try
{
OnStart(args);
WriteLogEntry(SR.StartSuccessful);
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_RUNNING;
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.StartFailed, e.ToString()), true);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
}
_startCompletedSignal.Set();
}
/// <devdoc>
/// ServiceMain callback is called by NT .
/// It is expected that we register the command handler,
/// and start the service at this point.
/// </devdoc>
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
string[] args = null;
if (argCount > 0)
{
char** argsAsPtr = (char**)argPointer.ToPointer();
//Lets read the arguments
// the first arg is always the service name. We don't want to pass that in.
args = new string[argCount - 1];
for (int index = 0; index < args.Length; ++index)
{
// we increment the pointer first so we skip over the first argument.
argsAsPtr++;
args[index] = Marshal.PtrToStringUni((IntPtr)(*argsAsPtr));
}
}
// If we are being hosted, then Run will not have been called, since the EXE's Main entrypoint is not called.
if (!_initialized)
{
Initialize(true);
}
_statusHandle = RegisterServiceCtrlHandlerEx(ServiceName, (Delegate)_commandCallbackEx, (IntPtr)0);
_nameFrozen = true;
if (_statusHandle == (IntPtr)0)
{
string errorMessage = new Win32Exception().Message;
WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), true);
}
_status.controlsAccepted = _acceptedCommands;
_commandPropsFrozen = true;
if ((_status.controlsAccepted & AcceptOptions.ACCEPT_STOP) != 0)
{
_status.controlsAccepted = _status.controlsAccepted | AcceptOptions.ACCEPT_SHUTDOWN;
}
_status.currentState = ServiceControlStatus.STATE_START_PENDING;
bool statusOK = SetServiceStatus(_statusHandle, pStatus);
if (!statusOK)
{
return;
}
// Need to execute the start method on a thread pool thread.
// Most applications will start asynchronous operations in the
// OnStart method. If such a method is executed in the current
// thread, the async operations might get canceled immediately
// since NT will terminate this thread right after this function
// finishes.
_startCompletedSignal = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServiceQueuedMainCallback), args);
_startCompletedSignal.WaitOne();
statusOK = SetServiceStatus(_statusHandle, pStatus);
if (!statusOK)
{
WriteLogEntry(SR.Format(SR.StartFailed, new Win32Exception().Message), true);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
}
}
private void WriteLogEntry(string message, bool error = false)
{
// EventLog failures shouldn't affect the service operation
try
{
if (AutoLog)
{
EventLog.WriteEntry(message);
}
}
catch
{
// Do nothing. Not having the event log is bad, but not starting the service as a result is worse.
}
}
}
}
| |
using UnityEngine.Rendering;
using System;
using System.Linq;
using UnityEngine.Experimental.PostProcessing;
using UnityEngine.Experimental.Rendering.HDPipeline.TilePass;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[ExecuteInEditMode]
// This HDRenderPipeline assume linear lighting. Don't work with gamma.
public class HDRenderPipeline : RenderPipelineAsset
{
const string k_HDRenderPipelinePath = "Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.asset";
#if UNITY_EDITOR
[MenuItem("RenderPipeline/Create HDRenderPipeline")]
static void CreateHDRenderPipeline()
{
var instance = CreateInstance<HDRenderPipeline>();
AssetDatabase.CreateAsset(instance, k_HDRenderPipelinePath);
}
[UnityEditor.MenuItem("HDRenderPipeline/UpdateHDRenderPipeline")]
static void UpdateHDRenderPipeline()
{
var guids = AssetDatabase.FindAssets("t:HDRenderPipeline");
foreach (var guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
var pipeline = AssetDatabase.LoadAssetAtPath<HDRenderPipeline>(path);
EditorUtility.SetDirty(pipeline);
}
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light Data\" (if not present)")]
static void AddAdditionalLightData()
{
Light[] lights = FindObjectsOfType(typeof(Light)) as Light[];
foreach (Light light in lights)
{
// Do not add a component if there already is one.
if (light.GetComponent<AdditionalLightData>() == null)
{
light.gameObject.AddComponent<AdditionalLightData>();
}
}
}
#endif
private HDRenderPipeline()
{}
[SerializeField]
private LightLoopProducer m_LightLoopProducer;
public LightLoopProducer lightLoopProducer
{
get { return m_LightLoopProducer; }
set { m_LightLoopProducer = value; }
}
protected override IRenderPipeline InternalCreatePipeline()
{
return new HDRenderPipelineInstance(this);
}
// NOTE:
// All those properties are public because of how HDRenderPipelineInspector retrieve those properties via serialization/reflection
// Those that are not will be refatored later.
// Debugging
public DebugDisplaySettings debugDisplaySettings = new DebugDisplaySettings();
// Renderer Settings (per project)
public RenderingSettings renderingSettings = new RenderingSettings();
public SubsurfaceScatteringSettings sssSettings = new SubsurfaceScatteringSettings();
[SerializeField]
ShadowSettings m_ShadowSettings = ShadowSettings.Default;
[SerializeField]
TextureSettings m_TextureSettings = TextureSettings.Default;
public ShadowSettings shadowSettings { get { return m_ShadowSettings; } }
public TextureSettings textureSettings { get { return m_TextureSettings; } set { m_TextureSettings = value; } }
// Renderer Settings (per "scene")
[SerializeField] private CommonSettings.Settings m_CommonSettings = CommonSettings.Settings.s_Defaultsettings;
[SerializeField] private SkySettings m_SkySettings;
public CommonSettings.Settings commonSettingsToUse
{
get
{
if (CommonSettingsSingleton.overrideSettings)
return CommonSettingsSingleton.overrideSettings.settings;
return m_CommonSettings;
}
}
public SkySettings skySettings
{
get { return m_SkySettings; }
set { m_SkySettings = value; }
}
public SkySettings skySettingsToUse
{
get
{
if (SkySettingsSingleton.overrideSettings)
return SkySettingsSingleton.overrideSettings;
return m_SkySettings;
}
}
public void ApplyDebugDisplaySettings()
{
m_ShadowSettings.enabled = debugDisplaySettings.lightingDebugSettings.enableShadows;
LightingDebugSettings lightingDebugSettings = debugDisplaySettings.lightingDebugSettings;
Vector4 debugAlbedo = new Vector4(lightingDebugSettings.debugLightingAlbedo.r, lightingDebugSettings.debugLightingAlbedo.g, lightingDebugSettings.debugLightingAlbedo.b, 0.0f);
Vector4 debugSmoothness = new Vector4(lightingDebugSettings.overrideSmoothness ? 1.0f : 0.0f, lightingDebugSettings.overrideSmoothnessValue, 0.0f, 0.0f);
Shader.SetGlobalInt("_DebugViewMaterial", (int)debugDisplaySettings.GetDebugMaterialIndex());
Shader.SetGlobalInt("_DebugLightingMode", (int)debugDisplaySettings.GetDebugLightingMode());
Shader.SetGlobalVector("_DebugLightingAlbedo", debugAlbedo);
Shader.SetGlobalVector("_DebugLightingSmoothness", debugSmoothness);
}
public void UpdateCommonSettings()
{
var commonSettings = commonSettingsToUse;
m_ShadowSettings.directionalLightCascadeCount = commonSettings.shadowCascadeCount;
m_ShadowSettings.directionalLightCascades = new Vector3(commonSettings.shadowCascadeSplit0, commonSettings.shadowCascadeSplit1, commonSettings.shadowCascadeSplit2);
m_ShadowSettings.maxShadowDistance = commonSettings.shadowMaxDistance;
m_ShadowSettings.directionalLightNearPlaneOffset = commonSettings.shadowNearPlaneOffset;
}
public void OnValidate()
{
debugDisplaySettings.OnValidate();
sssSettings.OnValidate();
}
void OnEnable()
{
debugDisplaySettings.RegisterDebug();
}
}
[Serializable]
public class RenderingSettings
{
public bool useForwardRenderingOnly = false; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool useDepthPrepass = false;
// we have to fallback to forward-only rendering when scene view is using wireframe rendering mode --
// as rendering everything in wireframe + deferred do not play well together
public bool ShouldUseForwardRenderingOnly()
{
return useForwardRenderingOnly || GL.wireframe;
}
}
public struct HDCamera
{
public Camera camera;
public Vector4 screenSize;
public Matrix4x4 viewProjectionMatrix;
public Matrix4x4 invViewProjectionMatrix;
public Matrix4x4 invProjectionMatrix;
public Vector4 invProjectionParam;
}
public class GBufferManager
{
public const int MaxGbuffer = 8;
public void SetBufferDescription(int index, string stringId, RenderTextureFormat inFormat, RenderTextureReadWrite inSRGBWrite)
{
IDs[index] = Shader.PropertyToID(stringId);
RTIDs[index] = new RenderTargetIdentifier(IDs[index]);
formats[index] = inFormat;
sRGBWrites[index] = inSRGBWrite;
}
public void InitGBuffers(int width, int height, CommandBuffer cmd)
{
for (int index = 0; index < gbufferCount; index++)
{
/* RTs[index] = */
cmd.GetTemporaryRT(IDs[index], width, height, 0, FilterMode.Point, formats[index], sRGBWrites[index]);
}
}
public RenderTargetIdentifier[] GetGBuffers()
{
var colorMRTs = new RenderTargetIdentifier[gbufferCount];
for (int index = 0; index < gbufferCount; index++)
{
colorMRTs[index] = RTIDs[index];
}
return colorMRTs;
}
/*
public void BindBuffers(Material mat)
{
for (int index = 0; index < gbufferCount; index++)
{
mat.SetTexture(IDs[index], RTs[index]);
}
}
*/
public int gbufferCount { get; set; }
int[] IDs = new int[MaxGbuffer];
RenderTargetIdentifier[] RTIDs = new RenderTargetIdentifier[MaxGbuffer];
RenderTextureFormat[] formats = new RenderTextureFormat[MaxGbuffer];
RenderTextureReadWrite[] sRGBWrites = new RenderTextureReadWrite[MaxGbuffer];
}
public class HDRenderPipelineInstance : RenderPipeline
{
private readonly HDRenderPipeline m_Owner;
// TODO: Find a way to automatically create/iterate through deferred material
// TODO TO CHECK: SebL I move allocation from Build() to here, but there was a comment "// Our object can be garbage collected, so need to be allocate here", it is still true ?
private readonly Lit.RenderLoop m_LitRenderLoop = new Lit.RenderLoop();
readonly GBufferManager m_gbufferManager = new GBufferManager();
// Various set of material use in render loop
readonly Material m_FilterSubsurfaceScattering;
readonly Material m_FilterAndCombineSubsurfaceScattering;
private Material m_DebugDisplayShadowMap;
private Material m_DebugViewMaterialGBuffer;
private Material m_DebugDisplayLatlong;
// Various buffer
readonly int m_CameraColorBuffer;
readonly int m_CameraSubsurfaceBuffer;
readonly int m_CameraFilteringBuffer;
readonly int m_VelocityBuffer;
readonly int m_DistortionBuffer;
// 'm_CameraColorBuffer' does not contain diffuse lighting of SSS materials until the SSS pass.
// It is stored within 'm_CameraSubsurfaceBufferRT'.
readonly RenderTargetIdentifier m_CameraColorBufferRT;
readonly RenderTargetIdentifier m_CameraSubsurfaceBufferRT;
readonly RenderTargetIdentifier m_CameraFilteringBufferRT;
readonly RenderTargetIdentifier m_VelocityBufferRT;
readonly RenderTargetIdentifier m_DistortionBufferRT;
private RenderTexture m_CameraDepthStencilBuffer = null;
private RenderTexture m_CameraDepthStencilBufferCopy = null;
private RenderTargetIdentifier m_CameraDepthStencilBufferRT;
private RenderTargetIdentifier m_CameraDepthStencilBufferCopyRT;
// Post-processing context (recycled on every frame to avoid GC alloc)
readonly PostProcessRenderContext m_PostProcessContext;
// Detect when windows size is changing
int m_CurrentWidth;
int m_CurrentHeight;
ShadowRenderPass m_ShadowPass;
ShadowOutput m_ShadowsResult = new ShadowOutput();
public int GetCurrentShadowCount() { return m_ShadowsResult.shadowLights == null ? 0 : m_ShadowsResult.shadowLights.Length; }
readonly SkyManager m_SkyManager = new SkyManager();
private readonly BaseLightLoop m_LightLoop;
private DebugDisplaySettings debugDisplaySettings
{
get { return m_Owner.debugDisplaySettings; }
}
public SubsurfaceScatteringSettings sssSettings
{
get { return m_Owner.sssSettings; }
}
public HDRenderPipelineInstance(HDRenderPipeline owner)
{
m_Owner = owner;
m_CameraColorBuffer = Shader.PropertyToID("_CameraColorTexture");
m_CameraSubsurfaceBuffer = Shader.PropertyToID("_CameraSubsurfaceTexture");
m_CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringBuffer");
m_CameraColorBufferRT = new RenderTargetIdentifier(m_CameraColorBuffer);
m_CameraSubsurfaceBufferRT = new RenderTargetIdentifier(m_CameraSubsurfaceBuffer);
m_CameraFilteringBufferRT = new RenderTargetIdentifier(m_CameraFilteringBuffer);
m_FilterSubsurfaceScattering = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CombineSubsurfaceScattering");
m_FilterSubsurfaceScattering.DisableKeyword("SSS_FILTER_HORIZONTAL_AND_COMBINE");
m_FilterSubsurfaceScattering.SetFloat("_DstBlend", (float)BlendMode.Zero);
m_FilterAndCombineSubsurfaceScattering = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CombineSubsurfaceScattering");
m_FilterAndCombineSubsurfaceScattering.EnableKeyword("SSS_FILTER_HORIZONTAL_AND_COMBINE");
m_FilterAndCombineSubsurfaceScattering.SetFloat("_DstBlend", (float)BlendMode.One);
InitializeDebugMaterials();
m_ShadowPass = new ShadowRenderPass(owner.shadowSettings);
// Init Gbuffer description
m_gbufferManager.gbufferCount = m_LitRenderLoop.GetMaterialGBufferCount();
RenderTextureFormat[] RTFormat;
RenderTextureReadWrite[] RTReadWrite;
m_LitRenderLoop.GetMaterialGBufferDescription(out RTFormat, out RTReadWrite);
for (int gbufferIndex = 0; gbufferIndex < m_gbufferManager.gbufferCount; ++gbufferIndex)
{
m_gbufferManager.SetBufferDescription(gbufferIndex, "_GBufferTexture" + gbufferIndex, RTFormat[gbufferIndex], RTReadWrite[gbufferIndex]);
}
m_VelocityBuffer = Shader.PropertyToID("_VelocityTexture");
if (ShaderConfig.s_VelocityInGbuffer == 1)
{
// If velocity is in GBuffer then it is in the last RT. Assign a different name to it.
m_gbufferManager.SetBufferDescription(m_gbufferManager.gbufferCount, "_VelocityTexture", Builtin.RenderLoop.GetVelocityBufferFormat(), Builtin.RenderLoop.GetVelocityBufferReadWrite());
m_gbufferManager.gbufferCount++;
}
m_VelocityBufferRT = new RenderTargetIdentifier(m_VelocityBuffer);
m_DistortionBuffer = Shader.PropertyToID("_DistortionTexture");
m_DistortionBufferRT = new RenderTargetIdentifier(m_DistortionBuffer);
m_LitRenderLoop.Build();
if (owner.lightLoopProducer)
m_LightLoop = owner.lightLoopProducer.CreateLightLoop();
if (m_LightLoop != null)
m_LightLoop.Build(owner.textureSettings);
m_SkyManager.Build();
m_SkyManager.skySettings = owner.skySettingsToUse;
m_PostProcessContext = new PostProcessRenderContext();
}
void InitializeDebugMaterials()
{
m_DebugDisplayShadowMap = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DebugDisplayShadowMap");
m_DebugViewMaterialGBuffer = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DebugViewMaterialGBuffer");
m_DebugDisplayLatlong = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DebugDisplayLatlong");
}
public override void Dispose()
{
base.Dispose();
if (m_LightLoop != null)
m_LightLoop.Cleanup();
m_LitRenderLoop.Cleanup();
Utilities.Destroy(m_DebugDisplayShadowMap);
Utilities.Destroy(m_DebugViewMaterialGBuffer);
Utilities.Destroy(m_DebugDisplayLatlong);
m_SkyManager.Cleanup();
#if UNITY_EDITOR
SupportedRenderingFeatures.active = SupportedRenderingFeatures.Default;
#endif
}
#if UNITY_EDITOR
private static readonly SupportedRenderingFeatures s_NeededFeatures = new SupportedRenderingFeatures()
{
reflectionProbe = SupportedRenderingFeatures.ReflectionProbe.Rotation
};
#endif
void CreateDepthBuffer(Camera camera)
{
if (m_CameraDepthStencilBuffer != null)
{
m_CameraDepthStencilBuffer.Release();
}
m_CameraDepthStencilBuffer = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 24, RenderTextureFormat.Depth);
m_CameraDepthStencilBuffer.filterMode = FilterMode.Point;
m_CameraDepthStencilBuffer.Create();
m_CameraDepthStencilBufferRT = new RenderTargetIdentifier(m_CameraDepthStencilBuffer);
if (NeedDepthBufferCopy())
{
if (m_CameraDepthStencilBufferCopy != null)
{
m_CameraDepthStencilBufferCopy.Release();
}
m_CameraDepthStencilBufferCopy = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 24, RenderTextureFormat.Depth);
m_CameraDepthStencilBufferCopy.filterMode = FilterMode.Point;
m_CameraDepthStencilBufferCopy.Create();
m_CameraDepthStencilBufferCopyRT = new RenderTargetIdentifier(m_CameraDepthStencilBufferCopy);
}
}
void Resize(Camera camera)
{
// TODO: Detect if renderdoc just load and force a resize in this case, as often renderdoc require to realloc resource.
// TODO: This is the wrong way to handle resize/allocation. We can have several different camera here, mean that the loop on camera will allocate and deallocate
// the below buffer which is bad. Best is to have a set of buffer for each camera that is persistent and reallocate resource if need
// For now consider we have only one camera that go to this code, the main one.
m_SkyManager.skySettings = m_Owner.skySettingsToUse;
m_SkyManager.Resize(camera.nearClipPlane, camera.farClipPlane); // TODO: Also a bad naming, here we just want to realloc texture if skyparameters change (usefull for lookdev)
if (m_LightLoop == null)
return;
bool resolutionChanged = camera.pixelWidth != m_CurrentWidth || camera.pixelHeight != m_CurrentHeight;
if (resolutionChanged || m_CameraDepthStencilBuffer == null)
{
CreateDepthBuffer(camera);
}
if (resolutionChanged || m_LightLoop.NeedResize())
{
if (m_CurrentWidth > 0 && m_CurrentHeight > 0)
{
m_LightLoop.ReleaseResolutionDependentBuffers();
}
m_LightLoop.AllocResolutionDependentBuffers(camera.pixelWidth, camera.pixelHeight);
}
// update recorded window resolution
m_CurrentWidth = camera.pixelWidth;
m_CurrentHeight = camera.pixelHeight;
}
public void PushGlobalParams(HDCamera hdCamera, ScriptableRenderContext renderContext, SubsurfaceScatteringSettings sssParameters)
{
var cmd = new CommandBuffer {name = "Push Global Parameters"};
cmd.SetGlobalVector("_ScreenSize", hdCamera.screenSize);
cmd.SetGlobalMatrix("_ViewProjMatrix", hdCamera.viewProjectionMatrix);
cmd.SetGlobalMatrix("_InvViewProjMatrix", hdCamera.invViewProjectionMatrix);
cmd.SetGlobalMatrix("_InvProjMatrix", hdCamera.invProjectionMatrix);
cmd.SetGlobalVector("_InvProjParam", hdCamera.invProjectionParam);
// TODO: cmd.SetGlobalInt() does not exist, so we are forced to use Shader.SetGlobalInt() instead.
if (m_SkyManager.IsSkyValid())
{
m_SkyManager.SetGlobalSkyTexture();
Shader.SetGlobalInt("_EnvLightSkyEnabled", 1);
}
else
{
Shader.SetGlobalInt("_EnvLightSkyEnabled", 0);
}
// Broadcast SSS parameters to all shaders.
Shader.SetGlobalInt("_EnableSSS", debugDisplaySettings.renderingDebugSettings.enableSSS ? 1 : 0);
Shader.SetGlobalInt("_TransmissionFlags", sssParameters.transmissionFlags);
Shader.SetGlobalInt("_TexturingModeFlags", sssParameters.texturingModeFlags);
cmd.SetGlobalFloatArray("_ThicknessRemaps", sssParameters.thicknessRemaps);
cmd.SetGlobalVectorArray("_TintColors", sssParameters.tintColors);
cmd.SetGlobalVectorArray("_HalfRcpVariancesAndLerpWeights", sssParameters.halfRcpVariancesAndLerpWeights);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
bool NeedDepthBufferCopy()
{
// For now we consider only PS4 to be able to read from a bound depth buffer. Need to test/implement for other platforms.
return SystemInfo.graphicsDeviceType != GraphicsDeviceType.PlayStation4;
}
Texture GetDepthTexture()
{
if (NeedDepthBufferCopy())
return m_CameraDepthStencilBufferCopy;
else
return m_CameraDepthStencilBuffer;
}
private void CopyDepthBufferIfNeeded(ScriptableRenderContext renderContext)
{
var cmd = new CommandBuffer() { name = NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer"};
if (NeedDepthBufferCopy())
{
using (new Utilities.ProfilingSample("Copy depth-stencil buffer", renderContext))
{
cmd.CopyTexture(m_CameraDepthStencilBufferRT, m_CameraDepthStencilBufferCopyRT);
}
}
cmd.SetGlobalTexture("_MainDepthTexture", GetDepthTexture());
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
base.Render(renderContext, cameras);
#if UNITY_EDITOR
SupportedRenderingFeatures.active = s_NeededFeatures;
#endif
GraphicsSettings.lightsUseLinearIntensity = true;
GraphicsSettings.lightsUseColorTemperature = true;
if (!m_LitRenderLoop.isInit)
m_LitRenderLoop.RenderInit(renderContext);
// Do anything we need to do upon a new frame.
if (m_LightLoop != null)
m_LightLoop.NewFrame();
m_Owner.ApplyDebugDisplaySettings();
m_Owner.UpdateCommonSettings();
// Set Frame constant buffer
// TODO...
// we only want to render one camera for now
// select the most main camera!
Camera camera = cameras.OrderByDescending(x => x.tag == "MainCamera").FirstOrDefault();
if (camera == null)
{
renderContext.Submit();
return;
}
// Set camera constant buffer
// TODO...
CullingParameters cullingParams;
if (!CullResults.GetCullingParameters(camera, out cullingParams))
{
renderContext.Submit();
return;
}
m_ShadowPass.UpdateCullingParameters(ref cullingParams);
var cullResults = CullResults.Cull(ref cullingParams, renderContext);
Resize(camera);
renderContext.SetupCameraProperties(camera);
HDCamera hdCamera = Utilities.GetHDCamera(camera);
// TODO: Find a correct place to bind these material textures
// We have to bind the material specific global parameters in this mode
m_LitRenderLoop.Bind();
InitAndClearBuffer(camera, renderContext);
RenderDepthPrepass(cullResults, camera, renderContext);
// Forward opaque with deferred/cluster tile require that we fill the depth buffer
// correctly to build the light list.
// TODO: avoid double lighting by tagging stencil or gbuffer that we must not lit.
RenderForwardOnlyOpaqueDepthPrepass(cullResults, camera, renderContext);
RenderGBuffer(cullResults, camera, renderContext);
// If full forward rendering, we did not do any rendering yet, so don't need to copy the buffer.
// If Deferred then the depth buffer is full (regular GBuffer + ForwardOnly depth prepass are done so we can copy it safely.
if (!m_Owner.renderingSettings.useForwardRenderingOnly)
{
CopyDepthBufferIfNeeded(renderContext);
}
if (debugDisplaySettings.IsDebugMaterialDisplayEnabled())
{
RenderDebugViewMaterial(cullResults, hdCamera, renderContext);
}
else
{
using (new Utilities.ProfilingSample("Shadow", renderContext))
{
m_ShadowPass.Render(renderContext, cullResults, out m_ShadowsResult);
}
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render
if (m_LightLoop != null)
{
using (new Utilities.ProfilingSample("Build Light list", renderContext))
{
m_LightLoop.PrepareLightsForGPU(m_Owner.shadowSettings, cullResults, camera, ref m_ShadowsResult);
m_LightLoop.RenderShadows(renderContext, cullResults);
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render
m_LightLoop.BuildGPULightLists(camera, renderContext, m_CameraDepthStencilBufferRT); // TODO: Use async compute here to run light culling during shadow
}
}
PushGlobalParams(hdCamera, renderContext, m_Owner.sssSettings);
// Caution: We require sun light here as some sky use the sun light to render, mean UpdateSkyEnvironment
// must be call after BuildGPULightLists.
// TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).
UpdateSkyEnvironment(hdCamera, renderContext);
RenderDeferredLighting(hdCamera, renderContext);
// We compute subsurface scattering here. Therefore, no objects rendered afterwards will exhibit SSS.
// Currently, there is no efficient way to switch between SRT and MRT for the forward pass;
// therefore, forward-rendered objects do not output split lighting required for the SSS pass.
CombineSubsurfaceScattering(hdCamera, renderContext, m_Owner.sssSettings);
// For opaque forward we have split rendering in two categories
// Material that are always forward and material that can be deferred or forward depends on render pipeline options (like switch to rendering forward only mode)
// Material that are always forward are unlit and complex (Like Hair) and don't require sorting, so it is ok to split them.
RenderForward(cullResults, camera, renderContext, true); // Render deferred or forward opaque
RenderForwardOnlyOpaque(cullResults, camera, renderContext);
RenderLightingDebug(hdCamera, renderContext, m_CameraColorBufferRT);
// If full forward rendering, we did just rendered everything, so we can copy the depth buffer
// If Deferred nothing needs copying anymore.
if (m_Owner.renderingSettings.useForwardRenderingOnly)
{
CopyDepthBufferIfNeeded(renderContext);
}
RenderSky(hdCamera, renderContext);
// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(cullResults, camera, renderContext, false);
// Planar and real time cubemap doesn't need post process and render in FP16
if (camera.cameraType == CameraType.Reflection)
{
// Simple blit
var cmd = new CommandBuffer { name = "Blit to final RT" };
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
else
{
RenderVelocity(cullResults, camera, renderContext); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
// TODO: Check with VFX team.
// Rendering distortion here have off course lot of artifact.
// But resolving at each objects that write in distortion is not possible (need to sort transparent, render those that do not distort, then resolve, then etc...)
// Instead we chose to apply distortion at the end after we cumulate distortion vector and desired blurriness. This
RenderDistortion(cullResults, camera, renderContext);
RenderPostProcesses(camera, renderContext);
}
}
RenderDebugOverlay(camera, renderContext);
// bind depth surface for editor grid/gizmo/selection rendering
if (camera.cameraType == CameraType.SceneView)
{
var cmd = new CommandBuffer();
cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
renderContext.Submit();
}
void RenderOpaqueRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, string passName, RendererConfiguration rendererConfiguration = 0)
{
if (!debugDisplaySettings.renderingDebugSettings.displayOpaqueObjects)
return;
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName(passName))
{
rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonOpaque }
};
settings.inputFilter.SetQueuesOpaque();
renderContext.DrawRenderers(ref settings);
}
void RenderTransparentRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, string passName, RendererConfiguration rendererConfiguration = 0)
{
if (!debugDisplaySettings.renderingDebugSettings.displayTransparentObjects)
return;
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName(passName))
{
rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonTransparent }
};
settings.inputFilter.SetQueuesTransparent();
renderContext.DrawRenderers(ref settings);
}
void RenderDepthPrepass(CullResults cull, Camera camera, ScriptableRenderContext renderContext)
{
// If we are forward only we will do a depth prepass
// TODO: Depth prepass should be enabled based on light loop settings. LightLoop define if they need a depth prepass + forward only...
if (!m_Owner.renderingSettings.useDepthPrepass)
return;
using (new Utilities.ProfilingSample("Depth Prepass", renderContext))
{
// TODO: Must do opaque then alpha masked for performance!
// TODO: front to back for opaque and by materal for opaque tested when we split in two
Utilities.SetRenderTarget(renderContext, m_CameraDepthStencilBufferRT);
RenderOpaqueRenderList(cull, camera, renderContext, "DepthOnly");
}
}
void RenderGBuffer(CullResults cull, Camera camera, ScriptableRenderContext renderContext)
{
if (m_Owner.renderingSettings.ShouldUseForwardRenderingOnly())
{
return;
}
string passName = debugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer";
using (new Utilities.ProfilingSample(passName, renderContext))
{
// setup GBuffer for rendering
Utilities.SetRenderTarget(renderContext, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
// render opaque objects into GBuffer
RenderOpaqueRenderList(cull, camera, renderContext, passName, Utilities.kRendererConfigurationBakedLighting);
}
}
// This pass is use in case of forward opaque and deferred rendering. We need to render forward objects before tile lighting pass
void RenderForwardOnlyOpaqueDepthPrepass(CullResults cull, Camera camera, ScriptableRenderContext renderContext)
{
// If we are forward only we don't need to render ForwardOnlyOpaqueDepthOnly object
// But in case we request a prepass we render it
if (m_Owner.renderingSettings.ShouldUseForwardRenderingOnly() && !m_Owner.renderingSettings.useDepthPrepass)
return;
using (new Utilities.ProfilingSample("Forward opaque depth", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraDepthStencilBufferRT);
RenderOpaqueRenderList(cull, camera, renderContext, "ForwardOnlyOpaqueDepthOnly");
}
}
void RenderDebugViewMaterial(CullResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext)
{
using (new Utilities.ProfilingSample("DisplayDebug ViewMaterial", renderContext))
// Render Opaque forward
{
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, Utilities.kClearAll, Color.black);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, "ForwardDisplayDebug", Utilities.kRendererConfigurationBakedLighting);
}
// Render GBuffer opaque
if (!m_Owner.renderingSettings.ShouldUseForwardRenderingOnly())
{
Utilities.SetupMaterialHDCamera(hdCamera, m_DebugViewMaterialGBuffer);
// m_gbufferManager.BindBuffers(m_DebugViewMaterialGBuffer);
// TODO: Bind depth textures
var cmd = new CommandBuffer { name = "DebugViewMaterialGBuffer" };
cmd.Blit(null, m_CameraColorBufferRT, m_DebugViewMaterialGBuffer, 0);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
// Render forward transparent
{
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, "ForwardDisplayDebug", Utilities.kRendererConfigurationBakedLighting);
}
// Last blit
{
var cmd = new CommandBuffer { name = "Blit DebugView Material Debug" };
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
}
void RenderDeferredLighting(HDCamera hdCamera, ScriptableRenderContext renderContext)
{
if (m_Owner.renderingSettings.ShouldUseForwardRenderingOnly() || m_LightLoop == null)
{
return;
}
RenderTargetIdentifier[] colorRTs = { m_CameraColorBufferRT, m_CameraSubsurfaceBufferRT };
if (debugDisplaySettings.renderingDebugSettings.enableSSS)
{
// Output split lighting for materials tagged with the SSS stencil bit.
m_LightLoop.RenderDeferredLighting(hdCamera, renderContext, debugDisplaySettings, colorRTs, m_CameraDepthStencilBufferRT, new RenderTargetIdentifier(GetDepthTexture()), true);
}
// Output combined lighting for all the other materials.
m_LightLoop.RenderDeferredLighting(hdCamera, renderContext, debugDisplaySettings, colorRTs, m_CameraDepthStencilBufferRT, new RenderTargetIdentifier(GetDepthTexture()), false);
}
// Combines specular lighting and diffuse lighting with subsurface scattering.
void CombineSubsurfaceScattering(HDCamera hdCamera, ScriptableRenderContext context, SubsurfaceScatteringSettings sssParameters)
{
// Currently, forward-rendered objects do not output split lighting required for the SSS pass.
if (m_Owner.renderingSettings.ShouldUseForwardRenderingOnly()) return;
if (!debugDisplaySettings.renderingDebugSettings.enableSSS) return;
var cmd = new CommandBuffer() { name = "Subsurface Scattering" };
// Perform the vertical SSS filtering pass.
m_FilterSubsurfaceScattering.SetVectorArray("_FilterKernels", sssParameters.filterKernels);
m_FilterSubsurfaceScattering.SetVectorArray("_HalfRcpWeightedVariances", sssParameters.halfRcpWeightedVariances);
cmd.SetGlobalTexture("_IrradianceSource", m_CameraSubsurfaceBufferRT);
Utilities.DrawFullScreen(cmd, m_FilterSubsurfaceScattering, hdCamera,
m_CameraFilteringBufferRT, m_CameraDepthStencilBufferRT);
// Perform the horizontal SSS filtering pass, and combine diffuse and specular lighting.
m_FilterAndCombineSubsurfaceScattering.SetVectorArray("_FilterKernels", sssParameters.filterKernels);
m_FilterAndCombineSubsurfaceScattering.SetVectorArray("_HalfRcpWeightedVariances", sssParameters.halfRcpWeightedVariances);
cmd.SetGlobalTexture("_IrradianceSource", m_CameraFilteringBufferRT);
Utilities.DrawFullScreen(cmd, m_FilterAndCombineSubsurfaceScattering, hdCamera,
m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
context.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
void UpdateSkyEnvironment(HDCamera hdCamera, ScriptableRenderContext renderContext)
{
m_SkyManager.UpdateEnvironment(hdCamera, m_LightLoop == null ? null : m_LightLoop.GetCurrentSunLight(), renderContext);
}
void RenderSky(HDCamera hdCamera, ScriptableRenderContext renderContext)
{
m_SkyManager.RenderSky(hdCamera, m_LightLoop == null ? null : m_LightLoop.GetCurrentSunLight(), m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, renderContext);
}
public Texture2D ExportSkyToTexture()
{
return m_SkyManager.ExportSkyToTexture();
}
void RenderLightingDebug(HDCamera camera, ScriptableRenderContext renderContext, RenderTargetIdentifier colorBuffer)
{
if (m_LightLoop != null)
m_LightLoop.RenderLightingDebug(camera, renderContext, colorBuffer);
}
void RenderForward(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext, bool renderOpaque)
{
// TODO: Currently we can't render opaque object forward when deferred is enabled
// miss option
if (!m_Owner.renderingSettings.ShouldUseForwardRenderingOnly() && renderOpaque)
return;
string passName = debugDisplaySettings.IsDebugDisplayEnabled() ? "ForwardDisplayDebug" : "Forward";
using (new Utilities.ProfilingSample(passName, renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
if (m_LightLoop != null)
m_LightLoop.RenderForward(camera, renderContext, renderOpaque);
if (renderOpaque)
{
RenderOpaqueRenderList(cullResults, camera, renderContext, passName, Utilities.kRendererConfigurationBakedLighting);
}
else
{
RenderTransparentRenderList(cullResults, camera, renderContext, passName, Utilities.kRendererConfigurationBakedLighting);
}
}
}
// Render material that are forward opaque only (like eye), this include unlit material
void RenderForwardOnlyOpaque(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext)
{
string passName = debugDisplaySettings.IsDebugDisplayEnabled() ? "ForwardOnlyOpaqueDisplayDebug" : "ForwardOnlyOpaque";
using (new Utilities.ProfilingSample(passName, renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
if (m_LightLoop != null)
m_LightLoop.RenderForward(camera, renderContext, true);
RenderOpaqueRenderList(cullResults, camera, renderContext, passName, Utilities.kRendererConfigurationBakedLighting);
}
}
void RenderVelocity(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext)
{
using (new Utilities.ProfilingSample("Velocity", renderContext))
{
// If opaque velocity have been render during GBuffer no need to render it here
if ((ShaderConfig.s_VelocityInGbuffer == 1) || m_Owner.renderingSettings.ShouldUseForwardRenderingOnly())
return;
int w = camera.pixelWidth;
int h = camera.pixelHeight;
var cmd = new CommandBuffer { name = "" };
cmd.GetTemporaryRT(m_VelocityBuffer, w, h, 0, FilterMode.Point, Builtin.RenderLoop.GetVelocityBufferFormat(), Builtin.RenderLoop.GetVelocityBufferReadWrite());
cmd.SetRenderTarget(m_VelocityBufferRT, m_CameraDepthStencilBufferRT);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
RenderOpaqueRenderList(cullResults, camera, renderContext, "MotionVectors");
}
}
void RenderDistortion(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext)
{
if (!debugDisplaySettings.renderingDebugSettings.enableDistortion)
return;
using (new Utilities.ProfilingSample("Distortion", renderContext))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;
var cmd = new CommandBuffer { name = "" };
cmd.GetTemporaryRT(m_DistortionBuffer, w, h, 0, FilterMode.Point, Builtin.RenderLoop.GetDistortionBufferFormat(), Builtin.RenderLoop.GetDistortionBufferReadWrite());
cmd.SetRenderTarget(m_DistortionBufferRT, m_CameraDepthStencilBufferRT);
cmd.ClearRenderTarget(false, true, Color.black); // TODO: can we avoid this clear for performance ?
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
// Only transparent object can render distortion vectors
RenderTransparentRenderList(cullResults, camera, renderContext, "DistortionVectors");
}
}
void RenderPostProcesses(Camera camera, ScriptableRenderContext renderContext)
{
using (new Utilities.ProfilingSample("Post-processing", renderContext))
{
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
var cmd = new CommandBuffer { name = "" };
if (postProcessLayer != null && postProcessLayer.enabled)
{
cmd.SetGlobalTexture("_CameraDepthTexture", GetDepthTexture());
var context = m_PostProcessContext;
context.Reset();
context.source = m_CameraColorBufferRT;
context.destination = BuiltinRenderTextureType.CameraTarget;
context.command = cmd;
context.camera = camera;
context.sourceFormat = RenderTextureFormat.ARGBHalf; // ?
context.flip = true;
postProcessLayer.Render(context);
}
else
{
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
}
void NextOverlayCoord(ref float x, ref float y, float overlaySize, float width)
{
x += overlaySize;
// Go to next line if it goes outside the screen.
if (x + overlaySize > width)
{
x = 0;
y -= overlaySize;
}
}
void RenderDebugOverlay(Camera camera, ScriptableRenderContext renderContext)
{
// We don't want any overlay for these kind of rendering
if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
return;
CommandBuffer debugCB = new CommandBuffer();
debugCB.name = "Debug Overlay";
float x = 0;
float overlayRatio = debugDisplaySettings.debugOverlayRatio;
float overlaySize = Math.Min(camera.pixelHeight, camera.pixelWidth) * overlayRatio;
float y = camera.pixelHeight - overlaySize;
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
LightingDebugSettings lightingDebug = debugDisplaySettings.lightingDebugSettings;
if (lightingDebug.shadowDebugMode != ShadowMapDebugMode.None)
{
if (lightingDebug.shadowDebugMode == ShadowMapDebugMode.VisualizeShadowMap)
{
uint visualizeShadowIndex = Math.Min(lightingDebug.shadowMapIndex, (uint)(GetCurrentShadowCount() - 1));
ShadowLight shadowLight = m_ShadowsResult.shadowLights[visualizeShadowIndex];
for (int slice = 0; slice < shadowLight.shadowSliceCount; ++slice)
{
ShadowSliceData sliceData = m_ShadowsResult.shadowSlices[shadowLight.shadowSliceIndex + slice];
Vector4 texcoordScaleBias = new Vector4((float)sliceData.shadowResolution / m_Owner.shadowSettings.shadowAtlasWidth,
(float)sliceData.shadowResolution / m_Owner.shadowSettings.shadowAtlasHeight,
(float)sliceData.atlasX / m_Owner.shadowSettings.shadowAtlasWidth,
(float)sliceData.atlasY / m_Owner.shadowSettings.shadowAtlasHeight);
propertyBlock.SetVector("_TextureScaleBias", texcoordScaleBias);
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayShadowMap, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
NextOverlayCoord(ref x, ref y, overlaySize, camera.pixelWidth);
}
}
else if (lightingDebug.shadowDebugMode == ShadowMapDebugMode.VisualizeAtlas)
{
propertyBlock.SetVector("_TextureScaleBias", new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayShadowMap, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
NextOverlayCoord(ref x, ref y, overlaySize, camera.pixelWidth);
}
}
if (lightingDebug.displaySkyReflection)
{
Texture skyReflection = m_SkyManager.skyReflection;
propertyBlock.SetTexture("_InputCubemap", skyReflection);
propertyBlock.SetFloat("_Mipmap", lightingDebug.skyReflectionMipmap);
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
NextOverlayCoord(ref x, ref y, overlaySize, camera.pixelWidth);
}
renderContext.ExecuteCommandBuffer(debugCB);
}
// Function to prepare light structure for GPU lighting
void PrepareLightsForGPU(ShadowSettings shadowSettings, CullResults cullResults, Camera camera, ref ShadowOutput shadowOutput)
{
// build per tile light lists
if (m_LightLoop != null)
m_LightLoop.PrepareLightsForGPU(shadowSettings, cullResults, camera, ref shadowOutput);
}
void InitAndClearBuffer(Camera camera, ScriptableRenderContext renderContext)
{
using (new Utilities.ProfilingSample("InitAndClearBuffer", renderContext))
{
// We clear only the depth buffer, no need to clear the various color buffer as we overwrite them.
// Clear depth/stencil and init buffers
using (new Utilities.ProfilingSample("InitGBuffers and clear Depth/Stencil", renderContext))
{
var cmd = new CommandBuffer();
cmd.name = "";
// Init buffer
// With scriptable render loop we must allocate ourself depth and color buffer (We must be independent of backbuffer for now, hope to fix that later).
// Also we manage ourself the HDR format, here allocating fp16 directly.
// With scriptable render loop we can allocate temporary RT in a command buffer, they will not be release with ExecuteCommandBuffer
// These temporary surface are release automatically at the end of the scriptable render pipeline if not release explicitly
int w = camera.pixelWidth;
int h = camera.pixelHeight;
cmd.GetTemporaryRT(m_CameraColorBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
cmd.GetTemporaryRT(m_CameraSubsurfaceBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
cmd.GetTemporaryRT(m_CameraFilteringBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
if (!m_Owner.renderingSettings.ShouldUseForwardRenderingOnly())
{
m_gbufferManager.InitGBuffers(w, h, cmd);
}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearDepth);
}
// Clear the diffuse SSS lighting target
using (new Utilities.ProfilingSample("Clear SSS diffuse target", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraSubsurfaceBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
}
// Clear the SSS filtering target
using (new Utilities.ProfilingSample("Clear SSS filtering target", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraFilteringBuffer, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
}
// TEMP: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
// Clear the HDR target
using (new Utilities.ProfilingSample("Clear HDR target", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
}
// Clear GBuffers
if (!m_Owner.renderingSettings.ShouldUseForwardRenderingOnly())
{
using (new Utilities.ProfilingSample("Clear GBuffer", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
}
}
// END TEMP
}
}
}
}
| |
// 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.Xml
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
/// <summary>
/// This writer implements XmlOutputMethod.AutoDetect. If the first element is "html", then output will be
/// directed to an Html writer. Otherwise, output will be directed to an Xml writer.
/// </summary>
internal class XmlAutoDetectWriter : XmlRawWriter, IRemovableWriter
{
private XmlRawWriter _wrapped;
private OnRemoveWriter _onRemove;
private readonly XmlWriterSettings _writerSettings;
private readonly XmlEventCache _eventCache; // Cache up events until first StartElement is encountered
private readonly TextWriter _textWriter;
private readonly Stream _strm;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
private XmlAutoDetectWriter(XmlWriterSettings writerSettings)
{
Debug.Assert(writerSettings.OutputMethod == XmlOutputMethod.AutoDetect);
_writerSettings = (XmlWriterSettings)writerSettings.Clone();
_writerSettings.ReadOnly = true;
// Start caching all events
_eventCache = new XmlEventCache(string.Empty, true);
}
public XmlAutoDetectWriter(TextWriter textWriter, XmlWriterSettings writerSettings)
: this(writerSettings)
{
_textWriter = textWriter;
}
public XmlAutoDetectWriter(Stream strm, XmlWriterSettings writerSettings)
: this(writerSettings)
{
_strm = strm;
}
//-----------------------------------------------
// IRemovableWriter interface
//-----------------------------------------------
/// <summary>
/// This writer will raise this event once it has determined whether to replace itself with the Html or Xml writer.
/// </summary>
public OnRemoveWriter OnRemoveWriterEvent
{
get { return _onRemove; }
set { _onRemove = value; }
}
//-----------------------------------------------
// XmlWriter interface
//-----------------------------------------------
public override XmlWriterSettings Settings
{
get { return _writerSettings; }
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (_wrapped == null)
{
// This is the first time WriteStartElement has been called, so create the Xml or Html writer
if (ns.Length == 0 && IsHtmlTag(localName))
CreateWrappedWriter(XmlOutputMethod.Html);
else
CreateWrappedWriter(XmlOutputMethod.Xml);
}
_wrapped.WriteStartElement(prefix, localName, ns);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
Debug.Assert(_wrapped != null);
_wrapped.WriteEndAttribute();
}
public override void WriteCData(string text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteCData(text);
else
_eventCache.WriteCData(text);
}
public override void WriteComment(string text)
{
if (_wrapped == null)
_eventCache.WriteComment(text);
else
_wrapped.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
if (_wrapped == null)
_eventCache.WriteProcessingInstruction(name, text);
else
_wrapped.WriteProcessingInstruction(name, text);
}
public override void WriteWhitespace(string ws)
{
if (_wrapped == null)
_eventCache.WriteWhitespace(ws);
else
_wrapped.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteString(text);
else
_eventCache.WriteString(text);
}
public override void WriteChars(char[] buffer, int index, int count)
{
WriteString(new string(buffer, index, count));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
WriteRaw(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
if (TextBlockCreatesWriter(data))
_wrapped.WriteRaw(data);
else
_eventCache.WriteRaw(data);
}
public override void WriteEntityRef(string name)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteCharEntity(ch);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteBinHex(buffer, index, count);
}
public override void Close()
{
// Flush any cached events to an Xml writer
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.Close();
}
public override void Flush()
{
// Flush any cached events to an Xml writer
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.Flush();
}
public override void WriteValue(object value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(string value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(bool value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(double value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(float value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(decimal value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(int value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
public override void WriteValue(long value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
}
//-----------------------------------------------
// XmlRawWriter interface
//-----------------------------------------------
internal override IXmlNamespaceResolver NamespaceResolver
{
get
{
return this.resolver;
}
set
{
this.resolver = value;
if (_wrapped == null)
_eventCache.NamespaceResolver = value;
else
_wrapped.NamespaceResolver = value;
}
}
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
// Forces xml writer to be created
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteXmlDeclaration(standalone);
}
internal override void WriteXmlDeclaration(string xmldecl)
{
// Forces xml writer to be created
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteXmlDeclaration(xmldecl);
}
internal override void StartElementContent()
{
Debug.Assert(_wrapped != null);
_wrapped.StartElementContent();
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
Debug.Assert(_wrapped != null);
_wrapped.WriteEndElement(prefix, localName, ns);
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
Debug.Assert(_wrapped != null);
_wrapped.WriteFullEndElement(prefix, localName, ns);
}
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteNamespaceDeclaration(prefix, ns);
}
internal override bool SupportsNamespaceDeclarationInChunks
{
get
{
return _wrapped.SupportsNamespaceDeclarationInChunks;
}
}
internal override void WriteStartNamespaceDeclaration(string prefix)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteStartNamespaceDeclaration(prefix);
}
internal override void WriteEndNamespaceDeclaration()
{
_wrapped.WriteEndNamespaceDeclaration();
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Return true if "tagName" == "html" (case-insensitive).
/// </summary>
private static bool IsHtmlTag(string tagName)
{
if (tagName.Length != 4)
return false;
if (tagName[0] != 'H' && tagName[0] != 'h')
return false;
if (tagName[1] != 'T' && tagName[1] != 't')
return false;
if (tagName[2] != 'M' && tagName[2] != 'm')
return false;
if (tagName[3] != 'L' && tagName[3] != 'l')
return false;
return true;
}
/// <summary>
/// If a wrapped writer has not yet been created, create one.
/// </summary>
private void EnsureWrappedWriter(XmlOutputMethod outMethod)
{
if (_wrapped == null)
CreateWrappedWriter(outMethod);
}
/// <summary>
/// If the specified text consist only of whitespace, then cache the whitespace, as it is not enough to
/// force the creation of a wrapped writer. Otherwise, create a wrapped writer if one has not yet been
/// created and return true.
/// </summary>
private bool TextBlockCreatesWriter(string textBlock)
{
if (_wrapped == null)
{
// Whitespace-only text blocks aren't enough to determine Xml vs. Html
if (XmlCharType.Instance.IsOnlyWhitespace(textBlock))
{
return false;
}
// Non-whitespace text block selects Xml method
CreateWrappedWriter(XmlOutputMethod.Xml);
}
return true;
}
/// <summary>
/// Create either the Html or Xml writer and send any cached events to it.
/// </summary>
private void CreateWrappedWriter(XmlOutputMethod outMethod)
{
Debug.Assert(_wrapped == null);
// Create either the Xml or Html writer
_writerSettings.ReadOnly = false;
_writerSettings.OutputMethod = outMethod;
// If Indent was not set by the user, then default to True for Html
if (outMethod == XmlOutputMethod.Html && _writerSettings.IndentInternal == TriState.Unknown)
_writerSettings.Indent = true;
_writerSettings.ReadOnly = true;
if (_textWriter != null)
_wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_textWriter, _writerSettings)).RawWriter;
else
_wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_strm, _writerSettings)).RawWriter;
// Send cached events to the new writer
_eventCache.EndEvents();
_eventCache.EventsToWriter(_wrapped);
// Send OnRemoveWriter event
if (_onRemove != null)
(this._onRemove)(_wrapped);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Chat;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Chat.Selection
{
public class ChannelSelectionOverlay : WaveOverlayContainer
{
public static readonly float WIDTH_PADDING = 170;
private const float transition_duration = 500;
private readonly Box bg;
private readonly Triangles triangles;
private readonly Box headerBg;
private readonly SearchTextBox search;
private readonly SearchContainer<ChannelSection> sectionsFlow;
public Action<Channel> OnRequestJoin;
public Action<Channel> OnRequestLeave;
public ChannelSelectionOverlay()
{
RelativeSizeAxes = Axes.X;
Waves.FirstWaveColour = OsuColour.FromHex("353535");
Waves.SecondWaveColour = OsuColour.FromHex("434343");
Waves.ThirdWaveColour = OsuColour.FromHex("515151");
Waves.FourthWaveColour = OsuColour.FromHex("595959");
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
Children = new Drawable[]
{
bg = new Box
{
RelativeSizeAxes = Axes.Both,
},
triangles = new Triangles
{
RelativeSizeAxes = Axes.Both,
TriangleScale = 5,
},
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 85, Right = WIDTH_PADDING },
Children = new[]
{
new OsuScrollContainer
{
RelativeSizeAxes = Axes.Both,
Children = new[]
{
sectionsFlow = new SearchContainer<ChannelSection>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
LayoutDuration = 200,
LayoutEasing = Easing.OutQuint,
Spacing = new Vector2(0f, 20f),
Padding = new MarginPadding { Vertical = 20, Left = WIDTH_PADDING },
},
},
},
},
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
headerBg = new Box
{
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0f, 10f),
Padding = new MarginPadding { Top = 10f, Bottom = 10f, Left = WIDTH_PADDING, Right = WIDTH_PADDING },
Children = new Drawable[]
{
new OsuSpriteText
{
Text = @"Chat Channels",
Font = OsuFont.GetFont(size: 20),
Shadow = false,
},
search = new HeaderSearchTextBox
{
RelativeSizeAxes = Axes.X,
PlaceholderText = @"Search",
Exit = Hide,
},
},
},
},
},
};
search.Current.ValueChanged += term => sectionsFlow.SearchTerm = term.NewValue;
}
public void UpdateAvailableChannels(IEnumerable<Channel> channels)
{
Scheduler.Add(() =>
{
sectionsFlow.ChildrenEnumerable = new[]
{
new ChannelSection
{
Header = "All Channels",
Channels = channels,
},
};
foreach (ChannelSection s in sectionsFlow.Children)
{
foreach (ChannelListItem c in s.ChannelFlow.Children)
{
c.OnRequestJoin = channel => { OnRequestJoin?.Invoke(channel); };
c.OnRequestLeave = channel => { OnRequestLeave?.Invoke(channel); };
}
}
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
bg.Colour = colours.Gray3;
triangles.ColourDark = colours.Gray3;
triangles.ColourLight = OsuColour.FromHex(@"353535");
headerBg.Colour = colours.Gray2.Opacity(0.75f);
}
protected override void OnFocus(FocusEvent e)
{
search.TakeFocus();
base.OnFocus(e);
}
protected override void PopIn()
{
if (Alpha == 0) this.MoveToY(DrawHeight);
this.FadeIn(transition_duration, Easing.OutQuint);
this.MoveToY(0, transition_duration, Easing.OutQuint);
search.HoldFocus = true;
base.PopIn();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.InSine);
this.MoveToY(DrawHeight, transition_duration, Easing.InSine);
search.HoldFocus = false;
base.PopOut();
}
private class HeaderSearchTextBox : SearchTextBox
{
[BackgroundDependencyLoader]
private void load()
{
BackgroundFocused = Color4.Black.Opacity(0.2f);
BackgroundUnfocused = Color4.Black.Opacity(0.2f);
}
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Tests
{
public class AddSignalRTests
{
[Fact]
public void ServicesAddedBeforeAddSignalRAreUsed()
{
var serviceCollection = new ServiceCollection();
var markerService = new SignalRCoreMarkerService();
serviceCollection.AddSingleton(markerService);
serviceCollection.AddSingleton<IUserIdProvider, CustomIdProvider>();
serviceCollection.AddSingleton(typeof(HubLifetimeManager<>), typeof(CustomHubLifetimeManager<>));
serviceCollection.AddSingleton<IHubProtocolResolver, CustomHubProtocolResolver>();
serviceCollection.AddScoped(typeof(IHubActivator<>), typeof(CustomHubActivator<>));
serviceCollection.AddSingleton(typeof(IHubContext<>), typeof(CustomHubContext<>));
serviceCollection.AddSingleton(typeof(IHubContext<,>), typeof(CustomHubContext<,>));
var hubOptions = new HubOptionsSetup(new List<IHubProtocol>());
serviceCollection.AddSingleton<IConfigureOptions<HubOptions>>(hubOptions);
serviceCollection.AddSignalR();
var serviceProvider = serviceCollection.BuildServiceProvider();
Assert.IsType<CustomIdProvider>(serviceProvider.GetRequiredService<IUserIdProvider>());
Assert.IsType<CustomHubLifetimeManager<CustomHub>>(serviceProvider.GetRequiredService<HubLifetimeManager<CustomHub>>());
Assert.IsType<CustomHubProtocolResolver>(serviceProvider.GetRequiredService<IHubProtocolResolver>());
Assert.IsType<CustomHubActivator<CustomHub>>(serviceProvider.GetRequiredService<IHubActivator<CustomHub>>());
Assert.IsType<CustomHubContext<CustomHub>>(serviceProvider.GetRequiredService<IHubContext<CustomHub>>());
Assert.IsType<CustomHubContext<CustomTHub, string>>(serviceProvider.GetRequiredService<IHubContext<CustomTHub, string>>());
Assert.IsType<CustomHubContext<CustomDynamicHub>>(serviceProvider.GetRequiredService<IHubContext<CustomDynamicHub>>());
Assert.Equal(hubOptions, serviceProvider.GetRequiredService<IConfigureOptions<HubOptions>>());
Assert.Equal(markerService, serviceProvider.GetRequiredService<SignalRCoreMarkerService>());
}
[Fact]
public void ServicesAddedAfterAddSignalRAreUsed()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSignalR();
serviceCollection.AddSingleton<IUserIdProvider, CustomIdProvider>();
serviceCollection.AddSingleton(typeof(HubLifetimeManager<>), typeof(CustomHubLifetimeManager<>));
serviceCollection.AddSingleton<IHubProtocolResolver, CustomHubProtocolResolver>();
serviceCollection.AddScoped(typeof(IHubActivator<>), typeof(CustomHubActivator<>));
serviceCollection.AddSingleton(typeof(IHubContext<>), typeof(CustomHubContext<>));
serviceCollection.AddSingleton(typeof(IHubContext<,>), typeof(CustomHubContext<,>));
var serviceProvider = serviceCollection.BuildServiceProvider();
Assert.IsType<CustomIdProvider>(serviceProvider.GetRequiredService<IUserIdProvider>());
Assert.IsType<CustomHubLifetimeManager<CustomHub>>(serviceProvider.GetRequiredService<HubLifetimeManager<CustomHub>>());
Assert.IsType<CustomHubProtocolResolver>(serviceProvider.GetRequiredService<IHubProtocolResolver>());
Assert.IsType<CustomHubActivator<CustomHub>>(serviceProvider.GetRequiredService<IHubActivator<CustomHub>>());
Assert.IsType<CustomHubContext<CustomHub>>(serviceProvider.GetRequiredService<IHubContext<CustomHub>>());
Assert.IsType<CustomHubContext<CustomTHub, string>>(serviceProvider.GetRequiredService<IHubContext<CustomTHub, string>>());
Assert.IsType<CustomHubContext<CustomDynamicHub>>(serviceProvider.GetRequiredService<IHubContext<CustomDynamicHub>>());
}
[Fact]
public void HubSpecificOptionsDoNotAffectGlobalHubOptions()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSignalR().AddHubOptions<CustomHub>(options =>
{
options.SupportedProtocols.Clear();
options.AddFilter(new CustomHubFilter());
});
var serviceProvider = serviceCollection.BuildServiceProvider();
Assert.Equal(1, serviceProvider.GetRequiredService<IOptions<HubOptions>>().Value.SupportedProtocols.Count);
Assert.Equal(0, serviceProvider.GetRequiredService<IOptions<HubOptions<CustomHub>>>().Value.SupportedProtocols.Count);
Assert.Null(serviceProvider.GetRequiredService<IOptions<HubOptions>>().Value.HubFilters);
Assert.Single(serviceProvider.GetRequiredService<IOptions<HubOptions<CustomHub>>>().Value.HubFilters);
}
[Fact]
public void HubSpecificOptionsHaveSameValuesAsGlobalHubOptions()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSignalR().AddHubOptions<CustomHub>(options =>
{
});
var serviceProvider = serviceCollection.BuildServiceProvider();
var hubOptions = serviceProvider.GetRequiredService<IOptions<HubOptions<CustomHub>>>().Value;
var globalHubOptions = serviceProvider.GetRequiredService<IOptions<HubOptions>>().Value;
Assert.Equal(globalHubOptions.MaximumReceiveMessageSize, hubOptions.MaximumReceiveMessageSize);
Assert.Equal(globalHubOptions.StreamBufferCapacity, hubOptions.StreamBufferCapacity);
Assert.Equal(globalHubOptions.EnableDetailedErrors, hubOptions.EnableDetailedErrors);
Assert.Equal(globalHubOptions.KeepAliveInterval, hubOptions.KeepAliveInterval);
Assert.Equal(globalHubOptions.HandshakeTimeout, hubOptions.HandshakeTimeout);
Assert.Equal(globalHubOptions.SupportedProtocols, hubOptions.SupportedProtocols);
Assert.Equal(globalHubOptions.ClientTimeoutInterval, hubOptions.ClientTimeoutInterval);
Assert.Equal(globalHubOptions.MaximumParallelInvocationsPerClient, hubOptions.MaximumParallelInvocationsPerClient);
Assert.True(hubOptions.UserHasSetValues);
}
[Fact]
public void StreamBufferCapacityGetSet()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSignalR().AddHubOptions<CustomHub>(options =>
{
options.StreamBufferCapacity = 42;
});
var serviceProvider = serviceCollection.BuildServiceProvider();
Assert.Equal(42, serviceProvider.GetRequiredService<IOptions<HubOptions<CustomHub>>>().Value.StreamBufferCapacity);
}
[Fact]
public void UserSpecifiedOptionsRunAfterDefaultOptions()
{
var serviceCollection = new ServiceCollection();
// null is special when the default options setup runs, so we set to null to verify that our options run after the default
// setup runs
serviceCollection.AddSignalR(options =>
{
options.MaximumReceiveMessageSize = null;
options.StreamBufferCapacity = null;
options.EnableDetailedErrors = null;
options.KeepAliveInterval = null;
options.HandshakeTimeout = null;
options.SupportedProtocols = null;
options.ClientTimeoutInterval = TimeSpan.FromSeconds(1);
options.MaximumParallelInvocationsPerClient = 3;
});
var serviceProvider = serviceCollection.BuildServiceProvider();
var globalOptions = serviceProvider.GetRequiredService<IOptions<HubOptions>>().Value;
Assert.Null(globalOptions.MaximumReceiveMessageSize);
Assert.Null(globalOptions.StreamBufferCapacity);
Assert.Null(globalOptions.EnableDetailedErrors);
Assert.Null(globalOptions.KeepAliveInterval);
Assert.Null(globalOptions.HandshakeTimeout);
Assert.Null(globalOptions.SupportedProtocols);
Assert.Equal(3, globalOptions.MaximumParallelInvocationsPerClient);
Assert.Equal(TimeSpan.FromSeconds(1), globalOptions.ClientTimeoutInterval);
}
[Fact]
public void HubProtocolsWithNonDefaultAttributeNotAddedToSupportedProtocols()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSignalR().AddHubOptions<CustomHub>(options =>
{
});
serviceCollection.TryAddEnumerable(ServiceDescriptor.Singleton<IHubProtocol, CustomHubProtocol>());
serviceCollection.TryAddEnumerable(ServiceDescriptor.Singleton<IHubProtocol, MessagePackHubProtocol>());
var serviceProvider = serviceCollection.BuildServiceProvider();
Assert.Collection(serviceProvider.GetRequiredService<IOptions<HubOptions<CustomHub>>>().Value.SupportedProtocols,
p =>
{
Assert.Equal("json", p);
},
p =>
{
Assert.Equal("messagepack", p);
});
}
[Fact]
public void ThrowsIfSetInvalidValueForMaxInvokes()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new HubOptions() { MaximumParallelInvocationsPerClient = 0 });
}
}
public class CustomHub : Hub
{
}
public class CustomTHub : Hub<string>
{
}
public class CustomDynamicHub : DynamicHub
{
}
public class CustomIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
throw new System.NotImplementedException();
}
}
public class CustomHubProtocolResolver : IHubProtocolResolver
{
public IReadOnlyList<IHubProtocol> AllProtocols => throw new System.NotImplementedException();
public IHubProtocol GetProtocol(string protocolName, IReadOnlyList<string> supportedProtocols)
{
throw new System.NotImplementedException();
}
}
public class CustomHubActivator<THub> : IHubActivator<THub> where THub : Hub
{
public THub Create()
{
throw new System.NotImplementedException();
}
public void Release(THub hub)
{
throw new System.NotImplementedException();
}
}
public class CustomHubContext<THub> : IHubContext<THub> where THub : Hub
{
public IHubClients Clients => throw new System.NotImplementedException();
public IGroupManager Groups => throw new System.NotImplementedException();
}
public class CustomHubContext<THub, T> : IHubContext<THub, T>
where THub : Hub<T>
where T : class
{
public IHubClients<T> Clients => throw new System.NotImplementedException();
public IGroupManager Groups => throw new System.NotImplementedException();
}
public class CustomHubLifetimeManager<THub> : HubLifetimeManager<THub> where THub : Hub
{
public override Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task OnConnectedAsync(HubConnectionContext connection)
{
throw new System.NotImplementedException();
}
public override Task OnDisconnectedAsync(HubConnectionContext connection)
{
throw new System.NotImplementedException();
}
public override Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendAllAsync(string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendAllExceptAsync(string methodName, object[] args, IReadOnlyList<string> excludedConnectionIds, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendConnectionAsync(string connectionId, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendConnectionsAsync(IReadOnlyList<string> connectionIds, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendGroupAsync(string groupName, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendGroupExceptAsync(string groupName, string methodName, object[] args, IReadOnlyList<string> excludedConnectionIds, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendGroupsAsync(IReadOnlyList<string> groupNames, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendUserAsync(string userId, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
public override Task SendUsersAsync(IReadOnlyList<string> userIds, string methodName, object[] args, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
}
[NonDefaultHubProtocol]
internal class CustomHubProtocol : IHubProtocol
{
public string Name => "custom";
public int Version => throw new NotImplementedException();
public TransferFormat TransferFormat => throw new NotImplementedException();
public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)
{
throw new NotImplementedException();
}
public bool IsVersionSupported(int version)
{
throw new NotImplementedException();
}
public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, out HubMessage message)
{
throw new NotImplementedException();
}
public void WriteMessage(HubMessage message, IBufferWriter<byte> output)
{
throw new NotImplementedException();
}
}
internal class CustomHubFilter : IHubFilter
{
public ValueTask<object> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object>> next)
{
throw new NotImplementedException();
}
}
}
namespace Microsoft.AspNetCore.SignalR.Internal
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
internal class NonDefaultHubProtocolAttribute : Attribute
{
}
}
| |
// Progress bar for VBScript
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Drawing;
using System;
namespace VBScripting
{
/// <summary> Supplies a progress bar to VBScript, for illustration purposes. </summary>
[ProgId("VBScripting.ProgressBar"),
ClassInterface(ClassInterfaceType.None),
Guid("2650C2AB-4AF8-495F-AB4D-6C61BD463EA4")]
public class ProgressBar : IProgressBar
{
private Form form;
private System.Windows.Forms.ProgressBar pbar;
private int pctX = -1; // percentage of avail. screen
private int pctY = -1;
/// Constructor <summary></summary>
public ProgressBar()
{
this.form = new System.Windows.Forms.Form();
this.pbar = new System.Windows.Forms.ProgressBar();
this.SuspendLayout();
this.form.Controls.Add(this.pbar);
this.ResumeLayout(false);
this.Debug = false;
this.Minimum = 0;
this.Maximum = 100;
}
/// <summary> Gets or sets the progress bar's visibility. </summary>
/// <remarks> A boolean. The default is False. </remarks>
public bool Visible
{
get
{
return this.pbar.Visible && this.form.Visible;
}
set
{
this.form.Visible = value;
this.pbar.Visible = value;
}
}
/// <summary> Advances the progress bar one step.</summary>
public void PerformStep()
{
this.pbar.PerformStep();
}
/// <summary> Sets the size of the window. </summary>
/// <parameters> width, height </parameters>
public void FormSize(int width, int height)
{
this.form.ClientSize = new Size(width, height);
// if positioning window by percentage,
// reposition with new size
if (this.pctX > -1 && this.pctY > -1)
{
this.FormLocationByPercentage(this.pctX, this.pctY);
}
}
/// <summary> Sets the size of the progress bar. </summary>
/// <parameters> width, height </parameters>
public void PBarSize(int width, int height)
{
this.pbar.Size = new Size(width, height);
}
/// <summary> Gets or sets the value at which there is no apparent progress. </summary>
/// <remarks> An integer. The default is 0. </remarks>
public int Minimum
{
get { return this.pbar.Minimum; }
set { this.pbar.Minimum = value; }
}
/// <summary> Gets or sets the value at which the progress appears to be complete. </summary>
/// <remarks> An integer. The default is 100. </remarks>
public int Maximum
{
get { return this.pbar.Maximum; }
set { this.pbar.Maximum = value; }
}
/// <summary> Gets or sets the apparent progress. </summary>
/// <remarks> An integer. Should be at or above the minimum and at or below the maximum. </remarks>
public int Value
{
get { return this.pbar.Value; }
set
{
if (value > pbar.Maximum)
{
this.pbar.Value = pbar.Maximum;
}
else if (value < pbar.Minimum)
{
this.pbar.Value = pbar.Minimum;
}
else
{
this.pbar.Value = value;
}
}
}
/// <summary> Gets or sets the increment between steps. </summary>
public int Step
{
get { return this.pbar.Step; }
set { this.pbar.Step = value; }
}
/// <summary> Gets or sets the window title-bar text. </summary>
public string Caption
{
get { return this.form.Text; }
set { this.form.Text = value;
}
}
/// <summary> Sets the position of the window, in pixels. </summary>
/// <parameters> x, y </parameters>
public void FormLocation(int x, int y)
{
// mark as not positioning by percentage
this.pctX = -1; this.pctY = -1;
// enable manual positioning
this.form.StartPosition = FormStartPosition.Manual;
// position (locate) the window
this.form.Location = new Point(x, y);
}
/// <summary> Sets the position of the window, as a percentage of screen width and height. </summary>
/// <parameters> x, y </parameters>
public void FormLocationByPercentage(int x, int y)
{
// save percentages; if the form is resized later,
// this method will be run again to readjust the location.
this.pctX = x; this.pctY = y;
// enable manual positioning
this.form.StartPosition = FormStartPosition.Manual;
// get available screen width and height
Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
// convert percentages to pixels
int pxX = (int)((workingArea.Width - this.form.Width) * x * .0101);
int pxY = (int)((workingArea.Height - this.form.Height) * y * .0101);
// position (locate) the window
this.form.Location = new Point(pxX, pxY);
}
/// <summary> Sets the location of the progress bar within the window. </summary>
/// <parameters> x, y </parameters>
public void PBarLocation(int x, int y)
{
this.pbar.Location = new Point(x, y);
}
/// <summary> Suspends drawing of the window temporarily. </summary>
public void SuspendLayout()
{
this.form.SuspendLayout();
}
/// <summary> Resumes drawing the window. </summary>
public void ResumeLayout(bool performLayout)
{
this.form.ResumeLayout(performLayout);
}
/// <summary> Sets the icon given the filespec of an .ico file. </summary>
/// <parameters> fileName </parameters>
/// <remarks> Environment variables are allowed. </remarks>
public void SetIconByIcoFile(string fileName)
{
try
{
this.form.Icon = new Icon(System.Environment.ExpandEnvironmentVariables(fileName));
}
catch (System.IO.FileNotFoundException fnfe)
{
if (Debug)
{
MessageBox.Show(fnfe.Message, "Couldn't find icon file",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception e)
{
if (Debug) { MessageBox.Show(e.ToString()); }
}
}
/// <summary> Sets the icon given the filespec of a .dll or .exe file and an index. </summary>
/// <parameters> fileName, index </parameters>
/// <remarks> The index is an integer that identifies the icon. Environment variables are allowed. </remarks>
public void SetIconByDllFile(string fileName, int index)
{
try
{
this.form.Icon = IconExtractor.Extract(System.Environment.ExpandEnvironmentVariables(fileName), index, false);
}
catch (System.IO.FileNotFoundException fnfe)
{
if (Debug)
{
MessageBox.Show(fnfe.Message, "Couldn't find icon file",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else throw;
}
catch (Exception e)
{
if (Debug)
{
MessageBox.Show(string.Format(
" Error setting icon from file \n" +
" {0} \n with index {1} \n\n {2}",
fileName, index, e.ToString()
));
}
else throw;
}
}
/// <summary> Gets or sets whether the type is under development. </summary>
/// <remarks> Affects the behavior of two methods, SetIconByIcoFile and SetIconByDllFile, if exceptions are thrown: when debugging, a message box is shown. Default is False. </remarks>
public bool Debug { get; set; }
/// <summary> Provides an object useful in VBScript for setting FormBorderStyle. </summary>
/// <returns> a FormBorderStyleT </returns>
public FormBorderStyleT BorderStyle
{
get { return new FormBorderStyleT(); }
private set { }
}
/// <summary> Sets the style of the window border. </summary>
/// <remarks> An integer. One of the BorderStyle property return values can be used: Fixed3D, FixedDialog, FixedSingle, FixedToolWindow, None, Sizable (default), or SizableToolWindow. VBScript example: <pre> pb.FormBorderStyle = pb.BorderStyle.Fixed3D </pre></remarks>
public int FormBorderStyle
{
set
{
if (value == this.BorderStyle.Fixed3D)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
}
else if (value == this.BorderStyle.FixedDialog)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
}
else if (value == this.BorderStyle.FixedSingle)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
}
else if (value == this.BorderStyle.FixedToolWindow)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
}
else if (value == this.BorderStyle.None)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
else if (value == this.BorderStyle.Sizable)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
}
else if (value == this.BorderStyle.SizableToolWindow)
{
this.form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
}
}
}
/// <summary> Disposes of the object's resources. </summary>
public void Dispose()
{
this.pbar.Dispose();
this.form.Dispose();
}
}
/// <summary> Enumeration of border styles. </summary>
/// <remarks> This class is available to VBScript via the <tt>ProgressBar.BorderStyle</tt> property. </remarks>
[Guid("2650C2AB-4DF8-495F-AB4D-6C61BD463EA4")]
public class FormBorderStyleT
{
/// <returns> 1 </returns>
public int Fixed3D
{
get { return 1; }
private set { }
}
/// <returns> 2 </returns>
public int FixedDialog
{
get { return 2; }
private set { }
}
/// <returns> 3 </returns>
public int FixedSingle
{
get { return 3; }
private set { }
}
/// <returns> 4 </returns>
public int FixedToolWindow
{
get { return 4; }
private set { }
}
/// <returns> 5 </returns>
public int None
{
get { return 5; }
private set { }
}
/// <returns> 6 </returns>
public int Sizable
{
get { return 6; }
private set { }
}
/// <returns> 7 </returns>
public int SizableToolWindow
{
get { return 7; }
private set { }
}
}
/// <summary> Exposes the VBScripting.ProgressBar members to COM/VBScript. </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
Guid("2650C2AB-4BF8-495F-AB4D-6C61BD463EA4")]
public interface IProgressBar
{
/// <summary> </summary>
[DispId(1)]
bool Visible { get; set; }
/// <summary> </summary>
[DispId(2)]
void PerformStep();
/// <summary> </summary>
[DispId(3)]
void FormSize(int width, int height);
/// <summary> </summary>
[DispId(4)]
void PBarSize(int width, int height);
/// <summary> </summary>
[DispId(5)]
int Minimum { get; set; }
/// <summary> </summary>
[DispId(6)]
int Maximum { get; set; }
/// <summary> </summary>
[DispId(7)]
int Value { get; set; }
/// <summary> </summary>
[DispId(8)]
int Step { get; set; }
/// <summary> </summary>
[DispId(10)]
string Caption { get; set; }
/// <summary> </summary>
[DispId(11)]
void FormLocation(int x, int y);
/// <summary> </summary>
[DispId(15)]
void FormLocationByPercentage(int x, int y);
/// <summary> </summary>
[DispId(12)]
void PBarLocation(int x, int y);
/// <summary> </summary>
[DispId(13)]
void SuspendLayout();
/// <summary> </summary>
[DispId(14)]
void ResumeLayout(bool performLayout);
/// <summary> </summary>
[DispId(20)]
void SetIconByIcoFile(string fileName);
/// <summary> </summary>
[DispId(16)]
void SetIconByDllFile(string fileName, int index);
/// <summary> </summary>
[DispId(17)]
bool Debug { get; set; }
/// <summary> </summary>
[DispId(18)]
FormBorderStyleT BorderStyle { get; }
/// <summary> </summary>
[DispId(19)]
int FormBorderStyle { set; }
/// <summary> </summary>
[DispId(21)]
void Dispose();
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.decoration
{
/// <summary>
/// <para>Mixin for the box shadow CSS property.
/// This mixin is usually used by <see cref="qx.ui.decoration.DynamicDecorator"/>.</para>
/// <para>Keep in mind that this is not supported by all browsers:</para>
/// <list type="bullet">
/// <item>Firefox 3,5+</item>
/// <item>IE9+</item>
/// <item>Safari 3.0+</item>
/// <item>Opera 10.5+</item>
/// <item>Chrome 4.0+</item>
/// </list>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.decoration.MBoxShadow", OmitOptionalParameters = true, Export = false)]
public partial class MBoxShadow
{
#region Properties
/// <summary>
/// <para>Inset shadows are drawn inside the border.</para>
/// </summary>
[JsProperty(Name = "inset", NativeField = true)]
public bool Inset { get; set; }
/// <summary>
/// <para>The blur radius of the shadow.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "shadowBlurRadius", NativeField = true)]
public double ShadowBlurRadius { get; set; }
/// <summary>
/// <para>The color of the shadow.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "shadowColor", NativeField = true)]
public string ShadowColor { get; set; }
/// <summary>
/// <para>Horizontal length of the shadow.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "shadowHorizontalLength", NativeField = true)]
public double ShadowHorizontalLength { get; set; }
/// <summary>
/// <para>Property group to set the shadow length.</para>
/// </summary>
[JsProperty(Name = "shadowLength", NativeField = true)]
public object ShadowLength { get; set; }
/// <summary>
/// <para>The spread radius of the shadow.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "shadowSpreadRadius", NativeField = true)]
public double ShadowSpreadRadius { get; set; }
/// <summary>
/// <para>Vertical length of the shadow.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "shadowVerticalLength", NativeField = true)]
public double ShadowVerticalLength { get; set; }
#endregion Properties
#region Methods
public MBoxShadow() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property inset.</para>
/// </summary>
[JsMethod(Name = "getInset")]
public bool GetInset() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property shadowBlurRadius.</para>
/// </summary>
[JsMethod(Name = "getShadowBlurRadius")]
public double GetShadowBlurRadius() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property shadowColor.</para>
/// </summary>
[JsMethod(Name = "getShadowColor")]
public string GetShadowColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property shadowHorizontalLength.</para>
/// </summary>
[JsMethod(Name = "getShadowHorizontalLength")]
public double GetShadowHorizontalLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property shadowSpreadRadius.</para>
/// </summary>
[JsMethod(Name = "getShadowSpreadRadius")]
public double GetShadowSpreadRadius() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property shadowVerticalLength.</para>
/// </summary>
[JsMethod(Name = "getShadowVerticalLength")]
public double GetShadowVerticalLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property inset
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property inset.</param>
[JsMethod(Name = "initInset")]
public void InitInset(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property shadowBlurRadius
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property shadowBlurRadius.</param>
[JsMethod(Name = "initShadowBlurRadius")]
public void InitShadowBlurRadius(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property shadowColor
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property shadowColor.</param>
[JsMethod(Name = "initShadowColor")]
public void InitShadowColor(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property shadowHorizontalLength
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property shadowHorizontalLength.</param>
[JsMethod(Name = "initShadowHorizontalLength")]
public void InitShadowHorizontalLength(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property shadowSpreadRadius
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property shadowSpreadRadius.</param>
[JsMethod(Name = "initShadowSpreadRadius")]
public void InitShadowSpreadRadius(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property shadowVerticalLength
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property shadowVerticalLength.</param>
[JsMethod(Name = "initShadowVerticalLength")]
public void InitShadowVerticalLength(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property inset equals true.</para>
/// </summary>
[JsMethod(Name = "isInset")]
public void IsInset() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property inset.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetInset")]
public void ResetInset() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowBlurRadius.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowBlurRadius")]
public void ResetShadowBlurRadius() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowColor.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowColor")]
public void ResetShadowColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowHorizontalLength.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowHorizontalLength")]
public void ResetShadowHorizontalLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowLength.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowLength")]
public void ResetShadowLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowSpreadRadius.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowSpreadRadius")]
public void ResetShadowSpreadRadius() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property shadowVerticalLength.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetShadowVerticalLength")]
public void ResetShadowVerticalLength() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property inset.</para>
/// </summary>
/// <param name="value">New value for property inset.</param>
[JsMethod(Name = "setInset")]
public void SetInset(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property shadowBlurRadius.</para>
/// </summary>
/// <param name="value">New value for property shadowBlurRadius.</param>
[JsMethod(Name = "setShadowBlurRadius")]
public void SetShadowBlurRadius(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property shadowColor.</para>
/// </summary>
/// <param name="value">New value for property shadowColor.</param>
[JsMethod(Name = "setShadowColor")]
public void SetShadowColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property shadowHorizontalLength.</para>
/// </summary>
/// <param name="value">New value for property shadowHorizontalLength.</param>
[JsMethod(Name = "setShadowHorizontalLength")]
public void SetShadowHorizontalLength(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group shadowLength.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="shadowHorizontalLength">Sets the value of the property #shadowHorizontalLength.</param>
/// <param name="shadowVerticalLength">Sets the value of the property #shadowVerticalLength.</param>
[JsMethod(Name = "setShadowLength")]
public void SetShadowLength(object shadowHorizontalLength, object shadowVerticalLength) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property shadowSpreadRadius.</para>
/// </summary>
/// <param name="value">New value for property shadowSpreadRadius.</param>
[JsMethod(Name = "setShadowSpreadRadius")]
public void SetShadowSpreadRadius(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property shadowVerticalLength.</para>
/// </summary>
/// <param name="value">New value for property shadowVerticalLength.</param>
[JsMethod(Name = "setShadowVerticalLength")]
public void SetShadowVerticalLength(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property inset.</para>
/// </summary>
[JsMethod(Name = "toggleInset")]
public void ToggleInset() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
namespace Macabresoft.Macabre2D.UI.Common;
using System;
using System.ComponentModel;
using Avalonia.Input;
using Macabresoft.Macabre2D.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
/// <summary>
/// A base class for gizmos that can operate on one axis or the other.
/// </summary>
public abstract class BaseAxisGizmo : BaseDrawer, IGizmo {
/// <summary>
/// The size used on a gizmo's point (the place where the gizmo can be grabbed by the mouse).
/// </summary>
protected const int GizmoPointSize = 16;
private const float FloatingPointTolerance = 0.0001f;
private ICamera _camera;
/// <summary>
/// Initializes a new instance of the <see cref="BaseAxisGizmo" /> class.
/// </summary>
/// <param name="editorService">The editor service.</param>
/// <param name="sceneService">The scene service.</param>
/// <param name="entityService">The selection service.</param>
protected BaseAxisGizmo(IEditorService editorService, ISceneService sceneService, IEntityService entityService) {
this.UseDynamicLineThickness = true;
this.LineThickness = 1f;
this.EditorService = editorService;
this.EditorService.PropertyChanged += this.EditorService_PropertyChanged;
this.SceneService = sceneService;
this.EntityService = entityService;
this.EntityService.PropertyChanged += this.SelectionService_PropertyChanged;
}
/// <inheritdoc />
public override BoundingArea BoundingArea => this._camera?.BoundingArea ?? BoundingArea.Empty;
/// <inheritdoc />
public abstract GizmoKind GizmoKind { get; }
/// <summary>
/// Gets the camera.
/// </summary>
protected ICamera Camera => this._camera;
/// <summary>
/// Gets the editor service.
/// </summary>
protected IEditorService EditorService { get; }
/// <summary>
/// Gets the selection service.
/// </summary>
protected IEntityService EntityService { get; }
/// <summary>
/// Gets the scene service.
/// </summary>
protected ISceneService SceneService { get; }
/// <summary>
/// Gets or sets the current axis being operated on.
/// </summary>
protected GizmoAxis CurrentAxis { get; set; } = GizmoAxis.None;
/// <summary>
/// Gets or sets the neutral axis position, which is the intersection of the X and Y axis.
/// </summary>
protected Vector2 NeutralAxisPosition { get; private set; }
/// <summary>
/// Gets or sets the end point of the x axis line.
/// </summary>
protected Vector2 XAxisPosition { get; set; }
/// <summary>
/// Gets or sets the end point of the y axis line.
/// </summary>
protected Vector2 YAxisPosition { get; set; }
/// <inheritdoc />
public override void Initialize(IScene scene, IEntity entity) {
base.Initialize(scene, entity);
this.LineThickness = 3f;
if (this.TryGetParentEntity(out this._camera)) {
this.Camera.PropertyChanged += this.Camera_PropertyChanged;
}
else {
throw new NullReferenceException(nameof(this._camera));
}
this.ResetIsEnabled();
}
/// <inheritdoc />
public override void Render(FrameTime frameTime, BoundingArea viewBoundingArea) {
if (this.Scene.Game.SpriteBatch is SpriteBatch spriteBatch && this.PrimitiveDrawer is PrimitiveDrawer drawer) {
var lineThickness = this.GetLineThickness(viewBoundingArea.Height);
var lineOffset = lineThickness * this.Scene.Game.Project.Settings.InversePixelsPerUnit * -0.5f;
var lineOffsetVector = new Vector2(-lineOffset, lineOffset);
var pixelsPerUnit = this.Scene.Game.Project.Settings.PixelsPerUnit;
drawer.DrawLine(spriteBatch, pixelsPerUnit, this.NeutralAxisPosition, this.XAxisPosition, this.EditorService.DropShadowColor, lineThickness);
drawer.DrawLine(spriteBatch, pixelsPerUnit, this.NeutralAxisPosition, this.YAxisPosition, this.EditorService.DropShadowColor, lineThickness);
drawer.DrawLine(spriteBatch, pixelsPerUnit, this.NeutralAxisPosition + lineOffsetVector, this.XAxisPosition + lineOffsetVector, this.EditorService.XAxisColor, lineThickness);
drawer.DrawLine(spriteBatch, pixelsPerUnit, this.NeutralAxisPosition + lineOffsetVector, this.YAxisPosition + lineOffsetVector, this.EditorService.YAxisColor, lineThickness);
}
}
/// <inheritdoc />
public virtual bool Update(FrameTime frameTime, InputState inputState) {
if (this.EntityService.Selected != null && this.CurrentAxis == GizmoAxis.None) {
this.ResetEndPoints();
}
return false;
}
/// <summary>
/// Gets the length of an axis line based on the view height.
/// </summary>
/// <returns>The length of an axis line.</returns>
protected float GetAxisLength() {
return this._camera.BoundingArea.Height * 0.1f;
}
/// <summary>
/// Gets the axis that is currently under the mouse.
/// </summary>
/// <param name="mousePosition">The mouse position.</param>
/// <returns>The axis currently under the mouse, or none if the mouse is not over an axis.</returns>
protected GizmoAxis GetAxisUnderMouse(Vector2 mousePosition) {
var result = GizmoAxis.None;
var viewRatio = this.Scene.Game.Project.Settings.GetPixelAgnosticRatio(this.Camera.ViewHeight, this.Scene.Game.ViewportSize.Y);
var radius = viewRatio * GizmoPointSize * this.Scene.Game.Project.Settings.InversePixelsPerUnit * 0.5f;
if (Vector2.Distance(this.XAxisPosition, mousePosition) < radius) {
result = GizmoAxis.X;
}
else if (Vector2.Distance(this.YAxisPosition, mousePosition) < radius) {
result = GizmoAxis.Y;
}
else if (Vector2.Distance(this.NeutralAxisPosition, mousePosition) < radius) {
result = GizmoAxis.Neutral;
}
return result;
}
/// <summary>
/// Moves the end positions of the gizmo along the axis appropriately. Basically, this makes sure the drag operation is all
/// good.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <param name="moveToPosition">The position to move to (typically the mouse position).</param>
/// <returns>The new position the dragged end position should be.</returns>
protected Vector2 MoveAlongAxis(Vector2 start, Vector2 end, Vector2 moveToPosition) {
var slope = Math.Abs(end.X - start.X) > FloatingPointTolerance ? (end.Y - start.Y) / (end.X - start.X) : 1f;
var yIntercept = end.Y - slope * end.X;
Vector2 newPosition;
if (Math.Abs(slope) <= 0.5f) {
if (Math.Abs(slope) < FloatingPointTolerance) {
newPosition = new Vector2(moveToPosition.X, end.Y);
}
else {
var newX = (moveToPosition.Y - yIntercept) / slope;
newPosition = new Vector2(newX, moveToPosition.Y);
}
}
else {
if (Math.Abs(Math.Abs(slope) - 1f) < FloatingPointTolerance) {
newPosition = new Vector2(end.X, moveToPosition.Y);
}
else {
var newY = slope * moveToPosition.X + yIntercept;
newPosition = new Vector2(moveToPosition.X, newY);
}
}
return newPosition;
}
/// <summary>
/// Resets the end points for each axis of the gizmo.
/// </summary>
protected void ResetEndPoints() {
var transformable = this.EntityService.Selected;
if (transformable != null) {
var axisLength = this.GetAxisLength();
var worldTransform = transformable.Transform;
this.NeutralAxisPosition = worldTransform.Position;
this.XAxisPosition = worldTransform.Position + new Vector2(axisLength, 0f);
this.YAxisPosition = worldTransform.Position + new Vector2(0f, axisLength);
}
}
/// <summary>
/// Sets the cursor type for the Avalonia window.
/// </summary>
/// <param name="cursorType">The cursor type.</param>
protected void SetCursor(StandardCursorType cursorType) {
this.EditorService.CursorType = cursorType;
}
/// <summary>
/// A check that gets called when the selected gizmo, selected entity, or selected component changes.
/// </summary>
/// <returns>A value indicating whether or not this should be enabled.</returns>
protected virtual bool ShouldBeEnabled() {
return this.GizmoKind == this.EditorService.SelectedGizmo && !(this.EntityService.Selected is IScene);
}
private void Camera_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(ICamera.ViewHeight)) {
this.ResetEndPoints();
}
}
private void EditorService_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(IEditorService.SelectedGizmo)) {
this.ResetIsEnabled();
}
else if (e.PropertyName == nameof(IEditorService.XAxisColor)) {
}
else if (e.PropertyName == nameof(IEditorService.YAxisColor)) {
}
}
private void ResetIsEnabled() {
this.IsEnabled = this.ShouldBeEnabled();
this.IsVisible = this.IsEnabled;
if (this.IsVisible) {
this.ResetEndPoints();
}
}
private void SelectionService_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(IEntityService.Selected)) {
this.ResetIsEnabled();
}
}
/// <summary>
/// Represents the axis a gizmo is being operated on.
/// </summary>
protected enum GizmoAxis {
X,
Y,
Neutral,
None
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This class will encapsulate an uint and
** provide an Object representation of it.
**
**
===========================================================*/
using System.Globalization;
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
// * Wrapper for unsigned 32 bit integers.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct UInt32 : IComparable, IFormattable, IConvertible
, IComparable<UInt32>, IEquatable<UInt32>
{
private uint m_value;
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt32)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt32"));
}
public int CompareTo(UInt32 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is UInt32))
{
return false;
}
return m_value == ((UInt32)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(UInt32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return ((int)m_value);
}
// The base 10 representation of the number with no extra padding.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s)
{
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, IFormatProvider provider)
{
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt32 result)
{
return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return m_value;
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
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 MiniOa.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.Collections.ObjectModel;
using System.Data.Entity.Migrations;
using System.Linq;
using BikeMates.DataAccess.Repository;
using BikeMates.Domain.Entities;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using BikeMates.DataAccess.Managers;
namespace BikeMates.DataAccess.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<BikeMatesDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(BikeMatesDbContext context)
{
SeedBikeMates(context);
}
private void SeedBikeMates(BikeMatesDbContext context)
{
User user = new User();
CreateRole("Admin", context);
CreateRole("User", context);
AddInitialAdmin("admin@admin.com", "admin", "admin", "Qwerty1#",context);
int routesCount=0;
for (int i = 0; i < 100; i++)
{
user = AddUser(i, context);
for (int j = 0; j < 10; j++)
{
routesCount++;
AddRoute(routesCount, user, context);
}
}
//TEST: adding custom route
var routeRepository = new RouteRepository(context);
routeRepository.Add(new Route
{
Author = user,
Title = "Madness",
MeetingPlace = "NOVUS, near Osokorki station.",
Description = "Insane way to get to another subway station...",
Start = DateTime.Now,
MapData = new MapData
{
End = new Coordinate
{
Latitude =50.3942303,
Longitude =30.600585700000011
},
Start = new Coordinate
{
Latitude =50.394672,
Longitude =30.616593799999919
},
Waypoints = new List<Coordinate>
{
new Coordinate
{
Latitude =50.418354099999988,
Longitude =30.709839500000044
},
new Coordinate
{
Latitude =50.523433,
Longitude =30.627987800000028
},
new Coordinate
{
Latitude =50.5202178,
Longitude =30.453903099999934
},
new Coordinate
{
Latitude =50.6150969,
Longitude =30.166428999999994
},
new Coordinate
{
Latitude =50.506747999999988,
Longitude =30.053443000000016
},
new Coordinate
{
Latitude =50.3581845,
Longitude =30.156392600000004
}
}
},
Distance = 171.321
});
}
private void CreateRole(string roleName, BikeMatesDbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var role = new IdentityRole();
if (!roleManager.RoleExists(roleName))
{
role = new IdentityRole();
role.Name = roleName;
roleManager.Create(role);
}
}
private void AddInitialAdmin(string email, string firstname, string lastname, string password, BikeMatesDbContext context)
{
var userManager = new UserManager(context);
var admin = new User { Email = email, UserName = email, Role = "Admin", FirstName = firstname, SecondName = lastname };
if (userManager.FindByEmail(email) == null)
{
userManager.Create(admin, password);
userManager.AddToRole(admin.Id, "Admin");
}
}
private void AddRoute(int index, User author, BikeMatesDbContext context)
{
Route route = new Route();
Coordinate start = context.Coordinates.Add(new Coordinate
{
Latitude = 50.4653661,
Longitude = 30.521903599999973
});
Coordinate end = context.Coordinates.Add(new Coordinate
{
Latitude = 50.466008599999988,
Longitude = 30.511753699999986
});
MapData mapdata = context.MapDatas.Add(new MapData { Start = start, End = end });
Collection<User> subscribers = new Collection<User>();
if (context.Users.Count() > 10)
{
var randomUsers = context.Users.OrderBy(r => Guid.NewGuid()).Take(5);
foreach (var item in randomUsers)
{
subscribers.Add(item);
}
}
route = context.Routes.Add(new Route
{
Start = DateTime.Today,
Distance = 1.897,
Description =
"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor." +
" Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus." +
" Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. ",
Title = "Test-route-" + index,
IsBanned = index%2==0,
MeetingPlace =
"Near the Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.",
MapData = mapdata,
Author = author,
Subscribers = subscribers
});
context.Routes.Add(route);
context.SaveChanges();
}
private User AddUser(int index, BikeMatesDbContext context)
{
var userManager = new UserManager(context);
User user = new User
{
FirstName = "John-" + index,
SecondName = "Doe-" + index,
Email = "Username-" + index + "@bikemates.com",
EmailConfirmed = true,
UserName = "Username-" + index + "@bikemates.com",
About =
@"I'm just a test user. My whole life story:\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. ",
PasswordHash = "AEPu4Rln+Qak4i79daRuRlcAe70OQ+uvYDJreFYyoudb0iWaorIkAV/crymPqTpV6w==", //1234qwerQ_
SecurityStamp = "b56fd8f5-0dac-4360-9def-175f9dab8aaf",
PhoneNumberConfirmed = false,
TwoFactorEnabled = false,
LockoutEnabled = false,
IsBanned = index%2==0,
AccessFailedCount = 0
};
user = context.Users.Add(user);
context.SaveChanges();
user.Role = "User";
userManager.AddToRole(user.Id, "User");
return user;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using static PInvoke.Kernel32;
using Win32Exception = System.ComponentModel.Win32Exception;
namespace BlackFox.Win32.Kernel32
{
public static class Kernel32Dll
{
static unsafe bool DeviceIoControlCore(
SafeObjectHandle hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
out int pBytesReturned,
OVERLAPPED? lpOverlapped)
{
using (var overlapped = lpOverlapped.Pin())
{
return Kernell32DllNativeMethods.DeviceIoControl(hDevice, dwIoControlCode, inBuffer, nInBufferSize,
outBuffer, nOutBufferSize, out pBytesReturned, (OVERLAPPED*)overlapped.Pointer);
}
}
public static bool DeviceIoControl(
SafeObjectHandle hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
OVERLAPPED lpOverlapped)
{
int pBytesReturned;
return DeviceIoControlCore(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer, nOutBufferSize,
out pBytesReturned, lpOverlapped);
}
public static bool DeviceIoControl(
SafeObjectHandle hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
out int pBytesReturned)
{
return DeviceIoControlCore(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer, nOutBufferSize,
out pBytesReturned, null);
}
const int ErrorIoPending = 997;
static void ThrowLastWin32Exception()
{
throw new Win32Exception();
}
static void SetFromLastWin32Exception<T>(TaskCompletionSource<T> tcs)
{
try
{
ThrowLastWin32Exception();
}
catch (Win32Exception exception)
{
tcs.SetException(exception);
}
}
unsafe delegate bool OverlappedMethod(OVERLAPPED* overlapped);
static unsafe Task<int> OverlappedAsync(SafeObjectHandle handle, OverlappedMethod nativeMethod,
CancellationToken cancellationToken)
{
var finishedEvent = new ManualResetEvent(false);
var overlapped = new OVERLAPPED
{
hEvent = finishedEvent.SafeWaitHandle.DangerousGetHandle()
}.Pin();
var result = nativeMethod((OVERLAPPED*)overlapped.Pointer);
var completionSource = new TaskCompletionSource<int>();
var finishedSynchronously = FinishOverlappedSynchronously(handle, cancellationToken,
overlapped, completionSource, result);
if (finishedSynchronously)
{
overlapped.Dispose();
finishedEvent.Dispose();
}
else
{
FinishOverlappedAsynchronously(handle, overlapped, finishedEvent, completionSource, cancellationToken);
}
return completionSource.Task;
}
private class OverlappedState
{
public bool IsCancellation { get; }
public RegisteredWaitHandle OtherRegistration { get; set; }
public OverlappedState(bool isCancellation)
{
IsCancellation = isCancellation;
}
public void Unregister()
{
OtherRegistration?.Unregister(null);
}
}
static unsafe void FinishOverlappedAsynchronously(SafeObjectHandle handle, PinnedStruct<OVERLAPPED> overlapped,
ManualResetEvent finishedEvent, TaskCompletionSource<int> completionSource, CancellationToken cancellationToken)
{
var alreadyFinished = false;
var lockObject = new object();
WaitOrTimerCallback callback = (state, timedOut) =>
{
var overlappedState = (OverlappedState) state;
lock (lockObject)
{
if (alreadyFinished)
{
return;
}
overlappedState.Unregister();
if (overlappedState.IsCancellation || cancellationToken.IsCancellationRequested)
{
CancelIoEx(handle, (OVERLAPPED*) overlapped.Pointer);
completionSource.SetCanceled();
}
else
{
int bytesReturned;
var overlappedResult = GetOverlappedResult(handle, (OVERLAPPED*)overlapped.Pointer,
out bytesReturned, false);
overlapped.Dispose();
finishedEvent.Dispose();
if (overlappedResult)
{
completionSource.SetResult(bytesReturned);
}
else
{
SetFromLastWin32Exception(completionSource);
}
}
alreadyFinished = true;
}
};
lock (lockObject)
{
var finishedState = new OverlappedState(false);
var cancelledState = new OverlappedState(true);
var finishedWait = ThreadPool.RegisterWaitForSingleObject(finishedEvent, callback, finishedState, -1, true);
cancelledState.OtherRegistration = finishedWait;
if (cancellationToken != CancellationToken.None)
{
var cancelledWait = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle,
callback,
cancelledState, -1, true);
finishedState.OtherRegistration = cancelledWait;
}
}
}
static unsafe bool FinishOverlappedSynchronously(SafeObjectHandle handle, CancellationToken cancellationToken,
PinnedStruct<OVERLAPPED> overlapped, TaskCompletionSource<int> completionSource, bool nativeMethodResult)
{
if (!nativeMethodResult)
{
var error = Marshal.GetLastWin32Error();
if (error != ErrorIoPending)
{
if (cancellationToken.IsCancellationRequested)
{
completionSource.SetCanceled();
}
else
{
SetFromLastWin32Exception(completionSource);
}
return true;
}
// Async IO in progress
return false;
}
int pBytesReturned;
GetOverlappedResult(handle, (OVERLAPPED*)overlapped.Pointer,
out pBytesReturned, false);
if (cancellationToken.IsCancellationRequested)
{
completionSource.SetCanceled();
}
else
{
completionSource.SetResult(pBytesReturned);
}
return true;
}
public static unsafe Task<int> DeviceIoControlAsync(
SafeObjectHandle hDevice,
uint dwIoControlCode,
IntPtr inBuffer,
int nInBufferSize,
IntPtr outBuffer,
int nOutBufferSize,
CancellationToken cancellationToken = default(CancellationToken))
{
return OverlappedAsync(hDevice, lpOverlapped =>
{
int pBytesReturned;
return Kernell32DllNativeMethods.DeviceIoControl(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer,
nOutBufferSize, out pBytesReturned, lpOverlapped);
}, cancellationToken);
}
public static unsafe Task<int> WriteFileAsync(
SafeObjectHandle handle,
IntPtr buffer,
int numberOfBytesToWrite,
CancellationToken cancellationToken = default(CancellationToken))
{
return OverlappedAsync(handle, lpOverlapped =>
{
return WriteFile(handle, buffer.ToPointer(), numberOfBytesToWrite, null, lpOverlapped);
}, cancellationToken);
}
public static async Task<int> WriteFileAsync<T>(SafeObjectHandle handle, ArraySegment<T> arraySegment,
CancellationToken cancellationToken = default(CancellationToken))
where T : struct
{
using (var asFixed = new FixedArraySegment<T>(arraySegment))
{
return await WriteFileAsync(handle, asFixed.Pointer, asFixed.SizeInBytes, cancellationToken);
}
}
public static unsafe Task<int> ReadFileAsync(SafeObjectHandle handle, IntPtr buffer, int numberOfBytesToRead,
CancellationToken cancellationToken = default(CancellationToken))
{
return OverlappedAsync(handle, lpOverlapped =>
{
return ReadFile(handle, buffer.ToPointer(), numberOfBytesToRead, null, lpOverlapped);
}, cancellationToken);
}
public static async Task<ArraySegment<T>> ReadFileAsync<T>(SafeObjectHandle handle, int numberOfElementsToRead,
CancellationToken cancellationToken = default(CancellationToken))
where T : struct
{
var buffer = new T[numberOfElementsToRead];
var segment = new ArraySegment<T>(buffer);
using (var asFixed = new FixedArraySegment<T>(segment))
{
var bytesRead = await ReadFileAsync(handle, asFixed.Pointer, asFixed.SizeInBytes, cancellationToken);
var elementsRead = bytesRead / asFixed.ElementSize;
return new ArraySegment<T>(buffer, 0, elementsRead);
}
}
}
}
| |
using EIDSS.Reports.Document.Veterinary.AvianInvestigation;
using EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockSampleDataSetTableAdapters;
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class LivestockSampleReport
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LivestockSampleReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.m_DataSet = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockSampleDataSet();
this.m_Adapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockSampleDataSetTableAdapters.SamplesLivestockAdapter();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell22,
this.xrTableCell2,
this.xrTableCell19,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell15,
this.xrTableCell20,
this.xrTableCell24,
this.xrTableCell14});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
//
// xrTableCell5
//
this.xrTableCell5.Angle = 90F;
this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strSampeType")});
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
//
// xrTableCell6
//
this.xrTableCell6.Angle = 90F;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strFieldSampleID")});
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
//
// xrTableCell22
//
this.xrTableCell22.Angle = 90F;
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strAnimalID")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
//
// xrTableCell2
//
this.xrTableCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strSpecies")});
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
//
// xrTableCell19
//
this.xrTableCell19.Angle = 90F;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.datCollected", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
//
// xrTableCell16
//
this.xrTableCell16.Angle = 90F;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.datAccession", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strCondition")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strComment")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strCollectedByOffice")});
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
//
// xrTableCell24
//
this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strCollectedByPerson")});
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "SamplesLivestock.strSendToOffice")});
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.xrTableCell1,
this.xrTableCell21,
this.xrTableCell4,
this.xrTableCell11,
this.xrTableCell9,
this.xrTableCell12,
this.xrTableCell8,
this.xrTableCell13,
this.xrTableCell23,
this.xrTableCell7});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
//
// xrTableCell3
//
this.xrTableCell3.Angle = 90F;
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
//
// xrTableCell1
//
this.xrTableCell1.Angle = 90F;
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
//
// xrTableCell21
//
this.xrTableCell21.Angle = 90F;
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
//
// xrTableCell11
//
this.xrTableCell11.Angle = 90F;
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
//
// xrTableCell9
//
this.xrTableCell9.Angle = 90F;
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
//
// xrTableCell23
//
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "SampleDataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// LivestockSampleReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DataAdapter = this.m_Adapter;
this.DataMember = "SamplesLivestock";
this.DataSource = this.m_DataSet;
resources.ApplyResources(this, "$this");
this.ExportOptions.Xls.SheetName = resources.GetString("LivestockSampleReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("LivestockSampleReport.ExportOptions.Xlsx.SheetName");
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Version = "14.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private LivestockSampleDataSet m_DataSet;
private SamplesLivestockAdapter m_Adapter;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Scriban.Runtime;
namespace Scriban.Syntax
{
/// <summary>
/// A for in loop statement.
/// </summary>
[ScriptSyntax("for statement", "for <variable> in <expression> ... end")]
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptForStatement : ScriptLoopStatementBase, IScriptNamedArgumentContainer
{
private ScriptKeyword _forOrTableRowKeyword;
private ScriptExpression _variable;
private ScriptKeyword _inKeyword;
private ScriptExpression _iterator;
private ScriptList<ScriptNamedArgument> _namedArguments;
private ScriptBlockStatement _body;
private ScriptElseStatement _else;
public ScriptForStatement()
{
ForOrTableRowKeyword = this is ScriptTableRowStatement ? ScriptKeyword.TableRow() : ScriptKeyword.For();
InKeyword = ScriptKeyword.In();
}
public ScriptKeyword ForOrTableRowKeyword
{
get => _forOrTableRowKeyword;
set => ParentToThis(ref _forOrTableRowKeyword, value);
}
public ScriptExpression Variable
{
get => _variable;
set => ParentToThis(ref _variable, value);
}
public ScriptKeyword InKeyword
{
get => _inKeyword;
set => ParentToThis(ref _inKeyword, value);
}
public ScriptExpression Iterator
{
get => _iterator;
set => ParentToThis(ref _iterator, value);
}
public ScriptList<ScriptNamedArgument> NamedArguments
{
get => _namedArguments;
set => ParentToThis(ref _namedArguments, value);
}
public ScriptBlockStatement Body
{
get => _body;
set => ParentToThis(ref _body, value);
}
public ScriptElseStatement Else
{
get => _else;
set => ParentToThis(ref _else, value);
}
/// <summary>
/// <c>true</c> to set the global variable `continue` after the loop (used by liquid)
/// </summary>
public bool SetContinue { get; set; }
internal ScriptNode IteratorOrLastParameter => NamedArguments != null && NamedArguments.Count > 0
? NamedArguments[NamedArguments.Count - 1]
: Iterator;
protected override object LoopItem(TemplateContext context, LoopState state)
{
return context.Evaluate(Body);
}
protected virtual ScriptVariable GetLoopVariable(TemplateContext context)
{
return ScriptVariable.ForObject;
}
protected override object EvaluateImpl(TemplateContext context)
{
var loopIterator = context.Evaluate(Iterator);
var list = loopIterator as IList;
if (list == null)
{
var iterator = loopIterator as IEnumerable;
if (iterator != null)
{
list = new ScriptArray(iterator);
}
}
if (list != null)
{
object loopResult = null;
object previousValue = null;
bool reversed = false;
int startIndex = 0;
int limit = list.Count;
if (NamedArguments != null)
{
foreach (var option in NamedArguments)
{
switch (option.Name.Name)
{
case "offset":
startIndex = context.ToInt(option.Value.Span, context.Evaluate(option.Value));
break;
case "reversed":
reversed = true;
break;
case "limit":
limit = context.ToInt(option.Value.Span, context.Evaluate(option.Value));
break;
default:
ProcessArgument(context, option);
break;
}
}
}
var endIndex = Math.Min(limit + startIndex, list.Count) - 1;
var index = reversed ? endIndex : startIndex;
var dir = reversed ? -1 : 1;
bool isFirst = true;
int i = 0;
BeforeLoop(context);
var loopState = CreateLoopState();
context.SetValue(GetLoopVariable(context), loopState);
loopState.Length = list.Count;
bool enteredLoop = false;
while (!reversed && index <= endIndex || reversed && index >= startIndex)
{
enteredLoop = true;
if (!context.StepLoop(this))
{
return null;
}
// We update on next run on previous value (in order to handle last)
var value = list[index];
bool isLast = reversed ? index == startIndex : index == endIndex;
loopState.Index = index;
loopState.LocalIndex = i;
loopState.IsLast = isLast;
loopState.ValueChanged = isFirst || !Equals(previousValue, value);
if (Variable is ScriptVariable loopVariable)
{
context.SetLoopVariable(loopVariable, value);
}
else
{
context.SetValue(Variable, value);
}
loopResult = LoopItem(context, loopState);
if (!ContinueLoop(context))
{
break;
}
previousValue = value;
isFirst = false;
index += dir;
i++;
}
AfterLoop(context);
if (SetContinue)
{
context.SetValue(ScriptVariable.Continue, index);
}
if (!enteredLoop && Else != null)
{
loopResult = context.Evaluate(Else);
}
return loopResult;
}
if (loopIterator != null)
{
throw new ScriptRuntimeException(Iterator.Span, $"Unexpected type `{loopIterator.GetType()}` for iterator");
}
return null;
}
public override void PrintTo(ScriptPrinter printer)
{
printer.Write(ForOrTableRowKeyword).ExpectSpace();
printer.Write(Variable).ExpectSpace();
if (!printer.PreviousHasSpace)
{
printer.Write(" ");
}
printer.Write(InKeyword).ExpectSpace();
printer.Write(Iterator);
if (NamedArguments != null)
{
foreach (var arg in NamedArguments)
{
printer.ExpectSpace();
printer.Write(arg);
}
}
printer.ExpectEos();
printer.Write(Body).ExpectEos();
printer.Write(Else);
}
protected virtual void ProcessArgument(TemplateContext context, ScriptNamedArgument argument)
{
throw new ScriptRuntimeException(argument.Span, $"Unsupported argument `{argument.Name}` for statement: `{this}`");
}
#if !SCRIBAN_NO_ASYNC
protected virtual ValueTask ProcessArgumentAsync(TemplateContext context, ScriptNamedArgument argument)
{
throw new ScriptRuntimeException(argument.Span, $"Unsupported argument `{argument.Name}` for statement: `{this}`");
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Phonix.Test
{
using NUnit.Framework;
[TestFixture]
public class RuleSetTest
{
public static RuleSet GetTestSet()
{
var rs = new RuleSet();
rs.Add(RuleTest.TestRule);
return rs;
}
[Test]
public void Add()
{
var rs = new RuleSet();
var rule1 = new Rule("rule1", new IRuleSegment[] { new MockSegment() }, new IRuleSegment[] { new MockSegment() });
var rule2 = new Rule("rule2", new IRuleSegment[] { new MockSegment() }, new IRuleSegment[] { new MockSegment() });
rs.Add(rule1);
Assert.AreEqual(1, rs.OrderedRules.Count());
Assert.IsTrue(rs.OrderedRules.Contains(rule1));
Assert.IsFalse(rs.OrderedRules.Contains(rule2));
rs.Add(rule2);
Assert.AreEqual(2, rs.OrderedRules.Count());
Assert.IsTrue(rs.OrderedRules.Contains(rule1));
Assert.IsTrue(rs.OrderedRules.Contains(rule2));
Assert.AreEqual(0, rs.PersistentRules.Count());
}
[Test]
public void AddPersistent()
{
var rs = new RuleSet();
var rule1 = new Rule("rule1", new IRuleSegment[] { new MockSegment() }, new IRuleSegment[] { new MockSegment() });
var rule2 = new Rule("rule2", new IRuleSegment[] { new MockSegment() }, new IRuleSegment[] { new MockSegment() });
rs.AddPersistent(rule1);
Assert.AreEqual(1, rs.PersistentRules.Count());
Assert.IsTrue(rs.PersistentRules.Contains(rule1));
Assert.IsFalse(rs.PersistentRules.Contains(rule2));
rs.AddPersistent(rule2);
Assert.AreEqual(2, rs.PersistentRules.Count());
Assert.IsTrue(rs.PersistentRules.Contains(rule1));
Assert.IsTrue(rs.PersistentRules.Contains(rule2));
Assert.AreEqual(0, rs.OrderedRules.Count());
}
[Test]
public void RuleDefined()
{
int calledDefined = 0;
AbstractRule gotRule = null;
var rs = new RuleSet();
rs.RuleDefined += r => { calledDefined++; gotRule = r; };
rs.Add(RuleTest.TestRule);
Assert.AreEqual(1, calledDefined);
Assert.AreSame(RuleTest.TestRule, gotRule);
}
[Test]
public void RuleRedefined()
{
int calledRedefined = 0;
AbstractRule newRule = null;
AbstractRule oldRule = null;
var rs = new RuleSet();
rs.RuleRedefined += (old, newer) => { calledRedefined++; oldRule = old; newRule = newer; };
var or = new Rule("test", new IRuleSegment[] {}, new IRuleSegment[] {});
var nr = new Rule("test", new IRuleSegment[] {}, new IRuleSegment[] {});
rs.Add(or);
rs.Add(nr);
Assert.AreEqual(1, calledRedefined);
Assert.AreSame(or, oldRule);
Assert.AreSame(nr, newRule);
}
[Test]
public void SyllableRuleRedefined()
{
int calledRedefined = 0;
var rs = new RuleSet();
var syll = new SyllableBuilder();
syll.Nuclei.Add(new IMatrixMatcher[] { new MatrixMatcher(FeatureMatrixTest.MatrixA) });
rs.RuleRedefined += (old, newer) => { calledRedefined++; };
rs.Add(syll.GetSyllableRule());
rs.Add(syll.GetSyllableRule());
Assert.AreEqual(0, calledRedefined);
}
[Test]
public void RuleApplied()
{
int entered = 0;
int exited = 0;
int applied = 0;
AbstractRule ruleEntered = null;
AbstractRule ruleExited = null;
Word wordEntered = null;
Word wordExited = null;
Rule rule = new Rule(
"test",
new IRuleSegment[] { new ActionSegment(MatrixMatcher.AlwaysMatches, MatrixCombiner.NullCombiner) },
new IRuleSegment[] { new ActionSegment(MatrixMatcher.NeverMatches, MatrixCombiner.NullCombiner) }
);
Word word = WordTest.GetTestWord();
RuleSet rs = new RuleSet();
rs.RuleEntered += (r, w) => { entered++; ruleEntered = r; wordEntered = w; };
rs.RuleExited += (r, w) => { exited++; ruleExited = r; wordExited = w; };
rs.RuleApplied += (r, w, s) => { applied++; };
rs.Add(rule);
rs.ApplyAll(word);
Assert.AreEqual(1, entered);
Assert.AreEqual(1, exited);
Assert.AreEqual(3, applied);
Assert.AreSame(rule, ruleEntered);
Assert.AreSame(rule, ruleExited);
Assert.AreSame(word, wordEntered);
Assert.AreSame(word, wordExited);
}
[Test]
public void RuleAppliedUndefinedVariable()
{
int undefUsed = 0;
var fs = FeatureSetTest.GetTestSet();
Rule ruleInUndef = null;
IFeatureValue varInUndef = null;
var combo = new MatrixCombiner(new ICombinable[] { fs.Get<Feature>("un").VariableValue });
Rule rule = new Rule(
"test",
new IRuleSegment[] { new ActionSegment(MatrixMatcher.AlwaysMatches, combo) },
new IRuleSegment[] { new ActionSegment(MatrixMatcher.NeverMatches, MatrixCombiner.NullCombiner) }
);
Word word = WordTest.GetTestWord();
RuleSet rs = new RuleSet();
rs.UndefinedVariableUsed += (r, v) => { undefUsed++; ruleInUndef = r; varInUndef = v; };
rs.Add(rule);
rs.ApplyAll(word);
Assert.AreEqual(word.Count(), undefUsed);
Assert.AreSame(rule, ruleInUndef);
Assert.AreSame(fs.Get<Feature>("un").VariableValue, varInUndef);
}
[Test]
public void PersistentRule()
{
int ruleCount = 0;
int persistentCount = 0;
Rule rule = new Rule(
"test",
new IRuleSegment[] { new ActionSegment(MatrixMatcher.AlwaysMatches, MatrixCombiner.NullCombiner) },
new IRuleSegment[] { new ActionSegment(MatrixMatcher.NeverMatches, MatrixCombiner.NullCombiner) }
);
Rule persistent = new Rule(
"test",
new IRuleSegment[] { new ActionSegment(MatrixMatcher.AlwaysMatches, MatrixCombiner.NullCombiner) },
new IRuleSegment[] { new ActionSegment(MatrixMatcher.NeverMatches, MatrixCombiner.NullCombiner) }
);
rule.Entered += (r, w) => { ruleCount++; };
persistent.Entered += (r, w) => { persistentCount++; };
Word word = WordTest.GetTestWord();
RuleSet rs = new RuleSet();
rs.Add(rule);
rs.AddPersistent(persistent);
rs.ApplyAll(word);
Assert.AreEqual(4, persistentCount);
Assert.AreEqual(1, ruleCount);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO;
using System.IO.IsolatedStorage;
#endregion
namespace Nano
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
InputState input = new InputState();
SpriteBatch spriteBatch;
SpriteFont font;
Texture2D blankTexture;
bool isInitialized;
bool traceEnabled;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
/// <summary>
/// A default font shared by all the screens. This saves
/// each screen having to bother loading their own local copy.
/// </summary>
public SpriteFont Font
{
get { return font; }
}
/// <summary>
/// If true, the manager prints out a list of all the screens
/// each time it is updated. This can be useful for making sure
/// everything is being added and removed at the right times.
/// </summary>
public bool TraceEnabled
{
get { return traceEnabled; }
set { traceEnabled = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
// we must set EnabledGestures before we can query for them, but
// we don't assume the game wants to read them.
TouchPanel.EnabledGestures = GestureType.None;
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
font = content.Load<SpriteFont>("menufont");
blankTexture = content.Load<Texture2D>("blank");
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
input.Update();
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput(input);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
// Print debug trace?
if (traceEnabled)
TraceScreens();
}
/// <summary>
/// Prints a list of all the screens, for debugging.
/// </summary>
void TraceScreens()
{
List<string> screenNames = new List<string>();
foreach (GameScreen screen in screens)
screenNames.Add(screen.GetType().Name);
Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
// update the TouchPanel to respond to gestures this screen is interested in
TouchPanel.EnabledGestures = screen.EnabledGestures;
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
// if there is a screen still in the manager, update TouchPanel
// to respond to gestures that screen is interested in.
if (screens.Count > 0)
{
TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
}
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
/// <summary>
/// Helper draws a translucent black fullscreen sprite, used for fading
/// screens in and out, and for darkening the background behind popups.
/// </summary>
public void FadeBackBufferToBlack(float alpha)
{
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Begin();
spriteBatch.Draw(blankTexture,
new Rectangle(0, 0, viewport.Width, viewport.Height),
Color.Black * alpha);
spriteBatch.End();
}
/// <summary>
/// Informs the screen manager to serialize its state to disk.
/// </summary>
public void SerializeState()
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// if our screen manager directory already exists, delete the contents
if (storage.DirectoryExists("ScreenManager"))
{
DeleteState(storage);
}
// otherwise just create the directory
else
{
storage.CreateDirectory("ScreenManager");
}
// create a file we'll use to store the list of screens in the stack
using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
// write out the full name of all the types in our stack so we can
// recreate them if needed.
foreach (GameScreen screen in screens)
{
if (screen.IsSerializable)
{
writer.Write(screen.GetType().AssemblyQualifiedName);
}
}
}
}
// now we create a new file stream for each screen so it can save its state
// if it needs to. we name each file "ScreenX.dat" where X is the index of
// the screen in the stack, to ensure the files are uniquely named
int screenIndex = 0;
foreach (GameScreen screen in screens)
{
if (screen.IsSerializable)
{
string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
// open up the stream and let the screen serialize whatever state it wants
using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
{
screen.Serialize(stream);
}
screenIndex++;
}
}
}
}
public bool DeserializeState()
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// see if our saved state directory exists
if (storage.DirectoryExists("ScreenManager"))
{
try
{
// see if we have a screen list
if (storage.FileExists("ScreenManager\\ScreenList.dat"))
{
// load the list of screen types
using (IsolatedStorageFileStream stream = storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open, FileAccess.Read))
{
using (BinaryReader reader = new BinaryReader(stream))
{
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// read a line from our file
string line = reader.ReadString();
// if it isn't blank, we can create a screen from it
if (!string.IsNullOrEmpty(line))
{
Type screenType = Type.GetType(line);
GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
AddScreen(screen, PlayerIndex.One);
}
}
}
}
}
// next we give each screen a chance to deserialize from the disk
for (int i = 0; i < screens.Count; i++)
{
string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
using (IsolatedStorageFileStream stream = storage.OpenFile(filename, FileMode.Open, FileAccess.Read))
{
screens[i].Deserialize(stream);
}
}
return true;
}
catch (Exception)
{
// if an exception was thrown while reading, odds are we cannot recover
// from the saved state, so we will delete it so the game can correctly
// launch.
DeleteState(storage);
}
}
}
return false;
}
/// <summary>
/// Deletes the saved state files from isolated storage.
/// </summary>
private void DeleteState(IsolatedStorageFile storage)
{
// get all of the files in the directory and delete them
string[] files = storage.GetFileNames("ScreenManager\\*");
foreach (string file in files)
{
storage.DeleteFile(Path.Combine("ScreenManager", file));
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System.Threading.Tasks;
namespace System.Collections.Tests
{
public class Hashtable_SynchronizedTests
{
private Hashtable _hsh2;
private int _iNumberOfElements = 20;
[Fact]
[OuterLoop]
public void TestSynchronizedBasic()
{
Hashtable hsh1;
string strValue;
Task[] workers;
Action ts1;
int iNumberOfWorkers = 3;
DictionaryEntry[] strValueArr;
string[] strKeyArr;
Hashtable hsh3;
Hashtable hsh4;
IDictionaryEnumerator idic;
object oValue;
//[]Vanila - Syncronized returns a wrapped HT. We must make sure that all the methods
//are accounted for here for the wrapper
hsh1 = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
hsh1.Add("Key_" + i, "Value_" + i);
}
_hsh2 = Hashtable.Synchronized(hsh1);
//Count
Assert.Equal(_hsh2.Count, hsh1.Count);
//get/set item
for (int i = 0; i < _iNumberOfElements; i++)
{
Assert.True(((string)_hsh2["Key_" + i]).Equals("Value_" + i));
}
Assert.Throws<ArgumentNullException>(() =>
{
oValue = _hsh2[null];
});
_hsh2.Clear();
for (int i = 0; i < _iNumberOfElements; i++)
{
_hsh2["Key_" + i] = "Value_" + i;
}
strValueArr = new DictionaryEntry[_hsh2.Count];
_hsh2.CopyTo(strValueArr, 0);
//ContainsXXX
hsh3 = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
Assert.True(_hsh2.Contains("Key_" + i));
Assert.True(_hsh2.ContainsKey("Key_" + i));
Assert.True(_hsh2.ContainsValue("Value_" + i));
//we still need a way to make sure that there are all these unique values here -see below code for that
Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));
hsh3.Add(strValueArr[i], null);
}
hsh4 = (Hashtable)_hsh2.Clone();
Assert.Equal(hsh4.Count, hsh1.Count);
strValueArr = new DictionaryEntry[hsh4.Count];
hsh4.CopyTo(strValueArr, 0);
//ContainsXXX
hsh3 = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
Assert.True(hsh4.Contains("Key_" + i));
Assert.True(hsh4.ContainsKey("Key_" + i));
Assert.True(hsh4.ContainsValue("Value_" + i));
//we still need a way to make sure that there are all these unique values here -see below code for that
Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));
hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
}
Assert.False(hsh4.IsReadOnly);
Assert.True(hsh4.IsSynchronized);
//Phew, back to other methods
idic = _hsh2.GetEnumerator();
hsh3 = new Hashtable();
hsh4 = new Hashtable();
while (idic.MoveNext())
{
Assert.True(_hsh2.ContainsKey(idic.Key));
Assert.True(_hsh2.ContainsValue(idic.Value));
hsh3.Add(idic.Key, null);
hsh4.Add(idic.Value, null);
}
hsh4 = (Hashtable)_hsh2.Clone();
strValueArr = new DictionaryEntry[hsh4.Count];
hsh4.CopyTo(strValueArr, 0);
hsh3 = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
Assert.True(hsh4.Contains("Key_" + i));
Assert.True(hsh4.ContainsKey("Key_" + i));
Assert.True(hsh4.ContainsValue("Value_" + i));
//we still need a way to make sure that there are all these unique values here -see below code for that
Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));
hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
}
Assert.False(hsh4.IsReadOnly);
Assert.True(hsh4.IsSynchronized);
//Properties
Assert.False(_hsh2.IsReadOnly);
Assert.True(_hsh2.IsSynchronized);
Assert.Equal(_hsh2.SyncRoot, hsh1.SyncRoot);
//we will test the Keys & Values
string[] strValueArr11 = new string[hsh1.Count];
strKeyArr = new string[hsh1.Count];
_hsh2.Keys.CopyTo(strKeyArr, 0);
_hsh2.Values.CopyTo(strValueArr11, 0);
hsh3 = new Hashtable();
hsh4 = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
Assert.True(_hsh2.ContainsKey(strKeyArr[i]));
Assert.True(_hsh2.ContainsValue(strValueArr11[i]));
hsh3.Add(strKeyArr[i], null);
hsh4.Add(strValueArr11[i], null);
}
//now we test the modifying methods
_hsh2.Remove("Key_1");
Assert.False(_hsh2.ContainsKey("Key_1"));
Assert.False(_hsh2.ContainsValue("Value_1"));
_hsh2.Add("Key_1", "Value_1");
Assert.True(_hsh2.ContainsKey("Key_1"));
Assert.True(_hsh2.ContainsValue("Value_1"));
_hsh2["Key_1"] = "Value_Modified_1";
Assert.True(_hsh2.ContainsKey("Key_1"));
Assert.False(_hsh2.ContainsValue("Value_1"));
///////////////////////////
Assert.True(_hsh2.ContainsValue("Value_Modified_1"));
hsh3 = Hashtable.Synchronized(_hsh2);
//we are not going through all of the above again:) we will just make sure that this syncrnized and that
//values are there
Assert.Equal(hsh3.Count, hsh1.Count);
Assert.True(hsh3.IsSynchronized);
_hsh2.Clear();
Assert.Equal(_hsh2.Count, 0);
//[] Synchronized returns a HT that is thread safe
// We will try to test this by getting a number of threads to write some items
// to a synchronized IList
hsh1 = new Hashtable();
_hsh2 = Hashtable.Synchronized(hsh1);
workers = new Task[iNumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
ts1 = new Action(() => AddElements(name));
workers[i] = Task.Run(ts1);
}
Task.WaitAll(workers);
//checking time
Assert.Equal(_hsh2.Count, _iNumberOfElements * iNumberOfWorkers);
for (int i = 0; i < iNumberOfWorkers; i++)
{
for (int j = 0; j < _iNumberOfElements; j++)
{
strValue = "Thread worker " + i + "_" + j;
Assert.True(_hsh2.Contains(strValue));
}
}
//I dont think that we can make an assumption on the order of these items though
//now we are going to remove all of these
workers = new Task[iNumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
ts1 = new Action(() => RemoveElements(name));
workers[i] = Task.Run(ts1);
}
Task.WaitAll(workers);
Assert.Equal(_hsh2.Count, 0);
Assert.False(hsh1.IsSynchronized);
Assert.True(_hsh2.IsSynchronized);
//[] Tyr calling Synchronized with null
Assert.Throws<ArgumentNullException>(() =>
{
Hashtable.Synchronized(null);
}
);
}
void AddElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hsh2.Add(strName + "_" + i, "string_" + i);
}
}
void RemoveElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hsh2.Remove(strName + "_" + i);
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DeviceExtensionsCollectionRequest.
/// </summary>
public partial class DeviceExtensionsCollectionRequest : BaseRequest, IDeviceExtensionsCollectionRequest
{
/// <summary>
/// Constructs a new DeviceExtensionsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DeviceExtensionsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension)
{
return this.AddAsync(extension, CancellationToken.None);
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
extension.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(extension.GetType().FullName));
return this.SendAsync<Extension>(extension, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IDeviceExtensionsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IDeviceExtensionsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<DeviceExtensionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Expand(Expression<Func<Extension, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Select(Expression<Func<Extension, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IDeviceExtensionsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
using UtfUnknown.Core.Models;
namespace UtfUnknown.Core.Models.MultiByte;
internal class UCS2LE_SMModel : StateMachineModel
{
private static readonly int[] UCS2LE_cls =
{
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 00 - 07
BitPackage.Pack4bits(
0,
0,
1,
0,
0,
2,
0,
0), // 08 - 0f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 10 - 17
BitPackage.Pack4bits(
0,
0,
0,
3,
0,
0,
0,
0), // 18 - 1f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 20 - 27
BitPackage.Pack4bits(
0,
3,
3,
3,
3,
3,
0,
0), // 28 - 2f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 30 - 37
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 38 - 3f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 40 - 47
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 48 - 4f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 50 - 57
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 58 - 5f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 60 - 67
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 68 - 6f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 70 - 77
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 78 - 7f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 80 - 87
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 88 - 8f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 90 - 97
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // 98 - 9f
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // a0 - a7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // a8 - af
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // b0 - b7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // b8 - bf
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // c0 - c7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // c8 - cf
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // d0 - d7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // d8 - df
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // e0 - e7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // e8 - ef
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
0,
0), // f0 - f7
BitPackage.Pack4bits(
0,
0,
0,
0,
0,
0,
4,
5) // f8 - ff
};
private static readonly int[] UCS2LE_st =
{
BitPackage.Pack4bits(
6,
6,
7,
6,
4,
3,
ERROR,
ERROR), //00-07
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ITSME,
ITSME,
ITSME,
ITSME), //08-0f
BitPackage.Pack4bits(
ITSME,
ITSME,
5,
5,
5,
ERROR,
ITSME,
ERROR), //10-17
BitPackage.Pack4bits(
5,
5,
5,
ERROR,
5,
ERROR,
6,
6), //18-1f
BitPackage.Pack4bits(
7,
6,
8,
8,
5,
5,
5,
ERROR), //20-27
BitPackage.Pack4bits(
5,
5,
5,
ERROR,
ERROR,
ERROR,
5,
5), //28-2f
BitPackage.Pack4bits(
5,
5,
5,
ERROR,
5,
ERROR,
START,
START) //30-37
};
private static readonly int[] UCS2LECharLenTable =
{
2,
2,
2,
2,
2,
2
};
public UCS2LE_SMModel()
: base(
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
UCS2LE_cls),
6,
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
UCS2LE_st),
UCS2LECharLenTable,
CodepageName.UTF16_LE) { }
}
| |
using NUnit.Framework;
using StructureMap.Testing.GenericWidgets;
using StructureMap.Testing.Graph;
using StructureMap.Testing.Widget;
namespace StructureMap.Testing.Pipeline
{
[TestFixture]
public class NestedContainerSupportTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
}
#endregion
public class ContainerHolder
{
private readonly IContainer _container;
public ContainerHolder(IContainer container)
{
_container = container;
}
public IContainer Container { get { return _container; } }
}
public interface IBar
{
}
public class AFoo : IBar
{
}
public class BFoo : IBar
{
}
public class CFoo : IBar
{
}
[Test]
public void allow_nested_container_to_report_what_it_has()
{
var container = new Container(x => x.For<IAutomobile>().Use<Mustang>());
IContainer nestedContainer = container.GetNestedContainer();
nestedContainer.Inject<IEngine>(new PushrodEngine());
container.WhatDoIHave().ShouldNotBeEmpty().ShouldNotContain(typeof (IEngine).Name);
nestedContainer.WhatDoIHave().ShouldNotBeEmpty().ShouldContain(typeof (IEngine).Name);
}
[Test]
public void disposing_the_child_container_does_not_affect_the_parent_container()
{
var container = new Container(x =>
{
x.Scan(o =>
{
o.TheCallingAssembly();
o.AddAllTypesOf<IBar>();
});
});
container.GetAllInstances<IBar>().Count.ShouldBeGreaterThan(0);
using (IContainer nested = container.GetNestedContainer())
{
nested.GetAllInstances<IBar>().Count.ShouldBeGreaterThan(0);
}
container.GetAllInstances<IBar>().Count.ShouldBeGreaterThan(0);
}
[Test]
public void get_a_nested_container_for_a_profile()
{
var parent = new Container(x =>
{
x.For<IWidget>().Use<ColorWidget>()
.WithCtorArg("color").EqualTo("red");
x.Profile("green", o =>
{
o.Type<IWidget>().Is.OfConcreteType<ColorWidget>()
.WithCtorArg("color").EqualTo("green");
});
});
IContainer child = parent.GetNestedContainer("green");
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
var childWidget3 = child.GetInstance<IWidget>();
var parentWidget = parent.GetInstance<IWidget>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
parentWidget.ShouldBeOfType<ColorWidget>().Color.ShouldEqual("red");
childWidget1.ShouldBeOfType<ColorWidget>().Color.ShouldEqual("green");
}
[Test]
public void inject_into_the_child_does_not_affect_the_parent_container()
{
var parent = new Container(x => { x.For<IWidget>().Use<AWidget>(); });
IContainer child = parent.GetNestedContainer();
var childWidget = new ColorWidget("blue");
child.Inject<IWidget>(childWidget);
// do the check repeatedly
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
// now, compare to the parent
parent.GetInstance<IWidget>().ShouldNotBeTheSameAs(childWidget);
}
[Test]
public void singleton_service_from_open_type_in_the_parent_is_found_by_the_child()
{
var parent =
new Container(
x => { x.For(typeof (IService<>)).CacheBy(InstanceScope.Singleton).Use(typeof (Service<>)); });
IContainer child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IService<string>>();
var childWidget2 = child.GetInstance<IService<string>>();
var childWidget3 = child.GetInstance<IService<string>>();
var parentWidget = parent.GetInstance<IService<string>>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldBeTheSameAs(parentWidget);
}
[Test]
public void singleton_service_in_the_parent_is_found_by_the_child()
{
var parent = new Container(x => { x.ForSingletonOf<IWidget>().Use<AWidget>(); });
var parentWidget = parent.GetInstance<IWidget>();
IContainer child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
parentWidget.ShouldBeTheSameAs(childWidget1);
parentWidget.ShouldBeTheSameAs(childWidget2);
}
[Test]
public void the_nested_container_delivers_itself_as_the_IContainer()
{
var parent = new Container(x => { x.For<IWidget>().Use<AWidget>(); });
IContainer child = parent.GetNestedContainer();
child.GetInstance<IContainer>().ShouldBeTheSameAs(child);
}
[Test]
public void the_nested_container_will_deliver_itself_into_a_constructor_of_something_else()
{
var parent = new Container(x => { x.For<IWidget>().Use<AWidget>(); });
IContainer child = parent.GetNestedContainer();
child.GetInstance<ContainerHolder>().Container.ShouldBeTheSameAs(child);
}
[Test]
public void
transient_open_generics_service_in_the_parent_container_is_effectively_a_singleton_for_the_nested_container()
{
var parent = new Container(x => { x.For(typeof (IService<>)).Use(typeof (Service<>)); });
IContainer child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IService<string>>();
var childWidget2 = child.GetInstance<IService<string>>();
var childWidget3 = child.GetInstance<IService<string>>();
var parentWidget = parent.GetInstance<IService<string>>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
}
[Test]
public void transient_service_in_the_parent_container_is_effectively_a_singleton_for_the_nested_container()
{
var parent = new Container(x =>
{
// IWidget is a "transient"
x.For<IWidget>().Use<AWidget>();
});
IContainer child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
var childWidget3 = child.GetInstance<IWidget>();
var parentWidget = parent.GetInstance<IWidget>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
}
}
}
| |
/*
* 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.Reflection;
using System.Timers;
using System.Threading;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Timer=System.Timers.Timer;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.World.Region
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RestartModule")]
public class RestartModule : INonSharedRegionModule, IRestartModule
{
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_Scene;
protected Timer m_CountdownTimer = null;
protected DateTime m_RestartBegin;
protected List<int> m_Alerts;
protected string m_Message;
protected UUID m_Initiator;
protected bool m_Notice = false;
protected IDialogModule m_DialogModule = null;
public void Initialise(IConfigSource config)
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
scene.RegisterModuleInterface<IRestartModule>(this);
MainConsole.Instance.Commands.AddCommand("RestartModule",
false, "region restart bluebox",
"region restart bluebox <message> <time> ...",
"Restart the region", HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("RestartModule",
false, "region restart notice",
"region restart notice <message> <time> ...",
"Restart the region", HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("RestartModule",
false, "region restart abort",
"region restart abort [<message>]",
"Restart the region", HandleRegionRestart);
}
public void RegionLoaded(Scene scene)
{
m_DialogModule = m_Scene.RequestModuleInterface<IDialogModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "RestartModule"; }
}
public Type ReplaceableInterface
{
get { return typeof(IRestartModule); }
}
public TimeSpan TimeUntilRestart
{
get { return DateTime.Now - m_RestartBegin; }
}
public void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice)
{
if (m_CountdownTimer != null)
return;
if (alerts == null)
{
m_Scene.RestartNow();
return;
}
m_Message = message;
m_Initiator = initiator;
m_Notice = notice;
m_Alerts = new List<int>(alerts);
m_Alerts.Sort();
m_Alerts.Reverse();
if (m_Alerts[0] == 0)
{
m_Scene.RestartNow();
return;
}
int nextInterval = DoOneNotice();
SetTimer(nextInterval);
}
public int DoOneNotice()
{
if (m_Alerts.Count == 0 || m_Alerts[0] == 0)
{
m_Scene.RestartNow();
return 0;
}
int nextAlert = 0;
while (m_Alerts.Count > 1)
{
if (m_Alerts[1] == m_Alerts[0])
{
m_Alerts.RemoveAt(0);
continue;
}
nextAlert = m_Alerts[1];
break;
}
int currentAlert = m_Alerts[0];
m_Alerts.RemoveAt(0);
int minutes = currentAlert / 60;
string currentAlertString = String.Empty;
if (minutes > 0)
{
if (minutes == 1)
currentAlertString += "1 minute";
else
currentAlertString += String.Format("{0} minutes", minutes);
if ((currentAlert % 60) != 0)
currentAlertString += " and ";
}
if ((currentAlert % 60) != 0)
{
int seconds = currentAlert % 60;
if (seconds == 1)
currentAlertString += "1 second";
else
currentAlertString += String.Format("{0} seconds", seconds);
}
string msg = String.Format(m_Message, currentAlertString);
if (m_DialogModule != null && msg != String.Empty)
{
if (m_Notice)
m_DialogModule.SendGeneralAlert(msg);
else
m_DialogModule.SendNotificationToUsersInRegion(m_Initiator, "System", msg);
}
return currentAlert - nextAlert;
}
public void SetTimer(int intervalSeconds)
{
m_CountdownTimer = new Timer();
m_CountdownTimer.AutoReset = false;
m_CountdownTimer.Interval = intervalSeconds * 1000;
m_CountdownTimer.Elapsed += OnTimer;
m_CountdownTimer.Start();
}
private void OnTimer(object source, ElapsedEventArgs e)
{
int nextInterval = DoOneNotice();
SetTimer(nextInterval);
}
public void AbortRestart(string message)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
if (m_DialogModule != null && message != String.Empty)
m_DialogModule.SendGeneralAlert(message);
}
}
private void HandleRegionRestart(string module, string[] args)
{
if (!(MainConsole.Instance.ConsoleScene is Scene))
return;
if (MainConsole.Instance.ConsoleScene != m_Scene)
return;
if (args.Length < 5)
{
if (args.Length > 2)
{
if (args[2] == "abort")
{
string msg = String.Empty;
if (args.Length > 3)
msg = args[3];
AbortRestart(msg);
MainConsole.Instance.Output("Region restart aborted");
return;
}
}
MainConsole.Instance.Output("Error: restart region <mode> <name> <time> ...");
return;
}
bool notice = false;
if (args[2] == "notice")
notice = true;
List<int> times = new List<int>();
for (int i = 4 ; i < args.Length ; i++)
times.Add(Convert.ToInt32(args[i]));
ScheduleRestart(UUID.Zero, args[3], times.ToArray(), notice);
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Wosad 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Wosad.Common.CalculationLogger;
using Wosad.Dynamo.Common;
using Dynamo.Nodes;
using System.Windows.Input;
using System.Windows;
using System.Xml;
using Wosad.Dynamo.Common.Infra.TreeItems;
using Wosad.Dynamo.UI.Views.Analysis.Beam.Flexure;
using GalaSoft.MvvmLight.CommandWpf;
using Wosad.Dynamo.UI.Common.TreeItems;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
namespace Wosad.Analysis.Beam.Flexure
{
/// <summary>
///Selection of beam load and boundary condition case for deflection calculation
/// </summary>
[NodeName("Beam deflection case selection")]
[NodeCategory("Wosad.Analysis.Beam.Flexure")]
[NodeDescription("Selection of beam load and boundary condition case for deflection calculation")]
[IsDesignScriptCompatible]
public class BeamDeflectionCaseSelection : UiNodeBase
{
public BeamDeflectionCaseSelection()
{
ReportEntry = "";
BeamDeflectionCaseId = "C1B_1";
BeamForcesCaseDescription = "Simply supported. Uniform load on full span. Uniformly distributed load";
//OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)"));
OutPortData.Add(new PortData("BeamDeflectionCaseId", "Case ID used in calculation of the beam deflection"));
RegisterAllPorts();
//PropertyChanged += NodePropertyChanged;
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region Properties
#region InputProperties
#endregion
#region OutputProperties
#region BeamDeflectionCaseIdProperty
/// <summary>
/// BeamDeflectionCaseId property
/// </summary>
/// <value>Case ID used in calculation of the beam forces</value>
public string _BeamDeflectionCaseId;
public string BeamDeflectionCaseId
{
get { return _BeamDeflectionCaseId; }
set
{
_BeamDeflectionCaseId = value;
RaisePropertyChanged("BeamDeflectionCaseId");
OnNodeModified(true);
}
}
#endregion
#region BeamForcesCaseDescription Property
private string _BeamForcesCaseDescription;
public string BeamForcesCaseDescription
{
get { return _BeamForcesCaseDescription; }
set
{
_BeamForcesCaseDescription = value;
RaisePropertyChanged("BeamForcesCaseDescription");
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
nodeElement.SetAttribute("BeamDeflectionCaseId", BeamDeflectionCaseId);
}
/// <summary>
///Retrieved property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var attrib = nodeElement.Attributes["BeamDeflectionCaseId"];
if (attrib == null)
return;
BeamDeflectionCaseId = attrib.Value;
SetCaseDescription();
}
private void SetCaseDescription()
{
Uri uri = new Uri("pack://application:,,,/WosadDynamoUI;component/Views/Analysis/Beam/Flexure/BeamForceCaseTreeData.xml");
XmlTreeHelper treeHelper = new XmlTreeHelper();
treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindCaseDescription));
}
private void FindCaseDescription(XmlNode node)
{
if (null != node.Attributes["Id"])
{
if (node.Attributes["Id"].Value == BeamDeflectionCaseId)
{
BeamForcesCaseDescription = node.Attributes["Description"].Value;
}
}
}
public void UpdateSelectionEvents()
{
if (TreeViewControl != null)
{
TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged;
}
}
private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
OnSelectedItemChanged(e.NewValue);
}
#endregion
#region TreeView elements
public TreeView TreeViewControl { get; set; }
private ICommand selectedItemChanged;
public ICommand SelectedItemChanged
{
get
{
selectedItemChanged = new RelayCommand<object>((i) =>
{
OnSelectedItemChanged(i);
});
return selectedItemChanged;
}
}
public void DisplayComponentUI(XTreeItem selectedComponent)
{
}
private XTreeItem selectedItem;
public XTreeItem SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
}
}
private void OnSelectedItemChanged(object i)
{
XmlElement item = i as XmlElement;
XTreeItem xtreeItem = new XTreeItem()
{
Header = item.GetAttribute("Header"),
Description = item.GetAttribute("Description"),
Id = item.GetAttribute("Id"),
ResourcePath = item.GetAttribute("ResourcePath"),
Tag = item.GetAttribute("Tag"),
TemplateName = item.GetAttribute("TemplateName")
};
if (item != null)
{
string id = xtreeItem.Id;
if (id != "X")
{
BeamDeflectionCaseId = xtreeItem.Id;
SelectedItem = xtreeItem;
BeamForcesCaseDescription = xtreeItem.Description;
}
}
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class BeamDeflectionCaseSelectionViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<BeamDeflectionCaseSelection>
{
public void CustomizeView(BeamDeflectionCaseSelection model, NodeView nodeView)
{
base.CustomizeView(model, nodeView);
BeamDeflectionCaseView control = new BeamDeflectionCaseView();
control.DataContext = model;
//remove this part if control does not contain tree
TreeView tv = control.FindName("selectionTree") as TreeView;
if (tv!=null)
{
model.TreeViewControl = tv;
model.UpdateSelectionEvents();
}
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
/****************************************************************************/
/* */
/* The Mondo Libraries */
/* */
/* Namespace: Mondo.Common */
/* File: StringList.cs */
/* Class(es): StringList */
/* Purpose: A collection of strings */
/* */
/* Original Author: Jim Lightfoot */
/* Creation Date: 12 Sep 2001 */
/* */
/* Copyright (c) 2001-2008 - Jim Lightfoot, All rights reserved */
/* */
/* Licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* */
/****************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml;
using System.Text;
using Mondo.Xml;
namespace Mondo.Common
{
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A list of strings
/// </summary>
public class StringList : List<string>
{
/****************************************************************************/
public StringList()
{
}
/****************************************************************************/
public StringList(IEnumerable aItems, bool bRemoveEmptys)
{
Add(aItems, bRemoveEmptys);
}
/****************************************************************************/
public StringList(Exception ex)
{
while(ex != null)
{
this.Add(ex.Message);
ex = ex.InnerException;
}
}
/****************************************************************************/
public StringList(IEnumerable aItems) : this(aItems, false)
{
}
/****************************************************************************/
public StringList(string strList, string separator, bool bRemoveEmptys, bool trim = true)
{
Parse(strList, separator, bRemoveEmptys, trim);
}
/****************************************************************************/
protected void Parse(string strList, string separator, bool bRemoveEmptys, bool bTrim = true)
{
string[] aParts = strList.Split(new string[] {separator}, bRemoveEmptys ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
foreach(string strPart in aParts)
Add(strPart, false, bTrim);
return;
}
/****************************************************************************/
public StringList(string strList, string[] aSeparators, bool bRemoveEmptys)
{
string[] aParts = strList.Split(aSeparators, bRemoveEmptys ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
foreach(string strPart in aParts)
if(strPart.Trim() != "")
Add(strPart.Trim());
return;
}
/****************************************************************************/
public StringList(XmlNode xmlParent, string xPath, string strAttributeName)
{
XmlNodeList aNodes = xmlParent.SelectNodes(xPath);
foreach(XmlNode xmlNode in aNodes)
Add(xmlNode.GetAttribute(strAttributeName));
}
/****************************************************************************/
public StringList(XmlNode xmlParent, string xPath) : this(xmlParent.SelectNodes(xPath))
{
}
/****************************************************************************/
public StringList(XmlNodeList aNodes)
{
foreach(XmlNode xmlNode in aNodes)
Add(xmlNode.InnerText.Trim());
}
/****************************************************************************/
public void Add(object obj)
{
Add(obj, false);
}
/****************************************************************************/
public void Add(object obj, bool bRemoveEmptys)
{
Add(obj, bRemoveEmptys, true);
}
/****************************************************************************/
public void Add(object obj, bool bRemoveEmptys, bool bTrim)
{
string strValue = "";
if(obj is string)
strValue = bTrim ? obj.Normalized() : obj.ToString();
else if(obj is IEnumerable)
{
IEnumerable aItems = obj as IEnumerable;
foreach(object objItem in aItems)
Add(objItem.Normalized(), bRemoveEmptys);
return;
}
else
strValue = bTrim ? obj.Normalized() : obj.ToString();
if(!bRemoveEmptys || strValue != "")
base.Add(strValue);
return;
}
/****************************************************************************/
public static string Pack(IEnumerable aItems, string separator)
{
StringList aList = new StringList(aItems);
return(aList.Pack(separator));
}
/****************************************************************************/
public static string Pack(IEnumerable aItems, string strFormat, string separator)
{
StringList aList = new StringList(aItems);
return(aList.Pack(strFormat, separator));
}
/****************************************************************************/
/// <summary>
/// Packs the given list into a single string separating them by the given separator.
/// </summary>
/// <param name="aItems">A list of string to pack</param>
/// <param name="separator">A string that will separate the values</param>
/// <param name="bRemoveEmptys">Removes any empty strings if true</param>
/// <returns>A string with the packed values</returns>
public static string Pack(IEnumerable aItems, string separator, bool bRemoveEmptys)
{
StringList aList = new StringList(aItems, bRemoveEmptys);
return(aList.Pack(separator));
}
/****************************************************************************/
public string Pack(string strFormat, string separator)
{
StringBuilder sb = new StringBuilder();
foreach(string strAdd in this)
{
if(sb.Length != 0)
sb.Append(separator);
if(strAdd == "")
{
string temp = string.Format(strFormat, "__789sdfJK^%$#");
temp = temp.Replace("__789sdfJK^%$#", "");
sb.Append(temp);
}
else
sb.AppendFormat(strFormat, strAdd);
}
return(sb.ToString());
}
/****************************************************************************/
public void Pack(StringBuilder sb, string strFormat, string separator)
{
foreach(string strAdd in this)
{
if(sb.Length != 0)
sb.Append(separator);
sb.AppendFormat(strFormat, strAdd);
}
return;
}
/****************************************************************************/
public string Pack(string separator)
{
StringBuilder sb = new StringBuilder();
foreach(string strAdd in this)
{
if(sb.Length != 0)
sb.Append(separator);
sb.Append(strAdd);
}
return(sb.ToString());
}
/****************************************************************************/
public static string GetPart(IList<string> aParts, int iIndex)
{
if(iIndex >= aParts.Count)
return("");
return(aParts[iIndex]);
}
/****************************************************************************/
public static int GetPartInt(IList<string> aParts, int iIndex)
{
return(Utility.ToInt(GetPart(aParts, iIndex)));
}
/****************************************************************************/
public static List<string> GetTextRows(string strFileData, bool bRemoveEmptys)
{
const string kRandomChars1 = "*()@Kldwkld30p2elk;dl9sdlJKL^%0p";
const string kRandomChars2 = "p90e23iop#w2ep0-d0p9-pioswd()*$@";
strFileData = strFileData.Replace("\r\n", kRandomChars1);
strFileData = strFileData.Replace("\r", kRandomChars2);
strFileData = strFileData.Replace("\n", "\r\n");
strFileData = strFileData.Replace(kRandomChars1, "\r\n");
strFileData = strFileData.Replace(kRandomChars2, "\r\n");
return(StringList.ParseString(strFileData, "\r\n", bRemoveEmptys));
}
/****************************************************************************/
/// <summary>
/// Takes the given string containing a list of values separated by the given
/// separator and returns a List<string>, removing emptys if requested.
/// </summary>
/// <param name="strList">A string containing the list</param>
/// <param name="separator">A string that separates the values</param>
/// <param name="bRemoveEmptys">Removes any empty string if true</param>
/// <returns>A StringCollection containing the list of strings</returns>
public static List<string> ParseString(string strList, string separator, bool bRemoveEmptys)
{
List<string> aReturn = new List<string>();
if(strList != null && strList.Length > 0)
{
int iSepLen = separator.Length;
string strTemp = strList;
while(true)
{
strTemp = strTemp.Trim();
int iFind = strTemp.IndexOf(separator);
if(iFind == -1)
{
if(!bRemoveEmptys || strTemp != "")
aReturn.Add(strTemp);
break;
}
string strAdd = strTemp.Substring(0, iFind).Trim();
if(!bRemoveEmptys || strAdd != "")
aReturn.Add(strAdd);
strTemp = strTemp.Remove(0, iFind + iSepLen);
}
}
return (aReturn);
}
}
/****************************************************************************/
/****************************************************************************/
/// <summary>
/// A dictionary of strings
/// </summary>
public class StringDictionary : Dictionary<string, string>
{
/****************************************************************************/
public StringDictionary()
{
}
/****************************************************************************/
public StringDictionary(string strList, string separator)
{
string[] aStrings = strList.Split(new string[] {separator}, StringSplitOptions.RemoveEmptyEntries);
foreach(string strValue in aStrings)
{
string strNew = strValue.Normalized();
this.Add(strNew, strNew);
}
}
/****************************************************************************/
public StringDictionary(string strList, string separator, string separator2)
{
string[] aStrings = strList.Split(new string[] {separator}, StringSplitOptions.RemoveEmptyEntries);
foreach(string strValue in aStrings)
{
string[] aPair = strValue.Split(new string[] {separator2}, StringSplitOptions.None);
this.Add(aPair[0].Trim(), aPair[1].Trim());
}
}
/****************************************************************************/
public StringDictionary(IEnumerable aItems)
{
foreach(object objValue in aItems)
{
string strValue = objValue.Normalized();
this.Add(strValue, strValue);
}
}
}
}
| |
/*
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.Linq;
using System.Xml.Linq;
using Microsoft.Xrm.Portal.Runtime;
using Microsoft.Xrm.Sdk.Metadata;
namespace Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView
{
public abstract class CellMetadata : ICellMetadata
{
protected CellMetadata(XNode cellNode, EntityMetadata entityMetadata, int languageCode, Func<XNode, EntityMetadata, string> getDataFieldName)
{
cellNode.ThrowOnNull("cellNode");
entityMetadata.ThrowOnNull("entityMetadata");
string colSpan;
if (XNodeUtility.TryGetAttributeValue(cellNode, ".", "colspan", out colSpan))
{
ColumnSpan = int.Parse(colSpan);
}
string rowSpan;
if (XNodeUtility.TryGetAttributeValue(cellNode, ".", "rowspan", out rowSpan))
{
RowSpan = int.Parse(rowSpan);
}
EntityMetadata = entityMetadata;
LanguageCode = languageCode;
var dataFieldName = getDataFieldName(cellNode, entityMetadata);
var attributeMetadata = entityMetadata.Attributes.FirstOrDefault(attribute => attribute.LogicalName == dataFieldName);
if (string.IsNullOrEmpty(dataFieldName) || attributeMetadata == null)
{
Disabled = true;
return;
}
DataFieldName = dataFieldName;
AttributeMetadata = attributeMetadata;
ExtractMetadata();
}
public string AttributeType
{
get { return AttributeMetadata == null ? null : AttributeMetadata.AttributeType.Value.ToString(); }
}
public int? ColumnSpan { get; private set; }
public string DataFieldName { get; private set; }
public bool Disabled { get; protected set; }
public string Format { get; private set; }
public bool IsRequired
{
get
{
if (AttributeMetadata == null)
{
return false;
}
try
{
return AttributeMetadata.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired
|| AttributeMetadata.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired;
}
catch
{
return false;
}
}
}
public abstract string Label { get; }
public int LanguageCode { get; private set; }
public decimal? MaxValue { get; private set; }
public decimal? MinValue { get; private set; }
public IEnumerable<OptionMetadata> PicklistOptions
{
get
{
var picklistMetadata = AttributeMetadata as PicklistAttributeMetadata;
return picklistMetadata == null
? new List<OptionMetadata>() as IEnumerable<OptionMetadata>
: picklistMetadata.OptionSet.Options;
}
}
public int? RowSpan { get; private set; }
public abstract bool ShowLabel { get; }
public string ToolTip { get; private set; }
protected AttributeMetadata AttributeMetadata { get; private set; }
protected EntityMetadata EntityMetadata { get; private set; }
public bool HasAttributeType(string attributeTypeName)
{
try
{
return string.Equals(AttributeType, attributeTypeName, StringComparison.InvariantCultureIgnoreCase);
}
catch
{
return false;
}
}
private void ExtractMetadata()
{
if (AttributeMetadata.GetType() == typeof(BigIntAttributeMetadata))
{
var metadata = AttributeMetadata as BigIntAttributeMetadata;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(DateTimeAttributeMetadata))
{
var metadata = AttributeMetadata as DateTimeAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(DateTimeFormat), metadata.Format.Value)
: null;
}
else if (AttributeMetadata.GetType() == typeof(DecimalAttributeMetadata))
{
var metadata = AttributeMetadata as DecimalAttributeMetadata;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(DoubleAttributeMetadata))
{
var metadata = AttributeMetadata as DoubleAttributeMetadata;
MaxValue = (decimal)metadata.MaxValue;
MinValue = (decimal)metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(IntegerAttributeMetadata))
{
var metadata = AttributeMetadata as IntegerAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(IntegerFormat), metadata.Format.Value)
: null;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(MemoAttributeMetadata))
{
var metadata = AttributeMetadata as MemoAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
: null;
}
else if (AttributeMetadata.GetType() == typeof(MoneyAttributeMetadata))
{
var metadata = AttributeMetadata as MoneyAttributeMetadata;
MaxValue = (decimal)metadata.MaxValue;
MinValue = (decimal)metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(StringAttributeMetadata))
{
var metadata = AttributeMetadata as StringAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
: null;
}
var localiazedDescription = AttributeMetadata.Description.LocalizedLabels.SingleOrDefault(label => label.LanguageCode == LanguageCode);
if (localiazedDescription != null)
{
ToolTip = localiazedDescription.Label;
}
}
}
}
| |
/**
* 7/8/2013
*/
#define PRO
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
namespace ProGrids
{
[InitializeOnLoad]
public static class pg_Initializer
{
/**
* When opening Unity, remember whether or not ProGrids was open when Unity was shut down last.
* Only check within 10 seconds of opening Unity because otherwise Init will be called multiple
* times due to _instance not being set (OnAfterDeserialize is called after static constructors).
*/
static pg_Initializer()
{
if( pg_Editor.instance == null && EditorPrefs.GetBool(pg_Constant.ProGridsIsEnabled) )
pg_Editor.InitProGrids();
}
}
public class pg_Editor : ScriptableObject, ISerializationCallbackReceiver
{
#region MEMBERS
string ProGrids_Icons_Path = "Assets/ProCore/ProGrids/GUI/ProGridsToggles";
public static pg_Editor instance
{
get
{
if(_instance == null)
{
pg_Editor[] editor = Resources.FindObjectsOfTypeAll<pg_Editor>();
if(editor != null && editor.Length > 0)
{
_instance = editor[0];
for(int i = 1; i < editor.Length; i++)
{
GameObject.DestroyImmediate(editor[i]);
}
}
}
return _instance;
}
set
{
_instance = value;
}
}
private static pg_Editor _instance;
Color oldColor;
private bool useAxisConstraints = false;
private bool snapEnabled = true;
private SnapUnit snapUnit = SnapUnit.Meter;
#if PRO
private float snapValue = 1f; // the actual snap value, taking into account unit size
private float t_snapValue = 1f; // what the user sees
#else
private float snapValue = .25f;
private float t_snapValue = .25f;
#endif
private bool drawGrid = true;
private bool drawAngles = false;
public float angleValue = 45f;
private bool gridRepaint = true;
public bool predictiveGrid = true;
private bool _snapAsGroup = true;
public bool snapAsGroup
{
get
{
return EditorPrefs.HasKey(pg_Constant.SnapAsGroup) ? EditorPrefs.GetBool(pg_Constant.SnapAsGroup) : true;
}
set
{
_snapAsGroup = value;
EditorPrefs.SetBool(pg_Constant.SnapAsGroup, _snapAsGroup);
}
}
public bool fullGrid { get; private set; }
private bool _scaleSnapEnabled = false;
public bool ScaleSnapEnabled
{
get
{
return EditorPrefs.HasKey(pg_Constant.SnapScale) ? EditorPrefs.GetBool(pg_Constant.SnapScale) : false;
}
set
{
_scaleSnapEnabled = value;
EditorPrefs.SetBool(pg_Constant.SnapScale, _scaleSnapEnabled);
}
}
bool lockGrid = false;
private Axis renderPlane = Axis.Y;
#if PG_DEBUG
private GameObject _pivotGo;
public GameObject pivotGo
{
get
{
if(_pivotGo == null)
{
GameObject find = GameObject.Find("PG_PIVOT_CUBE");
if(find == null)
{
_pivotGo = GameObject.CreatePrimitive(PrimitiveType.Cube);
_pivotGo.name = "PG_PIVOT_CUBE";
}
else
_pivotGo = find;
}
return _pivotGo;
}
set
{
_pivotGo = value;
}
}
#endif
#endregion
#region CONSTANT
const int VERSION = 20;
const bool RESET_PREFS_REQ = true;
#if PRO
const int WINDOW_HEIGHT = 240;
#else
const int WINDOW_HEIGHT = 260;
#endif
const int MAX_LINES = 150; // the maximum amount of lines to display on screen in either direction
public static float alphaBump; // Every tenth line gets an alpha bump by this amount
const int BUTTON_SIZE = 46;
private Texture2D icon_extendoClose, icon_extendoOpen;
[SerializeField] private pg_ToggleContent gc_SnapToGrid = new pg_ToggleContent("Snap", "", "Snaps all selected objects to grid.");
[SerializeField] private pg_ToggleContent gc_GridEnabled = new pg_ToggleContent("Hide", "Show", "Toggles drawing of guide lines on or off. Note that object snapping is not affected by this setting.");
[SerializeField] private pg_ToggleContent gc_SnapEnabled = new pg_ToggleContent("On", "Off", "Toggles snapping on or off.");
[SerializeField] private pg_ToggleContent gc_LockGrid = new pg_ToggleContent("Lock", "Unlck", "Lock the perspective grid center in place.");
[SerializeField] private pg_ToggleContent gc_AngleEnabled = new pg_ToggleContent("> On", "> Off", "If on, ProGrids will draw angled line guides. Angle is settable in degrees.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneX = new pg_ToggleContent("X", "X", "Renders a grid on the X plane.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneY = new pg_ToggleContent("Y", "Y", "Renders a grid on the Y plane.");
[SerializeField] private pg_ToggleContent gc_RenderPlaneZ = new pg_ToggleContent("Z", "Z", "Renders a grid on the Z plane.");
[SerializeField] private pg_ToggleContent gc_RenderPerspectiveGrid = new pg_ToggleContent("Full", "Plane", "Renders a 3d grid in perspective mode.");
[SerializeField] private GUIContent gc_ExtendMenu = new GUIContent("", "Show or hide the scene view menu.");
[SerializeField] private GUIContent gc_SnapIncrement = new GUIContent("", "Set the snap increment.");
#endregion
#region PREFERENCES
/** Settings **/
public Color gridColorX, gridColorY, gridColorZ;
public Color gridColorX_primary, gridColorY_primary, gridColorZ_primary;
// private bool lockOrthographic;
public void LoadPreferences()
{
if( (EditorPrefs.HasKey(pg_Constant.PGVersion) ? EditorPrefs.GetInt(pg_Constant.PGVersion) : 0) < VERSION )
{
EditorPrefs.SetInt(pg_Constant.PGVersion, VERSION);
if(RESET_PREFS_REQ)
{
pg_Preferences.ResetPrefs();
// Debug.Log("Resetting Prefs");
}
}
if(EditorPrefs.HasKey(pg_Constant.SnapEnabled))
{
snapEnabled = EditorPrefs.GetBool(pg_Constant.SnapEnabled);
}
SetSnapValue(
EditorPrefs.HasKey(pg_Constant.GridUnit) ? (SnapUnit)EditorPrefs.GetInt(pg_Constant.GridUnit) : SnapUnit.Meter,
EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1,
EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100
);
if(EditorPrefs.HasKey(pg_Constant.UseAxisConstraints))
useAxisConstraints = EditorPrefs.GetBool(pg_Constant.UseAxisConstraints);
lockGrid = EditorPrefs.GetBool(pg_Constant.LockGrid);
if(lockGrid)
{
if(EditorPrefs.HasKey(pg_Constant.LockedGridPivot))
{
string piv = EditorPrefs.GetString(pg_Constant.LockedGridPivot);
string[] pivsplit = piv.Replace("(", "").Replace(")", "").Split(',');
float x, y, z;
if( !float.TryParse(pivsplit[0], out x) ) goto NoParseForYou;
if( !float.TryParse(pivsplit[1], out y) ) goto NoParseForYou;
if( !float.TryParse(pivsplit[2], out z) ) goto NoParseForYou;
pivot.x = x;
pivot.y = y;
pivot.z = z;
NoParseForYou:
; // appease the compiler
}
}
fullGrid = EditorPrefs.GetBool(pg_Constant.PerspGrid);
renderPlane = EditorPrefs.HasKey(pg_Constant.GridAxis) ? (Axis)EditorPrefs.GetInt(pg_Constant.GridAxis) : Axis.Y;
alphaBump = (EditorPrefs.HasKey("pg_alphaBump")) ? EditorPrefs.GetFloat("pg_alphaBump") : pg_Preferences.ALPHA_BUMP;
gridColorX = (EditorPrefs.HasKey("gridColorX")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorX")) : pg_Preferences.GRID_COLOR_X;
gridColorX_primary = new Color(gridColorX.r, gridColorX.g, gridColorX.b, gridColorX.a + alphaBump);
gridColorY = (EditorPrefs.HasKey("gridColorY")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorY")) : pg_Preferences.GRID_COLOR_Y;
gridColorY_primary = new Color(gridColorY.r, gridColorY.g, gridColorY.b, gridColorY.a + alphaBump);
gridColorZ = (EditorPrefs.HasKey("gridColorZ")) ? pg_Util.ColorWithString(EditorPrefs.GetString("gridColorZ")) : pg_Preferences.GRID_COLOR_Z;
gridColorZ_primary = new Color(gridColorZ.r, gridColorZ.g, gridColorZ.b, gridColorZ.a + alphaBump);
drawGrid = (EditorPrefs.HasKey("showgrid")) ? EditorPrefs.GetBool("showgrid") : pg_Preferences.SHOW_GRID;
predictiveGrid = EditorPrefs.HasKey(pg_Constant.PredictiveGrid) ? EditorPrefs.GetBool(pg_Constant.PredictiveGrid) : true;
_snapAsGroup = snapAsGroup;
_scaleSnapEnabled = ScaleSnapEnabled;
}
private GUISkin sixBySevenSkin;
#endregion
#region MENU
[MenuItem("Tools/ProGrids/About", false, 0)]
public static void MenuAboutProGrids()
{
pg_AboutWindow.Init("Assets/ProCore/ProGrids/About/pc_AboutEntry_ProGrids.txt", true);
}
[MenuItem("Tools/ProGrids/ProGrids Window", false, 15)]
public static void InitProGrids()
{
if( instance == null )
{
EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, true);
instance = ScriptableObject.CreateInstance<pg_Editor>();
instance.hideFlags = HideFlags.DontSave;
EditorApplication.delayCall += instance.Initialize;
}
else
{
// Close any additional ProGrids instances
CloseProGrids();
}
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Close ProGrids", true, 200)]
public static bool VerifyCloseProGrids()
{
return instance != null || Resources.FindObjectsOfTypeAll<pg_Editor>().Length > 0;
}
[MenuItem("Tools/ProGrids/Close ProGrids")]
public static void CloseProGrids()
{
foreach(pg_Editor editor in Resources.FindObjectsOfTypeAll<pg_Editor>())
editor.Close();
}
[MenuItem("Tools/ProGrids/Cycle SceneView Projection", false, 101)]
public static void CyclePerspective()
{
if(instance == null) return;
SceneView scnvw = SceneView.lastActiveSceneView;
if(scnvw == null) return;
int nextOrtho = EditorPrefs.GetInt(pg_Constant.LastOrthoToggledRotation);
switch(nextOrtho)
{
case 0:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.zero));
nextOrtho++;
break;
case 1:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.up * -90f));
nextOrtho++;
break;
case 2:
scnvw.orthographic = true;
scnvw.LookAt(scnvw.pivot, Quaternion.Euler(Vector3.right * 90f));
nextOrtho++;
break;
case 3:
scnvw.orthographic = false;
scnvw.LookAt(scnvw.pivot, new Quaternion(-0.1f, 0.9f, -0.2f, -0.4f) );
nextOrtho = 0;
break;
}
EditorPrefs.SetInt(pg_Constant.LastOrthoToggledRotation, nextOrtho);
}
[MenuItem("Tools/ProGrids/Cycle SceneView Projection", true, 101)]
[MenuItem("Tools/ProGrids/Increase Grid Size", true, 203)]
[MenuItem("Tools/ProGrids/Decrease Grid Size", true, 202)]
public static bool VerifyGridSizeAdjustment()
{
return instance != null;
}
[MenuItem("Tools/ProGrids/Decrease Grid Size", false, 202)]
public static void DecreaseGridSize()
{
if(instance == null) return;
int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100;
float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f;
multiplier /= 2;
instance.SetSnapValue(instance.snapUnit, val, multiplier);
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Increase Grid Size", false, 203)]
public static void IncreaseGridSize()
{
if(instance == null) return;
int multiplier = EditorPrefs.HasKey(pg_Constant.SnapMultiplier) ? EditorPrefs.GetInt(pg_Constant.SnapMultiplier) : 100;
float val = EditorPrefs.HasKey(pg_Constant.SnapValue) ? EditorPrefs.GetFloat(pg_Constant.SnapValue) : 1f;
multiplier *= 2;
instance.SetSnapValue(instance.snapUnit, val, multiplier);
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Nudge Perspective Backward", true, 304)]
[MenuItem("Tools/ProGrids/Nudge Perspective Forward", true, 305)]
[MenuItem("Tools/ProGrids/Reset Perspective Nudge", true, 306)]
public static bool VerifyMenuNudgePerspective()
{
return instance != null && !instance.fullGrid && !instance.ortho && instance.lockGrid;
}
[MenuItem("Tools/ProGrids/Nudge Perspective Backward", false, 304)]
public static void MenuNudgePerspectiveBackward()
{
if(!instance.lockGrid) return;
instance.offset -= instance.snapValue;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Nudge Perspective Forward", false, 305)]
public static void MenuNudgePerspectiveForward()
{
if(!instance.lockGrid) return;
instance.offset += instance.snapValue;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
[MenuItem("Tools/ProGrids/Reset Perspective Nudge", false, 306)]
public static void MenuNudgePerspectiveReset()
{
if(!instance.lockGrid) return;
instance.offset = 0;
instance.gridRepaint = true;
SceneView.RepaintAll();
}
#endregion
#region INITIALIZATION / SERIALIZATION
public void OnBeforeSerialize() {}
public void OnAfterDeserialize()
{
instance = this;
SceneView.onSceneGUIDelegate += OnSceneGUI;
EditorApplication.update += Update;
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
}
void OnEnable()
{
instance.LoadGUIResources();
}
public void Initialize()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
EditorApplication.update += Update;
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
LoadGUIResources();
LoadPreferences();
instance = this;
pg_GridRenderer.Init();
SetMenuIsExtended(false);
lastTime = Time.realtimeSinceStartup;
ToggleMenuVisibility();
gridRepaint = true;
RepaintSceneView();
}
void OnDestroy()
{
this.Close(true);
}
public void Close()
{
EditorPrefs.SetBool(pg_Constant.ProGridsIsEnabled, false);
GameObject.DestroyImmediate(this);
}
public void Close(bool isBeingDestroyed)
{
pg_GridRenderer.Destroy();
SceneView.onSceneGUIDelegate -= OnSceneGUI;
EditorApplication.update -= Update;
EditorApplication.hierarchyWindowChanged -= HierarchyWindowChanged;
instance = null;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(false);
SceneView.RepaintAll();
}
private void LoadGUIResources()
{
if(gc_GridEnabled.image_on == null)
gc_GridEnabled.image_on = LoadIcon("ProGrids2_GUI_Vis_On.png");
if(gc_GridEnabled.image_off == null)
gc_GridEnabled.image_off = LoadIcon("ProGrids2_GUI_Vis_Off.png");
if(gc_SnapEnabled.image_on == null)
gc_SnapEnabled.image_on = LoadIcon("ProGrids2_GUI_Snap_On.png");
if(gc_SnapEnabled.image_off == null)
gc_SnapEnabled.image_off = LoadIcon("ProGrids2_GUI_Snap_Off.png");
if(gc_SnapToGrid.image_on == null)
gc_SnapToGrid.image_on = LoadIcon("ProGrids2_GUI_PushToGrid_Normal.png");
if(gc_LockGrid.image_on == null)
gc_LockGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_Lock_On.png");
if(gc_LockGrid.image_off == null)
gc_LockGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_Lock_Off.png");
if(gc_AngleEnabled.image_on == null)
gc_AngleEnabled.image_on = LoadIcon("ProGrids2_GUI_AngleVis_On.png");
if(gc_AngleEnabled.image_off == null)
gc_AngleEnabled.image_off = LoadIcon("ProGrids2_GUI_AngleVis_Off.png");
if(gc_RenderPlaneX.image_on == null)
gc_RenderPlaneX.image_on = LoadIcon("ProGrids2_GUI_PGrid_X_On.png");
if(gc_RenderPlaneX.image_off == null)
gc_RenderPlaneX.image_off = LoadIcon("ProGrids2_GUI_PGrid_X_Off.png");
if(gc_RenderPlaneY.image_on == null)
gc_RenderPlaneY.image_on = LoadIcon("ProGrids2_GUI_PGrid_Y_On.png");
if(gc_RenderPlaneY.image_off == null)
gc_RenderPlaneY.image_off = LoadIcon("ProGrids2_GUI_PGrid_Y_Off.png");
if(gc_RenderPlaneZ.image_on == null)
gc_RenderPlaneZ.image_on = LoadIcon("ProGrids2_GUI_PGrid_Z_On.png");
if(gc_RenderPlaneZ.image_off == null)
gc_RenderPlaneZ.image_off = LoadIcon("ProGrids2_GUI_PGrid_Z_Off.png");
if(gc_RenderPerspectiveGrid.image_on == null)
gc_RenderPerspectiveGrid.image_on = LoadIcon("ProGrids2_GUI_PGrid_3D_On.png");
if(gc_RenderPerspectiveGrid.image_off == null)
gc_RenderPerspectiveGrid.image_off = LoadIcon("ProGrids2_GUI_PGrid_3D_Off.png");
if(icon_extendoOpen == null)
icon_extendoOpen = LoadIcon("ProGrids2_MenuExtendo_Open.png");
if(icon_extendoClose == null)
icon_extendoClose = LoadIcon("ProGrids2_MenuExtendo_Close.png");
}
private Texture2D LoadIcon(string iconName)
{
string iconPath = ProGrids_Icons_Path + "/" + iconName;
if(!File.Exists(iconPath))
{
string[] path = Directory.GetFiles("Assets", iconName, SearchOption.AllDirectories);
if(path.Length > 0)
{
ProGrids_Icons_Path = Path.GetDirectoryName(path[0]);
iconPath = path[0];
}
else
{
Debug.LogError("ProGrids failed to locate menu image: " + iconName + ".\nThis can happen if the GUI folder is moved or deleted. Deleting and re-importing ProGrids will fix this error.");
return (Texture2D) null;
}
}
return LoadAssetAtPath<Texture2D>(iconPath);
}
T LoadAssetAtPath<T>(string path) where T : UnityEngine.Object
{
return (T) AssetDatabase.LoadAssetAtPath(path, typeof(T));
}
#endregion
#region INTERFACE
GUIStyle gridButtonStyle = new GUIStyle();
GUIStyle extendoStyle = new GUIStyle();
GUIStyle gridButtonStyleBlank = new GUIStyle();
GUIStyle backgroundStyle = new GUIStyle();
bool guiInitialized = false;
public float GetSnapIncrement()
{
return t_snapValue;
}
public void SetSnapIncrement(float inc)
{
SetSnapValue(snapUnit, Mathf.Max(inc, .001f), 100);
}
void RepaintSceneView()
{
SceneView.RepaintAll();
}
int MENU_HIDDEN { get { return menuIsOrtho ? -192 : -173; } }
const int MENU_EXTENDED = 8;
const int PAD = 3;
Rect r = new Rect(8, MENU_EXTENDED, 42, 16);
Rect backgroundRect = new Rect(00,0,0,0);
Rect extendoButtonRect = new Rect(0,0,0,0);
bool menuOpen = true;
float menuStart = MENU_EXTENDED;
const float MENU_SPEED = 500f;
float deltaTime = 0f;
float lastTime = 0f;
const float FADE_SPEED = 2.5f;
float backgroundFade = 1f;
bool mouseOverMenu = false;
Color menuBackgroundColor = new Color(0f, 0f, 0f, .5f);
Color extendoNormalColor = new Color(.9f, .9f, .9f, .7f);
Color extendoHoverColor = new Color(0f, 1f, .4f, 1f);
bool extendoButtonHovering = false;
bool menuIsOrtho = false;
void Update()
{
deltaTime = Time.realtimeSinceStartup - lastTime;
lastTime = Time.realtimeSinceStartup;
if( menuOpen && menuStart < MENU_EXTENDED || !menuOpen && menuStart > MENU_HIDDEN )
{
menuStart += deltaTime * MENU_SPEED * (menuOpen ? 1f : -1f);
menuStart = Mathf.Clamp(menuStart, MENU_HIDDEN, MENU_EXTENDED);
RepaintSceneView();
}
float a = menuBackgroundColor.a;
backgroundFade = (mouseOverMenu || !menuOpen) ? FADE_SPEED : -FADE_SPEED;
menuBackgroundColor.a = Mathf.Clamp(menuBackgroundColor.a + backgroundFade * deltaTime, 0f, .5f);
extendoNormalColor.a = menuBackgroundColor.a;
extendoHoverColor.a = (menuBackgroundColor.a / .5f);
if( !Mathf.Approximately(menuBackgroundColor.a,a) )
RepaintSceneView();
}
void DrawSceneGUI()
{
// GUILayout.BeginArea(new Rect(300, 200, 400, 600));
// off = EditorGUILayout.RectField("Rect", off);
// extendoHoverColor = EditorGUI.ColorField(new Rect(200, 40, 200, 18), "howver", extendoHoverColor);
// GUILayout.EndArea();
GUI.backgroundColor = menuBackgroundColor;
backgroundRect.x = r.x - 4;
backgroundRect.y = 0;
backgroundRect.width = r.width + 8;
backgroundRect.height = r.y + r.height + PAD;
GUI.Box(backgroundRect, "", backgroundStyle);
// when hit testing mouse for showing the background, add some leeway
backgroundRect.width += 32f;
backgroundRect.height += 32f;
GUI.backgroundColor = Color.white;
if( !guiInitialized )
{
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
guiInitialized = true;
backgroundStyle.normal.background = EditorGUIUtility.whiteTexture;
Texture2D icon_button_normal = LoadIcon("ProGrids2_Button_Normal.png");
Texture2D icon_button_hover = LoadIcon("ProGrids2_Button_Hover.png");
if(icon_button_normal == null)
{
gridButtonStyleBlank = new GUIStyle("button");
}
else
{
gridButtonStyleBlank.normal.background = icon_button_normal;
gridButtonStyleBlank.hover.background = icon_button_hover;
gridButtonStyleBlank.normal.textColor = icon_button_normal != null ? Color.white : Color.black;
gridButtonStyleBlank.hover.textColor = new Color(.7f, .7f, .7f, 1f);
}
gridButtonStyleBlank.padding = new RectOffset(1,2,1,2);
gridButtonStyleBlank.alignment = TextAnchor.MiddleCenter;
}
r.y = menuStart;
gc_SnapIncrement.text = t_snapValue.ToString();
if( GUI.Button(r, gc_SnapIncrement, gridButtonStyleBlank) )
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
// On Mac ShowAsDropdown and ShowAuxWindow both throw stack pop exceptions when initialized.
pg_ParameterWindow options = EditorWindow.GetWindow<pg_ParameterWindow>(true, "ProGrids Settings", true);
Rect screenRect = SceneView.lastActiveSceneView.position;
options.editor = this;
options.position = new Rect(screenRect.x + r.x + r.width + PAD,
screenRect.y + r.y + 24,
256,
162);
#else
pg_ParameterWindow options = ScriptableObject.CreateInstance<pg_ParameterWindow>();
Rect screenRect = SceneView.lastActiveSceneView.position;
options.editor = this;
options.ShowAsDropDown(new Rect(screenRect.x + r.x + r.width + PAD,
screenRect.y + r.y + 24,
0,
0),
new Vector2(256, 162));
#endif
}
r.y += r.height + PAD;
// Draw grid
if(pg_ToggleContent.ToggleButton(r, gc_GridEnabled, drawGrid, gridButtonStyle, EditorStyles.miniButton))
SetGridEnabled(!drawGrid);
r.y += r.height + PAD;
// Snap enabled
if(pg_ToggleContent.ToggleButton(r, gc_SnapEnabled, snapEnabled, gridButtonStyle, EditorStyles.miniButton))
SetSnapEnabled(!snapEnabled);
r.y += r.height + PAD;
// Push to grid
if(pg_ToggleContent.ToggleButton(r, gc_SnapToGrid, true, gridButtonStyle, EditorStyles.miniButton))
SnapToGrid(Selection.transforms);
r.y += r.height + PAD;
// Lock grid
if(pg_ToggleContent.ToggleButton(r, gc_LockGrid, lockGrid, gridButtonStyle, EditorStyles.miniButton))
{
lockGrid = !lockGrid;
EditorPrefs.SetBool(pg_Constant.LockGrid, lockGrid);
EditorPrefs.SetString(pg_Constant.LockedGridPivot, pivot.ToString());
// if we've modified the nudge value, reset the pivot here
if(!lockGrid)
offset = 0f;
gridRepaint = true;
RepaintSceneView();
}
if(menuIsOrtho)
{
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_AngleEnabled, drawAngles, gridButtonStyle, EditorStyles.miniButton))
SetDrawAngles(!drawAngles);
}
/**
* Perspective Toggles
*/
r.y += r.height + PAD + 4;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneX, (renderPlane & Axis.X) == Axis.X && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.X);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneY, (renderPlane & Axis.Y) == Axis.Y && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.Y);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPlaneZ, (renderPlane & Axis.Z) == Axis.Z && !fullGrid, gridButtonStyle, EditorStyles.miniButton))
SetRenderPlane(Axis.Z);
r.y += r.height + PAD;
if(pg_ToggleContent.ToggleButton(r, gc_RenderPerspectiveGrid, fullGrid, gridButtonStyle, EditorStyles.miniButton))
{
fullGrid = !fullGrid;
gridRepaint = true;
EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid);
RepaintSceneView();
}
r.y += r.height + PAD;
extendoButtonRect.x = r.x;
extendoButtonRect.y = r.y;
extendoButtonRect.width = r.width;
extendoButtonRect.height = r.height;
GUI.backgroundColor = extendoButtonHovering ? extendoHoverColor : extendoNormalColor;
gc_ExtendMenu.text = icon_extendoOpen == null ? (menuOpen ? "Close" : "Open") : "";
if(GUI.Button(r, gc_ExtendMenu, icon_extendoOpen ? extendoStyle : gridButtonStyleBlank))
{
ToggleMenuVisibility();
extendoButtonHovering = false;
}
GUI.backgroundColor = Color.white;
}
void ToggleMenuVisibility()
{
menuOpen = !menuOpen;
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(menuOpen);
RepaintSceneView();
}
// skip color fading and stuff
void SetMenuIsExtended(bool isExtended)
{
menuOpen = isExtended;
menuIsOrtho = ortho;
menuStart = menuOpen ? MENU_EXTENDED : MENU_HIDDEN;
menuBackgroundColor.a = 0f;
extendoNormalColor.a = menuBackgroundColor.a;
extendoHoverColor.a = (menuBackgroundColor.a / .5f);
extendoStyle.normal.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
extendoStyle.hover.background = menuOpen ? icon_extendoClose : icon_extendoOpen;
foreach(System.Action<bool> listener in toolbarEventSubscribers)
listener(menuOpen);
}
private void OpenProGridsPopup()
{
if( EditorUtility.DisplayDialog(
"Upgrade to ProGrids", // Title
"Enables all kinds of super-cool features, like different snap values, more units of measurement, and angles.", // Message
"Upgrade", // Okay
"Cancel" // Cancel
))
// #if UNITY_4
// AssetStore.OpenURL(pg_Constant.ProGridsUpgradeURL);
// #else
Application.OpenURL(pg_Constant.ProGridsUpgradeURL);
// #endif
}
#endregion
#region ONSCENEGUI
private Transform lastTransform;
const string AXIS_CONSTRAINT_KEY = "s";
const string TEMP_DISABLE_KEY = "d";
private bool toggleAxisConstraint = false;
private bool toggleTempSnap = false;
private Vector3 lastPosition = Vector3.zero;
// private Vector3 lastRotation = Vector3.zero;
private Vector3 lastScale = Vector3.one;
private Vector3 pivot = Vector3.zero, lastPivot = Vector3.zero;
private Vector3 camDir = Vector3.zero, prevCamDir = Vector3.zero;
private float lastDistance = 0f; ///< Distance from camera to pivot at the last time the grid mesh was updated.
public float offset = 0f;
private bool firstMove = true;
#if PROFILE_TIMES
pb_Profiler profiler = new pb_Profiler();
#endif
public bool ortho { get; private set; }
private bool prevOrtho = false;
float planeGridDrawDistance = 0f;
public void OnSceneGUI(SceneView scnview)
{
bool isCurrentView = scnview == SceneView.lastActiveSceneView;
if( isCurrentView )
{
Handles.BeginGUI();
DrawSceneGUI();
Handles.EndGUI();
}
// don't snap stuff in play mode
if(EditorApplication.isPlayingOrWillChangePlaymode)
return;
Event e = Event.current;
// repaint scene gui if mouse is near controls
if( isCurrentView && e.type == EventType.MouseMove )
{
bool tmp = extendoButtonHovering;
extendoButtonHovering = extendoButtonRect.Contains(e.mousePosition);
if( extendoButtonHovering != tmp )
RepaintSceneView();
mouseOverMenu = backgroundRect.Contains(e.mousePosition);
}
if (e.Equals(Event.KeyboardEvent(AXIS_CONSTRAINT_KEY)))
{
toggleAxisConstraint = true;
}
if (e.Equals(Event.KeyboardEvent(TEMP_DISABLE_KEY)))
{
toggleTempSnap = true;
}
if(e.type == EventType.KeyUp)
{
toggleAxisConstraint = false;
toggleTempSnap = false;
bool used = true;
switch(e.keyCode)
{
case KeyCode.Equals:
IncreaseGridSize();
break;
case KeyCode.Minus:
DecreaseGridSize();
break;
case KeyCode.LeftBracket:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveBackward();
break;
case KeyCode.RightBracket:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveForward();
break;
case KeyCode.Alpha0:
if(VerifyMenuNudgePerspective())
MenuNudgePerspectiveReset();
break;
case KeyCode.Backslash:
CyclePerspective();
break;
default:
used = false;
break;
}
if(used)
e.Use();
}
Camera cam = Camera.current;
if(cam == null)
return;
ortho = cam.orthographic && IsRounded(scnview.rotation.eulerAngles.normalized);
camDir = pg_Util.CeilFloor( pivot - cam.transform.position );
if(ortho && !prevOrtho || ortho != menuIsOrtho)
OnSceneBecameOrtho(isCurrentView);
if(!ortho && prevOrtho)
OnSceneBecamePersp(isCurrentView);
prevOrtho = ortho;
float camDistance = Vector3.Distance(cam.transform.position, lastPivot); // distance from camera to pivot
if(fullGrid)
{
pivot = lockGrid || Selection.activeTransform == null ? pivot : Selection.activeTransform.position;
}
else
{
Vector3 sceneViewPlanePivot = pivot;
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
Plane plane = new Plane(Vector3.up, pivot);
float dist;
// the only time a locked grid should ever move is if it's pivot is out
// of the camera's frustum.
if( (lockGrid && !cam.InFrustum(pivot)) || !lockGrid || scnview != SceneView.lastActiveSceneView)
{
if(plane.Raycast(ray, out dist))
sceneViewPlanePivot = ray.GetPoint( Mathf.Min(dist, planeGridDrawDistance/2f) );
else
sceneViewPlanePivot = ray.GetPoint( Mathf.Min(cam.farClipPlane/2f, planeGridDrawDistance/2f) );
}
if(lockGrid)
{
pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(pivot, renderPlane);
}
else
{
pivot = Selection.activeTransform == null ? pivot : Selection.activeTransform.position;
if( Selection.activeTransform == null || !cam.InFrustum(pivot) )
{
pivot = pg_Enum.InverseAxisMask(sceneViewPlanePivot, renderPlane) + pg_Enum.AxisMask(Selection.activeTransform == null ? pivot : Selection.activeTransform.position, renderPlane);
}
}
}
#if PG_DEBUG
pivotGo.transform.position = pivot;
#endif
if(drawGrid)
{
if(ortho)
{
// ortho don't care about pivots
DrawGridOrthographic(cam);
}
else
{
#if PROFILE_TIMES
profiler.LogStart("DrawGridPerspective");
#endif
if( gridRepaint || pivot != lastPivot || Mathf.Abs(camDistance - lastDistance) > lastDistance/2 || camDir != prevCamDir)
{
prevCamDir = camDir;
gridRepaint = false;
lastPivot = pivot;
lastDistance = camDistance;
if(fullGrid)
{
// if perspective and 3d, use pivot like normal
pg_GridRenderer.DrawGridPerspective(cam, pivot, snapValue, new Color[3] { gridColorX, gridColorY, gridColorZ }, alphaBump );
}
else
{
if( (renderPlane & Axis.X) == Axis.X)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.right * offset, Vector3.up, Vector3.forward, snapValue, gridColorX, alphaBump);
if( (renderPlane & Axis.Y) == Axis.Y)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.up * offset, Vector3.right, Vector3.forward, snapValue, gridColorY, alphaBump);
if( (renderPlane & Axis.Z) == Axis.Z)
planeGridDrawDistance = pg_GridRenderer.DrawPlane(cam, pivot + Vector3.forward * offset, Vector3.up, Vector3.right, snapValue, gridColorZ, alphaBump);
}
}
#if PROFILE_TIMES
profiler.LogFinish("DrawGridPerspective");
#endif
}
}
// Always keep track of the selection
if(!Selection.transforms.Contains(lastTransform))
{
if(Selection.activeTransform)
{
lastTransform = Selection.activeTransform;
lastPosition = Selection.activeTransform.position;
lastScale = Selection.activeTransform.localScale;
}
}
if( e.type == EventType.MouseUp )
firstMove = true;
if(!snapEnabled || GUIUtility.hotControl < 1)
return;
// Bugger.SetKey("Toggle Snap Off", toggleTempSnap);
/**
* Snapping (for all the junk in PG, this method is literally the only code that actually affects anything).
*/
if(Selection.activeTransform)
{
if( !FuzzyEquals(lastTransform.position, lastPosition) )
{
Transform selected = lastTransform;
if( !toggleTempSnap )
{
Vector3 old = selected.position;
Vector3 mask = old - lastPosition;
bool constraintsOn = toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints;
if(constraintsOn)
selected.position = pg_Util.SnapValue(old, mask, snapValue);
else
selected.position = pg_Util.SnapValue(old, snapValue);
Vector3 offset = selected.position - old;
if( predictiveGrid && firstMove && !fullGrid )
{
firstMove = false;
Axis dragAxis = pg_Util.CalcDragAxis(offset, scnview.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
if(_snapAsGroup)
{
OffsetTransforms(Selection.transforms, selected, offset);
}
else
{
foreach(Transform t in Selection.transforms)
t.position = constraintsOn ? pg_Util.SnapValue(t.position, mask, snapValue) : pg_Util.SnapValue(t.position, snapValue);
}
}
lastPosition = selected.position;
}
if( !FuzzyEquals(lastTransform.localScale, lastScale) && _scaleSnapEnabled )
{
if( !toggleTempSnap )
{
Vector3 old = lastTransform.localScale;
Vector3 mask = old - lastScale;
if( predictiveGrid )
{
Axis dragAxis = pg_Util.CalcDragAxis( Selection.activeTransform.TransformDirection(mask), scnview.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
foreach(Transform t in Selection.transforms)
t.localScale = pg_Util.SnapValue(t.localScale, mask, snapValue);
lastScale = lastTransform.localScale;
}
}
}
}
void OnSceneBecameOrtho(bool isCurrentView)
{
pg_GridRenderer.Destroy();
if(isCurrentView && ortho != menuIsOrtho)
SetMenuIsExtended(menuOpen);
}
void OnSceneBecamePersp(bool isCurrentView)
{
if(isCurrentView && ortho != menuIsOrtho)
SetMenuIsExtended(menuOpen);
}
#endregion
#region GRAPHICS
GameObject go;
private void DrawGridOrthographic(Camera cam)
{
Axis camAxis = AxisWithVector(Camera.current.transform.TransformDirection(Vector3.forward).normalized);
if(drawGrid) {
switch(camAxis)
{
case Axis.X:
case Axis.NegX:
DrawGridOrthographic(cam, camAxis, gridColorX_primary, gridColorX);
break;
case Axis.Y:
case Axis.NegY:
DrawGridOrthographic(cam, camAxis, gridColorY_primary, gridColorY);
break;
case Axis.Z:
case Axis.NegZ:
DrawGridOrthographic(cam, camAxis, gridColorZ_primary, gridColorZ);
break;
}
}
}
int PRIMARY_COLOR_INCREMENT = 10;
Color previousColor;
private void DrawGridOrthographic(Camera cam, Axis camAxis, Color primaryColor, Color secondaryColor)
{
previousColor = Handles.color;
Handles.color = primaryColor;
// !-- TODO: Update this stuff only when necessary. Currently it runs evvverrrryyy frame
Vector3 bottomLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(Vector2.zero), snapValue);
Vector3 bottomRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, 0f)), snapValue);
Vector3 topLeft = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(0f, cam.pixelHeight)), snapValue);
Vector3 topRight = pg_Util.SnapToFloor(cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, cam.pixelHeight)), snapValue);
Vector3 axis = VectorWithAxis(camAxis);
float width = Vector3.Distance(bottomLeft, bottomRight);
float height = Vector3.Distance(bottomRight, topRight);
// Shift lines to 10m forward of the camera
bottomLeft += axis*10f;
topRight += axis*10f;
bottomRight += axis*10f;
topLeft += axis*10f;
/**
* Draw Vertical Lines
*/
Vector3 cam_right = cam.transform.right;
Vector3 cam_up = cam.transform.up;
float _snapVal = snapValue;
int segs = (int)Mathf.Ceil(width / _snapVal) + 2;
float n = 2f;
while(segs > MAX_LINES) {
_snapVal = _snapVal*n;
segs = (int)Mathf.Ceil(width / _snapVal ) + 2;
n++;
}
/// Screen start and end
Vector3 bl = cam_right.Sum() > 0 ? pg_Util.SnapToFloor(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToCeil(bottomLeft, cam_right, _snapVal*PRIMARY_COLOR_INCREMENT);
Vector3 start = bl - cam_up * (height+_snapVal*2);
Vector3 end = bl + cam_up * (height+_snapVal*2);
segs += PRIMARY_COLOR_INCREMENT;
/// The current line start and end
Vector3 line_start = Vector3.zero;
Vector3 line_end = Vector3.zero;
for(int i = -1; i < segs; i++)
{
line_start = start + (i * (cam_right * _snapVal));
line_end = end + (i * (cam_right * _snapVal) );
Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor;
Handles.DrawLine( line_start, line_end );
}
/**
* Draw Horizontal Lines
*/
segs = (int)Mathf.Ceil(height / _snapVal) + 2;
n = 2;
while(segs > MAX_LINES) {
_snapVal = _snapVal*n;
segs = (int)Mathf.Ceil(height / _snapVal ) + 2;
n++;
}
Vector3 tl = cam_up.Sum() > 0 ? pg_Util.SnapToCeil(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT) : pg_Util.SnapToFloor(topLeft, cam_up, _snapVal*PRIMARY_COLOR_INCREMENT);
start = tl - cam_right * (width+_snapVal*2);
end = tl + cam_right * (width+_snapVal*2);
segs += (int)PRIMARY_COLOR_INCREMENT;
for(int i = -1; i < segs; i++)
{
line_start = start + (i * (-cam_up * _snapVal));
line_end = end + (i * (-cam_up * _snapVal));
Handles.color = i % PRIMARY_COLOR_INCREMENT == 0 ? primaryColor : secondaryColor;
Handles.DrawLine(line_start, line_end);
}
#if PRO
if(drawAngles)
{
Vector3 cen = pg_Util.SnapValue(((topRight + bottomLeft) / 2f), snapValue);
float half = (width > height) ? width : height;
float opposite = Mathf.Tan( Mathf.Deg2Rad*angleValue ) * half;
Vector3 up = cam.transform.up * opposite;
Vector3 right = cam.transform.right * half;
Vector3 bottomLeftAngle = cen - (up+right);
Vector3 topRightAngle = cen + (up+right);
Vector3 bottomRightAngle = cen + (right-up);
Vector3 topLeftAngle = cen + (up-right);
Handles.color = primaryColor;
// y = 1x+1
Handles.DrawLine(bottomLeftAngle, topRightAngle);
// y = -1x-1
Handles.DrawLine(topLeftAngle, bottomRightAngle);
}
#endif
Handles.color = previousColor;
}
#endregion
#region ENUM UTILITY
public SnapUnit SnapUnitWithString(string str)
{
foreach(SnapUnit su in SnapUnit.GetValues(typeof(SnapUnit)))
{
if(su.ToString() == str)
return su;
}
return (SnapUnit)0;
}
public Axis AxisWithVector(Vector3 val)
{
Vector3 v = new Vector3(Mathf.Abs(val.x), Mathf.Abs(val.y), Mathf.Abs(val.z));
if(v.x > v.y && v.x > v.z) {
if(val.x > 0)
return Axis.X;
else
return Axis.NegX;
}
else
if(v.y > v.x && v.y > v.z) {
if(val.y > 0)
return Axis.Y;
else
return Axis.NegY;
}
else {
if(val.z > 0)
return Axis.Z;
else
return Axis.NegZ;
}
}
public Vector3 VectorWithAxis(Axis axis)
{
switch(axis)
{
case Axis.X:
return Vector3.right;
case Axis.Y:
return Vector3.up;
case Axis.Z:
return Vector3.forward;
case Axis.NegX:
return -Vector3.right;
case Axis.NegY:
return -Vector3.up;
case Axis.NegZ:
return -Vector3.forward;
default:
return Vector3.forward;
}
}
public bool IsRounded(Vector3 v)
{
return ( Mathf.Approximately(v.x, 1f) || Mathf.Approximately(v.y, 1f) || Mathf.Approximately(v.z, 1f) ) || v == Vector3.zero;
}
public Vector3 RoundAxis(Vector3 v)
{
return VectorWithAxis(AxisWithVector(v));
}
#endregion
#region MOVING TRANSFORMS
static bool FuzzyEquals(Vector3 lhs, Vector3 rhs)
{
return Mathf.Abs(lhs.x - rhs.x) < .001f && Mathf.Abs(lhs.y - rhs.y) < .001f && Mathf.Abs(lhs.z - rhs.z) < .001f;
}
public void OffsetTransforms(Transform[] trsfrms, Transform ignore, Vector3 offset)
{
foreach(Transform t in trsfrms)
{
if(t != ignore)
t.position += offset;
}
}
void HierarchyWindowChanged()
{
if( Selection.activeTransform != null)
lastPosition = Selection.activeTransform.position;
}
#endregion
#region SETTINGS
public void SetSnapEnabled(bool enable)
{
EditorPrefs.SetBool(pg_Constant.SnapEnabled, enable);
if(Selection.activeTransform)
{
lastTransform = Selection.activeTransform;
lastPosition = Selection.activeTransform.position;
}
snapEnabled = enable;
gridRepaint = true;
RepaintSceneView();
}
public void SetSnapValue(SnapUnit su, float val, int multiplier)
{
int clamp_multiplier = (int)(Mathf.Min(Mathf.Max(25, multiplier), 102400));
float value_multiplier = clamp_multiplier / 100f;
/**
* multiplier is a value modifies the snap val. 100 = no change,
* 50 is half val, 200 is double val, etc.
*/
#if PRO
snapValue = pg_Enum.SnapUnitValue(su) * val * value_multiplier;
RepaintSceneView();
EditorPrefs.SetInt(pg_Constant.GridUnit, (int)su);
EditorPrefs.SetFloat(pg_Constant.SnapValue, val);
EditorPrefs.SetInt(pg_Constant.SnapMultiplier, clamp_multiplier);
// update gui (only necessary when calling with editorpref values)
t_snapValue = val * value_multiplier;
snapUnit = su;
switch(su)
{
case SnapUnit.Inch:
PRIMARY_COLOR_INCREMENT = 12; // blasted imperial units
break;
case SnapUnit.Foot:
PRIMARY_COLOR_INCREMENT = 3;
break;
default:
PRIMARY_COLOR_INCREMENT = 10;
break;
}
gridRepaint = true;
#else
Debug.LogWarning("Ye ought not be seein' this ye scurvy pirate.");
#endif
}
public void SetRenderPlane(Axis axis)
{
offset = 0f;
fullGrid = false;
renderPlane = axis;
EditorPrefs.SetBool(pg_Constant.PerspGrid, fullGrid);
EditorPrefs.SetInt(pg_Constant.GridAxis, (int)renderPlane);
gridRepaint = true;
RepaintSceneView();
}
public void SetGridEnabled(bool enable)
{
drawGrid = enable;
if(!drawGrid)
pg_GridRenderer.Destroy();
EditorPrefs.SetBool("showgrid", enable);
gridRepaint = true;
RepaintSceneView();
}
public void SetDrawAngles(bool enable)
{
drawAngles = enable;
gridRepaint = true;
RepaintSceneView();
}
private void SnapToGrid(Transform[] transforms)
{
Undo.RecordObjects(transforms as Object[], "Snap to Grid");
foreach(Transform t in transforms)
t.position = pg_Util.SnapValue(t.position, snapValue);
gridRepaint = true;
PushToGrid(snapValue);
}
#endregion
#region GLOBAL SETTING
internal bool GetUseAxisConstraints() { return toggleAxisConstraint ? !useAxisConstraints : useAxisConstraints; }
internal float GetSnapValue() { return snapValue; }
internal bool GetSnapEnabled() { return (toggleTempSnap ? !snapEnabled : snapEnabled); }
/**
* Returns the value of useAxisConstraints, accounting for the shortcut key toggle.
*/
public static bool UseAxisConstraints()
{
return instance != null ? instance.GetUseAxisConstraints() : false;
}
/**
* Return the current snap value.
*/
public static float SnapValue()
{
return instance != null ? instance.GetSnapValue() : 0f;
}
/**
* Return true if snapping is enabled, false otherwise.
*/
public static bool SnapEnabled()
{
return instance == null ? false : instance.GetSnapEnabled();
}
public static void AddPushToGridListener(System.Action<float> listener)
{
pushToGridListeners.Add(listener);
}
public static void RemovePushToGridListener(System.Action<float> listener)
{
pushToGridListeners.Remove(listener);
}
public static void AddToolbarEventSubscriber(System.Action<bool> listener)
{
toolbarEventSubscribers.Add(listener);
}
public static void RemoveToolbarEventSubscriber(System.Action<bool> listener)
{
toolbarEventSubscribers.Remove(listener);
}
public static bool SceneToolbarActive()
{
return instance != null;
}
[SerializeField] static List<System.Action<float>> pushToGridListeners = new List<System.Action<float>>();
[SerializeField] static List<System.Action<bool>> toolbarEventSubscribers = new List<System.Action<bool>>();
private void PushToGrid(float snapValue)
{
foreach(System.Action<float> listener in pushToGridListeners)
listener(snapValue);
}
public static void OnHandleMove(Vector3 worldDirection)
{
if (instance != null)
instance.OnHandleMove_Internal(worldDirection);
}
private void OnHandleMove_Internal(Vector3 worldDirection)
{
if( predictiveGrid && firstMove && !fullGrid )
{
firstMove = false;
Axis dragAxis = pg_Util.CalcDragAxis(worldDirection, SceneView.lastActiveSceneView.camera);
if(dragAxis != Axis.None && dragAxis != renderPlane)
SetRenderPlane(dragAxis);
}
}
#endregion
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define USE_TRACING
#define DEBUG
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Net;
using NUnit.Framework;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Calendar;
namespace Google.GData.Client.UnitTests
{
[TestFixture]
[Ignore("This test assumes you have a writable, generic gData server")]
public class WriteTestSuite : BaseTestClass
{
//////////////////////////////////////////////////////////////////////
/// <summary>default empty constructor</summary>
//////////////////////////////////////////////////////////////////////
public WriteTestSuite()
{
}
//////////////////////////////////////////////////////////////////////
/// <summary>deletes all entries in defhost feed</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostDeleteAll()
{
Tracing.TraceMsg("Entering DefaultHostDeleteAll");
FeedQuery query = new FeedQuery();
Service service = new Service();
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultHost);
AtomFeed returnFeed = service.Query(query);
foreach (AtomEntry entry in returnFeed.Entries )
{
entry.Delete();
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>[Test] creates a new entry, saves and loads it back</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostInsertOneAndDelete()
{
Tracing.TraceMsg("Entering DefaultHostInsertOneAndDelete");
AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1);
Service service = new Service();
FeedQuery query = new FeedQuery();
service.RequestFactory = this.factory;
int iCount=0;
string strTitle = "DefaultHostInsertOneAndDelete" + Guid.NewGuid().ToString();
entry.Title.Text = strTitle;
query.Uri = new Uri(this.defaultHost);
AtomFeed returnFeed = service.Query(query);
iCount = returnFeed.Entries.Count;
for (int i = 0; i < this.iIterations; i++)
{
Tracing.TraceMsg("DefaultHostInsertOneAndDelete, iteration : " + i);
Stream s = service.EntrySend(new Uri(this.defaultHost), entry, GDataRequestType.Insert);
s.Close();
returnFeed = service.Query(query);
Assert.AreEqual(iCount+1, returnFeed.Entries.Count, "feed should have one more entry now");
AtomEntry returnEntry = null;
foreach (AtomEntry feedEntry in returnFeed.Entries )
{
if (String.Compare(feedEntry.Title.Text, strTitle) == 0)
{
// got him
returnEntry = feedEntry;
break;
}
}
Assert.IsTrue(returnEntry != null, "did not find the just inserted entry");
returnEntry.Delete();
// query again and check count
returnFeed = service.Query(query);
Assert.AreEqual(iCount, returnFeed.Entries.Count, "feed has different number of entries as expected");
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>creates a number or rows </summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostInsertAndStay()
{
Tracing.TraceMsg("Entering DefaultHostInsertAndStay");
int iCount=0;
FeedQuery query = new FeedQuery();
Service service = new Service();
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultHost);
AtomFeed returnFeed = service.Query(query);
AtomEntry entry;
iCount = returnFeed.Entries.Count;
// now we have all we need.
for (int i = 0; i < this.iIterations; i++)
{
Tracing.TraceMsg("DefaultHostInsertAndStay: inserting entry #: " + i);
entry = ObjectModelHelper.CreateAtomEntry(i);
entry = returnFeed.Insert(entry);
}
Tracing.TraceMsg("DefaultHostInsertAndStay: inserted lot's of entries");
// done doing the inserts...
// now query the guy again.
returnFeed = service.Query(query);
Assert.AreEqual(iCount+this.iIterations, returnFeed.Entries.Count, "feed should have " + this.iIterations + " more entries now");
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>creates a number or rows and delets them again</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostMassiveInsertAndDelete()
{
Tracing.TraceMsg("Entering DefaultHostMassiveInsertAndDelete");
int iCount=0;
FeedQuery query = new FeedQuery();
Service service = new Service();
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultHost);
AtomFeed returnFeed = service.Query(query);
AtomEntry entry;
iCount = returnFeed.Entries.Count;
AtomEntryCollection newEntries = new AtomEntryCollection(null);
// now we have all we need.
for (int i = 0; i < this.iIterations; i++)
{
entry = ObjectModelHelper.CreateAtomEntry(i);
entry = returnFeed.Insert(entry);
newEntries.Add(entry);
}
Tracing.TraceMsg("DefaultHostMassiveInsert: inserted lot's of entries");
// done doing the inserts...
// now query the guy again.
returnFeed = service.Query(query);
Assert.AreEqual(iCount+this.iIterations, returnFeed.Entries.Count, "feed should have " + this.iIterations + " more entries now");
// now udpate the 100 entries we have added
for (int i = 0; i < this.iIterations; i++)
{
entry = newEntries[i];
entry.Title.Text = Guid.NewGuid().ToString();
entry.Update();
}
Tracing.TraceMsg("DefaultHostMassiveInsert: updated lot's of entries");
returnFeed = service.Query(query);
Assert.AreEqual(iCount+this.iIterations, returnFeed.Entries.Count, "feed should have " + this.iIterations + " more entries now");
// let's find them and delete them...
for (int i = 0; i < this.iIterations; i++)
{
entry = newEntries[i];
foreach (AtomEntry feedEntry in returnFeed.Entries )
{
if (String.Compare(feedEntry.Title.Text, entry.Title.Text) == 0)
{
// got him
Tracing.TraceMsg("trying to delete entry: " + feedEntry.Title.Text +" = " + entry.Title.Text);
feedEntry.Delete();
break;
}
}
}
// and a last time
returnFeed = service.Query(query);
Assert.AreEqual(iCount, returnFeed.Entries.Count, "feed should have the same number again");
Tracing.TraceMsg("DefaultHostMassiveInsertAndDelete: deleted lot's of entries");
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>creates X rows and updates it</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostMassiveInsertAndUpdate()
{
Tracing.TraceMsg("Entering DefaultHostMassiveInsertAndUpdate");
int iCount=0;
FeedQuery query = new FeedQuery();
Service service = new Service();
service.RequestFactory = this.factory;
query.Uri = new Uri(this.defaultHost);
AtomFeed returnFeed = service.Query(query);
AtomEntry entry;
iCount = returnFeed.Entries.Count;
// now we have all we need.
int z = 0;
for (int i = 0; i < this.iIterations; i++)
{
z++;
if (z > 500)
{
z = 0;
// do a requery every hundreth to see mem usage
Tracing.TraceMsg("Query at point: " + i);
returnFeed = service.Query(query);
}
Tracing.TraceMsg("Inserting entry: " + i);
entry = ObjectModelHelper.CreateAtomEntry(i);
entry = returnFeed.Insert(entry);
entry.Content.Content = "Updated entry: " + Guid.NewGuid().ToString();
entry.Update();
}
// now query the guy again.
returnFeed = service.Query(query);
Assert.AreEqual(iCount+this.iIterations, returnFeed.Entries.Count, "feed should have " + this.iIterations + " more entries now");
Tracing.TraceMsg("Exiting DefaultHostMassiveInsertAndUpdate");
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>reads one external feed and inserts it locally</summary>
//////////////////////////////////////////////////////////////////////
[Test] public void DefaultHostInsertExternalFeed()
{
Tracing.TraceMsg("Entering DefaultHostInsertExternalFeed");
if (this.strRemoteHost != null)
{
// remove old data
DefaultHostDeleteAll();
FeedQuery query = new FeedQuery();
Service service = new Service();
service.RequestFactory = (IGDataRequestFactory) new GDataLoggingRequestFactory(this.ServiceName, this.ApplicationName);
query.Uri = new Uri(this.strRemoteHost);
AtomFeed remoteFeed = service.Query(query);
query.Uri = new Uri(this.defaultHost);
AtomFeed localFeed = service.Query(query);
foreach (AtomEntry remoteEntry in remoteFeed.Entries)
{
localFeed.Entries.Add(remoteEntry);
Tracing.TraceInfo("added: " + remoteEntry.Title.Text);
}
bool f;
foreach (AtomEntry localEntry in localFeed.Entries)
{
f = localEntry.IsDirty();
Assert.AreEqual(true, f, "This entry better be dirty now");
}
f = localFeed.IsDirty();
Assert.AreEqual(true, f, "This feed better be dirty now");
localFeed.Publish();
foreach (AtomEntry localEntry in localFeed.Entries)
{
f = localEntry.IsDirty();
Assert.AreEqual(false, f, "This entry better NOT be dirty now");
}
f = localFeed.IsDirty();
Assert.AreEqual(false, f, "This feed better NOT be dirty now");
// requery
localFeed = service.Query(query);
foreach (AtomEntry localEntry in localFeed.Entries)
{
AtomSource source = localEntry.Source;
Assert.AreEqual(source.Id.Uri.ToString(), remoteFeed.Id.Uri.ToString(), "This entry better has the same source ID than the remote feed");
}
}
}
/////////////////////////////////////////////////////////////////////////////
} /// end of WriteTestSuite
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
**
** Purpose: An array implementation of a stack.
**
**
=============================================================================*/
namespace System.Collections {
using System;
using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class Stack : ICollection, ICloneable {
private Object[] _array; // Storage for stack elements
[ContractPublicPropertyName("Count")]
private int _size; // Number of items in the stack.
private int _version; // Used to keep enumerator in sync w/ collection.
[NonSerialized]
private Object _syncRoot;
private const int _defaultCapacity = 10;
public Stack() {
_array = new Object[_defaultCapacity];
_size = 0;
_version = 0;
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int initialCapacity) {
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (initialCapacity < _defaultCapacity)
initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
_array = new Object[initialCapacity];
_size = 0;
_version = 0;
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
//
public Stack(ICollection col) : this((col==null ? 32 : col.Count))
{
if (col==null)
throw new ArgumentNullException("col");
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while(en.MoveNext())
Push(en.Current);
}
public virtual int Count {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
public virtual bool IsSynchronized {
get { return false; }
}
public virtual Object SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the Stack.
public virtual void Clear() {
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
_version++;
}
public virtual Object Clone() {
Contract.Ensures(Contract.Result<Object>() != null);
Stack s = new Stack(_size);
s._size = _size;
Array.Copy(_array, 0, s._array, 0, _size);
s._version = _version;
return s;
}
public virtual bool Contains(Object obj) {
int count = _size;
while (count-- > 0) {
if (obj == null) {
if (_array[count] == null)
return true;
}
else if (_array[count] != null && _array[count].Equals(obj)) {
return true;
}
}
return false;
}
// Copies the stack into an array.
public virtual void CopyTo(Array array, int index) {
if (array==null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < _size)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
int i = 0;
if (array is Object[]) {
Object[] objArray = (Object[]) array;
while(i < _size) {
objArray[i+index] = _array[_size-i-1];
i++;
}
}
else {
while(i < _size) {
array.SetValue(_array[_size-i-1], i+index);
i++;
}
}
}
// Returns an IEnumerator for this Stack.
public virtual IEnumerator GetEnumerator() {
Contract.Ensures(Contract.Result<IEnumerator>() != null);
return new StackEnumerator(this);
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public virtual Object Peek() {
if (_size==0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
Contract.EndContractBlock();
return _array[_size-1];
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public virtual Object Pop() {
if (_size == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
//Contract.Ensures(Count == Contract.OldValue(Count) - 1);
Contract.EndContractBlock();
_version++;
Object obj = _array[--_size];
_array[_size] = null; // Free memory quicker.
return obj;
}
// Pushes an item to the top of the stack.
//
public virtual void Push(Object obj) {
//Contract.Ensures(Count == Contract.OldValue(Count) + 1);
if (_size == _array.Length) {
Object[] newArray = new Object[2*_array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = obj;
_version++;
}
// Returns a synchronized Stack.
//
[HostProtection(Synchronization=true)]
public static Stack Synchronized(Stack stack) {
if (stack==null)
throw new ArgumentNullException("stack");
Contract.Ensures(Contract.Result<Stack>() != null);
Contract.EndContractBlock();
return new SyncStack(stack);
}
// Copies the Stack to an array, in the same order Pop would return the items.
public virtual Object[] ToArray()
{
Contract.Ensures(Contract.Result<Object[]>() != null);
Object[] objArray = new Object[_size];
int i = 0;
while(i < _size) {
objArray[i] = _array[_size-i-1];
i++;
}
return objArray;
}
[Serializable]
private class SyncStack : Stack
{
private Stack _s;
private Object _root;
internal SyncStack(Stack stack) {
_s = stack;
_root = stack.SyncRoot;
}
public override bool IsSynchronized {
get { return true; }
}
public override Object SyncRoot {
get {
return _root;
}
}
public override int Count {
get {
lock (_root) {
return _s.Count;
}
}
}
public override bool Contains(Object obj) {
lock (_root) {
return _s.Contains(obj);
}
}
public override Object Clone()
{
lock (_root) {
return new SyncStack((Stack)_s.Clone());
}
}
public override void Clear() {
lock (_root) {
_s.Clear();
}
}
public override void CopyTo(Array array, int arrayIndex) {
lock (_root) {
_s.CopyTo(array, arrayIndex);
}
}
public override void Push(Object value) {
lock (_root) {
_s.Push(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Pop() {
lock (_root) {
return _s.Pop();
}
}
public override IEnumerator GetEnumerator() {
lock (_root) {
return _s.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Peek() {
lock (_root) {
return _s.Peek();
}
}
public override Object[] ToArray() {
lock (_root) {
return _s.ToArray();
}
}
}
[Serializable]
private class StackEnumerator : IEnumerator, ICloneable
{
private Stack _stack;
private int _index;
private int _version;
private Object currentElement;
internal StackEnumerator(Stack stack) {
_stack = stack;
_version = _stack._version;
_index = -2;
currentElement = null;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual bool MoveNext() {
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (_index == -2) { // First call to enumerator.
_index = _stack._size-1;
retval = ( _index >= 0);
if (retval)
currentElement = _stack._array[_index];
return retval;
}
if (_index == -1) { // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
currentElement = _stack._array[_index];
else
currentElement = null;
return retval;
}
public virtual Object Current {
get {
if (_index == -2) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (_index == -1) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
public virtual void Reset() {
if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
_index = -2;
currentElement = null;
}
}
internal class StackDebugView {
private Stack stack;
public StackDebugView( Stack stack) {
if( stack == null)
throw new ArgumentNullException("stack");
Contract.EndContractBlock();
this.stack = stack;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Object[] Items {
get {
return stack.ToArray();
}
}
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Gumps;
using Server.Network;
namespace Knives.Chat3
{
public delegate void GumpStateCallback(object obj);
public delegate void GumpCallback();
public abstract class GumpPlus : Gump
{
public static void RefreshGump(Mobile m, Type type)
{
if (m.NetState == null)
return;
foreach (Gump g in m.NetState.Gumps)
if (g is GumpPlus && g.GetType() == type)
{
m.CloseGump(type);
((GumpPlus)g).NewGump();
return;
}
}
private Mobile c_Owner;
private Hashtable c_Buttons, c_Fields;
private bool c_Override;
public Mobile Owner{ get{ return c_Owner; } }
public GumpInfo Info { get { return GumpInfo.GetInfo(c_Owner, this.GetType()); } }
public bool Override{ get{ return c_Override; } set{ c_Override = value; } }
public GumpPlus( Mobile m, int x, int y ) : base( x, y )
{
c_Owner = m;
c_Buttons = new Hashtable();
c_Fields = new Hashtable();
Events.InvokeGumpCreated(new GumpCreatedEventArgs(m, this));
Timer.DelayCall(TimeSpan.Zero, new TimerCallback(NewGump));
}
public void Clear()
{
Entries.Clear();
c_Buttons.Clear();
c_Fields.Clear();
}
public virtual void NewGump()
{
NewGump( true );
}
public void NewGump( bool clear )
{
if ( clear )
Clear();
BuildGump();
if ( c_Override )
ModifyGump();
c_Owner.SendGump( this );
}
public void SameGump()
{
c_Owner.SendGump( this );
}
protected abstract void BuildGump();
private void ModifyGump()
{
try
{
AddPage(0);
int maxWidth = 0;
int maxHeight = 0;
GumpBackground bg;
foreach (GumpEntry entry in Entries)
if (entry is GumpBackground)
{
bg = (GumpBackground)entry;
if (bg.X + bg.Width > maxWidth)
maxWidth = bg.X + bg.Width;
if (bg.Y + bg.Height > maxHeight)
maxHeight = bg.Y + bg.Height;
}
if (Owner.AccessLevel >= AccessLevel.Administrator || !GumpInfo.ForceMenu)
{
AddImage(maxWidth, maxHeight, 0x28DC, GumpInfo.ForceMenu ? 0x26 : 0x387);
AddButton(maxWidth + 10, maxHeight + 4, 0x93A, 0x93A, "Transparency", new GumpCallback(Trans));
AddButton(maxWidth + 10, maxHeight + 15, 0x938, 0x938, "Default", new GumpCallback(Default));
if (Owner.AccessLevel >= AccessLevel.Administrator)
AddButton(maxWidth + 10, maxHeight + 26, 0x82C, 0x82C, "ForceMenu", new GumpCallback(Force));
AddButton(maxWidth - 5, maxHeight + 2, 0x2626, 0x2627, "BackgroundDown", new GumpCallback(BackDown));
AddButton(maxWidth + 19, maxHeight + 2, 0x2622, 0x2623, "BackgroundUp", new GumpCallback(BackUp));
AddButton(maxWidth - 5, maxHeight + 13, 0x2626, 0x2627, "TextColorDown", new GumpCallback(TextDown));
AddButton(maxWidth + 19, maxHeight + 13, 0x2622, 0x2623, "TextColorUp", new GumpCallback(TextUp));
}
if (!GumpInfo.HasMods(c_Owner, GetType()))
return;
ArrayList backs = new ArrayList();
foreach (GumpEntry entry in new ArrayList(Entries))
{
if (entry is GumpBackground)
{
if (entry is BackgroundPlus && !((BackgroundPlus)entry).Override)
continue;
if (Info.Background != -1)
((GumpBackground)entry).GumpID = Info.Background;
backs.Add(entry);
}
else if (entry is GumpAlphaRegion && !Info.DefaultTrans && !Info.Transparent)
{
((GumpAlphaRegion)entry).Width = 0;
((GumpAlphaRegion)entry).Height = 0;
}
else if (entry is HtmlPlus)
{
if (!((HtmlPlus)entry).Override || Info.TextColorRGB == "")
continue;
string text = ((HtmlPlus)entry).Text;
int num = 0;
int length = 0;
char[] chars;
if (text == null)
continue;
while ((num = text.ToLower().IndexOf("<basefont")) != -1 || (num = text.ToLower().IndexOf("</font")) != -1)
{
length = 0;
chars = text.ToCharArray();
for (int i = num; i < chars.Length; ++i)
if (chars[i] == '>')
{
length = i - num + 1;
break;
}
if (length == 0)
break;
text = text.Substring(0, num) + text.Substring(num + length, text.Length - num - length);
}
((HtmlPlus)entry).Text = Info.TextColor + text;
}
}
if (!Info.DefaultTrans && Info.Transparent)
foreach (GumpBackground back in backs)
AddAlphaRegion(back.X, back.Y, back.Width, back.Height);
SortEntries();
}
catch { Errors.Report("GumpPlus-> ModifyGump-> " + GetType()); }
}
private void SortEntries()
{
ArrayList list = new ArrayList();
foreach( GumpEntry entry in new ArrayList( Entries ) )
if ( entry is GumpBackground )
{
list.Add( entry );
Entries.Remove( entry );
}
foreach( GumpEntry entry in new ArrayList( Entries ) )
if ( entry is GumpAlphaRegion )
{
list.Add( entry );
Entries.Remove( entry );
}
list.AddRange( Entries );
Entries.Clear();
foreach (GumpEntry entry in list)
Entries.Add(entry);
}
private int UniqueButton()
{
int random = 0;
do
{
random = Utility.Random( 20000 );
}while( c_Buttons[random] != null );
return random;
}
private int UniqueTextId()
{
int random = 0;
do
{
random = Utility.Random(20000);
} while (c_Buttons[random] != null);
return random;
}
public void AddBackgroundZero(int x, int y, int width, int height, int back)
{
AddBackgroundZero(x, y, width, height, back, true);
}
public void AddBackgroundZero(int x, int y, int width, int height, int back, bool over)
{
BackgroundPlus plus = new BackgroundPlus(x, y, width, height, back, over);
Entries.Insert(0, plus);
}
public new void AddBackground(int x, int y, int width, int height, int back)
{
AddBackground(x, y, width, height, back, true);
}
public void AddBackground(int x, int y, int width, int height, int back, bool over)
{
BackgroundPlus plus = new BackgroundPlus(x, y, width, height, back, over);
Add(plus);
}
public void AddButton(int x, int y, int id, GumpCallback callback)
{
AddButton(x, y, id, id, "None", callback);
}
public void AddButton(int x, int y, int id, GumpStateCallback callback, object arg)
{
AddButton(x, y, id, id, "None", callback, arg);
}
public void AddButton(int x, int y, int id, string name, GumpCallback callback)
{
AddButton(x, y, id, id, name, callback);
}
public void AddButton(int x, int y, int id, string name, GumpStateCallback callback, object arg)
{
AddButton(x, y, id, id, name, callback, arg);
}
public void AddButton(int x, int y, int up, int down, GumpCallback callback)
{
AddButton(x, y, up, down, "None", callback);
}
public void AddButton(int x, int y, int up, int down, string name, GumpCallback callback)
{
int id = UniqueButton();
ButtonPlus button = new ButtonPlus( x, y, up, down, id, name, callback );
Add( button );
c_Buttons[id] = button;
}
public void AddButton( int x, int y, int up, int down, GumpStateCallback callback, object arg )
{
AddButton( x, y, up, down, "None", callback, arg );
}
public void AddButton( int x, int y, int up, int down, string name, GumpStateCallback callback, object arg )
{
int id = UniqueButton();
ButtonPlus button = new ButtonPlus( x, y, up, down, id, name, callback, arg );
Add( button );
c_Buttons[id] = button;
}
public void AddHtml(int x, int y, int width, string text)
{
AddHtml(x, y, width, 21, HTML.White + text, false, false, true);
}
public void AddHtml(int x, int y, int width, string text, bool over)
{
AddHtml(x, y, width, 21, HTML.White + text, false, false, over);
}
public new void AddHtml(int x, int y, int width, int height, string text, bool back, bool scroll)
{
AddHtml(x, y, width, height, HTML.White + text, back, scroll, true);
}
public void AddHtml(int x, int y, int width, int height, string text, bool back, bool scroll, bool over)
{
HtmlPlus html = new HtmlPlus(x, y, width, height, HTML.White + text, back, scroll, over);
Add(html);
}
public void AddTextField(int x, int y, int width, int height, int color, int back, string name, string text)
{
int id = UniqueTextId();
AddImageTiled(x, y, width, height, back);
base.AddTextEntry(x, y, width, height, color, id, text);
c_Fields[id] = name;
c_Fields[name] = text;
}
public string GetTextField(string name)
{
if (c_Fields[name] == null)
return "";
return c_Fields[name].ToString();
}
public int GetTextFieldInt(string name)
{
return Utility.ToInt32(GetTextField(name));
}
protected virtual void OnClose()
{
}
public override void OnResponse(NetState state, RelayInfo info)
{
string name = "";
try
{
if (info.ButtonID == -5)
{
NewGump();
return;
}
foreach (TextRelay t in info.TextEntries)
c_Fields[c_Fields[t.EntryID].ToString()] = t.Text;
if (info.ButtonID == 0)
OnClose();
if (c_Buttons[info.ButtonID] == null || !(c_Buttons[info.ButtonID] is ButtonPlus))
return;
name = ((ButtonPlus)c_Buttons[info.ButtonID]).Name;
((ButtonPlus)c_Buttons[info.ButtonID]).Invoke();
}
catch (Exception e)
{
Errors.Report("An error occured during a gump response. More information can be found on the console.");
if(name != "")
Console.WriteLine("{0} gump name triggered an error.", name);
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
Console.WriteLine(e.StackTrace);
}
}
private void Trans()
{
Info.Transparent = !Info.Transparent;
NewGump();
}
private void BackUp()
{
Info.BackgroundUp();
NewGump();
}
private void BackDown()
{
Info.BackgroundDown();
NewGump();
}
private void TextUp()
{
Info.TextColorUp();
NewGump();
}
private void TextDown()
{
Info.TextColorDown();
NewGump();
}
private void Default()
{
Info.Default();
NewGump();
}
private void Force()
{
GumpInfo.ForceMenu = !GumpInfo.ForceMenu;
if (GumpInfo.ForceMenu)
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(242));
else
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(243));
NewGump();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator.Utilities
{
/// <summary>
/// Extensions for syntax types.
/// </summary>
internal static class SymbolSyntaxExtensions
{
public static string GetParsableReplacementName(this INamedTypeSymbol originalType, string replacementTypeName)
{
var t = originalType.WithoutTypeParameters();
var ns = t.GetNamespaceName();
if (!string.IsNullOrWhiteSpace(ns)) ns += '.';
return ns + replacementTypeName + t.GetGenericTypeSuffix();
}
public static SyntaxKind ToSyntaxKind(this SpecialType specialType)
{
switch (specialType)
{
case SpecialType.System_Object:
return SyntaxKind.ObjectKeyword;
case SpecialType.System_Void:
return SyntaxKind.VoidKeyword;
case SpecialType.System_Boolean:
return SyntaxKind.BoolKeyword;
case SpecialType.System_Char:
return SyntaxKind.CharKeyword;
case SpecialType.System_SByte:
return SyntaxKind.SByteKeyword;
case SpecialType.System_Byte:
return SyntaxKind.ByteKeyword;
case SpecialType.System_Int16:
return SyntaxKind.ShortKeyword;
case SpecialType.System_UInt16:
return SyntaxKind.UShortKeyword;
case SpecialType.System_Int32:
return SyntaxKind.IntKeyword;
case SpecialType.System_UInt32:
return SyntaxKind.UIntKeyword;
case SpecialType.System_Int64:
return SyntaxKind.LongKeyword;
case SpecialType.System_UInt64:
return SyntaxKind.ULongKeyword;
case SpecialType.System_Decimal:
return SyntaxKind.DecimalKeyword;
case SpecialType.System_Single:
return SyntaxKind.FloatKeyword;
case SpecialType.System_Double:
return SyntaxKind.DoubleKeyword;
case SpecialType.System_String:
return SyntaxKind.StringKeyword;
default:
return SyntaxKind.None;
}
}
public static bool GetPredefinedType(INamedTypeSymbol type, out PredefinedTypeSyntax predefined)
{
var kind = type.SpecialType.ToSyntaxKind();
if (kind == SyntaxKind.None)
{
predefined = null;
return false;
}
predefined = PredefinedType(Token(kind));
return true;
}
public static TypeSyntax ToTypeSyntax(this ITypeSymbol typeSymbol)
{
if (typeSymbol is IErrorTypeSymbol error)
{
Console.WriteLine(
$"Warning: attempted to get TypeSyntax for unknown (error) type, \"{error}\"."
+ $" Possible reason: {error.CandidateReason}."
+ $" Possible candidates: {string.Join(", ", error.CandidateSymbols.Select(s => s.ToDisplayString()))}");
}
if (typeSymbol is INamedTypeSymbol named) return named.ToTypeSyntax();
return ParseTypeName(typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}
public static TypeSyntax ToTypeSyntax(this INamedTypeSymbol type, Func<SymbolDisplayFormat, SymbolDisplayFormat> modifyFormat = null)
{
if (GetPredefinedType(type, out var predefined))
{
return predefined;
}
var format = SymbolDisplayFormat.FullyQualifiedFormat;
if (modifyFormat != null) format = modifyFormat(format);
return ParseTypeName(type.ToDisplayString(format));
}
public static NameSyntax ToNameSyntax(this INamedTypeSymbol type, bool includeNamespace = true)
{
var format = SymbolDisplayFormat.FullyQualifiedFormat;
if (!includeNamespace)
{
format = format.WithTypeQualificationStyle(SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
}
return ParseName(type.ToDisplayString(format));
}
public static ParenthesizedExpressionSyntax GetBindingFlagsParenthesizedExpressionSyntax(SyntaxKind operationKind, params System.Reflection.BindingFlags[] bindingFlags)
{
if (bindingFlags.Length < 2)
{
throw new ArgumentOutOfRangeException(
nameof(bindingFlags),
$"Can't create parenthesized binary expression with {bindingFlags.Length} arguments");
}
var flags = AliasQualifiedName("global", IdentifierName("System")).Member("Reflection").Member("BindingFlags");
var bindingFlagsBinaryExpression = BinaryExpression(
operationKind,
flags.Member(bindingFlags[0].ToString()),
flags.Member(bindingFlags[1].ToString()));
for (var i = 2; i < bindingFlags.Length; i++)
{
bindingFlagsBinaryExpression = BinaryExpression(
operationKind,
bindingFlagsBinaryExpression,
flags.Member(bindingFlags[i].ToString()));
}
return ParenthesizedExpression(bindingFlagsBinaryExpression);
}
public static MethodDeclarationSyntax GetDeclarationSyntax(this IMethodSymbol method)
{
if (!(method.ReturnType is INamedTypeSymbol returnType)) throw new InvalidOperationException($"Return type \"{method.ReturnType?.GetType()}\" for method {method} is not a named type.");
var syntax =
MethodDeclaration(ToTypeSyntax(returnType), method.Name.ToIdentifier())
.WithParameterList(ParameterList().AddParameters(method.Parameters.Select(p => Parameter(p.Name.ToIdentifier()).WithType(p.Type.ToTypeSyntax())).ToArray()));
if (method.IsGenericMethod)
{
syntax = syntax.WithTypeParameterList(TypeParameterList().AddParameters(method.GetTypeParameterListSyntax()));
// Handle type constraints on type parameters.
var typeParameters = method.TypeParameters;
var typeParameterConstraints = new List<TypeParameterConstraintClauseSyntax>();
foreach (var arg in typeParameters)
{
typeParameterConstraints.AddRange(GetTypeParameterConstraints(arg));
}
if (typeParameterConstraints.Count > 0)
{
syntax = syntax.AddConstraintClauses(typeParameterConstraints.ToArray());
}
}
syntax = syntax.WithModifiers(syntax.Modifiers.AddAccessibilityModifiers(method.DeclaredAccessibility));
return syntax;
}
public static ArrayTypeSyntax GetArrayTypeSyntax(this TypeSyntax type)
{
return ArrayType(type, SingletonList(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))));
}
public static ConstructorDeclarationSyntax GetConstructorDeclarationSyntax(this IMethodSymbol constructor, string typeName)
{
var syntax =
ConstructorDeclaration(typeName.ToIdentifier())
.WithParameterList(ParameterList().AddParameters(constructor.GetParameterListSyntax()));
syntax.WithModifiers(syntax.Modifiers.AddAccessibilityModifiers(constructor.DeclaredAccessibility));
return syntax;
}
public static SyntaxTokenList AddAccessibilityModifiers(this SyntaxTokenList syntax, Accessibility accessibility)
{
switch (accessibility)
{
case Accessibility.Public:
syntax = With(syntax, SyntaxKind.PublicKeyword);
break;
case Accessibility.Private:
syntax = With(syntax, SyntaxKind.PrivateKeyword);
break;
case Accessibility.Internal:
syntax = With(syntax, SyntaxKind.InternalKeyword);
break;
case Accessibility.Protected:
syntax = With(syntax, SyntaxKind.ProtectedKeyword);
break;
case Accessibility.ProtectedOrInternal:
syntax = With(With(syntax, SyntaxKind.ProtectedKeyword), SyntaxKind.InternalKeyword);
break;
case Accessibility.ProtectedAndInternal:
syntax = With(With(syntax, SyntaxKind.PrivateKeyword), SyntaxKind.ProtectedKeyword);
break;
}
SyntaxTokenList With(SyntaxTokenList s, SyntaxKind keyword)
{
foreach (var t in s)
{
if (t.IsKind(keyword)) return s;
}
return s.Add(Token(keyword));
}
return syntax;
}
public static ParameterSyntax[] GetParameterListSyntax(this IMethodSymbol method)
{
return
method.Parameters
.Select(
(parameter, parameterIndex) =>
Parameter(parameter.Name.ToIdentifier())
.WithType(parameter.Type.ToTypeSyntax()))
.ToArray();
}
public static TypeParameterSyntax[] GetTypeParameterListSyntax(this IMethodSymbol method)
{
return method.TypeParameters
.Select(parameter => TypeParameter(parameter.Name))
.ToArray();
}
public static TypeParameterConstraintClauseSyntax[] GetTypeConstraintSyntax(this INamedTypeSymbol type)
{
if (type.IsGenericType)
{
var constraints = new List<TypeParameterConstraintClauseSyntax>();
foreach (var genericParameter in type.GetHierarchyTypeParameters())
{
constraints.AddRange(GetTypeParameterConstraints(genericParameter));
}
return constraints.ToArray();
}
return new TypeParameterConstraintClauseSyntax[0];
}
private static TypeParameterConstraintClauseSyntax[] GetTypeParameterConstraints(ITypeParameterSymbol genericParameter)
{
var results = new List<TypeParameterConstraintClauseSyntax>();
var parameterConstraints = new List<TypeParameterConstraintSyntax>();
// The "class" or "struct" constraints must come first.
if (genericParameter.HasReferenceTypeConstraint)
{
parameterConstraints.Add(ClassOrStructConstraint(SyntaxKind.ClassConstraint));
}
else if (genericParameter.HasValueTypeConstraint)
{
parameterConstraints.Add(ClassOrStructConstraint(SyntaxKind.StructConstraint));
}
// Follow with the base class or interface constraints.
foreach (var genericType in genericParameter.ConstraintTypes)
{
// If the "struct" constraint was specified, skip the corresponding "ValueType" constraint.
if (genericType.SpecialType == SpecialType.System_ValueType)
{
continue;
}
parameterConstraints.Add(TypeConstraint(genericType.ToTypeSyntax()));
}
// The "new()" constraint must be the last constraint in the sequence.
if (genericParameter.HasConstructorConstraint
&& !genericParameter.HasValueTypeConstraint)
{
parameterConstraints.Add(ConstructorConstraint());
}
if (parameterConstraints.Count > 0)
{
results.Add(
TypeParameterConstraintClause(genericParameter.Name)
.AddConstraints(parameterConstraints.ToArray()));
}
return results.ToArray();
}
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, string member)
{
return instance.Member(member.ToIdentifierName());
}
public static MemberAccessExpressionSyntax Member(
this ExpressionSyntax instance,
string member,
params INamedTypeSymbol[] genericTypes)
{
return
instance.Member(
member.ToGenericName()
.AddTypeArgumentListArguments(genericTypes.Select(_ => _.ToTypeSyntax()).ToArray()));
}
public static MemberAccessExpressionSyntax Member<TInstance, T>(
this ExpressionSyntax instance,
Expression<Func<TInstance, T>> member,
params INamedTypeSymbol[] genericTypes)
{
switch (member.Body)
{
case MethodCallExpression methodCall:
if (genericTypes != null && genericTypes.Length > 0)
{
return instance.Member(methodCall.Method.Name, genericTypes);
}
return instance.Member(methodCall.Method.Name.ToIdentifierName());
case MemberExpression memberAccess:
if (genericTypes != null && genericTypes.Length > 0)
{
return instance.Member(memberAccess.Member.Name, genericTypes);
}
return instance.Member(memberAccess.Member.Name.ToIdentifierName());
}
throw new ArgumentException("Expression type unsupported.");
}
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, IdentifierNameSyntax member)
{
return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member);
}
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, GenericNameSyntax member)
{
return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member);
}
}
}
| |
/* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 the ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
/*
* This file was automatically generated.
*/
namespace OWASPZAPDotNetAPI.Generated
{
public class Search
{
private ClientApi api = null;
public Search(ClientApi api)
{
this.api = api;
}
/// <summary>
///Returns the URLs of the HTTP messages that match the given regular expression in the URL optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse urlsByUrlRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "urlsByUrlRegex", parameters);
}
/// <summary>
///Returns the URLs of the HTTP messages that match the given regular expression in the request optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse urlsByRequestRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "urlsByRequestRegex", parameters);
}
/// <summary>
///Returns the URLs of the HTTP messages that match the given regular expression in the response optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse urlsByResponseRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "urlsByResponseRegex", parameters);
}
/// <summary>
///Returns the URLs of the HTTP messages that match the given regular expression in the header(s) optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse urlsByHeaderRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "urlsByHeaderRegex", parameters);
}
/// <summary>
///Returns the HTTP messages that match the given regular expression in the URL optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse messagesByUrlRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "messagesByUrlRegex", parameters);
}
/// <summary>
///Returns the HTTP messages that match the given regular expression in the request optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse messagesByRequestRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "messagesByRequestRegex", parameters);
}
/// <summary>
///Returns the HTTP messages that match the given regular expression in the response optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse messagesByResponseRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "messagesByResponseRegex", parameters);
}
/// <summary>
///Returns the HTTP messages that match the given regular expression in the header(s) optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public IApiResponse messagesByHeaderRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("search", "view", "messagesByHeaderRegex", parameters);
}
/// <summary>
///Returns the HTTP messages, in HAR format, that match the given regular expression in the URL optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public byte[] harByUrlRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApiOther("search", "other", "harByUrlRegex", parameters);
}
/// <summary>
///Returns the HTTP messages, in HAR format, that match the given regular expression in the request optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public byte[] harByRequestRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApiOther("search", "other", "harByRequestRegex", parameters);
}
/// <summary>
///Returns the HTTP messages, in HAR format, that match the given regular expression in the response optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public byte[] harByResponseRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApiOther("search", "other", "harByResponseRegex", parameters);
}
/// <summary>
///Returns the HTTP messages, in HAR format, that match the given regular expression in the header(s) optionally filtered by URL and paginated with 'start' position and 'count' of messages.
/// </summary>
/// <returns></returns>
public byte[] harByHeaderRegex(string regex, string baseurl, string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("baseurl", baseurl);
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApiOther("search", "other", "harByHeaderRegex", parameters);
}
}
}
| |
using System;
using System.Collections;
using System.Web;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Content.Security;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Web.UI;
using History=Rainbow.Framework.History;
using ImageButton=Rainbow.Framework.Web.UI.WebControls.ImageButton;
using Label=Rainbow.Framework.Web.UI.WebControls.Label;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
///
/// </summary>
/// <remarks>
/// known bugs
/// 1) if you delete the entire thread while viewing in this window,
/// it should automatically take you back to the Dicussion.ascx view
/// </remarks>
[History("jminond", "2006/2/23", "Converted to partial class")]
public partial class DiscussionViewThread : EditItemPage
{
//protected System.Web.UI.WebControls.DataList ThreadList;
/// <summary>
/// On the first invocation of Page_Load, the data is bound using BindList();
/// </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)
{
if (Page.IsPostBack == false)
{
BindList(GetItemID());
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
/// <value>The allowed modules.</value>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("2D86166C-4BDC-4A6F-A028-D17C2BB177C8");
al.Add("2502DB18-B580-4F90-8CB4-C15E6E531030"); // Access from portalSearch
al.Add("2502DB18-B580-4F90-8CB4-C15E6E531052"); // Access from serviceItemList
return al;
}
}
/// <summary>
/// extracts this threads ItemID from the URL
/// </summary>
/// <returns></returns>
private int GetItemID()
{
if (HttpContext.Current != null && Request.Params["ItemID"] != null)
{
return Int32.Parse(Request.Params["ItemID"]);
}
else
{
/* throw up an error dialog here */
Response.Write("Error, invalid <ItemID> given to DiscussionViewThread");
return 0;
}
}
/// <summary>
/// Binds the threads from the database to the list control
/// </summary>
/// <param name="ItemID">itemID of ANY of the topics in the thread</param>
private void BindList(int ItemID)
{
// Obtain a list of discussion messages for the module and bind to datalist
DiscussionDB discuss = new DiscussionDB();
ThreadList.DataSource = discuss.GetThreadMessages(ItemID, 'Y'); // 'Y' means include rootmessage
ThreadList.DataBind();
}
/// <summary>
/// ThreadList_Select processes user events to add, edit, and delete topics
/// </summary>
/// <param name="Sender">The source of the event.</param>
/// <param name="e">DataListCommandEventAargs e</param>
public void ThreadList_Select(object Sender, DataListCommandEventArgs e)
{
// Determine the command of the button
string command = ((CommandEventArgs) (e)).CommandName;
switch (command)
{
case "delete":
DiscussionDB discuss = new DiscussionDB();
int ItemID = Int32.Parse(e.CommandArgument.ToString());
discuss.DeleteChildren(ItemID);
break;
case "return_to_discussion_list":
RedirectBackToReferringPage();
break;
default:
break;
}
BindList(GetItemID());
return;
}
/// <summary>
/// Invoked when each data row is bound to the list.
/// Adds a clientside Java script to confirm row deltes
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">DataListCommandEventAargs e</param>
protected void OnItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.FindControl("deleteBtn") != null)
{
// 13/7/2004 Added Localization Mario Endara mario@softworks.com.uy
((ImageButton) e.Item.FindControl("deleteBtn")).Attributes.Add("onClick", "return confirm('" +
General.GetString(
"DISCUSSION_DELETE_RESPONSE",
"Are you sure you want to delete the selected response message and ALL of its children ?") +
"');");
}
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (e.Item.FindControl("Label10") != null)
{
if (((Label) e.Item.FindControl("Label10")).Text == "unknown")
{
((Label) e.Item.FindControl("Label10")).Text = General.GetString("UNKNOWN", "unknown");
}
}
}
/// <summary>
/// GetReplyImage check to see whether the current user has permissions to contribute to the discussion thread
/// Users with proper permission see an image they can click on to post a reply, otherwise they see nothing.
/// </summary>
/// <returns>
/// Returns either a 1x1 image or the reply.gif icon
/// </returns>
protected string GetReplyImage()
{
// leave next commented statement in for testing back doors
// return "~/images/reply.gif";
if (DiscussionPermissions.HasAddPermissions(ModuleID) == true)
return getLocalImage("reply.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// Gets the edit image.
/// </summary>
/// <param name="itemUserEmail">The item user email.</param>
/// <returns></returns>
protected string GetEditImage(string itemUserEmail)
{
if (DiscussionPermissions.HasEditPermissions(ModuleID, itemUserEmail))
return getLocalImage("edit.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// Gets the delete image.
/// </summary>
/// <param name="itemID">The item ID.</param>
/// <param name="itemUserEmail">The item user email.</param>
/// <returns></returns>
protected string GetDeleteImage(int itemID, string itemUserEmail)
{
if (DiscussionPermissions.HasDeletePermissions(ModuleID, itemID, itemUserEmail) == true)
return getLocalImage("delete.gif");
else
return getLocalImage("1x1.gif");
}
/// <summary>
/// The FormatUrl method is a helper messages called by a
/// databinding statement within the <asp:DataList> server
/// control template. It is defined as a helper method here
/// (as opposed to inline within the template) to improve
/// code organization and avoid embedding logic within the
/// content template.
/// </summary>
/// <param name="item">ID of the currently selected topic</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Returns a properly formatted URL to call the DiscussionEdit page
/// </returns>
protected string FormatUrlEditItem(int item, string mode)
{
return
(HttpUrlBuilder.BuildUrl("~/DesktopModules/Discussion/DiscussionEdit.aspx",
"ItemID=" + item + "&Mode=" + mode + "&mID=" + ModuleID + "&edit=1"));
}
/// <summary>
/// The NodeImage method is a helper method called by a
/// databinding statement within the <asp:datalist> server
/// control template. It controls whether or not an item
/// in the list should be rendered as an expandable topic
/// or just as a single node within the list.
/// </summary>
/// <param name="count">Number of replys to the selected topic</param>
/// <returns></returns>
protected string NodeImage(int count)
{
return getLocalImage("plus.gif");
}
/// <summary>
/// Gets the local image.
/// </summary>
/// <param name="img">The img.</param>
/// <returns></returns>
protected string getLocalImage(string img)
{
return Path.WebPathCombine(Path.ApplicationRoot, "DesktopModules/Discussion/images", img);
}
/// <summary>
/// Load settings
/// </summary>
protected override void LoadSettings()
{
// Verify that the current user has proper permissions for this module
// need to reanable this code as second level check in case users hack URLs to come to this page
// if (PortalSecurity.HasEditPermissions(ModuleID) == false && PortalSecurity.IsInRoles("Admins") == false)
// PortalSecurity.AccessDeniedEdit();
// base.LoadSettings();
}
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.Load += new System.EventHandler(this.Page_Load);
/*
* // Create a new Title the control
ModuleTitle = new DesktopModuleTitle();
// Add a link for the edit page
// ModuleTitle.AddTarget = "_new"; // uncomment this if you want replies and new posts in a new web browser window
ModuleTitle.AddText = "DS_NEWTHREAD";
ModuleTitle.AddUrl = "~/DesktopModules/Discussion/DiscussionEdit.aspx";
// Add title at the very beginning of the control's controls collection
Controls.AddAt(0, ModuleTitle);
*/
base.OnInit(e);
}
#endregion
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Region.Framework.Scenes;
namespace InWorldz.Region.Data.Thoosa.Tests
{
internal class Util
{
private readonly static Random rand = new Random();
public static Vector3 RandomVector()
{
return new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
public static Quaternion RandomQuat()
{
return new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
internal static byte RandomByte()
{
return (byte)rand.Next(byte.MaxValue);
}
public static SceneObjectPart RandomSOP(string name, uint localId)
{
var shape = new OpenSim.Framework.PrimitiveBaseShape();
shape.ExtraParams = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 };
shape.FlexiDrag = 0.3f;
shape.FlexiEntry = true;
shape.FlexiForceX = 1.0f;
shape.FlexiForceY = 2.0f;
shape.FlexiForceZ = 3.0f;
shape.FlexiGravity = 10.0f;
shape.FlexiSoftness = 1;
shape.FlexiTension = 999.4f;
shape.FlexiWind = 9292.33f;
shape.HollowShape = OpenSim.Framework.HollowShape.Square;
shape.LightColorA = 0.3f;
shape.LightColorB = 0.22f;
shape.LightColorG = 0.44f;
shape.LightColorR = 0.77f;
shape.LightCutoff = 0.4f;
shape.LightEntry = true;
shape.LightFalloff = 7474;
shape.LightIntensity = 0.0f;
shape.LightRadius = 10.0f;
shape.Media = new OpenSim.Framework.PrimitiveBaseShape.PrimMedia();
shape.Media.New(2);
shape.Media[0] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "bam.com",
EnableAlterntiveImage = true,
EnableWhiteList = false,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "yo mamma" },
Width = 5
};
shape.Media[1] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "kabam.com",
EnableAlterntiveImage = true,
EnableWhiteList = true,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "ur mamma" },
Width = 5
};
shape.PathBegin = 3;
shape.PathCurve = 127;
shape.PathEnd = 10;
shape.PathRadiusOffset = 127;
shape.PathRevolutions = 2;
shape.PathScaleX = 50;
shape.PathScaleY = 100;
shape.PathShearX = 33;
shape.PathShearY = 44;
shape.PathSkew = 126;
shape.PathTaperX = 110;
shape.PathTaperY = 66;
shape.PathTwist = 99;
shape.PathTwistBegin = 3;
shape.PCode = 3;
shape.PreferredPhysicsShape = PhysicsShapeType.Prim;
shape.ProfileBegin = 77;
shape.ProfileCurve = 5;
shape.ProfileEnd = 7;
shape.ProfileHollow = 9;
shape.ProfileShape = OpenSim.Framework.ProfileShape.IsometricTriangle;
shape.ProjectionAmbiance = 0.1f;
shape.ProjectionEntry = true;
shape.ProjectionFocus = 3.4f;
shape.ProjectionFOV = 4.0f;
shape.ProjectionTextureUUID = UUID.Random();
shape.Scale = Util.RandomVector();
shape.SculptEntry = true;
shape.SculptTexture = UUID.Random();
shape.SculptType = 40;
shape.VertexCount = 1;
shape.HighLODBytes = 2;
shape.MidLODBytes = 3;
shape.LowLODBytes = 4;
shape.LowestLODBytes = 5;
SceneObjectPart part = new SceneObjectPart(UUID.Zero, shape, new Vector3(1, 2, 3), new Quaternion(4, 5, 6, 7), Vector3.Zero, false);
part.Name = name;
part.Description = "Desc";
part.AngularVelocity = Util.RandomVector();
part.BaseMask = 0x0876;
part.Category = 10;
part.ClickAction = 5;
part.CollisionSound = UUID.Random();
part.CollisionSoundVolume = 1.1f;
part.CreationDate = OpenSim.Framework.Util.UnixTimeSinceEpoch();
part.CreatorID = UUID.Random();
part.EveryoneMask = 0x0543;
part.Flags = PrimFlags.CameraSource | PrimFlags.DieAtEdge;
part.GroupID = UUID.Random();
part.GroupMask = 0x0210;
part.LastOwnerID = UUID.Random();
part.LinkNum = 4;
part.LocalId = localId;
part.Material = 0x1;
part.MediaUrl = "http://bam";
part.NextOwnerMask = 0x0234;
part.CreatorID = UUID.Random();
part.ObjectFlags = 10101;
part.OwnerID = UUID.Random();
part.OwnerMask = 0x0567;
part.OwnershipCost = 5;
part.ParentID = 0202;
part.ParticleSystem = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.PassTouches = true;
part.PhysicalAngularVelocity = Util.RandomVector();
part.RegionHandle = 1234567;
part.RegionID = UUID.Random();
part.RotationOffset = Util.RandomQuat();
part.SalePrice = 42;
part.SavedAttachmentPoint = 6;
part.SavedAttachmentPos = Util.RandomVector();
part.SavedAttachmentRot = Util.RandomQuat();
part.ScriptAccessPin = 87654;
part.SerializedPhysicsData = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.ServerWeight = 3.0f;
part.StreamingCost = 2.0f;
part.SitName = "Sitting";
part.Sound = UUID.Random();
part.SoundGain = 3.4f;
part.SoundOptions = 9;
part.SoundRadius = 10.3f;
part.Text = "Test";
part.TextColor = System.Drawing.Color.FromArgb(1, 2, 3, 4);
part.TextureAnimation = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD };
part.TouchName = "DoIt";
part.UUID = UUID.Random();
part.Velocity = Util.RandomVector();
part.FromItemID = UUID.Random();
part.SetSitTarget(Util.RandomVector(), Util.RandomQuat(), false);
return part;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace EasyPeasy.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) 2014 Behrooz Amoozad
* 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 bd2 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 Behrooz Amoozad 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 BD2.Frontend.Table;
namespace BD2.Frontend.Table
{
public class GenericValueDeserializer : BD2.Frontend.Table.ValueSerializerBase
{
#region implemented abstract members of ValueSerializerBase
public override byte TypeToID (Type type)
{
if (type == null)
throw new Exception ("type is null");
string TFQN = type.FullName;
switch (TFQN) {
case "System.Boolean":
return 1;
case "System.Byte":
return 2;
case "System.SByte":
return 128;
case "System.Int16":
return 3;
case "System.UInt16":
return 129;
case "System.Int32":
return 4;
case "System.UInt32":
return 130;
case "System.Int64":
return 5;
case "System.UInt64":
return 131;
case "System.Double":
return 9;
case "System.String":
return 16;
case "System.Char":
return 144;
case "System.DateTime":
return 24;
case "System.Guid":
return 32;
case "System.Byte[]":
return 36;
case "System.String[]":
return 37;
case "System.Int64[]":
return 38;
default:
throw new Exception (string.Format ("Serialization for type <{0}> is not supported", type.FullName));
}
}
public override Type IDToType (byte id)
{
switch (id) {
case 1:
return typeof(Boolean);
case 2:
return typeof(Byte);
case 128:
return typeof(SByte);
case 3:
return typeof(Int16);
case 129:
return typeof(UInt16);
case 4:
return typeof(Int32);
case 130:
return typeof(UInt32);
case 5:
return typeof(Int64);
case 131:
return typeof(UInt64);
case 9:
return typeof(Double);
case 16:
return typeof(String);
case 144:
return typeof(Char);
case 24:
return typeof(DateTime);
case 32:
return typeof(Guid);
case 36:
return typeof(byte[]);
case 37:
return typeof(string[]);
case 38:
return typeof(Int64[]);
default:
throw new Exception (string.Format ("Serialization for type <{0}> is not supported", id));
}
}
#endregion
public override object Deserialize (System.IO.BinaryReader binaryReader)
{
bool hasValue = binaryReader.ReadBoolean ();
if (!hasValue)
return null;
int typeID = binaryReader.ReadByte ();
switch (typeID) {
case 1:
return binaryReader.ReadBoolean ();
case 2:
return binaryReader.ReadByte ();
case 128:
return binaryReader.ReadSByte ();
case 3:
return binaryReader.ReadInt16 ();
case 129:
return binaryReader.ReadUInt16 ();
case 4:
return binaryReader.ReadInt32 ();
case 130:
return binaryReader.ReadUInt32 ();
case 5:
return binaryReader.ReadInt64 ();
case 131:
return binaryReader.ReadUInt64 ();
case 9:
return binaryReader.ReadDouble ();
case 16:
return binaryReader.ReadString ();
case 144:
return binaryReader.ReadChar ();
case 24:
return new DateTime (binaryReader.ReadInt64 ());
case 32:
return new Guid (binaryReader.ReadBytes (16));
case 36:
return binaryReader.ReadBytes (binaryReader.ReadInt32 ());
case 37:
{
int count = binaryReader.ReadInt32 ();
string[] r = new string[count];
for (int n = 0; n != count; n++)
r [n] = binaryReader.ReadString ();
return r;
}
case 38:
{
int count = binaryReader.ReadInt32 ();
long[] r = new long[count];
for (int n = 0; n != count; n++)
r [n] = binaryReader.ReadInt64 ();
return r;
}
default:
throw new Exception (string.Format ("Serialization for type <{0}> is not supported", typeID));
}
}
public override void Serialize (object obj, System.IO.BinaryWriter binaryWriter)
{
if (obj == null) {
binaryWriter.Write (false);
return;
}
binaryWriter.Write (true);
byte typeID = TypeToID (obj.GetType ());
binaryWriter.Write (typeID);
switch (typeID) {
case 1:
binaryWriter.Write ((bool)obj);
break;
case 2:
binaryWriter.Write ((byte)obj);
break;
case 128:
binaryWriter.Write ((sbyte)obj);
break;
case 3:
binaryWriter.Write ((short)obj);
break;
case 129:
binaryWriter.Write ((ushort)obj);
break;
case 4:
binaryWriter.Write ((int)obj);
break;
case 130:
binaryWriter.Write ((uint)obj);
break;
case 5:
binaryWriter.Write ((long)obj);
break;
case 131:
binaryWriter.Write ((ulong)obj);
break;
case 16:
binaryWriter.Write ((string)obj);
break;
case 144:
binaryWriter.Write ((char)obj);
break;
case 9:
binaryWriter.Write ((Double)obj);
break;
case 24:
binaryWriter.Write (((DateTime)obj).Ticks);
break;
case 32:
binaryWriter.Write (((Guid)obj).ToByteArray ());
break;
case 36:
binaryWriter.Write (((byte[])obj).Length);
binaryWriter.Write ((byte[])obj);
break;
case 37:
{
string[] strs = (string[])obj;
binaryWriter.Write (strs.Length);
for (int n = 0; n != strs.Length; n++)
binaryWriter.Write (strs [n]);
break;
}
case 38:
{
long[] strs = (long[])obj;
binaryWriter.Write (strs.Length);
for (int n = 0; n != strs.Length; n++)
binaryWriter.Write (strs [n]);
break;
}
default:
throw new Exception (string.Format ("Serialization for type <{0}> is not supported", obj.GetType ()));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Object = System.Object;
public class FieldSPSSystem : HonoBehavior
{
public override void HonoUpdate()
{
this.Service();
}
private void LateUpdate()
{
if (!PersistenSingleton<UIManager>.Instance.IsPause)
{
this.GenerateSPS();
}
}
public void Init(FieldMap fieldMap)
{
this.rot = new Vector3(0f, 0f, 0f);
this._isReady = false;
this._spsList = new List<FieldSPS>();
this._spsBinDict = new Dictionary<Int32, KeyValuePair<Int32, Byte[]>>();
this._fieldMap = fieldMap;
for (Int32 i = 0; i < 16; i++)
{
GameObject gameObject = new GameObject("SPS_" + i.ToString("D4"));
gameObject.transform.parent = base.transform;
gameObject.transform.localScale = Vector3.one;
gameObject.transform.localPosition = Vector3.zero;
MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();
FieldSPS fieldSPS = gameObject.AddComponent<FieldSPS>();
fieldSPS.Init();
fieldSPS.fieldMap = fieldMap;
fieldSPS.spsIndex = i;
fieldSPS.spsTransform = gameObject.transform;
fieldSPS.meshRenderer = meshRenderer;
fieldSPS.meshFilter = meshFilter;
this._spsList.Add(fieldSPS);
FieldSPSActor fieldSPSActor = gameObject.AddComponent<FieldSPSActor>();
fieldSPSActor.sps = fieldSPS;
fieldSPS.spsActor = fieldSPSActor;
}
this.MapName = FF9StateSystem.Field.SceneName;
FieldMapInfo.fieldmapSPSExtraOffset.SetSPSOffset(this.MapName, this._spsList);
this._isReady = this._loadSPSTexture();
}
public void Service()
{
if (!this._isReady)
{
return;
}
for (Int32 i = 0; i < this._spsList.Count; i++)
{
FieldSPS fieldSPS = this._spsList[i];
if (fieldSPS.spsBin != null && (fieldSPS.attr & 1) != 0)
{
if (fieldSPS.lastFrame != -1)
{
fieldSPS.lastFrame = fieldSPS.curFrame;
fieldSPS.curFrame += fieldSPS.frameRate;
if (fieldSPS.curFrame >= fieldSPS.frameCount)
{
fieldSPS.curFrame = 0;
}
else if (fieldSPS.curFrame < 0)
{
fieldSPS.curFrame = (fieldSPS.frameCount >> 4) - 1 << 4;
}
}
}
}
}
public void GenerateSPS()
{
if (!this._isReady)
{
return;
}
for (Int32 i = 0; i < this._spsList.Count; i++)
{
FieldSPS fieldSPS = this._spsList[i];
if (fieldSPS.spsBin != null && (fieldSPS.attr & 1) != 0)
{
if (fieldSPS.charTran != (UnityEngine.Object)null && fieldSPS.boneTran != (UnityEngine.Object)null)
{
FieldMapActor component = fieldSPS.charTran.GetComponent<FieldMapActor>();
if (component != (UnityEngine.Object)null)
{
component.UpdateGeoAttach();
}
fieldSPS.pos = fieldSPS.boneTran.position + fieldSPS.posOffset;
}
fieldSPS.GenerateSPS();
fieldSPS.lastFrame = fieldSPS.curFrame;
fieldSPS.meshRenderer.enabled = true;
}
}
}
private Boolean _loadSPSTexture()
{
String[] tcbInfo;
Byte[] binAsset = AssetManager.LoadBytes("FieldMaps/" + this.MapName + "/spt.tcb", out tcbInfo);
if (binAsset != null)
{
using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(binAsset)))
{
UInt32 num = binaryReader.ReadUInt32();
UInt32 num2 = binaryReader.ReadUInt32();
Int32 num3 = binaryReader.ReadInt32();
binaryReader.BaseStream.Seek((Int64)((UInt64)num), SeekOrigin.Begin);
UInt32 num4 = binaryReader.ReadUInt32();
Int32 num5 = binaryReader.ReadInt32();
for (Int32 i = 0; i < num3; i++)
{
binaryReader.BaseStream.Seek((Int64)((UInt64)num2), SeekOrigin.Begin);
Int32 x = (Int32)binaryReader.ReadInt16();
Int32 y = (Int32)binaryReader.ReadInt16();
Int32 num6 = (Int32)binaryReader.ReadInt16();
Int32 num7 = (Int32)binaryReader.ReadInt16();
PSXTextureMgr.LoadImageBin(x, y, num6, num7, binaryReader);
UInt32 num8 = (UInt32)(num6 * num7 * 2);
num2 += num8 + 8u;
}
num += 8u;
for (Int32 j = 0; j < num5; j++)
{
binaryReader.BaseStream.Seek((Int64)((UInt64)num), SeekOrigin.Begin);
Int32 x2 = (Int32)binaryReader.ReadInt16();
Int32 y2 = (Int32)binaryReader.ReadInt16();
Int32 num9 = (Int32)binaryReader.ReadInt16();
Int32 num10 = (Int32)binaryReader.ReadInt16();
binaryReader.BaseStream.Seek((Int64)((UInt64)num4), SeekOrigin.Begin);
PSXTextureMgr.LoadImageBin(x2, y2, num9, num10, binaryReader);
UInt32 num8 = (UInt32)(num9 * num10 * 2);
num4 += num8;
num += 8u;
}
}
PSXTextureMgr.ClearObject();
return true;
}
return false;
}
private Int32 _GetSpsFrameCount(Byte[] spsBin)
{
return (Int32)(BitConverter.ToUInt16(spsBin, 0) & 32767) << 4;
}
private Boolean _loadSPSBin(Int32 spsNo)
{
if (this._spsBinDict.ContainsKey(spsNo))
{
return true;
}
String[] spsInfo;
Byte[] binAsset = AssetManager.LoadBytes(String.Concat(new Object[]
{
"FieldMaps/",
this.MapName,
"/",
spsNo,
".sps"
}), out spsInfo);
if (binAsset == null)
{
return false;
}
Int32 key = this._GetSpsFrameCount(binAsset);
this._spsBinDict.Add(spsNo, new KeyValuePair<Int32, Byte[]>(key, binAsset));
return true;
}
public void FF9FieldSPSSetObjParm(Int32 ObjNo, Int32 ParmType, Int32 Arg0, Int32 Arg1, Int32 Arg2)
{
FieldSPS fieldSPS = this._spsList[ObjNo];
if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_REF)
{
if (Arg0 != -1)
{
if (this._loadSPSBin(Arg0))
{
fieldSPS.spsBin = this._spsBinDict[Arg0].Value;
fieldSPS.curFrame = 0;
fieldSPS.lastFrame = -1;
fieldSPS.frameCount = this._spsBinDict[Arg0].Key;
}
fieldSPS.refNo = Arg0;
if (FF9StateSystem.Common.FF9.fldMapNo == 2553 && (fieldSPS.refNo == 464 || fieldSPS.refNo == 467 || fieldSPS.refNo == 506 || fieldSPS.refNo == 510))
{
fieldSPS.spsBin = null;
}
}
else
{
if ((FF9StateSystem.Common.FF9.fldMapNo == 911 || FF9StateSystem.Common.FF9.fldMapNo == 1911) && (fieldSPS.refNo == 33 || fieldSPS.refNo == 34))
{
fieldSPS.pos = Vector3.zero;
fieldSPS.scale = 4096;
fieldSPS.rot = Vector3.zero;
fieldSPS.rotArg = Vector3.zero;
}
fieldSPS.spsBin = null;
fieldSPS.meshRenderer.enabled = false;
fieldSPS.charTran = (Transform)null;
fieldSPS.boneTran = (Transform)null;
}
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_ATTR)
{
if (Arg1 == 0)
{
fieldSPS.attr = (Byte) (fieldSPS.attr & (Byte) (~(Byte) Arg0));
}
else
{
fieldSPS.attr = (Byte) (fieldSPS.attr | (Byte) Arg0);
}
if ((fieldSPS.attr & 1) == 0)
{
fieldSPS.meshRenderer.enabled = false;
}
else if (FF9StateSystem.Common.FF9.fldMapNo == 2928 || FF9StateSystem.Common.FF9.fldMapNo == 1206 || FF9StateSystem.Common.FF9.fldMapNo == 1223)
{
if (fieldSPS.spsBin != null)
{
fieldSPS.meshRenderer.enabled = true;
}
}
else
{
fieldSPS.meshRenderer.enabled = true;
}
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_POS)
{
if (FF9StateSystem.Common.FF9.fldMapNo == 911 || FF9StateSystem.Common.FF9.fldMapNo == 1911)
{
if (fieldSPS.spsBin != null)
{
fieldSPS.pos = new Vector3((Single)Arg0, (Single)(Arg1 * -1), (Single)Arg2);
}
}
else
{
fieldSPS.pos = new Vector3((Single)Arg0, (Single)(Arg1 * -1), (Single)Arg2);
}
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_ROT)
{
fieldSPS.rot = new Vector3((Single)Arg0 / 4096f * 360f, (Single)Arg1 / 4096f * 360f, (Single)Arg2 / 4096f * 360f);
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_SCALE)
{
fieldSPS.scale = Arg0;
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_CHAR)
{
Obj objUID = PersistenSingleton<EventEngine>.Instance.GetObjUID(Arg0);
fieldSPS.charNo = Arg0;
fieldSPS.boneNo = Arg1;
fieldSPS.charTran = objUID.go.transform;
fieldSPS.boneTran = objUID.go.transform.GetChildByName("bone" + fieldSPS.boneNo.ToString("D3"));
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_FADE)
{
fieldSPS.fade = (Byte)Arg0;
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_ARATE)
{
fieldSPS.arate = (Byte)Arg0;
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_FRAMERATE)
{
fieldSPS.frameRate = Arg0;
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_FRAME)
{
fieldSPS.curFrame = Arg0 << 4;
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_POSOFFSET)
{
fieldSPS.posOffset = new Vector3((Single)Arg0, (Single)(-(Single)Arg1), (Single)Arg2);
}
else if (ParmType == FieldSPSConst.FF9FIELDSPS_PARMTYPE_DEPTHOFFSET)
{
fieldSPS.depthOffset = Arg0;
}
}
public String MapName;
private Boolean _isReady;
private FieldMap _fieldMap;
private List<FieldSPS> _spsList;
private Dictionary<Int32, KeyValuePair<Int32, Byte[]>> _spsBinDict;
public Vector3 rot;
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Security;
using System.ServiceModel.Diagnostics.Application;
using System.Globalization;
using System.Collections.Generic;
namespace System.ServiceModel.Diagnostics
{
public static class TraceUtility
{
private const string ActivityIdKey = "ActivityId";
private const string AsyncOperationActivityKey = "AsyncOperationActivity";
private const string AsyncOperationStartTimeKey = "AsyncOperationStartTime";
private static long s_messageNumber = 0;
public const string E2EActivityId = "E2EActivityId";
public const string TraceApplicationReference = "TraceApplicationReference";
static internal void AddActivityHeader(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message));
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
static internal void AddAmbientActivityToMessage(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId);
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
}
static internal void CopyActivity(Message source, Message destination)
{
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source));
}
}
internal static long GetUtcBasedDurationForTrace(long startTicks)
{
if (startTicks > 0)
{
TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks);
return (long)elapsedTime.TotalMilliseconds;
}
return 0;
}
internal static ServiceModelActivity ExtractActivity(Message message)
{
ServiceModelActivity retval = null;
if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) &&
(message != null) &&
(message.State != MessageState.Closed))
{
object property;
if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property))
{
retval = property as ServiceModelActivity;
}
}
return retval;
}
internal static Guid ExtractActivityId(Message message)
{
if (TraceUtility.MessageFlowTracingOnly)
{
return ActivityIdHeader.ExtractActivityId(message);
}
ServiceModelActivity activity = ExtractActivity(message);
return activity == null ? Guid.Empty : activity.Id;
}
internal static Guid GetReceivedActivityId(OperationContext operationContext)
{
object activityIdFromProprties;
if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties))
{
return TraceUtility.ExtractActivityId(operationContext.IncomingMessage);
}
else
{
return (Guid)activityIdFromProprties;
}
}
internal static ServiceModelActivity ExtractAndRemoveActivity(Message message)
{
ServiceModelActivity retval = TraceUtility.ExtractActivity(message);
if (retval != null)
{
// If the property is just removed, the item is disposed and we don't want the thing
// to be disposed of.
message.Properties[TraceUtility.ActivityIdKey] = false;
}
return retval;
}
internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (activity != null && DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message);
if (null != incomingActivity && incomingActivity.Id != activity.Id)
{
using (ServiceModelActivity.BoundOperation(incomingActivity))
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(activity.Id);
}
}
}
TraceUtility.SetActivity(message, activity);
}
TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance);
}
}
internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(message, activity);
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(message);
}
TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance);
}
}
internal static void SetActivity(Message message, ServiceModelActivity activity)
{
if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed)
{
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher)
{
}
private static string GenerateMsdnTraceCode(int traceCode)
{
int group = (int)(traceCode & 0xFFFF0000);
string terminatorUri = null;
switch (group)
{
case TraceCode.Administration:
terminatorUri = "System.ServiceModel.Administration";
break;
case TraceCode.Channels:
terminatorUri = "System.ServiceModel.Channels";
break;
case TraceCode.ComIntegration:
terminatorUri = "System.ServiceModel.ComIntegration";
break;
case TraceCode.Diagnostics:
terminatorUri = "System.ServiceModel.Diagnostics";
break;
case TraceCode.PortSharing:
terminatorUri = "System.ServiceModel.PortSharing";
break;
case TraceCode.Security:
terminatorUri = "System.ServiceModel.Security";
break;
case TraceCode.Serialization:
terminatorUri = "System.Runtime.Serialization";
break;
case TraceCode.ServiceModel:
case TraceCode.ServiceModelTransaction:
terminatorUri = "System.ServiceModel";
break;
default:
terminatorUri = string.Empty;
break;
}
return string.Empty;
}
internal static Exception ThrowHelperError(Exception exception, Message message)
{
return exception;
}
internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source)
{
return exception;
}
internal static Exception ThrowHelperWarning(Exception exception, Message message)
{
return exception;
}
internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg)
{
return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg);
}
internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message)
{
return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message);
}
internal static string CreateSourceString(object source)
{
return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture);
}
internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source)
{
}
internal static void TraceUserCodeException(Exception e, MethodInfo method)
{
}
static TraceUtility()
{
//Maintain the order of calls
TraceUtility.SetEtwProviderId();
TraceUtility.SetEndToEndTracingFlags();
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores bool values.")]
[SecuritySafeCritical]
private static void SetEndToEndTracingFlags()
{
}
static public long RetrieveMessageNumber()
{
return Interlocked.Increment(ref TraceUtility.s_messageNumber);
}
static public bool PropagateUserActivity
{
get
{
return TraceUtility.ShouldPropagateActivity &&
TraceUtility.PropagateUserActivityCore;
}
}
// Most of the time, shouldPropagateActivity will be false.
// This property will rarely be executed as a result.
private static bool PropagateUserActivityCore
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
return false;
}
}
static internal string GetCallerInfo(OperationContext context)
{
return "null";
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")]
[SecuritySafeCritical]
static internal void SetEtwProviderId()
{
}
static internal void SetActivityId(MessageProperties properties)
{
Guid activityId;
if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId))
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
static internal bool ShouldPropagateActivity
{
get
{
return false;
}
}
static internal bool ShouldPropagateActivityGlobal
{
get
{
return false;
}
}
static internal bool ActivityTracing
{
get
{
return false;
}
}
static internal bool MessageFlowTracing
{
get
{
return false;
}
}
static internal bool MessageFlowTracingOnly
{
get
{
return false;
}
}
static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
if (TD.MessageSentToTransportIsEnabled())
{
TD.MessageSentToTransport(eventTraceActivity, correlationId);
}
}
}
static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (createNewActivityId)
{
if (!activityIdFound)
{
activityId = Guid.NewGuid();
activityIdFound = true;
}
//message flow tracing only - start fresh
DiagnosticTraceBase.ActivityId = Guid.Empty;
}
if (activityIdFound)
{
FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId);
}
}
if (TD.MessageReceivedFromTransportIsEnabled())
{
if (context == null)
{
context = OperationContext.Current;
}
TD.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context));
}
}
}
internal static string GetAnnotation(OperationContext context)
{
// Desktop obtains annotation from host
return String.Empty;
}
internal static void TransferFromTransport(Message message)
{
if (message != null && DiagnosticUtility.ShouldUseActivity)
{
Guid guid = Guid.Empty;
// Only look if we are allowing user propagation
if (TraceUtility.ShouldPropagateActivity)
{
guid = ActivityIdHeader.ExtractActivityId(message);
}
if (guid == Guid.Empty)
{
guid = Guid.NewGuid();
}
ServiceModelActivity activity = null;
bool emitStart = true;
if (ServiceModelActivity.Current != null)
{
if ((ServiceModelActivity.Current.Id == guid) ||
(ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
{
activity = ServiceModelActivity.Current;
emitStart = false;
}
else if (ServiceModelActivity.Current.PreviousActivity != null &&
ServiceModelActivity.Current.PreviousActivity.Id == guid)
{
activity = ServiceModelActivity.Current.PreviousActivity;
emitStart = false;
}
}
if (activity == null)
{
activity = ServiceModelActivity.CreateActivity(guid);
}
if (DiagnosticUtility.ShouldUseActivity)
{
if (emitStart)
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(guid);
}
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction);
}
}
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
static internal void UpdateAsyncOperationContextWithActivity(object activity)
{
if (OperationContext.Current != null && activity != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity;
}
}
static internal object ExtractAsyncOperationContextActivity()
{
object data = null;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey);
}
return data;
}
static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime)
{
if (OperationContext.Current != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime);
}
}
static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime)
{
EventTraceActivityTimeProperty data = null;
eventTraceActivity = null;
startTime = 0;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue<EventTraceActivityTimeProperty>(TraceUtility.AsyncOperationStartTimeKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey);
eventTraceActivity = data.EventTraceActivity;
startTime = data.StartTime;
}
}
internal class TracingAsyncCallbackState
{
private object _innerState;
private Guid _activityId;
internal TracingAsyncCallbackState(object innerState)
{
_innerState = innerState;
_activityId = DiagnosticTraceBase.ActivityId;
}
internal object InnerState
{
get { return _innerState; }
}
internal Guid ActivityId
{
get { return _activityId; }
}
}
internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback)
{
return (DiagnosticUtility.ShouldUseActivity && callback != null) ?
(new ExecuteUserCodeAsync(callback)).Callback
: callback;
}
internal sealed class ExecuteUserCodeAsync
{
private AsyncCallback _callback;
public ExecuteUserCodeAsync(AsyncCallback callback)
{
_callback = callback;
}
public AsyncCallback Callback
{
get
{
return Fx.ThunkCallback(new AsyncCallback(this.ExecuteUserCode));
}
}
private void ExecuteUserCode(IAsyncResult result)
{
using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity())
{
ServiceModelActivity.Start(activity, SR.ActivityCallback, ActivityType.ExecuteUserCode);
this._callback(result);
}
}
}
internal class EventTraceActivityTimeProperty
{
private long _startTime;
private EventTraceActivity _eventTraceActivity;
public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime)
{
_eventTraceActivity = eventTraceActivity;
_startTime = startTime;
}
internal long StartTime
{
get { return _startTime; }
}
internal EventTraceActivity EventTraceActivity
{
get { return _eventTraceActivity; }
}
}
}
}
| |
/*
* Wenger CD, Coon JJ. A Proteomics Search Algorithm Specifically Designed for High-Resolution Tandem Mass Spectra, Journal of Proteome Research, 2013; 12(3): 1377-86
* http://www.chem.wisc.edu/~coon/software.php#morpheus
* Licensed under the MIT license: <http://www.opensource.org/licenses/mit-license.php>
* Altered by Olivier Caron-Lizotte
* olivierlizotte@gmail.com
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using PeptidAce.Utilities;
namespace PeptidAce
{
public abstract class AminoAcidPolymer
{
private static MassType productMassType = MassType.Monoisotopic;
private string baseSequence;
public string BaseSequence
{
get
{
return baseSequence;
}
set
{
baseSequence = value;
Length = value.Length;
}
}
public char this[int index]
{
get
{
return baseSequence[index];
}
}
public int Length { get; private set; }
public static double ComputeMonoisotopicMass(string pepSeqWithMods)
{
double mass = Constants.WATER_MONOISOTOPIC_MASS;
bool cumulMod = false;
string strMod = "";
for(int i = 0; i < pepSeqWithMods.Length; i++)
{
if(pepSeqWithMods[i] == '(')
{
strMod = "";
cumulMod = true;
}
else if(pepSeqWithMods[i] == ')')
{
cumulMod = false;
mass += ModificationDictionary.Instance[strMod].MonoisotopicMassShift;
} else if(cumulMod)
strMod += pepSeqWithMods[i];
else
mass += AminoAcidMasses.GetMonoisotopicMass(pepSeqWithMods[i]);
}
return mass;
}
private double _preCalcMonoMass = 0.0;
public double MonoisotopicMass
{
get
{
if (_preCalcMonoMass > 0)
return _preCalcMonoMass;
else
{
_preCalcMonoMass = ComputeMonoisotopicMass(baseSequence);
if (fixedModifications != null)
foreach (List<Modification> fixed_modifications in fixedModifications.Values)
foreach (Modification fixed_modification in fixed_modifications)
_preCalcMonoMass += fixed_modification.MonoisotopicMassShift;
if (variableModifications != null)
foreach (Modification variable_modification in variableModifications.Values)
_preCalcMonoMass += variable_modification.MonoisotopicMassShift;
return _preCalcMonoMass;
}
}
}
public string BaseLeucineSequence
{
get { return baseSequence.Replace('I', 'L'); }
}
protected string _preCompSeq = null;
public string Sequence
{
get
{
if(_preCompSeq == null)
{
StringBuilder sequence = new StringBuilder();
// fixed modifications on protein N-terminus
if(fixedModifications != null)
{
List<Modification> prot_n_term_fixed_mods;
if(fixedModifications.TryGetValue(0, out prot_n_term_fixed_mods))
{
foreach(Modification fixed_modification in prot_n_term_fixed_mods)
{
sequence.Append('[' + fixed_modification.Description.ToString() + ']');
}
}
}
// variable modification on protein N-terminus
if(variableModifications != null)
{
Modification prot_n_term_variable_mod;
if(variableModifications.TryGetValue(0, out prot_n_term_variable_mod))
{
sequence.Append('(' + prot_n_term_variable_mod.Description.ToString() + ')');
}
}
// fixed modifications on peptide N-terminus
if(fixedModifications != null)
{
List<Modification> pep_n_term_fixed_mods;
if(fixedModifications.TryGetValue(1, out pep_n_term_fixed_mods))
{
foreach(Modification fixed_modification in pep_n_term_fixed_mods)
{
sequence.Append('[' + fixed_modification.Description.ToString() + ']');
}
}
}
// variable modification on peptide N-terminus
if(variableModifications != null)
{
Modification pep_n_term_variable_mod;
if(variableModifications.TryGetValue(1, out pep_n_term_variable_mod))
{
sequence.Append('(' + pep_n_term_variable_mod.Description.ToString() + ')');
}
}
for(int r = 0; r < Length; r++)
{
sequence.Append(this[r]);
// fixed modifications on this residue
if(fixedModifications != null)
{
List<Modification> residue_fixed_mods;
if(fixedModifications.TryGetValue(r + 2, out residue_fixed_mods))
{
foreach(Modification fixed_modification in residue_fixed_mods)
{
sequence.Append('[' + fixed_modification.Description.ToString() + ']');
}
}
}
// variable modification on this residue
if(variableModifications != null)
{
Modification residue_variable_mod;
if(variableModifications.TryGetValue(r + 2, out residue_variable_mod))
{
sequence.Append('(' + residue_variable_mod.Description.ToString() + ')');
}
}
}
// fixed modifications on peptide C-terminus
if(fixedModifications != null)
{
List<Modification> pep_c_term_fixed_mods;
if(fixedModifications.TryGetValue(Length + 2, out pep_c_term_fixed_mods))
{
foreach(Modification fixed_modification in pep_c_term_fixed_mods)
{
sequence.Append('[' + fixed_modification.Description.ToString() + ']');
}
}
}
// variable modification on peptide C-terminus
if(variableModifications != null)
{
Modification pep_c_term_variable_mod;
if(variableModifications.TryGetValue(Length + 2, out pep_c_term_variable_mod))
{
sequence.Append('(' + pep_c_term_variable_mod.Description.ToString() + ')');
}
}
// fixed modifications on protein C-terminus
if(fixedModifications != null)
{
List<Modification> prot_c_term_fixed_mods;
if(fixedModifications.TryGetValue(Length + 3, out prot_c_term_fixed_mods))
{
foreach(Modification fixed_modification in prot_c_term_fixed_mods)
{
sequence.Append('[' + fixed_modification.Description.ToString() + ']');
}
}
}
// variable modification on protein C-terminus
if(variableModifications != null)
{
Modification prot_c_term_variable_mod;
if(variableModifications.TryGetValue(Length + 3, out prot_c_term_variable_mod))
{
sequence.Append('(' + prot_c_term_variable_mod.Description.ToString() + ')');
}
}
_preCompSeq = sequence.ToString();
}
return _preCompSeq;
}
}
public string LeucineSequence
{
get { return Sequence.Replace('I', 'L'); }
}
private static readonly Regex INVALID_AMINO_ACIDS = new Regex("[^ACDEFGHIKLMNPQRSTVWY]");
public AminoAcidPolymer()
{
BaseSequence = "";
variableModifications = new Dictionary<int, Modification>();
fixedModifications = new Dictionary<int, List<Modification>>();
}
protected AminoAcidPolymer(string baseSequence, bool checkMods)
{
string[] seqSplits = baseSequence.Split(new char[]{ '(', ')' });
string seq = "";
for (int i = 0; i < seqSplits.Length; i += 2)
seq += seqSplits[i];
BaseSequence = INVALID_AMINO_ACIDS.Replace(seq, string.Empty);
}
protected AminoAcidPolymer(string baseSequence)
{
BaseSequence = baseSequence;
}
public override string ToString()
{
return Sequence;
}
private bool initializeProductArrays = true;
protected Dictionary<int, List<Modification>> fixedModifications;
public Dictionary<int, List<Modification>> FixedModifications
{
get { return fixedModifications; }
}
public void SetFixedModifications(Dictionary<int, List<Modification>> value)
{
fixedModifications = value;
initializeProductArrays = true;
}
private static string StringifyListMods(Dictionary<int, List<Modification>> mods)
{
if (mods == null)
return null;
string str = "";
foreach (int key in mods.Keys)
{
str += "|" + key;
foreach (Modification mod in mods[key])
str += "," + mod.Description;
}
if (string.IsNullOrEmpty(str))
return "";
else
return str.Substring(1);
}
private static Dictionary<int, List<Modification>> UnStringifyListMods(string str)
{
Dictionary<int, List<Modification>> dic = new Dictionary<int, List<Modification>>();
string[] mods = str.Split('|');
foreach (string mod in mods)
{
string[] pair = mod.Split(',');
List<Modification> newMods = new List<Modification>();
for(int i = 1; i < pair.Length; i++)
newMods.Add(ModificationDictionary.Instance[pair[i]]);
dic.Add(int.Parse(pair[0]), newMods);
}
return dic;
}
public string FixedModificationsInString
{
get { return StringifyListMods(fixedModifications); }
set
{
SetFixedModifications(UnStringifyListMods(value));
}
}
private Dictionary<int, Modification> variableModifications;
public Dictionary<int, Modification> VariableModifications
{
get { return variableModifications; }
}
public bool IsPionylated()
{
return (variableModifications != null && variableModifications.ContainsValue(ModificationDictionary.Pionylation));
}
public void SetVariableModifications(Dictionary<int, Modification> value)
{
variableModifications = new Dictionary<int,Modification>(value);
initializeProductArrays = true;
}
private static string StringifyMods(Dictionary<int, Modification> mods)
{
if (mods == null)
return null;
string str = "";
foreach (int key in mods.Keys)
str += "|" + key + "," + mods[key].Description;
if (string.IsNullOrEmpty(str))
return "";
else
return str.Substring(1);
}
private static Dictionary<int, Modification> UnStringifyMods(string str)
{
Dictionary<int, Modification> dic = new Dictionary<int,Modification>();
string[] mods = str.Split('|');
foreach (string mod in mods)
{
string[] pair = mod.Split(',');
dic.Add(int.Parse(pair[0]), ModificationDictionary.Instance[pair[1]]);
}
return dic;
}
public string VariableModificationsInString
{
get { return StringifyMods(variableModifications); }
set
{
SetVariableModifications(UnStringifyMods(value));
}
}
public void SetFixedModifications(IEnumerable<Modification> fixedModifications)
{
this.fixedModifications = new Dictionary<int, List<Modification>>(Length + 4);
foreach(Modification fixed_modification in fixedModifications)
{
if(fixed_modification.Type == ModificationType.ProteinNTerminus && (this is Protein ||
(this is Peptide && (((Peptide)this).StartResidueNumber == 1 || (((Peptide)this).StartResidueNumber == 2 && ((Peptide)this).Parent[0] == 'M')))))
{
List<Modification> prot_n_term_fixed_mods;
if(!this.fixedModifications.TryGetValue(0, out prot_n_term_fixed_mods))
{
prot_n_term_fixed_mods = new List<Modification>();
prot_n_term_fixed_mods.Add(fixed_modification);
this.fixedModifications.Add(0, prot_n_term_fixed_mods);
}
else
{
prot_n_term_fixed_mods.Add(fixed_modification);
}
}
if(fixed_modification.Type == ModificationType.PeptideNTerminus)
{
List<Modification> pep_n_term_fixed_mods;
if(!this.fixedModifications.TryGetValue(1, out pep_n_term_fixed_mods))
{
pep_n_term_fixed_mods = new List<Modification>();
pep_n_term_fixed_mods.Add(fixed_modification);
this.fixedModifications.Add(1, pep_n_term_fixed_mods);
}
else
{
pep_n_term_fixed_mods.Add(fixed_modification);
}
}
for(int r = 0; r < Length; r++)
{
if(fixed_modification.Type == ModificationType.AminoAcidResidue && this[r] == fixed_modification.AminoAcid && (variableModifications == null || !variableModifications.ContainsKey(r + 2)))
{
List<Modification> residue_fixed_mods;
if(!this.fixedModifications.TryGetValue(r + 2, out residue_fixed_mods))
{
residue_fixed_mods = new List<Modification>();
residue_fixed_mods.Add(fixed_modification);
this.fixedModifications.Add(r + 2, residue_fixed_mods);
}
else
{
residue_fixed_mods.Add(fixed_modification);
}
}
}
if(fixed_modification.Type == ModificationType.PeptideCTerminus)
{
List<Modification> pep_c_term_fixed_mods;
if(!this.fixedModifications.TryGetValue(Length + 2, out pep_c_term_fixed_mods))
{
pep_c_term_fixed_mods = new List<Modification>();
pep_c_term_fixed_mods.Add(fixed_modification);
this.fixedModifications.Add(Length + 2, pep_c_term_fixed_mods);
}
else
{
pep_c_term_fixed_mods.Add(fixed_modification);
}
}
if(fixed_modification.Type == ModificationType.ProteinCTerminus && (this is Protein || (this is Peptide && ((Peptide)this).EndResidueNumber == ((Peptide)this).Parent.Length - 1)))
{
List<Modification> prot_c_term_fixed_mods;
if(!this.fixedModifications.TryGetValue(Length + 3, out prot_c_term_fixed_mods))
{
prot_c_term_fixed_mods = new List<Modification>();
prot_c_term_fixed_mods.Add(fixed_modification);
this.fixedModifications.Add(Length + 3, prot_c_term_fixed_mods);
}
else
{
prot_c_term_fixed_mods.Add(fixed_modification);
}
}
}
if(this.fixedModifications.Count == 0)
{
this.fixedModifications = null;
}
initializeProductArrays = true;
}
private double[] cumulativeNTerminalMass;
private double[] cumulativeCTerminalMass;
private void InitializeProductArrays()
{
double mass_shift;
cumulativeNTerminalMass = new double[Length];
mass_shift = 0.0;
// fixed modifications on protein N-terminus
if(fixedModifications != null)
{
List<Modification> prot_n_term_fixed_mods;
if(fixedModifications.TryGetValue(0, out prot_n_term_fixed_mods))
{
foreach(Modification fixed_modification in prot_n_term_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on the protein N-terminus
if(variableModifications != null)
{
Modification protein_n_term_variable_mod;
if(variableModifications.TryGetValue(0, out protein_n_term_variable_mod))
{
mass_shift += protein_n_term_variable_mod.MonoisotopicMassShift;
}
}
// fixed modifications on peptide N-terminus
if(fixedModifications != null)
{
List<Modification> pep_n_term_fixed_mods;
if(fixedModifications.TryGetValue(1, out pep_n_term_fixed_mods))
{
foreach(Modification fixed_modification in pep_n_term_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on peptide N-terminus
if(variableModifications != null)
{
Modification pep_n_term_variable_mod;
if(variableModifications.TryGetValue(1, out pep_n_term_variable_mod))
{
mass_shift += pep_n_term_variable_mod.MonoisotopicMassShift;
}
}
cumulativeNTerminalMass[0] = mass_shift;
for(int r = 1; r < Length; r++)
{
mass_shift = 0.0;
// fixed modifications on this residue
if(fixedModifications != null)
{
List<Modification> residue_fixed_mods;
if(fixedModifications.TryGetValue(r + 1, out residue_fixed_mods))
{
foreach(Modification fixed_modification in residue_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on this residue
if(variableModifications != null)
{
Modification residue_variable_mod;
if(variableModifications.TryGetValue(r + 1, out residue_variable_mod))
{
mass_shift += residue_variable_mod.MonoisotopicMassShift;
}
}
cumulativeNTerminalMass[r] = cumulativeNTerminalMass[r - 1] + (productMassType == MassType.Average ? AminoAcidMasses.GetAverageMass(this[r - 1]) : AminoAcidMasses.GetMonoisotopicMass(this[r - 1])) + mass_shift;
}
cumulativeCTerminalMass = new double[Length];
mass_shift = 0.0;
// fixed modifications on protein C-terminus
if(fixedModifications != null)
{
List<Modification> prot_c_term_fixed_mods;
if(fixedModifications.TryGetValue(Length + 3, out prot_c_term_fixed_mods))
{
foreach(Modification fixed_modification in prot_c_term_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on protein C-terminus
if(variableModifications != null)
{
Modification prot_c_term_variable_mod;
if(variableModifications.TryGetValue(Length + 3, out prot_c_term_variable_mod))
{
mass_shift += prot_c_term_variable_mod.MonoisotopicMassShift;
}
}
// fixed modifications on peptide C-terminus
if(fixedModifications != null)
{
List<Modification> pep_c_term_fixed_mods;
if(fixedModifications.TryGetValue(Length + 2, out pep_c_term_fixed_mods))
{
foreach(Modification fixed_modification in pep_c_term_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on peptide C-terminus
if(variableModifications != null)
{
Modification pep_c_term_variable_mod;
if(variableModifications.TryGetValue(Length + 2, out pep_c_term_variable_mod))
{
mass_shift += pep_c_term_variable_mod.MonoisotopicMassShift;
}
}
cumulativeCTerminalMass[0] = mass_shift;
for(int r = 1; r < Length; r++)
{
mass_shift = 0.0;
// fixed modifications on this residue
if(fixedModifications != null)
{
List<Modification> residue_fixed_mods;
if(fixedModifications.TryGetValue(Length - r + 2, out residue_fixed_mods))
{
foreach(Modification fixed_modification in residue_fixed_mods)
{
mass_shift += fixed_modification.MonoisotopicMassShift;
}
}
}
// variable modification on this residue
if(variableModifications != null)
{
Modification residue_variable_mod;
if(variableModifications.TryGetValue(Length - r + 2, out residue_variable_mod))
{
mass_shift += residue_variable_mod.MonoisotopicMassShift;
}
}
cumulativeCTerminalMass[r] = cumulativeCTerminalMass[r - 1] + (productMassType == MassType.Average ? AminoAcidMasses.GetAverageMass(this[Length - r]) : AminoAcidMasses.GetMonoisotopicMass(this[Length - r])) + mass_shift;
}
initializeProductArrays = false;
}
private static readonly ProductCaps PRODUCT_CAPS = ProductCaps.Instance;
public double CalculateProductMass(ProductType productType, int productNumber)
{
if(initializeProductArrays)
{
InitializeProductArrays();
}
switch(productType)
{
case ProductType.b:
case ProductType.c:
return cumulativeNTerminalMass[productNumber] + PRODUCT_CAPS[productType, productMassType];
case ProductType.y:
case ProductType.zdot:
return cumulativeCTerminalMass[productNumber] + PRODUCT_CAPS[productType, productMassType];
default:
return double.NaN;
}
}
public Product CalculateProduct(ProductType productType, int productNumber)
{
if(initializeProductArrays)
{
InitializeProductArrays();
}
switch(productType)
{
case ProductType.b:
case ProductType.c:
return new Product(productType, productNumber, cumulativeNTerminalMass[productNumber] + PRODUCT_CAPS[productType, productMassType]);
case ProductType.y:
case ProductType.zdot:
return new Product(productType, productNumber, cumulativeCTerminalMass[productNumber] + PRODUCT_CAPS[productType, productMassType]);
default:
return null;
}
}
protected IEnumerable<Dictionary<int, Modification>> GetModificationDic(Dictionary<int, List<Modification>> possibleMods, int maxModPerPeptide, Dictionary<int, Modification> dic)
{
if (dic.Count < maxModPerPeptide)
{
foreach (int key in possibleMods.Keys)
{
if(!dic.ContainsKey(key))
{
List<Modification> list = possibleMods[key];
for (int i = 0; i < list.Count; i++)
{
dic.Add(key, list[i]);
yield return dic;
foreach (Dictionary<int, Modification> otherDic in GetModificationDic(possibleMods, maxModPerPeptide, dic))
yield return otherDic;
dic.Remove(key);
}
}
}
}
}
protected IEnumerable<Dictionary<int, Modification>> GetVariableModificationPatterns(Dictionary<int, List<Modification>> possibleVariableModifications, int maxModPerPeptide)
{
if(possibleVariableModifications.Count > 0 && maxModPerPeptide > 0)
{
foreach (Dictionary<int, Modification> dic in GetModificationDic(possibleVariableModifications, maxModPerPeptide, new Dictionary<int, Modification>()))
yield return dic;
//List<KeyValuePair<int, List<Modification>>> possible_variable_modifications = new List<KeyValuePair<int, List<Modification>>>(possibleVariableModifications);
//int[] base_variable_modification_pattern = new int[Length + 4];
//for (int variable_modifications = 0; variable_modifications <= possibleVariableModifications.Count; variable_modifications++)
//{
// foreach (int[] variable_modification_pattern in GetVariableModificationPatterns(possibleVariableModifications, possibleVariableModifications.Count - variable_modifications, base_variable_modification_pattern, 0, maxModPerPeptide))
// {
// Dictionary<int, Modification> dic = GetVariableModificationPattern(variable_modification_pattern, possibleVariableModifications);
// if (dic.Count > 0)
// yield return dic;
// }
//}
}
}
/*
protected IEnumerable<Dictionary<int, Modification>> GetVariableModificationPatterns(Dictionary<int, List<Modification>> possibleVariableModifications, int maxModPerPeptide)
{
if(possibleVariableModifications.Count > 0)
{
List<KeyValuePair<int, List<Modification>>> possible_variable_modifications = new List<KeyValuePair<int, List<Modification>>>(possibleVariableModifications);
int[] base_variable_modification_pattern = new int[Length + 4];
for(int variable_modifications = 0; variable_modifications <= possible_variable_modifications.Count; variable_modifications++)
{
foreach (int[] variable_modification_pattern in GetVariableModificationPatterns(possible_variable_modifications, possible_variable_modifications.Count - variable_modifications, base_variable_modification_pattern, 0, maxModPerPeptide))
{
Dictionary<int, Modification> dic = GetVariableModificationPattern(variable_modification_pattern, possibleVariableModifications);
if (dic.Count > 0)
yield return dic;
}
}
}
}//*/
private static IEnumerable<int[]> GetVariableModificationPatterns(List<KeyValuePair<int, List<Modification>>> possibleVariableModifications, int unmodifiedResiduesDesired, int[] variableModificationPattern, int index, int maxModPerPeptide)
{
if (index < possibleVariableModifications.Count - 1 && index < maxModPerPeptide)
{
if(unmodifiedResiduesDesired > 0)
{
variableModificationPattern[possibleVariableModifications[index].Key] = 0;
foreach (int[] new_variable_modification_pattern in GetVariableModificationPatterns(possibleVariableModifications, unmodifiedResiduesDesired - 1, variableModificationPattern, index + 1, maxModPerPeptide))
{
yield return new_variable_modification_pattern;
}
}
if(unmodifiedResiduesDesired < possibleVariableModifications.Count - index)
{
for(int i = 1; i <= possibleVariableModifications[index].Value.Count; i++)
{
variableModificationPattern[possibleVariableModifications[index].Key] = i;
foreach (int[] new_variable_modification_pattern in GetVariableModificationPatterns(possibleVariableModifications, unmodifiedResiduesDesired, variableModificationPattern, index + 1, maxModPerPeptide))
{
yield return new_variable_modification_pattern;
}
}
}
}
else
{
if(unmodifiedResiduesDesired > 0)
{
variableModificationPattern[possibleVariableModifications[index].Key] = 0;
yield return variableModificationPattern;
}
else
{
for(int i = 1; i <= possibleVariableModifications[index].Value.Count; i++)
{
variableModificationPattern[possibleVariableModifications[index].Key] = i;
yield return variableModificationPattern;
}
}
}
}
private static Dictionary<int, Modification> GetVariableModificationPattern(int[] variableModificationArray, Dictionary<int, List<Modification>> possibleVariableModifications)
{
Dictionary<int, Modification> modification_pattern = new Dictionary<int, Modification>();
foreach(KeyValuePair<int, List<Modification>> kvp in possibleVariableModifications)
{
if(variableModificationArray[kvp.Key] > 0)
{
modification_pattern.Add(kvp.Key, kvp.Value[variableModificationArray[kvp.Key] - 1]);
}
}
return modification_pattern;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlNode.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using MS.Internal.Xml.XPath;
using System.Globalization;
// Represents a single node in the document.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable {
internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly.
internal XmlNode () {
}
internal XmlNode( XmlDocument doc ) {
if ( doc == null )
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Null_Doc));
this.parentNode = doc;
}
public virtual XPathNavigator CreateNavigator() {
XmlDocument thisAsDoc = this as XmlDocument;
if ( thisAsDoc != null ) {
return thisAsDoc.CreateNavigator( this );
}
XmlDocument doc = OwnerDocument;
Debug.Assert( doc != null );
return doc.CreateNavigator( this );
}
// Selects the first node that matches the xpath expression
public XmlNode SelectSingleNode( string xpath ) {
XmlNodeList list = SelectNodes(xpath);
// SelectNodes returns null for certain node types
return list != null ? list[0] : null;
}
// Selects the first node that matches the xpath expression and given namespace context.
public XmlNode SelectSingleNode( string xpath, XmlNamespaceManager nsmgr ) {
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if( xn == null )
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp))[0];
}
// Selects all nodes that match the xpath expression
public XmlNodeList SelectNodes( string xpath ) {
XPathNavigator n = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if( n == null )
return null;
return new XPathNodeList( n.Select(xpath) );
}
// Selects all nodes that match the xpath expression and given namespace context.
public XmlNodeList SelectNodes( string xpath, XmlNamespaceManager nsmgr ) {
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if( xn == null )
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList( xn.Select(exp) );
}
// Gets the name of the node.
public abstract string Name {
get;
}
// Gets or sets the value of the node.
public virtual string Value {
get { return null;}
set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Res.GetString(Res.Xdom_Node_SetVal), NodeType.ToString()));}
}
// Gets the type of the current node.
public abstract XmlNodeType NodeType {
get;
}
// Gets the parent of this node (for nodes that can have parents).
public virtual XmlNode ParentNode {
get {
Debug.Assert(parentNode != null);
if (parentNode.NodeType != XmlNodeType.Document) {
return parentNode;
}
// Linear lookup through the children of the document
XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode;
if (firstChild != null) {
XmlLinkedNode node = firstChild;
do {
if (node == this) {
return parentNode;
}
node = node.next;
}
while (node != null
&& node != firstChild);
}
return null;
}
}
// Gets all children of this node.
public virtual XmlNodeList ChildNodes {
get { return new XmlChildNodes(this);}
}
// Gets the node immediately preceding this node.
public virtual XmlNode PreviousSibling {
get { return null;}
}
// Gets the node immediately following this node.
public virtual XmlNode NextSibling {
get { return null;}
}
// Gets a XmlAttributeCollection containing the attributes
// of this node.
public virtual XmlAttributeCollection Attributes {
get { return null;}
}
// Gets the XmlDocument that contains this node.
public virtual XmlDocument OwnerDocument {
get {
Debug.Assert( parentNode != null );
if ( parentNode.NodeType == XmlNodeType.Document)
return (XmlDocument)parentNode;
return parentNode.OwnerDocument;
}
}
// Gets the first child of this node.
public virtual XmlNode FirstChild {
get {
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null)
return linkedNode.next;
return null;
}
}
// Gets the last child of this node.
public virtual XmlNode LastChild {
get { return LastNode;}
}
internal virtual bool IsContainer {
get { return false;}
}
internal virtual XmlLinkedNode LastNode {
get { return null;}
set {}
}
internal bool AncestorNode(XmlNode node) {
XmlNode n = this.ParentNode;
while (n != null && n != this) {
if (n == node)
return true;
n = n.ParentNode;
}
return false;
}
//trace to the top to find out its parent node.
internal bool IsConnected()
{
XmlNode parent = ParentNode;
while (parent != null && !( parent.NodeType == XmlNodeType.Document ))
parent = parent.ParentNode;
return parent != null;
}
// Inserts the specified node immediately before the specified reference node.
public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) {
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Child));
if (refChild == null)
return AppendChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Contain));
if (refChild.ParentNode != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Path));
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Context));
if (!CanInsertBefore( newChild, refChild ))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Location));
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild( newChild );
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment) {
XmlNode first = newChild.FirstChild;
XmlNode node = first;
if (node != null) {
newChild.RemoveChild( node );
InsertBefore( node, refChild );
// insert the rest of the children after this one.
InsertAfter( newChild, node );
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_TypeConflict));
XmlLinkedNode newNode = (XmlLinkedNode) newChild;
XmlLinkedNode refNode = (XmlLinkedNode) refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs( newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert );
if (args != null)
BeforeEvent( args );
if (refNode == FirstChild) {
newNode.next = refNode;
LastNode.next = newNode;
newNode.SetParent(this);
if (newNode.IsText) {
if (refNode.IsText) {
NestTextNodes(newNode, refNode);
}
}
}
else {
XmlLinkedNode prevNode = (XmlLinkedNode) refNode.PreviousSibling;
newNode.next = refNode;
prevNode.next = newNode;
newNode.SetParent(this);
if (prevNode.IsText) {
if (newNode.IsText) {
NestTextNodes(prevNode, newNode);
if (refNode.IsText) {
NestTextNodes(newNode, refNode);
}
}
else {
if (refNode.IsText) {
UnnestTextNodes(prevNode, refNode);
}
}
}
else {
if (newNode.IsText) {
if (refNode.IsText) {
NestTextNodes(newNode, refNode);
}
}
}
}
if (args != null)
AfterEvent( args );
return newNode;
}
// Inserts the specified node immediately after the specified reference node.
public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) {
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Child));
if (refChild == null)
return PrependChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Contain));
if (refChild.ParentNode != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Path));
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Context));
if (!CanInsertAfter( newChild, refChild ))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Location));
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild( newChild );
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment) {
XmlNode last = refChild;
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null) {
XmlNode next = node.NextSibling;
newChild.RemoveChild( node );
InsertAfter( node, last );
last = node;
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_TypeConflict));
XmlLinkedNode newNode = (XmlLinkedNode) newChild;
XmlLinkedNode refNode = (XmlLinkedNode) refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs( newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert );
if (args != null)
BeforeEvent( args );
if (refNode == LastNode) {
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText) {
if (newNode.IsText) {
NestTextNodes(refNode, newNode);
}
}
}
else {
XmlLinkedNode nextNode = refNode.next;
newNode.next = nextNode;
refNode.next = newNode;
newNode.SetParent(this);
if (refNode.IsText) {
if (newNode.IsText) {
NestTextNodes(refNode, newNode);
if (nextNode.IsText) {
NestTextNodes(newNode, nextNode);
}
}
else {
if (nextNode.IsText) {
UnnestTextNodes(refNode, nextNode);
}
}
}
else {
if (newNode.IsText) {
if (nextNode.IsText) {
NestTextNodes(newNode, nextNode);
}
}
}
}
if (args != null)
AfterEvent( args );
return newNode;
}
// Replaces the child node oldChild with newChild node.
public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) {
XmlNode nextNode = oldChild.NextSibling;
RemoveChild(oldChild);
XmlNode node = InsertBefore( newChild, nextNode );
return oldChild;
}
// Removes specified child node.
public virtual XmlNode RemoveChild(XmlNode oldChild) {
if (!IsContainer)
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Remove_Contain));
if (oldChild.ParentNode != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Remove_Child));
XmlLinkedNode oldNode = (XmlLinkedNode) oldChild;
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = GetEventArgs( oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove );
if (args != null)
BeforeEvent( args );
XmlLinkedNode lastNode = LastNode;
if (oldNode == FirstChild) {
if (oldNode == lastNode) {
LastNode = null;
oldNode.next = null;
oldNode.SetParent( null );
}
else {
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText) {
if (oldNode.IsText) {
UnnestTextNodes(oldNode, nextNode);
}
}
lastNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent( null );
}
}
else {
if (oldNode == lastNode) {
XmlLinkedNode prevNode = (XmlLinkedNode) oldNode.PreviousSibling;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
oldNode.SetParent(null);
}
else {
XmlLinkedNode prevNode = (XmlLinkedNode) oldNode.PreviousSibling;
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText) {
if (prevNode.IsText) {
NestTextNodes(prevNode, nextNode);
}
else {
if (oldNode.IsText) {
UnnestTextNodes(oldNode, nextNode);
}
}
}
prevNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
if (args != null)
AfterEvent( args );
return oldChild;
}
// Adds the specified node to the beginning of the list of children of this node.
public virtual XmlNode PrependChild(XmlNode newChild) {
return InsertBefore(newChild, FirstChild);
}
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode AppendChild(XmlNode newChild) {
XmlDocument thisDoc = OwnerDocument;
if ( thisDoc == null ) {
thisDoc = this as XmlDocument;
}
if (!IsContainer)
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Contain));
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Child));
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild( newChild );
XmlDocument childDoc = newChild.OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(Res.GetString(Res.Xdom_Node_Insert_Context));
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment) {
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null) {
XmlNode next = node.NextSibling;
newChild.RemoveChild( node );
AppendChild( node );
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_TypeConflict));
if (!CanInsertAfter( newChild, LastChild ))
throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Insert_Location));
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs( newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert );
if (args != null)
BeforeEvent( args );
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode) newChild;
if (refNode == null) {
newNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
}
else {
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText) {
if (newNode.IsText) {
NestTextNodes(refNode, newNode);
}
}
}
if (args != null)
AfterEvent( args );
return newNode;
}
//the function is provided only at Load time to speed up Load process
internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) {
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad( newChild, this );
if (args != null)
doc.BeforeEvent( args );
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode) newChild;
if (refNode == null) {
newNode.next = newNode;
LastNode = newNode;
newNode.SetParentForLoad(this);
}
else {
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
if (refNode.IsText
&& newNode.IsText) {
NestTextNodes(refNode, newNode);
}
else {
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent( args );
return newNode;
}
internal virtual bool IsValidChildType( XmlNodeType type ) {
return false;
}
internal virtual bool CanInsertBefore( XmlNode newChild, XmlNode refChild ) {
return true;
}
internal virtual bool CanInsertAfter( XmlNode newChild, XmlNode refChild ) {
return true;
}
// Gets a value indicating whether this node has any child nodes.
public virtual bool HasChildNodes {
get { return LastNode != null;}
}
// Creates a duplicate of this node.
public abstract XmlNode CloneNode(bool deep);
internal virtual void CopyChildren( XmlDocument doc, XmlNode container, bool deep ) {
for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling) {
AppendChildForLoad( child.CloneNode(deep), doc );
}
}
// DOM Level 2
// Puts all XmlText nodes in the full depth of the sub-tree
// underneath this XmlNode into a "normal" form where only
// markup (e.g., tags, comments, processing instructions, CDATA sections,
// and entity references) separates XmlText nodes, that is, there
// are no adjacent XmlText nodes.
public virtual void Normalize() {
XmlNode firstChildTextLikeNode = null;
StringBuilder sb = new StringBuilder();
for ( XmlNode crtChild = this.FirstChild; crtChild != null; ) {
XmlNode nextChild = crtChild.NextSibling;
switch ( crtChild.NodeType ) {
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace: {
sb.Append( crtChild.Value );
XmlNode winner = NormalizeWinner( firstChildTextLikeNode, crtChild );
if ( winner == firstChildTextLikeNode ) {
this.RemoveChild( crtChild );
}
else {
if ( firstChildTextLikeNode != null )
this.RemoveChild( firstChildTextLikeNode );
firstChildTextLikeNode = crtChild;
}
break;
}
case XmlNodeType.Element: {
crtChild.Normalize();
goto default;
}
default : {
if ( firstChildTextLikeNode != null ) {
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
sb.Remove( 0, sb.Length );
break;
}
}
crtChild = nextChild;
}
if ( firstChildTextLikeNode != null && sb.Length > 0 )
firstChildTextLikeNode.Value = sb.ToString();
}
private XmlNode NormalizeWinner( XmlNode firstNode, XmlNode secondNode ) {
//first node has the priority
if ( firstNode == null )
return secondNode;
Debug.Assert( firstNode.NodeType == XmlNodeType.Text
|| firstNode.NodeType == XmlNodeType.SignificantWhitespace
|| firstNode.NodeType == XmlNodeType.Whitespace
|| secondNode.NodeType == XmlNodeType.Text
|| secondNode.NodeType == XmlNodeType.SignificantWhitespace
|| secondNode.NodeType == XmlNodeType.Whitespace );
if ( firstNode.NodeType == XmlNodeType.Text )
return firstNode;
if ( secondNode.NodeType == XmlNodeType.Text )
return secondNode;
if ( firstNode.NodeType == XmlNodeType.SignificantWhitespace )
return firstNode;
if ( secondNode.NodeType == XmlNodeType.SignificantWhitespace )
return secondNode;
if ( firstNode.NodeType == XmlNodeType.Whitespace )
return firstNode;
if ( secondNode.NodeType == XmlNodeType.Whitespace )
return secondNode;
Debug.Assert( true, "shouldn't have fall through here." );
return null;
}
// Test if the DOM implementation implements a specific feature.
public virtual bool Supports(string feature, string version) {
if (String.Compare("XML", feature, StringComparison.OrdinalIgnoreCase) == 0) {
if (version == null || version == "1.0" || version == "2.0")
return true;
}
return false;
}
// Gets the namespace URI of this node.
public virtual string NamespaceURI {
get { return string.Empty;}
}
// Gets or sets the namespace prefix of this node.
public virtual string Prefix {
get { return string.Empty;}
set {}
}
// Gets the name of the node without the namespace prefix.
public abstract string LocalName {
get;
}
// Microsoft extensions
// Gets a value indicating whether the node is read-only.
public virtual bool IsReadOnly {
get {
XmlDocument doc = OwnerDocument;
return HasReadOnlyParent( this );
}
}
internal static bool HasReadOnlyParent( XmlNode n ) {
while (n != null) {
switch (n.NodeType) {
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
n = ((XmlAttribute)n).OwnerElement;
break;
default:
n = n.ParentNode;
break;
}
}
return false;
}
// Creates a duplicate of this node.
public virtual XmlNode Clone() {
return this.CloneNode(true);
}
object ICloneable.Clone() {
return this.CloneNode(true);
}
// Provides a simple ForEach-style iteration over the
// collection of nodes in this XmlNamedNodeMap.
IEnumerator IEnumerable.GetEnumerator() {
return new XmlChildEnumerator(this);
}
public IEnumerator GetEnumerator() {
return new XmlChildEnumerator(this);
}
private void AppendChildText( StringBuilder builder ) {
for (XmlNode child = FirstChild; child != null; child = child.NextSibling) {
if (child.FirstChild == null) {
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA
|| child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace)
builder.Append( child.InnerText );
}
else {
child.AppendChildText( builder );
}
}
}
// Gets or sets the concatenated values of the node and
// all its children.
public virtual string InnerText {
get {
XmlNode fc = FirstChild;
if (fc == null) {
return string.Empty;
}
if (fc.NextSibling == null) {
XmlNodeType nodeType = fc.NodeType;
switch (nodeType) {
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return fc.Value;
}
}
StringBuilder builder = new StringBuilder();
AppendChildText( builder );
return builder.ToString();
}
set {
XmlNode firstChild = FirstChild;
if ( firstChild != null //there is one child
&& firstChild.NextSibling == null // and exactly one
&& firstChild.NodeType == XmlNodeType.Text )//which is a text node
{
//this branch is for perf reason and event fired when TextNode.Value is changed
firstChild.Value = value;
}
else {
RemoveAll();
AppendChild( OwnerDocument.CreateTextNode( value ) );
}
}
}
// Gets the markup representing this node and all its children.
public virtual string OuterXml {
get {
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter( sw );
try {
WriteTo( xw );
}
finally {
xw.Close();
}
return sw.ToString();
}
}
// Gets or sets the markup representing just the children of this node.
public virtual string InnerXml {
get {
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter( sw );
try {
WriteContentTo( xw );
}
finally {
xw.Close();
}
return sw.ToString();
}
set {
throw new InvalidOperationException( Res.GetString(Res.Xdom_Set_InnerXml ) );
}
}
public virtual IXmlSchemaInfo SchemaInfo {
get {
return XmlDocument.NotKnownSchemaInfo;
}
}
public virtual String BaseURI {
get {
XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref
while ( curNode != null ) {
XmlNodeType nt = curNode.NodeType;
//EntityReference's children come from the dtd where they are defined.
//we need to investigate the same thing for entity's children if they are defined in an external dtd file.
if ( nt == XmlNodeType.EntityReference )
return ((XmlEntityReference)curNode).ChildBaseURI;
if ( nt == XmlNodeType.Document
|| nt == XmlNodeType.Entity
|| nt == XmlNodeType.Attribute )
return curNode.BaseURI;
curNode = curNode.ParentNode;
}
return String.Empty;
}
}
// Saves the current node to the specified XmlWriter.
public abstract void WriteTo(XmlWriter w);
// Saves all the children of the node to the specified XmlWriter.
public abstract void WriteContentTo(XmlWriter w);
// Removes all the children and/or attributes
// of the current node.
public virtual void RemoveAll() {
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null) {
sibling = child.NextSibling;
RemoveChild( child );
child = sibling;
}
}
internal XmlDocument Document {
get {
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
return OwnerDocument;
}
}
// Looks up the closest xmlns declaration for the given
// prefix that is in scope for the current node and returns
// the namespace URI in the declaration.
public virtual string GetNamespaceOfPrefix(string prefix) {
string namespaceName = GetNamespaceOfPrefixStrict(prefix);
return namespaceName != null ? namespaceName : string.Empty;
}
internal string GetNamespaceOfPrefixStrict(string prefix) {
XmlDocument doc = Document;
if (doc != null) {
prefix = doc.NameTable.Get(prefix);
if (prefix == null)
return null;
XmlNode node = this;
while (node != null) {
if (node.NodeType == XmlNodeType.Element) {
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes) {
XmlAttributeCollection attrs = elem.Attributes;
if (prefix.Length == 0) {
for (int iAttr = 0; iAttr < attrs.Count; iAttr++) {
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0) {
if (Ref.Equal(attr.LocalName, doc.strXmlns)) {
return attr.Value; // found xmlns
}
}
}
}
else {
for (int iAttr = 0; iAttr < attrs.Count; iAttr++) {
XmlAttribute attr = attrs[iAttr];
if (Ref.Equal(attr.Prefix, doc.strXmlns)) {
if (Ref.Equal(attr.LocalName, prefix)) {
return attr.Value; // found xmlns:prefix
}
}
else if (Ref.Equal(attr.Prefix, prefix)) {
return attr.NamespaceURI; // found prefix:attr
}
}
}
}
if (Ref.Equal(node.Prefix, prefix)) {
return node.NamespaceURI;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute) {
node = ((XmlAttribute)node).OwnerElement;
}
else {
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strXml, prefix)) { // xmlns:xml
return doc.strReservedXml;
}
else if (Ref.Equal(doc.strXmlns, prefix)) { // xmlns:xmlns
return doc.strReservedXmlns;
}
}
return null;
}
// Looks up the closest xmlns declaration for the given namespace
// URI that is in scope for the current node and returns
// the prefix defined in that declaration.
public virtual string GetPrefixOfNamespace(string namespaceURI) {
string prefix = GetPrefixOfNamespaceStrict(namespaceURI);
return prefix != null ? prefix : string.Empty;
}
internal string GetPrefixOfNamespaceStrict(string namespaceURI) {
XmlDocument doc = Document;
if (doc != null) {
namespaceURI = doc.NameTable.Add(namespaceURI);
XmlNode node = this;
while (node != null) {
if (node.NodeType == XmlNodeType.Element) {
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes) {
XmlAttributeCollection attrs = elem.Attributes;
for (int iAttr = 0; iAttr < attrs.Count; iAttr++) {
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0) {
if (Ref.Equal(attr.LocalName, doc.strXmlns)) {
if (attr.Value == namespaceURI) {
return string.Empty; // found xmlns="namespaceURI"
}
}
}
else if (Ref.Equal(attr.Prefix, doc.strXmlns)) {
if (attr.Value == namespaceURI) {
return attr.LocalName; // found xmlns:prefix="namespaceURI"
}
}
else if (Ref.Equal(attr.NamespaceURI, namespaceURI)) {
return attr.Prefix; // found prefix:attr
// with prefix bound to namespaceURI
}
}
}
if (Ref.Equal(node.NamespaceURI, namespaceURI)) {
return node.Prefix;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute) {
node = ((XmlAttribute)node).OwnerElement;
}
else {
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strReservedXml, namespaceURI)) { // xmlns:xml
return doc.strXml;
}
else if (Ref.Equal(doc.strReservedXmlns, namespaceURI)) { // xmlns:xmlns
return doc.strXmlns;
}
}
return null;
}
// Retrieves the first child element with the specified name.
public virtual XmlElement this[string name]
{
get {
for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
if (n.NodeType == XmlNodeType.Element && n.Name == name)
return(XmlElement) n;
}
return null;
}
}
// Retrieves the first child element with the specified LocalName and
// NamespaceURI.
public virtual XmlElement this[string localname, string ns]
{
get {
for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns)
return(XmlElement) n;
}
return null;
}
}
internal virtual void SetParent( XmlNode node ) {
if (node == null) {
this.parentNode = OwnerDocument;
}
else {
this.parentNode = node;
}
}
internal virtual void SetParentForLoad( XmlNode node ) {
this.parentNode = node;
}
internal static void SplitName( string name, out string prefix, out string localName ) {
int colonPos = name.IndexOf(':'); // ordinal compare
if (-1 == colonPos || 0 == colonPos || name.Length-1 == colonPos) {
prefix = string.Empty;
localName = name;
}
else {
prefix = name.Substring(0, colonPos);
localName = name.Substring(colonPos+1);
}
}
internal virtual XmlNode FindChild( XmlNodeType type ) {
for (XmlNode child = FirstChild; child != null; child = child.NextSibling) {
if (child.NodeType == type) {
return child;
}
}
return null;
}
internal virtual XmlNodeChangedEventArgs GetEventArgs( XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action ) {
XmlDocument doc = OwnerDocument;
if (doc != null) {
if ( ! doc.IsLoading ) {
if ( ( (newParent != null && newParent.IsReadOnly) || ( oldParent != null && oldParent.IsReadOnly ) ) )
throw new InvalidOperationException( Res.GetString(Res.Xdom_Node_Modify_ReadOnly));
}
return doc.GetEventArgs( node, oldParent, newParent, oldValue, newValue, action );
}
return null;
}
internal virtual void BeforeEvent( XmlNodeChangedEventArgs args ) {
if (args != null)
OwnerDocument.BeforeEvent( args );
}
internal virtual void AfterEvent( XmlNodeChangedEventArgs args ) {
if (args != null)
OwnerDocument.AfterEvent( args );
}
internal virtual XmlSpace XmlSpace {
get {
XmlNode node = this;
XmlElement elem = null;
do {
elem = node as XmlElement;
if (elem != null && elem.HasAttribute("xml:space")) {
switch (XmlConvert.TrimString(elem.GetAttribute("xml:space"))) {
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
//should we throw exception if value is otherwise?
break;
}
}
node = node.ParentNode;
}
while (node != null);
return XmlSpace.None;
}
}
internal virtual String XmlLang {
get {
XmlNode node = this;
XmlElement elem = null;
do {
elem = node as XmlElement;
if ( elem != null ) {
if ( elem.HasAttribute( "xml:lang" ) )
return elem.GetAttribute( "xml:lang" );
}
node = node.ParentNode;
} while ( node != null );
return String.Empty;
}
}
internal virtual XPathNodeType XPNodeType {
get {
return (XPathNodeType)(-1);
}
}
internal virtual string XPLocalName {
get {
return string.Empty;
}
}
internal virtual string GetXPAttribute(string localName, string namespaceURI) {
return String.Empty;
}
internal virtual bool IsText {
get {
return false;
}
}
public virtual XmlNode PreviousText {
get {
return null;
}
}
internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode) {
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode;
}
internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode) {
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode.ParentNode;
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } }
}
[DebuggerDisplay("{ToString()}")]
internal struct DebuggerDisplayXmlNodeProxy {
private XmlNode node;
public DebuggerDisplayXmlNodeProxy(XmlNode node) {
this.node = node;
}
public override string ToString() {
XmlNodeType nodeType = node.NodeType;
string result = nodeType.ToString();
switch (nodeType) {
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
result += ", Name=\"" + node.Name + "\"";
break;
case XmlNodeType.Attribute:
case XmlNodeType.ProcessingInstruction:
result += ", Name=\"" + node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(node.Value) + "\"";
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.XmlDeclaration:
result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(node.Value) + "\"";
break;
case XmlNodeType.DocumentType:
XmlDocumentType documentType = (XmlDocumentType)node;
result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\"";
break;
default:
break;
}
return result;
}
}
}
| |
#region Copyright Notice
// Copyright 2011-2013 Eleftherios Aslanoglou
//
// 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
namespace NBA_Stats_Tracker.Data.Teams
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
using LeftosCommonLibrary;
using NBA_Stats_Tracker.Data.BoxScores;
using NBA_Stats_Tracker.Data.Players;
#endregion
public class TeamStatsRow
{
public TeamStatsRow()
{
PBPSList = new List<PlayerPBPStats>();
}
public TeamStatsRow(TeamStats ts, bool playoffs = false)
: this()
{
ID = ts.ID;
Name = ts.Name;
DisplayName = ts.DisplayName;
IsHidden = ts.IsHidden;
Games = !playoffs ? ts.GetGames() : ts.GetPlayoffGames();
Wins = !playoffs ? ts.Record[0] : ts.PlRecord[0];
Losses = !playoffs ? ts.Record[1] : ts.PlRecord[1];
var totals = !playoffs ? ts.Totals : ts.PlTotals;
var perGame = !playoffs ? ts.PerGame : ts.PlPerGame;
var metrics = !playoffs ? ts.Metrics : ts.PlMetrics;
MINS = totals[TAbbrT.MINS];
PF = totals[TAbbrT.PF];
PA = totals[TAbbrT.PA];
FGM = totals[TAbbrT.FGM];
FGMPG = ((float) FGM / Games);
FGA = totals[TAbbrT.FGA];
FGAPG = ((float) FGA / Games);
TPM = totals[TAbbrT.TPM];
TPMPG = ((float) TPM / Games);
TPA = totals[TAbbrT.TPA];
TPAPG = ((float) TPA / Games);
FTM = totals[TAbbrT.FTM];
FTMPG = ((float) FTM / Games);
FTA = totals[TAbbrT.FTA];
FTAPG = ((float) FTA / Games);
OREB = totals[TAbbrT.OREB];
DREB = totals[TAbbrT.DREB];
REB = (UInt16) (OREB + DREB);
STL = totals[TAbbrT.STL];
TOS = totals[TAbbrT.TOS];
BLK = totals[TAbbrT.BLK];
AST = totals[TAbbrT.AST];
FOUL = totals[TAbbrT.FOUL];
Wp = perGame[TAbbrPG.Wp];
Weff = perGame[TAbbrPG.Weff];
MPG = perGame[TAbbrPG.MPG];
PPG = perGame[TAbbrPG.PPG];
PAPG = perGame[TAbbrPG.PAPG];
PD = PPG - PAPG;
FGp = perGame[TAbbrPG.FGp];
FGeff = perGame[TAbbrPG.FGeff];
TPp = perGame[TAbbrPG.TPp];
TPeff = perGame[TAbbrPG.TPeff];
FTp = perGame[TAbbrPG.FTp];
FTeff = perGame[TAbbrPG.FTeff];
RPG = perGame[TAbbrPG.RPG];
ORPG = perGame[TAbbrPG.ORPG];
DRPG = perGame[TAbbrPG.DRPG];
SPG = perGame[TAbbrPG.SPG];
TPG = perGame[TAbbrPG.TPG];
BPG = perGame[TAbbrPG.BPG];
APG = perGame[TAbbrPG.APG];
FPG = perGame[TAbbrPG.FPG];
Poss = metrics["PossPG"];
Pace = metrics["Pace"];
ORTG = metrics["ORTG"];
DRTG = metrics["DRTG"];
ASTp = metrics["AST%"];
DREBp = metrics["DREB%"];
EFGp = metrics["EFG%"];
EFFd = metrics["EFFd"];
TOR = metrics["TOR"];
OREBp = metrics["OREB%"];
FTR = metrics["FTR"];
PWp = metrics["PW%"];
TSp = metrics["TS%"];
TPR = metrics["3PR"];
PythW = metrics["PythW"];
PythL = metrics["PythL"];
GmSc = metrics["GmSc"];
CurStreak = ts.CurStreak;
}
public TeamStatsRow(TeamStats ts, Dictionary<int, PlayerStats> pst, bool playoffs = false)
: this(ts, playoffs)
{
CalculateTotalContracts(pst);
CalculatePlayerCounts(pst);
}
public TeamStatsRow(TeamStats ts, Dictionary<int, Dictionary<string, TeamStats>> splitTeamStats, bool playoffs = false)
: this(ts, playoffs)
{
DivW = splitTeamStats[ID]["Division"].Record[0];
DivL = splitTeamStats[ID]["Division"].Record[1];
ConfW = splitTeamStats[ID]["Conference"].Record[0];
ConfL = splitTeamStats[ID]["Conference"].Record[1];
L10W = splitTeamStats[ID]["Last 10"].Record[0];
L10L = splitTeamStats[ID]["Last 10"].Record[1];
}
public TeamStatsRow(
TeamStats ts,
Dictionary<int, PlayerStats> pst,
Dictionary<int, Dictionary<string, TeamStats>> splitTeamStats,
bool playoffs = false)
: this(ts, splitTeamStats, playoffs)
{
CalculateTotalContracts(pst);
CalculatePlayerCounts(pst);
}
public double GmSc { get; set; }
public int ID { get; set; }
public uint Games { get; set; }
public uint Wins { get; set; }
public uint Losses { get; set; }
public uint MINS { get; set; }
public uint PF { get; set; }
public uint PA { get; set; }
public uint FGM { get; set; }
public uint FGA { get; set; }
public uint TPM { get; set; }
public uint TPA { get; set; }
public uint FTM { get; set; }
public uint FTA { get; set; }
public uint REB { get; set; }
public uint OREB { get; set; }
public uint DREB { get; set; }
public uint STL { get; set; }
public uint TOS { get; set; }
public uint BLK { get; set; }
public uint AST { get; set; }
public uint FOUL { get; set; }
public float Wp { get; set; }
public float Weff { get; set; }
public float MPG { get; set; }
public float PPG { get; set; }
public float PAPG { get; set; }
public float PD { get; set; }
public float FGp { get; set; }
public float FGeff { get; set; }
public float TPp { get; set; }
public float TPeff { get; set; }
public float FTp { get; set; }
public float FTeff { get; set; }
public float RPG { get; set; }
public float ORPG { get; set; }
public float DRPG { get; set; }
public float SPG { get; set; }
public float TPG { get; set; }
public float BPG { get; set; }
public float APG { get; set; }
public float FPG { get; set; }
public float FGMPG { get; set; }
public float FGAPG { get; set; }
public float TPMPG { get; set; }
public float TPAPG { get; set; }
public float FTMPG { get; set; }
public float FTAPG { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public double ORTG { get; set; }
public double DRTG { get; set; }
public double EFFd { get; set; }
public double PWp { get; set; }
public double PythW { get; set; }
public double PythL { get; set; }
public double TSp { get; set; }
public double EFGp { get; set; }
public double TPR { get; set; }
public double DREBp { get; set; }
public double OREBp { get; set; }
public double ASTp { get; set; }
public double TOR { get; set; }
public double FTR { get; set; }
public double Poss { get; set; }
public double Pace { get; set; }
public int ContractsY1 { get; set; }
public int ContractsY2 { get; set; }
public int ContractsY3 { get; set; }
public int ContractsY4 { get; set; }
public int ContractsY5 { get; set; }
public int ContractsY6 { get; set; }
public int ContractsY7 { get; set; }
public int PGCount { get; set; }
public int SGCount { get; set; }
public int SFCount { get; set; }
public int PFCount { get; set; }
public int CCount { get; set; }
public int PlCount { get; set; }
public uint DivW { get; set; }
public uint DivL { get; set; }
public string DivRecord
{
get { return String.Format("{0}-{1}", DivW, DivL); }
}
public uint ConfW { get; set; }
public uint ConfL { get; set; }
public string ConfRecord
{
get { return String.Format("{0}-{1}", ConfW, ConfL); }
}
public uint L10W { get; set; }
public uint L10L { get; set; }
public string L10Record
{
get { return String.Format("{0}-{1}", L10W, L10L); }
}
public string CurStreak { get; set; }
public bool IsHidden { get; set; }
public bool Highlight { get; set; }
public int InjuredCount { get; set; }
public List<PlayerPBPStats> PBPSList { get; set; }
public static void TryChangeTSR(ref TeamStatsRow tsr, Dictionary<string, string> dict)
{
tsr.Wins = tsr.Wins.TrySetValue(dict, "Wins", typeof(UInt16));
tsr.Losses = tsr.Losses.TrySetValue(dict, "Losses", typeof(UInt16));
tsr.MINS = tsr.MINS.TrySetValue(dict, "MINS", typeof(UInt16));
tsr.PF = tsr.PF.TrySetValue(dict, "PF", typeof(UInt16));
tsr.PA = tsr.PF.TrySetValue(dict, "PA", typeof(UInt16));
tsr.FGM = tsr.FGM.TrySetValue(dict, "FGM", typeof(UInt16));
tsr.FGA = tsr.FGA.TrySetValue(dict, "FGA", typeof(UInt16));
tsr.TPM = tsr.TPM.TrySetValue(dict, "3PM", typeof(UInt16));
tsr.TPA = tsr.TPA.TrySetValue(dict, "3PA", typeof(UInt16));
tsr.FTM = tsr.FTM.TrySetValue(dict, "FTM", typeof(UInt16));
tsr.FTA = tsr.FTA.TrySetValue(dict, "FTA", typeof(UInt16));
tsr.REB = tsr.REB.TrySetValue(dict, "REB", typeof(UInt16));
tsr.OREB = tsr.OREB.TrySetValue(dict, "OREB", typeof(UInt16));
tsr.DREB = tsr.DREB.TrySetValue(dict, "DREB", typeof(UInt16));
tsr.AST = tsr.AST.TrySetValue(dict, "AST", typeof(UInt16));
tsr.TOS = tsr.TOS.TrySetValue(dict, "TO", typeof(UInt16));
tsr.STL = tsr.STL.TrySetValue(dict, "STL", typeof(UInt16));
tsr.BLK = tsr.BLK.TrySetValue(dict, "BLK", typeof(UInt16));
tsr.FOUL = tsr.FOUL.TrySetValue(dict, "FOUL", typeof(UInt16));
}
public static void Refresh(ref TeamStatsRow tsr)
{
tsr = new TeamStatsRow(new TeamStats(tsr));
}
public void CalculateTotalContracts(Dictionary<int, PlayerStats> pst)
{
var teamPlayers = pst.Values.Where(ps => ps.TeamF == ID).ToList();
ContractsY1 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(1)).Sum();
ContractsY2 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(2)).Sum();
ContractsY3 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(3)).Sum();
ContractsY4 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(4)).Sum();
ContractsY5 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(5)).Sum();
ContractsY6 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(6)).Sum();
ContractsY7 = teamPlayers.Select(ps => ps.Contract.TryGetSalary(7)).Sum();
}
public void CalculatePlayerCounts(Dictionary<int, PlayerStats> pst)
{
var teamPlayers = pst.Values.Where(ps => ps.TeamF == ID).ToList();
PlCount = teamPlayers.Count;
PGCount = teamPlayers.Count(ps => ps.Position1 == Position.PG);
SGCount = teamPlayers.Count(ps => ps.Position1 == Position.SG);
SFCount = teamPlayers.Count(ps => ps.Position1 == Position.SF);
PFCount = teamPlayers.Count(ps => ps.Position1 == Position.PF);
CCount = teamPlayers.Count(ps => ps.Position1 == Position.C);
InjuredCount = teamPlayers.Count(ps => ps.Injury.IsInjured);
}
public void PopulatePBPSList(IEnumerable<BoxScoreEntry> bseList)
{
PBPSList.Clear();
var teamBSEList = bseList.Where(bse => bse.BS.Team1ID == ID || bse.BS.Team2ID == ID).ToList();
for (var i = 0; i < 7; i++)
{
PBPSList.Add(new PlayerPBPStats());
}
foreach (var bse in teamBSEList)
{
var pbpeList = bse.PBPEList;
var list = PBPSList;
var teamPlayerIDs = bse.PBSList.Where(pbs => pbs.TeamID == ID).Select(pbs => pbs.PlayerID).ToList();
PlayerPBPStats.AddShotsToList(ref list, teamPlayerIDs, pbpeList);
PBPSList[6].AddOtherStats(teamPlayerIDs, pbpeList, false);
}
}
public TResult GetValue<TResult>(string prop)
{
return this.GetValue<TeamStatsRow, TResult>(prop);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Common;
using ReactNative.Touch;
using ReactNative.Tracing;
using ReactNative.UIManager;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
#else
using System.Windows;
#endif
namespace ReactNative
{
/// <summary>
/// Default root view for applicaitons. Provides the ability to listen for
/// size changes so that the UI manager can re-layout its elements.
///
/// It is also responsible for handling touch events passed to any of it's
/// child views and sending those events to JavaScript via the
/// <see cref="UIManager.Events.RCTEventEmitter"/> module.
/// </summary>
public class ReactRootView : SizeMonitoringCanvas
{
private ReactInstanceManager _reactInstanceManager;
private string _jsModuleName;
private JObject _initialProps;
private bool _wasMeasured;
private bool _attachScheduled;
/// <summary>
/// Instantiates the <see cref="ReactRootView"/>.
/// </summary>
public ReactRootView()
{
TouchHandler = new TouchHandler(this);
}
/// <summary>
/// Gets the JavaScript module name.
/// </summary>
internal string JavaScriptModuleName
{
get
{
return _jsModuleName;
}
}
/// <summary>
/// The touch handler for the root view.
/// </summary>
internal TouchHandler TouchHandler
{
get; private set;
}
/// <summary>
/// The initial props.
/// </summary>
internal JObject InitialProps
{
get
{
return _initialProps;
}
}
/// <summary>
/// Schedule rendering of the React component rendered by the
/// JavaScript application from the given JavaScript module
/// <paramref name="moduleName"/> using the provided
/// <paramref name="reactInstanceManager"/> to attach to the JavaScript
/// context of that manager.
/// </summary>
/// <remarks>
/// Has to be called under the dispatcher the view is associated to.
/// </remarks>
/// <param name="reactInstanceManager">
/// The React instance manager.
/// </param>
/// <param name="moduleName">The module name.</param>
public void StartReactApplication(ReactInstanceManager reactInstanceManager, string moduleName)
{
StartReactApplication(reactInstanceManager, moduleName, default(JObject));
}
/// <summary>
/// Schedule rendering of the React component rendered by the
/// JavaScript application from the given JavaScript module.
/// <paramref name="moduleName"/> using the provided
/// <paramref name="reactInstanceManager"/> to attach to the JavaScript context of that manager.
/// Extra parameter
/// <paramref name="initialProps"/> can be used to pass initial props for the React component.
/// </summary>
/// <remarks>
/// Has to be called under the dispatcher associated with the view.
/// </remarks>
/// <param name="reactInstanceManager">
/// The React instance manager.
/// </param>
/// <param name="moduleName">The module name.</param>
/// <param name="initialProps">The initial props.</param>
public void StartReactApplication(ReactInstanceManager reactInstanceManager, string moduleName, JObject initialProps)
{
// Fire and forget async
Forget(StartReactApplicationAsync(reactInstanceManager, moduleName, initialProps));
}
private async Task StartReactApplicationAsync(ReactInstanceManager reactInstanceManager, string moduleName, JObject initialProps)
{
RnLog.Info(ReactConstants.RNW, $"ReactRootView: StartReactApplicationAsync ({moduleName}) - entry");
// This is called under the dispatcher associated with the view.
DispatcherHelpers.AssertOnDispatcher(this);
if (_reactInstanceManager != null)
{
throw new InvalidOperationException("This root view has already been attached to an instance manager.");
}
_reactInstanceManager = reactInstanceManager;
_jsModuleName = moduleName;
_initialProps = initialProps;
var getReactContextTaskTask =
DispatcherHelpers.CallOnDispatcher(async () => await _reactInstanceManager.GetOrCreateReactContextAsync(CancellationToken.None), true);
await getReactContextTaskTask.Unwrap();
// We need to wait for the initial `Measure` call, if this view has
// not yet been measured, we set the `_attachScheduled` flag, which
// will enable deferred attachment of the root node.
if (_wasMeasured)
{
await _reactInstanceManager.AttachMeasuredRootViewAsync(this);
}
else
{
_attachScheduled = true;
}
RnLog.Info(ReactConstants.RNW, $"ReactRootView: StartReactApplicationAsync ({moduleName}) - done ({(_attachScheduled ? "with scheduled work" : "completely")})");
}
/// <summary>
/// Frees resources associated with this root view (fire and forget version)
/// </summary>
/// <remarks>
/// Has to be called under the dispatcher associated with the view.
/// </remarks>
public void StopReactApplication()
{
Forget(StopReactApplicationAsync());
}
/// <summary>
/// Frees resources associated with this root view.
/// </summary>
/// <remarks>
/// Has to be called under the dispatcher associated with the view.
/// </remarks>
/// <returns>Awaitable task.</returns>
public async Task StopReactApplicationAsync()
{
RnLog.Info(ReactConstants.RNW, $"ReactRootView: StopReactApplicationAsync ({JavaScriptModuleName}) - entry");
DispatcherHelpers.AssertOnDispatcher(this);
var reactInstanceManager = _reactInstanceManager;
var attachScheduled = _attachScheduled;
_attachScheduled = false;
if (!attachScheduled && reactInstanceManager != null)
{
await reactInstanceManager.DetachRootViewAsync(this);
}
RnLog.Info(ReactConstants.RNW, $"ReactRootView: StopReactApplicationAsync ({JavaScriptModuleName}) - done");
}
/// <summary>
/// Hooks into the measurement event to potentially attach the React
/// root view.
/// </summary>
/// <param name="availableSize">The available size.</param>
/// <returns>The desired size.</returns>
protected override Size MeasureOverride(Size availableSize)
{
DispatcherHelpers.AssertOnDispatcher(this);
var result = base.MeasureOverride(availableSize);
// Fire and forget async
Forget(MeasureOverrideHelperAsync());
return result;
}
internal void StartTouchHandling()
{
if (TouchHandler == null)
{
TouchHandler = new TouchHandler(this);
}
}
internal void StopTouchHandling()
{
if (TouchHandler != null)
{
TouchHandler.Dispose();
TouchHandler = null;
}
}
#if WINDOWS_UWP
/// <summary>
/// Override ensuring the creation of an AutomationPeer for ReactRootView
/// root view.
/// </summary>
/// <returns>The new AutomationPeer.</returns>
protected override AutomationPeer OnCreateAutomationPeer()
{
//
// Older Windows OS'es (RS1, for ex.) don't create automation peers for normal Canvas elements.
// This is not an issue in general, but for ReactRootView in particular is, since it is the root of accessibility traversal
// done in AccessibilityHelper and so it needs a peer.
var peer = base.OnCreateAutomationPeer();
if (peer == null)
{
// Fallback to creating peer if base didn't provide one.
peer = new FrameworkElementAutomationPeer(this);
}
return peer;
}
#endif
private async Task MeasureOverrideHelperAsync()
{
DispatcherHelpers.AssertOnDispatcher(this);
_wasMeasured = true;
var reactInstanceManager = _reactInstanceManager;
var attachScheduled = _attachScheduled;
_attachScheduled = false;
if (attachScheduled && reactInstanceManager != null)
{
await reactInstanceManager.AttachMeasuredRootViewAsync(this);
}
}
private static void Forget(Task task)
{
task.ContinueWith(
t =>
{
RnLog.Fatal(ReactConstants.RNW, t.Exception, $"Exception in fire and forget asynchronous function");
},
TaskContinuationOptions.OnlyOnFaulted);
}
}
}
| |
//
// 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.RecoveryServices;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.RecoveryServices
{
public static partial class VaultExtendedInfoOperationsExtensions
{
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='extendedInfoArgs'>
/// Required. Create resource exnteded info input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultExtendedInfoOperations)s).CreateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='extendedInfoArgs'>
/// Required. Create resource exnteded info input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders)
{
return operations.CreateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the resource extended information object
/// </returns>
public static ResourceExtendedInformationResponse GetExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultExtendedInfoOperations)s).GetExtendedInfoAsync(resourceGroupName, resourceName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the resource extended information object
/// </returns>
public static Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetExtendedInfoAsync(resourceGroupName, resourceName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='extendedInfoArgs'>
/// Optional. Update resource exnteded info input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the resource extended information object
/// </returns>
public static ResourceExtendedInformationResponse UpdateExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultExtendedInfoOperations)s).UpdateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='extendedInfoArgs'>
/// Optional. Update resource exnteded info input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the resource extended information object
/// </returns>
public static Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders)
{
return operations.UpdateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='parameters'>
/// Required. Upload Vault Certificate input parameters.
/// </param>
/// <param name='certFriendlyName'>
/// Required. Certificate friendly name
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the upload certificate response
/// </returns>
public static UploadCertificateResponse UploadCertificate(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultExtendedInfoOperations)s).UploadCertificateAsync(resourceGroupName, resourceName, parameters, certFriendlyName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the vault extended info.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultExtendedInfoOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the job
/// collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='parameters'>
/// Required. Upload Vault Certificate input parameters.
/// </param>
/// <param name='certFriendlyName'>
/// Required. Certificate friendly name
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the upload certificate response
/// </returns>
public static Task<UploadCertificateResponse> UploadCertificateAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders)
{
return operations.UploadCertificateAsync(resourceGroupName, resourceName, parameters, certFriendlyName, customRequestHeaders, CancellationToken.None);
}
}
}
| |
// 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.Net.Http
{
public partial class ByteArrayContent : System.Net.Http.HttpContent
{
public ByteArrayContent(byte[] content) { }
public ByteArrayContent(byte[] content, int offset, int count) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
protected internal override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected internal override bool TryComputeLength(out long length) { throw null; }
}
public enum ClientCertificateOption
{
Automatic = 1,
Manual = 0,
}
public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler
{
protected DelegatingHandler() { }
protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
public System.Net.Http.HttpMessageHandler InnerHandler { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent
{
public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base (default(byte[])) { }
}
public partial class HttpClient : System.Net.Http.HttpMessageInvoker
{
public HttpClient() : base (default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler) : base (default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base (default(System.Net.Http.HttpMessageHandler)) { }
public System.Uri BaseAddress { get { throw null; } set { } }
public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { throw null; } }
public long MaxResponseContentBufferSize { get { throw null; } set { } }
public System.TimeSpan Timeout { get { throw null; } set { } }
public void CancelPendingRequests() { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
protected override void Dispose(bool disposing) { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { throw null; }
public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler
{
public HttpClientHandler() { }
public bool AllowAutoRedirect { get { throw null; } set { } }
public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } }
public bool CheckCertificateRevocationList { get { throw null; } set { } }
public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } }
public System.Net.CookieContainer CookieContainer { get { throw null; } set { } }
public System.Net.ICredentials Credentials { get { throw null; } set { } }
public System.Net.ICredentials DefaultProxyCredentials { get { throw null; } set { } }
public int MaxAutomaticRedirections { get { throw null; } set { } }
public int MaxConnectionsPerServer { get { throw null; } set { } }
public long MaxRequestContentBufferSize { get { throw null; } set { } }
public int MaxResponseHeadersLength { get { throw null; } set { } }
public bool PreAuthenticate { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } }
public System.Net.IWebProxy Proxy { get { throw null; } set { } }
public System.Func<System.Net.Http.HttpRequestMessage, System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography.X509Certificates.X509Chain, System.Net.Security.SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { throw null; } set { } }
public System.Security.Authentication.SslProtocols SslProtocols { get { throw null; } set { } }
public virtual bool SupportsAutomaticDecompression { get { throw null; } }
public virtual bool SupportsProxy { get { throw null; } }
public virtual bool SupportsRedirectConfiguration { get { throw null; } }
public bool UseCookies { get { throw null; } set { } }
public bool UseDefaultCredentials { get { throw null; } set { } }
public bool UseProxy { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum HttpCompletionOption
{
ResponseContentRead = 0,
ResponseHeadersRead = 1,
}
public abstract partial class HttpContent : System.IDisposable
{
protected HttpContent() { }
public System.Net.Http.Headers.HttpContentHeaders Headers { get { throw null; } }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { throw null; }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Threading.Tasks.Task LoadIntoBufferAsync() { throw null; }
public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { throw null; }
public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { throw null; }
public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { throw null; }
public System.Threading.Tasks.Task<string> ReadAsStringAsync() { throw null; }
protected internal abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context);
protected internal abstract bool TryComputeLength(out long length);
}
public abstract partial class HttpMessageHandler : System.IDisposable
{
protected HttpMessageHandler() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
}
public partial class HttpMessageInvoker : System.IDisposable
{
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { }
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod>
{
public HttpMethod(string method) { }
public static System.Net.Http.HttpMethod Delete { get { throw null; } }
public static System.Net.Http.HttpMethod Get { get { throw null; } }
public static System.Net.Http.HttpMethod Head { get { throw null; } }
public string Method { get { throw null; } }
public static System.Net.Http.HttpMethod Options { get { throw null; } }
public static System.Net.Http.HttpMethod Post { get { throw null; } }
public static System.Net.Http.HttpMethod Put { get { throw null; } }
public static System.Net.Http.HttpMethod Trace { get { throw null; } }
public bool Equals(System.Net.Http.HttpMethod other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; }
public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; }
public override string ToString() { throw null; }
}
public partial class HttpRequestException : System.Exception
{
public HttpRequestException() { }
public HttpRequestException(string message) { }
public HttpRequestException(string message, System.Exception inner) { }
}
public partial class HttpRequestMessage : System.IDisposable
{
public HttpRequestMessage() { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { }
public System.Net.Http.HttpContent Content { get { throw null; } set { } }
public System.Net.Http.Headers.HttpRequestHeaders Headers { get { throw null; } }
public System.Net.Http.HttpMethod Method { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } }
public System.Uri RequestUri { get { throw null; } set { } }
public System.Version Version { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override string ToString() { throw null; }
}
public partial class HttpResponseMessage : System.IDisposable
{
public HttpResponseMessage() { }
public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { }
public System.Net.Http.HttpContent Content { get { throw null; } set { } }
public System.Net.Http.Headers.HttpResponseHeaders Headers { get { throw null; } }
public bool IsSuccessStatusCode { get { throw null; } }
public string ReasonPhrase { get { throw null; } set { } }
public System.Net.Http.HttpRequestMessage RequestMessage { get { throw null; } set { } }
public System.Net.HttpStatusCode StatusCode { get { throw null; } set { } }
public System.Version Version { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler
{
protected MessageProcessingHandler() { }
protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken);
protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable
{
public MultipartContent() { }
public MultipartContent(string subtype) { }
public MultipartContent(string subtype, string boundary) { }
public virtual void Add(System.Net.Http.HttpContent content) { }
protected override void Dispose(bool disposing) { }
public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { throw null; }
protected internal override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
protected internal override bool TryComputeLength(out long length) { throw null; }
}
public partial class MultipartFormDataContent : System.Net.Http.MultipartContent
{
public MultipartFormDataContent() { }
public MultipartFormDataContent(string boundary) { }
public override void Add(System.Net.Http.HttpContent content) { }
public void Add(System.Net.Http.HttpContent content, string name) { }
public void Add(System.Net.Http.HttpContent content, string name, string fileName) { }
}
public partial class StreamContent : System.Net.Http.HttpContent
{
public StreamContent(System.IO.Stream content) { }
public StreamContent(System.IO.Stream content, int bufferSize) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; }
protected internal override bool TryComputeLength(out long length) { throw null; }
}
public partial class StringContent : System.Net.Http.ByteArrayContent
{
public StringContent(string content) : base (default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding) : base (default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base (default(byte[])) { }
}
}
namespace System.Net.Http.Headers
{
public partial class AuthenticationHeaderValue : System.ICloneable
{
public AuthenticationHeaderValue(string scheme) { }
public AuthenticationHeaderValue(string scheme, string parameter) { }
public string Parameter { get { throw null; } }
public string Scheme { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { throw null; }
}
public partial class CacheControlHeaderValue : System.ICloneable
{
public CacheControlHeaderValue() { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Extensions { get { throw null; } }
public System.Nullable<System.TimeSpan> MaxAge { get { throw null; } set { } }
public bool MaxStale { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> MaxStaleLimit { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> MinFresh { get { throw null; } set { } }
public bool MustRevalidate { get { throw null; } set { } }
public bool NoCache { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> NoCacheHeaders { get { throw null; } }
public bool NoStore { get { throw null; } set { } }
public bool NoTransform { get { throw null; } set { } }
public bool OnlyIfCached { get { throw null; } set { } }
public bool Private { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> PrivateHeaders { get { throw null; } }
public bool ProxyRevalidate { get { throw null; } set { } }
public bool Public { get { throw null; } set { } }
public System.Nullable<System.TimeSpan> SharedMaxAge { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { throw null; }
}
public partial class ContentDispositionHeaderValue : System.ICloneable
{
protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source) { }
public ContentDispositionHeaderValue(string dispositionType) { }
public System.Nullable<System.DateTimeOffset> CreationDate { get { throw null; } set { } }
public string DispositionType { get { throw null; } set { } }
public string FileName { get { throw null; } set { } }
public string FileNameStar { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> ModificationDate { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public System.Nullable<System.DateTimeOffset> ReadDate { get { throw null; } set { } }
public System.Nullable<long> Size { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { throw null; }
}
public partial class ContentRangeHeaderValue : System.ICloneable
{
public ContentRangeHeaderValue(long length) { }
public ContentRangeHeaderValue(long from, long to) { }
public ContentRangeHeaderValue(long from, long to, long length) { }
public System.Nullable<long> From { get { throw null; } }
public bool HasLength { get { throw null; } }
public bool HasRange { get { throw null; } }
public System.Nullable<long> Length { get { throw null; } }
public System.Nullable<long> To { get { throw null; } }
public string Unit { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { throw null; }
}
public partial class EntityTagHeaderValue : System.ICloneable
{
public EntityTagHeaderValue(string tag) { }
public EntityTagHeaderValue(string tag, bool isWeak) { }
public static System.Net.Http.Headers.EntityTagHeaderValue Any { get { throw null; } }
public bool IsWeak { get { throw null; } }
public string Tag { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { throw null; }
}
public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpContentHeaders() { }
public System.Collections.Generic.ICollection<string> Allow { get { throw null; } }
public System.Net.Http.Headers.ContentDispositionHeaderValue ContentDisposition { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> ContentEncoding { get { throw null; } }
public System.Collections.Generic.ICollection<string> ContentLanguage { get { throw null; } }
public System.Nullable<long> ContentLength { get { throw null; } set { } }
public System.Uri ContentLocation { get { throw null; } set { } }
public byte[] ContentMD5 { get { throw null; } set { } }
public System.Net.Http.Headers.ContentRangeHeaderValue ContentRange { get { throw null; } set { } }
public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Expires { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> LastModified { get { throw null; } set { } }
}
public abstract partial class HttpHeaders : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>, System.Collections.IEnumerable
{
protected HttpHeaders() { }
public void Add(string name, System.Collections.Generic.IEnumerable<string> values) { }
public void Add(string name, string value) { }
public void Clear() { }
public bool Contains(string name) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>> GetEnumerator() { throw null; }
public System.Collections.Generic.IEnumerable<string> GetValues(string name) { throw null; }
public bool Remove(string name) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override string ToString() { throw null; }
public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable<string> values) { throw null; }
public bool TryAddWithoutValidation(string name, string value) { throw null; }
public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable<string> values) { throw null; }
}
public sealed partial class HttpHeaderValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : class
{
internal HttpHeaderValueCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public void Add(T item) { }
public void Clear() { }
public bool Contains(T item) { throw null; }
public void CopyTo(T[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
public void ParseAdd(string input) { }
public bool Remove(T item) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override string ToString() { throw null; }
public bool TryParseAdd(string input) { throw null; }
}
public sealed partial class HttpRequestHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpRequestHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue> Accept { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptCharset { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptEncoding { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptLanguage { get { throw null; } }
public System.Net.Http.Headers.AuthenticationHeaderValue Authorization { get { throw null; } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } }
public System.Nullable<bool> ConnectionClose { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue> Expect { get { throw null; } }
public System.Nullable<bool> ExpectContinue { get { throw null; } set { } }
public string From { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfMatch { get { throw null; } }
public System.Nullable<System.DateTimeOffset> IfModifiedSince { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfNoneMatch { get { throw null; } }
public System.Net.Http.Headers.RangeConditionHeaderValue IfRange { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> IfUnmodifiedSince { get { throw null; } set { } }
public System.Nullable<int> MaxForwards { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } }
public System.Net.Http.Headers.AuthenticationHeaderValue ProxyAuthorization { get { throw null; } set { } }
public System.Net.Http.Headers.RangeHeaderValue Range { get { throw null; } set { } }
public System.Uri Referrer { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue> TE { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } }
public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> UserAgent { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } }
}
public sealed partial class HttpResponseHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpResponseHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> AcceptRanges { get { throw null; } }
public System.Nullable<System.TimeSpan> Age { get { throw null; } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } }
public System.Nullable<bool> ConnectionClose { get { throw null; } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } }
public System.Net.Http.Headers.EntityTagHeaderValue ETag { get { throw null; } set { } }
public System.Uri Location { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> ProxyAuthenticate { get { throw null; } }
public System.Net.Http.Headers.RetryConditionHeaderValue RetryAfter { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> Server { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } }
public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Vary { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> WwwAuthenticate { get { throw null; } }
}
public partial class MediaTypeHeaderValue : System.ICloneable
{
protected MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue source) { }
public MediaTypeHeaderValue(string mediaType) { }
public string CharSet { get { throw null; } set { } }
public string MediaType { get { throw null; } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { throw null; }
}
public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue
{
public MediaTypeWithQualityHeaderValue(string mediaType) : base (default(string)) { }
public MediaTypeWithQualityHeaderValue(string mediaType, double quality) : base (default(string)) { }
public System.Nullable<double> Quality { get { throw null; } set { } }
public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { throw null; }
}
public partial class NameValueHeaderValue : System.ICloneable
{
protected internal NameValueHeaderValue(System.Net.Http.Headers.NameValueHeaderValue source) { }
public NameValueHeaderValue(string name) { }
public NameValueHeaderValue(string name, string value) { }
public string Name { get { throw null; } }
public string Value { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { throw null; }
}
public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue, System.ICloneable
{
protected NameValueWithParametersHeaderValue(System.Net.Http.Headers.NameValueWithParametersHeaderValue source) : base (default(string)) { }
public NameValueWithParametersHeaderValue(string name) : base (default(string)) { }
public NameValueWithParametersHeaderValue(string name, string value) : base (default(string)) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { throw null; }
}
public partial class ProductHeaderValue : System.ICloneable
{
public ProductHeaderValue(string name) { }
public ProductHeaderValue(string name, string version) { }
public string Name { get { throw null; } }
public string Version { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { throw null; }
}
public partial class ProductInfoHeaderValue : System.ICloneable
{
public ProductInfoHeaderValue(System.Net.Http.Headers.ProductHeaderValue product) { }
public ProductInfoHeaderValue(string comment) { }
public ProductInfoHeaderValue(string productName, string productVersion) { }
public string Comment { get { throw null; } }
public System.Net.Http.Headers.ProductHeaderValue Product { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { throw null; }
}
public partial class RangeConditionHeaderValue : System.ICloneable
{
public RangeConditionHeaderValue(System.DateTimeOffset date) { }
public RangeConditionHeaderValue(System.Net.Http.Headers.EntityTagHeaderValue entityTag) { }
public RangeConditionHeaderValue(string entityTag) { }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public System.Net.Http.Headers.EntityTagHeaderValue EntityTag { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { throw null; }
}
public partial class RangeHeaderValue : System.ICloneable
{
public RangeHeaderValue() { }
public RangeHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue> Ranges { get { throw null; } }
public string Unit { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { throw null; }
}
public partial class RangeItemHeaderValue : System.ICloneable
{
public RangeItemHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Nullable<long> From { get { throw null; } }
public System.Nullable<long> To { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public partial class RetryConditionHeaderValue : System.ICloneable
{
public RetryConditionHeaderValue(System.DateTimeOffset date) { }
public RetryConditionHeaderValue(System.TimeSpan delta) { }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public System.Nullable<System.TimeSpan> Delta { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { throw null; }
}
public partial class StringWithQualityHeaderValue : System.ICloneable
{
public StringWithQualityHeaderValue(string value) { }
public StringWithQualityHeaderValue(string value, double quality) { }
public System.Nullable<double> Quality { get { throw null; } }
public string Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { throw null; }
}
public partial class TransferCodingHeaderValue : System.ICloneable
{
protected TransferCodingHeaderValue(System.Net.Http.Headers.TransferCodingHeaderValue source) { }
public TransferCodingHeaderValue(string value) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } }
public string Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { throw null; }
}
public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue
{
public TransferCodingWithQualityHeaderValue(string value) : base (default(string)) { }
public TransferCodingWithQualityHeaderValue(string value, double quality) : base (default(string)) { }
public System.Nullable<double> Quality { get { throw null; } set { } }
public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { throw null; }
}
public partial class ViaHeaderValue : System.ICloneable
{
public ViaHeaderValue(string protocolVersion, string receivedBy) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment) { }
public string Comment { get { throw null; } }
public string ProtocolName { get { throw null; } }
public string ProtocolVersion { get { throw null; } }
public string ReceivedBy { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { throw null; }
}
public partial class WarningHeaderValue : System.ICloneable
{
public WarningHeaderValue(int code, string agent, string text) { }
public WarningHeaderValue(int code, string agent, string text, System.DateTimeOffset date) { }
public string Agent { get { throw null; } }
public int Code { get { throw null; } }
public System.Nullable<System.DateTimeOffset> Date { get { throw null; } }
public string Text { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { throw null; }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { throw null; }
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Scoring;
using osu.Game.Screens;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Screens.Select;
using osu.Game.Tests.Resources;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Background
{
[TestFixture]
public class TestSceneUserDimBackgrounds : ManualInputManagerTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ScreenWithBeatmapBackground),
typeof(PlayerLoader),
typeof(Player),
typeof(UserDimContainer),
typeof(OsuScreen)
};
private DummySongSelect songSelect;
private TestPlayerLoader playerLoader;
private LoadBlockingTestPlayer player;
private BeatmapManager manager;
private RulesetStore rulesets;
[BackgroundDependencyLoader]
private void load(GameHost host, AudioManager audio)
{
Dependencies.Cache(rulesets = new RulesetStore(ContextFactory));
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, audio, host, Beatmap.Default));
Dependencies.Cache(new OsuConfigManager(LocalStorage));
manager.Import(TestResources.GetTestBeatmapForImport()).Wait();
Beatmap.SetDefault();
}
[SetUp]
public virtual void SetUp() => Schedule(() =>
{
var stack = new OsuScreenStack { RelativeSizeAxes = Axes.Both };
Child = stack;
stack.Push(songSelect = new DummySongSelect());
});
/// <summary>
/// Check if <see cref="PlayerLoader"/> properly triggers the visual settings preview when a user hovers over the visual settings panel.
/// </summary>
[Test]
public void PlayerLoaderSettingsHoverTest()
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer { BlockLoad = true })));
AddUntilStep("Wait for Player Loader to load", () => playerLoader?.IsLoaded ?? false);
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
AddStep("Trigger background preview", () =>
{
InputManager.MoveMouseTo(playerLoader.ScreenPos);
InputManager.MoveMouseTo(playerLoader.VisualSettingsPos);
});
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Stop background preview", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
waitForDim();
AddAssert("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && playerLoader.IsBlurCorrect());
}
/// <summary>
/// In the case of a user triggering the dim preview the instant player gets loaded, then moving the cursor off of the visual settings:
/// The OnHover of PlayerLoader will trigger, which could potentially cause visual settings to be unapplied unless checked for in PlayerLoader.
/// We need to check that in this scenario, the dim and blur is still properly applied after entering player.
/// </summary>
[Test]
public void PlayerLoaderTransitionTest()
{
performFullSetup();
AddStep("Trigger hover event", () => playerLoader.TriggerOnHover());
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Make sure the background is fully invisible (Alpha == 0) when the background should be disabled by the storyboard.
/// </summary>
[Test]
public void StoryboardBackgroundVisibilityTest()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
waitForDim();
AddAssert("Background is invisible, storyboard is visible", () => songSelect.IsBackgroundInvisible() && player.IsStoryboardVisible);
AddStep("Disable Storyboard", () =>
{
player.ReplacesBackground.Value = false;
player.StoryboardEnabled.Value = false;
});
waitForDim();
AddAssert("Background is visible, storyboard is invisible", () => songSelect.IsBackgroundVisible() && !player.IsStoryboardVisible);
}
/// <summary>
/// When exiting player, the screen that it suspends/exits to needs to have a fully visible (Alpha == 1) background.
/// </summary>
[Test]
public void StoryboardTransitionTest()
{
performFullSetup();
createFakeStoryboard();
AddStep("Exit to song select", () => player.Exit());
waitForDim();
AddAssert("Background is visible", () => songSelect.IsBackgroundVisible());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a background.
/// </summary>
[Test]
public void DisableUserDimBackgroundTest()
{
performFullSetup();
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Enable user dim", () => songSelect.DimEnabled.Value = false);
waitForDim();
AddAssert("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.IsUserBlurDisabled());
AddStep("Disable user dim", () => songSelect.DimEnabled.Value = true);
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a storyboard.
/// </summary>
[Test]
public void DisableUserDimStoryboardTest()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
AddStep("Enable user dim", () => player.DimmableStoryboard.EnableUserDim.Value = true);
AddStep("Set dim level to 1", () => songSelect.DimLevel.Value = 1f);
waitForDim();
AddAssert("Storyboard is invisible", () => !player.IsStoryboardVisible);
AddStep("Disable user dim", () => player.DimmableStoryboard.EnableUserDim.Value = false);
waitForDim();
AddAssert("Storyboard is visible", () => player.IsStoryboardVisible);
}
/// <summary>
/// Check if the visual settings container retains dim and blur when pausing
/// </summary>
[Test]
public void PauseTest()
{
performFullSetup(true);
AddStep("Pause", () => player.Pause());
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Unpause", () => player.Resume());
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Check if the visual settings container removes user dim when suspending <see cref="Player"/> for <see cref="SoloResults"/>
/// </summary>
[Test]
public void TransitionTest()
{
performFullSetup();
FadeAccessibleResults results = null;
AddStep("Transition to Results", () => player.Push(results =
new FadeAccessibleResults(new ScoreInfo { User = new User { Username = "osu!" } })));
AddUntilStep("Wait for results is current", () => results.IsCurrentScreen());
waitForDim();
AddAssert("Screen is undimmed, original background retained", () =>
songSelect.IsBackgroundUndimmed() && songSelect.IsBackgroundCurrent() && results.IsBlurCorrect());
}
/// <summary>
/// Check if background gets undimmed and unblurred when leaving <see cref="Player"/> for <see cref="PlaySongSelect"/>
/// </summary>
[Test]
public void TransitionOutTest()
{
performFullSetup();
AddStep("Exit to song select", () => player.Exit());
waitForDim();
AddAssert("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.IsBlurCorrect());
}
/// <summary>
/// Check if hovering on the visual settings dialogue after resuming from player still previews the background dim.
/// </summary>
[Test]
public void ResumeFromPlayerTest()
{
performFullSetup();
AddStep("Move mouse to Visual Settings", () => InputManager.MoveMouseTo(playerLoader.VisualSettingsPos));
AddStep("Resume PlayerLoader", () => player.Restart());
waitForDim();
AddAssert("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
waitForDim();
AddAssert("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && playerLoader.IsBlurCorrect());
}
private void waitForDim() => AddWaitStep("Wait for dim", 5);
private void createFakeStoryboard() => AddStep("Create storyboard", () =>
{
player.StoryboardEnabled.Value = false;
player.ReplacesBackground.Value = false;
player.DimmableStoryboard.Add(new OsuSpriteText
{
Size = new Vector2(500, 50),
Alpha = 1,
Colour = Color4.White,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = "THIS IS A STORYBOARD",
Font = new FontUsage(size: 50)
});
});
private void performFullSetup(bool allowPause = false)
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer(allowPause))));
AddUntilStep("Wait for Player Loader to load", () => playerLoader.IsLoaded);
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Wait for player to load", () => player.IsLoaded);
}
private void setupUserSettings()
{
AddUntilStep("Song select has selection", () => songSelect.Carousel?.SelectedBeatmap != null);
AddStep("Set default user settings", () =>
{
SelectedMods.Value = SelectedMods.Value.Concat(new[] { new OsuModNoFail() }).ToArray();
songSelect.DimLevel.Value = 0.7f;
songSelect.BlurLevel.Value = 0.4f;
});
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesets?.Dispose();
}
private class DummySongSelect : PlaySongSelect
{
protected override BackgroundScreen CreateBackground()
{
FadeAccessibleBackground background = new FadeAccessibleBackground(Beatmap.Value);
DimEnabled.BindTo(background.EnableUserDim);
return background;
}
public readonly Bindable<bool> DimEnabled = new Bindable<bool>();
public readonly Bindable<double> DimLevel = new BindableDouble();
public readonly Bindable<double> BlurLevel = new BindableDouble();
public new BeatmapCarousel Carousel => base.Carousel;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
config.BindWith(OsuSetting.DimLevel, DimLevel);
config.BindWith(OsuSetting.BlurLevel, BlurLevel);
}
public bool IsBackgroundDimmed() => ((FadeAccessibleBackground)Background).CurrentColour == OsuColour.Gray(1f - ((FadeAccessibleBackground)Background).CurrentDim);
public bool IsBackgroundUndimmed() => ((FadeAccessibleBackground)Background).CurrentColour == Color4.White;
public bool IsUserBlurApplied() => ((FadeAccessibleBackground)Background).CurrentBlur == new Vector2((float)BlurLevel.Value * BackgroundScreenBeatmap.USER_BLUR_FACTOR);
public bool IsUserBlurDisabled() => ((FadeAccessibleBackground)Background).CurrentBlur == new Vector2(0);
public bool IsBackgroundInvisible() => ((FadeAccessibleBackground)Background).CurrentAlpha == 0;
public bool IsBackgroundVisible() => ((FadeAccessibleBackground)Background).CurrentAlpha == 1;
public bool IsBlurCorrect() => ((FadeAccessibleBackground)Background).CurrentBlur == new Vector2(BACKGROUND_BLUR);
/// <summary>
/// Make sure every time a screen gets pushed, the background doesn't get replaced
/// </summary>
/// <returns>Whether or not the original background (The one created in DummySongSelect) is still the current background</returns>
public bool IsBackgroundCurrent() => ((FadeAccessibleBackground)Background).IsCurrentScreen();
}
private class FadeAccessibleResults : SoloResults
{
public FadeAccessibleResults(ScoreInfo score)
: base(score)
{
}
protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value);
public bool IsBlurCorrect() => ((FadeAccessibleBackground)Background).CurrentBlur == new Vector2(BACKGROUND_BLUR);
}
private class LoadBlockingTestPlayer : TestPlayer
{
protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value);
public new DimmableStoryboard DimmableStoryboard => base.DimmableStoryboard;
// Whether or not the player should be allowed to load.
public bool BlockLoad;
public Bindable<bool> StoryboardEnabled;
public readonly Bindable<bool> ReplacesBackground = new Bindable<bool>();
public readonly Bindable<bool> IsPaused = new Bindable<bool>();
public LoadBlockingTestPlayer(bool allowPause = true)
: base(allowPause)
{
}
public bool IsStoryboardVisible => DimmableStoryboard.ContentDisplayed;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, CancellationToken token)
{
while (BlockLoad && !token.IsCancellationRequested)
Thread.Sleep(1);
StoryboardEnabled = config.GetBindable<bool>(OsuSetting.ShowStoryboard);
ReplacesBackground.BindTo(Background.StoryboardReplacesBackground);
DrawableRuleset.IsPaused.BindTo(IsPaused);
}
}
private class TestPlayerLoader : PlayerLoader
{
public VisualSettings VisualSettingsPos => VisualSettings;
public BackgroundScreen ScreenPos => Background;
public TestPlayerLoader(Player player)
: base(() => player)
{
}
public void TriggerOnHover() => OnHover(new HoverEvent(new InputState()));
public bool IsBlurCorrect() => ((FadeAccessibleBackground)Background).CurrentBlur == new Vector2(BACKGROUND_BLUR);
protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value);
}
private class FadeAccessibleBackground : BackgroundScreenBeatmap
{
protected override DimmableBackground CreateFadeContainer() => dimmable = new TestDimmableBackground { RelativeSizeAxes = Axes.Both };
public Color4 CurrentColour => dimmable.CurrentColour;
public float CurrentAlpha => dimmable.CurrentAlpha;
public float CurrentDim => dimmable.DimLevel;
public Vector2 CurrentBlur => Background.BlurSigma;
private TestDimmableBackground dimmable;
public FadeAccessibleBackground(WorkingBeatmap beatmap)
: base(beatmap)
{
}
}
private class TestDimmableBackground : BackgroundScreenBeatmap.DimmableBackground
{
public Color4 CurrentColour => Content.Colour;
public float CurrentAlpha => Content.Alpha;
public new float DimLevel => base.DimLevel;
}
}
}
| |
// MsdnDocumenter.cs - a MSDN-like documenter
// Copyright (C) 2003 Don Kackman
// Parts copyright 2001 Kral Ferch, Jason Diamond
//
// 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
using System;
using System.Diagnostics;
using System.IO;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;
using NDoc.Core;
using NDoc.Core.Reflection;
using NDoc.Core.PropertyGridUI;
namespace NDoc.Documenter.NativeHtmlHelp2
{
/// <summary>
/// Specifies how the collection will be integrated with the help browser
/// </summary>
public enum TOCStyle
{
/// <summary>
/// Each root topic in the TOC is appears at the plug in point
/// </summary>
Flat,
/// <summary>
/// Creates a root node in the browser at the plug in point
/// </summary>
Hierarchical
}
/// <summary>
/// Config settings for the native Html Help 2 Documenter
/// </summary>
/// <remarks>
/// <para></para>
/// </remarks>
[DefaultProperty("OutputDirectory")]
public class NativeHtmlHelp2Config : BaseReflectionDocumenterConfig
{
private const string HTMLHELP2_CONFIG_CATEGORY = "Html Help 2 Settings";
private const string DEPLOYMENT_CATEGORY = "Html Help 2 Deployment";
private const string ADDITIONAL_CONTENT_CATEGORY = "Html Help 2 Additional Content";
/// <summary>Initializes a new instance of the NativeHtmlHelp2Config class.</summary>
public NativeHtmlHelp2Config( NativeHtmlHelp2DocumenterInfo info ) : base( info )
{
}
/// <summary>
/// Creates an instance of a documenter <see cref="IDocumenterConfig.CreateDocumenter"/>
/// </summary>
/// <returns>IDocumenter instance</returns>
public override IDocumenter CreateDocumenter()
{
return new NativeHtmlHelp2Documenter( this );
}
#region Main Settings properties
string _outputDirectory = string.Format( ".{0}doc{0}", Path.DirectorySeparatorChar );
/// <summary>Gets or sets the OutputDirectory property.</summary>
/// <remarks>The folder where the root of the HTML set will be located.
/// This can be absolute or relative from the .ndoc project file.</remarks>
[Category("Documentation Main Settings")]
[Description("The directory in which .html files and the .Hx* files will be generated.\nThis can be absolute or relative from the .ndoc project file.")]
[Editor(typeof(FolderNameEditor), typeof(UITypeEditor))]
public string OutputDirectory
{
get { return _outputDirectory; }
set
{
if ( value.IndexOfAny(new char[]{'#','?', ';'}) != -1)
{
throw new FormatException("Output Directory '" + value +
"' is not valid because it contains '#','?' or ';' which" +
" are reserved characters in HTML URLs.");
}
_outputDirectory = value;
if (!_outputDirectory.EndsWith( Path.DirectorySeparatorChar.ToString() ))
{
_outputDirectory += Path.DirectorySeparatorChar;
}
SetDirty();
}
}
void ResetOutputDirectory() { _outputDirectory = string.Format( ".{0}doc{0}", Path.DirectorySeparatorChar ); }
string _htmlHelpName = "Documentation";
/// <summary>Gets or sets the HtmlHelpName property.</summary>
/// <remarks>The HTML Help project file and the compiled HTML Help file
/// use this property plus the appropriate extension as names.</remarks>
[Category("Documentation Main Settings")]
[Description("The name of the HTML Help project and the Compiled HTML Help file.")]
public string HtmlHelpName
{
get { return _htmlHelpName; }
set
{
if (Path.GetExtension(value).ToLower() == ".hxs")
{
HtmlHelpName = Path.GetFileNameWithoutExtension(value);
}
else
{
_htmlHelpName = value;
}
SetDirty();
}
}
private string _Title = "An NDoc documented library";
/// <summary>Gets or sets the Title property.</summary>
/// <remarks>This is the title displayed at the top of every page.</remarks>
[Category("Documentation Main Settings")]
[Description("This is the title displayed at the top of every page.")]
public string Title
{
get { return _Title; }
set
{
_Title = value;
SetDirty();
}
}
#endregion
#region Deployment properties
bool _RegisterTitleWithNamespace = false;
/// <summary>
/// Gets or sets the RegisterTitleWithNamespace property
/// </summary>
/// <remarks>Should the compiled Html 2 title be registered on this
/// machine after it is compiled. Good for testing. (If true CollectionNamespace is required)</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("Should the compiled Html 2 title be registered on this machine after it is compiled. Good for testing. (If true CollectionNamespace is required).")]
[DefaultValue(false)]
public bool RegisterTitleWithNamespace
{
get { return _RegisterTitleWithNamespace; }
set
{
_RegisterTitleWithNamespace = value;
SetDirty();
}
}
string _CollectionNamespace = String.Empty;
/// <summary>
/// Gets or sets the CollectionNamespace property
/// </summary>
/// <remarks>The Html Help 2 registry namespace (avoid spaces).
/// Used in conjunction with GenerateCollectionFiles and RegisterTitleWithNamespace</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("The Html Help 2 registry namespace (avoid spaces). Used in conjunction with GenerateCollectionFiles and RegisterTitleWithNamespace.")]
[DefaultValue("")]
public string CollectionNamespace
{
get { return _CollectionNamespace; }
set
{
_CollectionNamespace = value;
SetDirty();
}
}
bool _RegisterTitleAsCollection = false;
/// <summary>
/// Gets or sets the RegisterTitleAsCollection property
/// </summary>
/// <remarks>If true the HxS title will be registered as a collection (ignored if RegisterTitleWithNamespace is true)</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("If true the HxS title will be registered as a collection on this machine (uses HtmlHelpName as the namespace name). Good for testing. (ignored if RegisterTitleWithNamespace is true)")]
[DefaultValue(false)]
public bool RegisterTitleAsCollection
{
get { return _RegisterTitleAsCollection; }
set
{
_RegisterTitleAsCollection = value;
SetDirty();
}
}
bool _GenerateCollectionFiles = false;
/// <summary>
/// Gets or sets the GenerateCollectionFiles property
/// </summary>
/// <remarks>If true creates collection files to contain the help title.
/// These all the title to be plugged into the Visual Studio help namespace during deployment.</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("If true creates collection files to contain the help title. These all the title to be plugged into the Visual Studio help namespace during deployment.")]
[DefaultValue(false)]
public bool GenerateCollectionFiles
{
get { return _GenerateCollectionFiles; }
set
{
_GenerateCollectionFiles = value;
SetDirty();
}
}
string _PlugInNamespace = "ms.vscc";
/// <summary>
/// Gets or sets the PlugInNamespace property
/// </summary>
/// <remarks>If GenerateCollectionFiles is true, the resulting
/// collection will be plugged into this namespace during deployment</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("If GenerateCollectionFiles is true, the resulting collection will be plugged into this namespace during deployment. ('ms.vscc' is the VS.NET help namespace)")]
[DefaultValue("ms.vscc")]
public string PlugInNamespace
{
get { return _PlugInNamespace; }
set
{
_PlugInNamespace = value;
SetDirty();
}
}
TOCStyle _CollectionTOCStyle = TOCStyle.Hierarchical;
/// <summary>
/// Gets or sets the CollectionTOCStyle property
/// </summary>
/// <remarks>Determines how the collection table of contents will appear in the help browser</remarks>
[Category(DEPLOYMENT_CATEGORY)]
[Description("Determines how the collection table of contents will appear in the help browser")]
[DefaultValue(TOCStyle.Hierarchical)]
public TOCStyle CollectionTOCStyle
{
get { return _CollectionTOCStyle; }
set
{
_CollectionTOCStyle = value;
SetDirty();
}
}
#endregion
#region HTML Help 2 properties
short _LangID = 1033;
/// <summary>Gets or sets the LangID property</summary>
/// <remarks>The language ID of the locale used by the compiled helpfile</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("The ID of the language the help file is in.")]
[DefaultValue((short)1033)]
[Editor(typeof(LangIdEditor), typeof(UITypeEditor))]
public short LangID
{
get { return _LangID; }
set
{
_LangID = value;
SetDirty();
}
}
bool _BuildSeparateIndexFile = false;
/// <summary>Gets or sets the BuildSeparateIndexFile property</summary>
/// <remarks>If true a seperate index file is generated, otherwise it is compiled into the HxS (recommended)</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("If true, create a separate index file (HxI), otherwise the index is compiled into the HxS file.")]
[DefaultValue(false)]
public bool BuildSeparateIndexFile
{
get { return _BuildSeparateIndexFile; }
set
{
_BuildSeparateIndexFile = value;
SetDirty();
}
}
string _DocSetList = "NETFramework";
/// <summary>Get's or sets the DocSetList property</summary>
/// <remarks>A comma-seperated list of DocSet filter identifiers in which topics in this title will included.</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("A comma-seperated list of DocSet filter identifiers in which topics in this title will included.")]
[DefaultValue("NETFramework")]
public string DocSetList
{
get { return _DocSetList; }
set
{
_DocSetList = value;
SetDirty();
}
}
string _Version = "1.0.0.0";
/// <summary>Get's or sets the version property</summary>
/// <remarks>The version number for the help file (#.#.#.#)</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("The version number for the help file (#.#.#.#)")]
[DefaultValue("1.0.0.0")]
public string Version
{
get { return _Version; }
set
{
_Version = value;
SetDirty();
}
}
bool _CreateFullTextIndex = true;
/// <summary>Gets or sets the CreateFullTextIndex property</summary>
/// <remarks>If true creates a full text index for the help file</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("If true creates a full text index for the help file")]
[DefaultValue(true)]
public bool CreateFullTextIndex
{
get { return _CreateFullTextIndex; }
set
{
_CreateFullTextIndex = value;
SetDirty();
}
}
bool _IncludeDefaultStopWordList = true;
/// <summary>Gets or sets the IncludeDefaultStopWordList property</summary>
/// <remarks>If true the default stop word list is compiled into the help file.
/// (A stop word list is a list of words that will be ignored during a full text search)</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("If true the default stop word list is compiled into the help file. (A stop word list is a " +
"list of words that will be ignored during a full text search)")]
[DefaultValue(true)]
public bool IncludeDefaultStopWordList
{
get { return _IncludeDefaultStopWordList; }
set
{
_IncludeDefaultStopWordList = value;
SetDirty();
}
}
FilePath _UseHelpNamespaceMappingFile = new FilePath();
/// <summary>Gets or sets the UseHelpNamespaceMappingFile property.</summary>
/// <remarks>If the documentation includes references to types registered in a seperate html help 2
/// namespace, supplying a mapping file allows XLinks to be created to topics within that namespace.
/// </remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("If the documentation includes references to types registered in a seperate html help 2 " +
"namespace, supplying a mapping file allows XLinks to be created to topics within that namespace. " +
"Refer to the user's guide for more information about XLinks to other topics.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select Namespace Mapping File", "XML files (*.xml)|*.xml|All files (*.*)|*.*")]
public FilePath UseHelpNamespaceMappingFile
{
get { return _UseHelpNamespaceMappingFile; }
set
{
if (_UseHelpNamespaceMappingFile.Path != value.Path)
{
_UseHelpNamespaceMappingFile = value;
SetDirty();
}
}
}
void ResetUseHelpNamespaceMappingFile() { _UseHelpNamespaceMappingFile = new FilePath(); }
string _HeaderHtml;
/// <summary>Gets or sets the HeaderHtml property.</summary>
/// <remarks>Raw HTML that is used as a page header instead of the default blue banner.
/// %FILE_NAME%\" is dynamically replaced by the name of the file for the current html page.
/// %TOPIC_TITLE%\" is dynamically replaced by the title of the current page.</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("Raw HTML that is used as a page header instead of the default blue banner. " +
"\"%FILE_NAME%\" is dynamically replaced by the name of the file for the current html page. " +
"\"%TOPIC_TITLE%\" is dynamically replaced by the title of the current page.")]
[Editor(typeof(TextEditor), typeof(UITypeEditor))]
public string HeaderHtml
{
get { return _HeaderHtml; }
set
{
_HeaderHtml = value;
SetDirty();
}
}
string _FooterHtml;
/// <summary>Gets or sets the FooterHtml property.</summary>
/// <remarks>Raw HTML that is used as a page footer instead of the default footer.
/// %FILE_NAME% is dynamically replaced by the name of the file for the current html page.
/// %ASSEMBLY_NAME% is dynamically replaced by the name of the assembly for the current page.
/// %ASSEMBLY_VERSION% is dynamically replaced by the version of the assembly for the current page.
/// %TOPIC_TITLE% is dynamically replaced by the title of the current page.</remarks>
[Category(HTMLHELP2_CONFIG_CATEGORY)]
[Description("Raw HTML that is used as a page footer instead of the default footer." +
"\"%FILE_NAME%\" is dynamically replaced by the name of the file for the current html page. " +
"\"%ASSEMBLY_NAME%\" is dynamically replaced by the name of the assembly for the current page. " +
"\"%ASSEMBLY_VERSION%\" is dynamically replaced by the version of the assembly for the current page. " +
"\"%TOPIC_TITLE%\" is dynamically replaced by the title of the current page.")]
[Editor(typeof(TextEditor), typeof(UITypeEditor))]
public string FooterHtml
{
get { return _FooterHtml; }
set
{
_FooterHtml = value;
SetDirty();
}
}
#endregion
#region Additonal content properties
FilePath _IntroductionPage = new FilePath();
/// <summary>Gets or sets the IntroductionPage property</summary>
/// <remarks>An HTML page that will be dispayed when the root TOC node is selected.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("An HTML page that will be dispayed when the root TOC node is selected")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select Introduction Page", "HTML files (*.html;*.htm)|*.html;*.htm|All files (*.*)|*.*")]
public FilePath IntroductionPage
{
get { return _IntroductionPage; }
set
{
if (_IntroductionPage.Path != value.Path)
{
_IntroductionPage = value;
SetDirty();
}
}
}
void ResetIntroductionPage() { _IntroductionPage = new FilePath(); }
FilePath _AboutPageInfo = new FilePath();
/// <summary>Gets or sets the AboutPageInfo property</summary>
/// <remarks>Displays product information in Help About.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("Displays product information in Help About.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select AboutPageInfo", "HTML files (*.html;*.htm)|*.html;*.htm|All files (*.*)|*.*")]
public FilePath AboutPageInfo
{
get { return _AboutPageInfo; }
set
{
if (_AboutPageInfo.Path != value.Path)
{
_AboutPageInfo = value;
SetDirty();
}
}
}
void ResetAboutPageInfo() { _AboutPageInfo = new FilePath(); }
FilePath _EmptyIndexTermPage = new FilePath();
/// <summary>Gets or sets the EmptyIndexTermPage property</summary>
/// <remarks>Displays when a user chooses a keyword index term that has
/// subkeywords but is not directly associated with a topic itself.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("Displays when a user chooses a keyword index term that has subkeywords but is not directly associated with a topic itself.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select EmptyIndexTerm Page", "HTML files (*.html;*.htm)|*.html;*.htm|All files (*.*)|*.*")]
public FilePath EmptyIndexTermPage
{
get { return _EmptyIndexTermPage; }
set
{
if (_EmptyIndexTermPage.Path != value.Path)
{
_EmptyIndexTermPage = value;
SetDirty();
}
}
}
void ResetEmptyIndexTermPage() { _EmptyIndexTermPage = new FilePath(); }
FilePath _NavFailPage = new FilePath();
/// <summary>Gets or sets the NavFailPage property</summary>
/// <remarks>Page that opens if a link to a topic or URL is broken.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("Opens if a link to a topic or URL is broken.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select NavFail Page", "HTML files (*.html;*.htm)|*.html;*.htm|All files (*.*)|*.*")]
public FilePath NavFailPage
{
get { return _NavFailPage; }
set
{
if (_NavFailPage.Path != value.Path)
{
_NavFailPage = value;
SetDirty();
}
}
}
void ResetNavFailPage() { _NavFailPage = new FilePath(); }
FilePath _AboutPageIconPage = new FilePath();
/// <summary>Gets or sets the AboutPageIconPage property</summary>
/// <remarks>HTML file that displays the Help About image.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("HTML file that displays the Help About image.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select AboutPageIcon Page", "HTML files (*.html;*.htm)|*.html;*.htm|All files (*.*)|*.*")]
public FilePath AboutPageIconPage
{
get { return _AboutPageIconPage; }
set
{
if (_AboutPageIconPage.Path != value.Path)
{
_AboutPageIconPage = value;
SetDirty();
}
}
}
void ResetAboutPageIconPage() { _AboutPageIconPage = new FilePath(); }
FolderPath _AdditionalContentResourceDirectory = new FolderPath();
/// <summary>Gets or sets the AdditionalContentResourceDirectory property</summary>
/// <remarks>Directory that contains resources (images etc.) used by the additional content pages.
/// This directory will be recursively compiled into the help file.</remarks>
[Category(ADDITIONAL_CONTENT_CATEGORY)]
[Description("Directory that contains resources (images etc.) used by the additional content pages. This directory will be recursively compiled into the help file.")]
[NDoc.Core.PropertyGridUI.FoldernameEditor.FolderDialogTitle("Select AdditionalContentResourceDirectory")]
public FolderPath AdditionalContentResourceDirectory
{
get { return _AdditionalContentResourceDirectory; }
set
{
if (_AdditionalContentResourceDirectory.Path != value.Path)
{
_AdditionalContentResourceDirectory = value;
SetDirty();
}
}
}
void ResetAdditionalContentResourceDirectory() { _AdditionalContentResourceDirectory = new FolderPath(); }
#endregion
#region Extensibility properties
FilePath _ExtensibilityStylesheet = new FilePath();
/// <summary>Gets or sets the ExtensibilityStylesheet property</summary>
/// <remarks>Path to an xslt stylesheet that contains templates for documenting extensibility tags.</remarks>
[Category("Extensibility")]
[Description("Path to an xslt stylesheet that contains templates for documenting extensibility tags. Refer to the NDoc user's guide for more details on extending NDoc.")]
[NDoc.Core.PropertyGridUI.FilenameEditor.FileDialogFilter
("Select Extensibility Stylesheet", "Stylesheet files (*.xslt)|*.xslt|All files (*.*)|*.*")]
public FilePath ExtensibilityStylesheet
{
get { return _ExtensibilityStylesheet; }
set
{
if (_ExtensibilityStylesheet != value)
{
_ExtensibilityStylesheet = value;
SetDirty();
}
}
}
void ResetExtensibilityStylesheet() { _ExtensibilityStylesheet = new FilePath(); }
#endregion
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
protected override string HandleUnknownPropertyType(string name, string value)
{
string FailureMessages = "";
if (String.Compare(name, "LinkToSdkDocVersion", true) == 0)
{
Trace.WriteLine("WARNING: " + base.DocumenterInfo.Name + " Configuration - property 'LinkToSdkDocVersion' is OBSOLETE. Please use new property 'SdkDocVersion'\n");
Project.SuspendDirtyCheck=false;
FailureMessages += base.ReadProperty("SdkDocVersion", value);
Project.SuspendDirtyCheck=true;
}
else
{
// if we don't know how to handle this, let the base class have a go
FailureMessages = base.HandleUnknownPropertyType(name, value);
}
return FailureMessages;
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Schema.Testing.Documents;
using Shouldly;
using Xunit;
using Issue = Marten.Schema.Testing.Documents.Issue;
namespace Marten.Schema.Testing
{
public class DocumentCleanerTests : IntegrationContext
{
private IDocumentCleaner theCleaner => theStore.Advanced.Clean;
[Fact]
public void clean_table()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
theSession.Store(new Target { Number = 5 });
theSession.Store(new Target { Number = 6 });
theSession.SaveChanges();
theSession.Dispose();
theCleaner.DeleteDocumentsByType(typeof(Target));
using (var session = theStore.QuerySession())
{
session.Query<Target>().Count().ShouldBe(0);
}
}
[Fact]
public void delete_all_documents()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new User());
theSession.Store(new Company());
theSession.Store(new Issue());
theSession.SaveChanges();
theSession.Dispose();
theCleaner.DeleteAllDocuments();
using (var session = theStore.QuerySession())
{
session.Query<Target>().Count().ShouldBe(0);
session.Query<User>().Count().ShouldBe(0);
session.Query<Issue>().Count().ShouldBe(0);
session.Query<Company>().Count().ShouldBe(0);
}
}
[Fact]
public async Task completely_remove_document_type()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.SaveChanges();
theSession.Dispose();
var tableName = theStore.Storage.MappingFor(typeof(Target)).TableName;
(await theStore.Tenancy.Default.DocumentTables()).Contains(tableName)
.ShouldBeTrue();
theCleaner.CompletelyRemove(typeof(Target));
(await theStore.Tenancy.Default.DocumentTables()).Contains(tableName)
.ShouldBeFalse();
}
[Fact]
public async Task completely_remove_document_removes_the_upsert_command_too()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
await theSession.SaveChangesAsync();
var upsertName = theStore.Storage.MappingFor(typeof(Target)).As<DocumentMapping>().UpsertFunction;
(await theStore.Tenancy.Default.Functions()).ShouldContain(upsertName);
await theCleaner.CompletelyRemoveAsync(typeof(Target));
(await theStore.Tenancy.Default.Functions()).ShouldNotContain(upsertName);
}
[Fact]
public async Task completely_remove_everything()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new User());
theSession.Store(new Company());
theSession.Store(new Issue());
await theSession.SaveChangesAsync();
theSession.Dispose();
await theCleaner.CompletelyRemoveAllAsync();
var tables = await theStore.Tenancy.Default.DocumentTables();
tables.ShouldBeEmpty();
var functions = await theStore.Tenancy.Default.Functions();
functions.Where(x => x.Name != "mt_immutable_timestamp" || x.Name != "mt_immutable_timestamptz")
.ShouldBeEmpty();
}
[Fact]
public void delete_all_event_data()
{
var streamId = Guid.NewGuid();
theSession.Events.StartStream<Quest>(streamId, new QuestStarted());
theSession.SaveChanges();
theCleaner.DeleteAllEventData();
theSession.Events.QueryRawEventDataOnly<QuestStarted>().ShouldBeEmpty();
theSession.Events.FetchStream(streamId).ShouldBeEmpty();
}
[Fact]
public async Task delete_all_event_data_async()
{
var streamId = Guid.NewGuid();
theSession.Events.StartStream<Quest>(streamId, new QuestStarted());
await theSession.SaveChangesAsync();
await theCleaner.DeleteAllEventDataAsync();
theSession.Events.QueryRawEventDataOnly<QuestStarted>().ShouldBeEmpty();
(await theSession.Events.FetchStreamAsync(streamId)).ShouldBeEmpty();
}
private static void ShouldBeEmpty<T>(T[] documentTables)
{
var stillInDatabase = string.Join(",", documentTables);
documentTables.Any().ShouldBeFalse(stillInDatabase);
}
[Fact]
public void delete_except_types()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new User());
theSession.Store(new Company());
theSession.Store(new Issue());
theSession.SaveChanges();
theSession.Dispose();
theCleaner.DeleteDocumentsExcept(typeof(Target), typeof(User));
using (var session = theStore.OpenSession())
{
// Not cleaned off
session.Query<Target>().Count().ShouldBe(2);
session.Query<User>().Count().ShouldBe(1);
// Should be cleaned off
session.Query<Issue>().Count().ShouldBe(0);
session.Query<Company>().Count().ShouldBe(0);
}
}
[Fact]
public async Task delete_except_types_async()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new User());
theSession.Store(new Company());
theSession.Store(new Issue());
await theSession.SaveChangesAsync();
theSession.Dispose();
await theCleaner.DeleteDocumentsExceptAsync(typeof(Target), typeof(User));
using var session = theStore.OpenSession();
// Not cleaned off
session.Query<Target>().Count().ShouldBe(2);
session.Query<User>().Count().ShouldBe(1);
// Should be cleaned off
session.Query<Issue>().Count().ShouldBe(0);
session.Query<Company>().Count().ShouldBe(0);
}
[Fact]
public async Task CanCleanSequences()
{
StoreOptions(opts =>
{
opts.Events.AddEventType(typeof(MembersJoined));
});
await theStore.Schema.ApplyAllConfiguredChangesToDatabaseAsync();
var allSchemas = theStore.Storage.AllSchemaNames();
int GetSequenceCount(IDocumentStore store)
{
using var session = store.QuerySession();
return session.Query<int>(@"select count(*) from information_schema.sequences s
where s.sequence_name like ? and s.sequence_schema = any(?);", "mt_%", allSchemas).First();
}
GetSequenceCount(theStore).ShouldBeGreaterThan(0);
await theStore.Advanced.Clean.CompletelyRemoveAllAsync();
GetSequenceCount(theStore).ShouldBe(0);
}
}
}
| |
// 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.Linq;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeClassTests : AbstractFileCodeElementTests
{
public FileCodeClassTests()
: base(@"using System;
public abstract class Foo : IDisposable, ICloneable
{
}
[Serializable]
public class Bar
{
int a;
public int A
{
get
{
return a;
}
}
}")
{
}
private CodeClass GetCodeClass(params object[] path)
{
return (CodeClass)GetCodeElement(path);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsAbstract()
{
CodeClass cc = GetCodeClass("Foo");
Assert.True(cc.IsAbstract);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Bases()
{
CodeClass cc = GetCodeClass("Foo");
var bases = cc.Bases;
Assert.Equal(bases.Count, 1);
Assert.Equal(bases.Cast<CodeElement>().Count(), 1);
Assert.NotNull(bases.Parent);
var parentClass = bases.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal(parentClass.FullName, "Foo");
Assert.True(bases.Item("object") is CodeClass);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void ImplementedInterfaces()
{
CodeClass cc = GetCodeClass("Foo");
var interfaces = cc.ImplementedInterfaces;
Assert.Equal(interfaces.Count, 2);
Assert.Equal(interfaces.Cast<CodeElement>().Count(), 2);
Assert.NotNull(interfaces.Parent);
var parentClass = interfaces.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal(parentClass.FullName, "Foo");
Assert.True(interfaces.Item("System.IDisposable") is CodeInterface);
Assert.True(interfaces.Item("ICloneable") is CodeInterface);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void KindTest()
{
CodeClass cc = GetCodeClass("Foo");
Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(10, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(8, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, startPoint.Line);
Assert.Equal(14, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, endPoint.Line);
Assert.Equal(15, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(19, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, endPoint.Line);
Assert.Equal(17, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
CodeClass testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(19, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint startPoint = testObject.StartPoint;
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[ConditionalWpfFact(typeof(x86))]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
CodeClass testObject = GetCodeClass("Bar");
TextPoint endPoint = testObject.EndPoint;
Assert.Equal(19, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
}
}
| |
/*
* 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.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Security.Policy;
using System.IO;
using System.Xml;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Yengine;
using OpenSim.Region.Framework.Scenes;
using log4net;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
// This class exists in the main app domain
//
namespace OpenSim.Region.ScriptEngine.Yengine
{
/**
* @brief Which queue it is in as far as running is concerned,
* ie, m_StartQueue, m_YieldQueue, m_SleepQueue, etc.
* Allowed transitions:
* Starts in CONSTRUCT when constructed
* CONSTRUCT->ONSTARTQ : only by thread that constructed and compiled it
* IDLE->ONSTARTQ,RESETTING : by any thread but must have m_QueueLock when transitioning
* ONSTARTQ->RUNNING,RESETTING : only by thread that removed it from m_StartQueue
* ONYIELDQ->RUNNING,RESETTING : only by thread that removed it from m_YieldQueue
* ONSLEEPQ->REMDFROMSLPQ : by any thread but must have m_SleepQueue when transitioning
* REMDFROMSLPQ->ONYIELDQ,RESETTING : only by thread that removed it from m_SleepQueue
* RUNNING->whatever1 : only by thread that transitioned it to RUNNING
* whatever1 = IDLE,ONSLEEPQ,ONYIELDQ,ONSTARTQ,SUSPENDED,FINISHED
* FINSHED->whatever2 : only by thread that transitioned it to FINISHED
* whatever2 = IDLE,ONSTARTQ,DISPOSED
* SUSPENDED->ONSTARTQ : by any thread (NOT YET IMPLEMENTED, should be under some kind of lock?)
* RESETTING->ONSTARTQ : only by the thread that transitioned it to RESETTING
*/
public enum XMRInstState
{
CONSTRUCT, // it is being constructed
IDLE, // nothing happening (finished last event and m_EventQueue is empty)
ONSTARTQ, // inserted on m_Engine.m_StartQueue
RUNNING, // currently being executed by RunOne()
ONSLEEPQ, // inserted on m_Engine.m_SleepQueue
REMDFROMSLPQ, // removed from m_SleepQueue but not yet on m_YieldQueue
ONYIELDQ, // inserted on m_Engine.m_YieldQueue
FINISHED, // just finished handling an event
SUSPENDED, // m_SuspendCount > 0
RESETTING, // being reset via external call
DISPOSED // has been disposed
}
public partial class XMRInstance: XMRInstAbstract, IDisposable
{
/******************************************************************\
* This module contains the instance variables for XMRInstance. *
\******************************************************************/
public const int MAXEVENTQUEUE = 64;
public static readonly DetectParams[] zeroDetectParams = new DetectParams[0];
public static readonly object[] zeroObjectArray = new object[0];
public static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public XMRInstance m_NextInst; // used by XMRInstQueue
public XMRInstance m_PrevInst;
// For a given m_Item.AssetID, do we have the compiled object code and where
// is it?
public static object m_CompileLock = new object();
private static Dictionary<string, ScriptObjCode> m_CompiledScriptObjCode = new Dictionary<string, ScriptObjCode>();
public XMRInstState m_IState;
public bool m_ForceRecomp = false;
public SceneObjectPart m_Part = null;
public uint m_LocalID = 0;
public TaskInventoryItem m_Item = null;
public UUID m_ItemID;
public UUID m_PartUUID;
private string m_CameFrom;
private string m_ScriptObjCodeKey;
private Yengine m_Engine = null;
private string m_ScriptBasePath;
private string m_StateFileName;
public string m_SourceCode;
public bool m_PostOnRez;
private DetectParams[] m_DetectParams = null;
public int m_StartParam = 0;
public StateSource m_StateSource;
public string m_DescName;
private bool[] m_HaveEventHandlers;
public int m_StackSize;
public int m_HeapSize;
private ArrayList m_CompilerErrors;
private DateTime m_LastRanAt = DateTime.MinValue;
private string m_RunOnePhase = "hasn't run";
private string m_CheckRunPhase = "hasn't checked";
public int m_InstEHEvent = 0; // number of events dequeued (StartEventHandler called)
public int m_InstEHSlice = 0; // number of times handler timesliced (ResumeEx called)
public double m_CPUTime = 0; // accumulated CPU time (milliseconds)
public double m_SliceStart = 0; // when did current exec start
// If code needs to have both m_QueueLock and m_RunLock,
// be sure to lock m_RunLock first then m_QueueLock, as
// that is the order used in RunOne().
// These locks are currently separated to allow the script
// to call API routines that queue events back to the script.
// If we just had one lock, then the queuing would deadlock.
// guards m_DetachQuantum, m_EventQueue, m_EventCounts, m_Running, m_Suspended
public Object m_QueueLock = new Object();
// true iff allowed to accept new events
public bool m_Running = true;
// queue of events that haven't been acted upon yet
public LinkedList<EventParams> m_EventQueue = new LinkedList<EventParams>();
// number of events of each code currently in m_EventQueue.
private int[] m_EventCounts = new int[(int)ScriptEventCode.Size];
// locked whilst running on the microthread stack (or about to run on it or just ran on it)
private Object m_RunLock = new Object();
// script won't step while > 0. bus-atomic updates only.
private int m_SuspendCount = 0;
// don't run any of script until this time
// or until one of these events are queued
public DateTime m_SleepUntil = DateTime.MinValue;
public int m_SleepEventMask1 = 0;
public int m_SleepEventMask2 = 0;
private XMRLSL_Api m_XMRLSLApi;
/*
* Makes sure migration data version is same on both ends.
*/
public static byte migrationVersion = 10;
// Incremented each time script gets reset.
public int m_ResetCount = 0;
// Scripts start suspended now. This means that event queues will
// accept events, but will not actually run them until the core
// tells it it's OK. This is needed to prevent loss of link messages
// in complex objects, where no event can be allowed to run until
// all possible link message receivers' queues are established.
// Guarded by m_QueueLock.
public bool m_Suspended = true;
// We really don't want to save state for a script that hasn't had
// a chance to run, because it's state will be blank. That would
// cause attachment state loss.
public bool m_HasRun = false;
// When llDie is executed within the attach(NULL_KEY) event of
// a script being detached to inventory, the DeleteSceneObject call
// it causes will delete the script instances before their state can
// be saved. Therefore, the instance needs to know that it's being
// detached to inventory, rather than to ground.
// Also, the attach(NULL_KEY) event needs to run with priority, and
// it also needs to have a limited quantum.
// If this is nonzero, we're detaching to inventory.
// Guarded by m_QueueLock.
private int m_DetachQuantum = 0;
// Finally, we need to wait until the quantum is done, or the script
// suspends itself. This should be efficient, so we use an event
// for it instead of spinning busy.
// It's born ready, but will be reset when the detach is posted.
// It will then be set again on suspend/completion
private ManualResetEvent m_DetachReady = new ManualResetEvent(true);
}
}
| |
// 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.Linq;
namespace Microsoft.CodeAnalysis.Editing
{
/// <summary>
/// An editor for making changes to a syntax tree.
/// </summary>
public class SyntaxEditor
{
private readonly SyntaxGenerator _generator;
private readonly List<Change> _changes;
/// <summary>
/// Creates a new <see cref="SyntaxEditor"/> instance.
/// </summary>
public SyntaxEditor(SyntaxNode root, Workspace workspace)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
OriginalRoot = root ?? throw new ArgumentNullException(nameof(root));
_generator = SyntaxGenerator.GetGenerator(workspace, root.Language);
_changes = new List<Change>();
}
internal SyntaxEditor(SyntaxNode root, SyntaxGenerator generator)
{
OriginalRoot = root ?? throw new ArgumentNullException(nameof(root));
_generator = generator;
_changes = new List<Change>();
}
/// <summary>
/// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed.
/// </summary>
public SyntaxNode OriginalRoot { get; }
/// <summary>
/// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s.
/// </summary>
public SyntaxGenerator Generator
{
get { return _generator; }
}
/// <summary>
/// Returns the changed root node.
/// </summary>
public SyntaxNode GetChangedRoot()
{
var nodes = Enumerable.Distinct(_changes.Select(c => c.Node));
var newRoot = OriginalRoot.TrackNodes(nodes);
foreach (var change in _changes)
{
newRoot = change.Apply(newRoot, _generator);
}
return newRoot;
}
/// <summary>
/// Makes sure the node is tracked, even if it is not changed.
/// </summary>
public void TrackNode(SyntaxNode node)
{
CheckNodeInTree(node);
_changes.Add(new NoChange(node));
}
/// <summary>
/// Remove the node from the tree.
/// </summary>
/// <param name="node">The node to remove that currently exists as part of the tree.</param>
public void RemoveNode(SyntaxNode node)
{
RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions);
}
/// <summary>
/// Remove the node from the tree.
/// </summary>
/// <param name="node">The node to remove that currently exists as part of the tree.</param>
/// <param name="options">Options that affect how node removal works.</param>
public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options)
{
CheckNodeInTree(node);
_changes.Add(new RemoveChange(node, options));
}
/// <summary>
/// Replace the specified node with a node produced by the function.
/// </summary>
/// <param name="node">The node to replace that already exists in the tree.</param>
/// <param name="computeReplacement">A function that computes a replacement node.
/// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param>
public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement)
{
CheckNodeInTree(node);
_changes.Add(new ReplaceChange(node, computeReplacement));
}
internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument)
{
CheckNodeInTree(node);
_changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument));
}
/// <summary>
/// Replace the specified node with a different node.
/// </summary>
/// <param name="node">The node to replace that already exists in the tree.</param>
/// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param>
public void ReplaceNode(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
if (node == newNode)
{
return;
}
this.ReplaceNode(node, (n, g) => newNode);
}
/// <summary>
/// Insert the new nodes before the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param>
/// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes)
{
CheckNodeInTree(node);
_changes.Add(new InsertChange(node, newNodes, isBefore: true));
}
/// <summary>
/// Insert the new node before the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param>
/// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertBefore(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
this.InsertBefore(node, new[] { newNode });
}
/// <summary>
/// Insert the new nodes after the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param>
/// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes)
{
CheckNodeInTree(node);
_changes.Add(new InsertChange(node, newNodes, isBefore: false));
}
/// <summary>
/// Insert the new node after the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param>
/// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertAfter(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
this.InsertAfter(node, new[] { newNode });
}
private void CheckNodeInTree(SyntaxNode node)
{
if (!OriginalRoot.Contains(node))
{
throw new ArgumentException(Microsoft.CodeAnalysis.WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node));
}
}
private abstract class Change
{
internal readonly SyntaxNode Node;
public Change(SyntaxNode node)
{
this.Node = node;
}
public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator);
}
private class NoChange : Change
{
public NoChange(SyntaxNode node)
: base(node)
{
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
return root;
}
}
private class RemoveChange : Change
{
private readonly SyntaxRemoveOptions _options;
public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options)
: base(node)
{
_options = options;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
return generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options);
}
}
private class ReplaceChange : Change
{
private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode> _modifier;
public ReplaceChange(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> modifier)
: base(node)
{
_modifier = modifier;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
var current = root.GetCurrentNode(this.Node);
var newNode = _modifier(current, generator);
return generator.ReplaceNode(root, current, newNode);
}
}
private class ReplaceChange<TArgument> : Change
{
private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier;
private readonly TArgument _argument;
public ReplaceChange(
SyntaxNode node,
Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier,
TArgument argument)
: base(node)
{
_modifier = modifier;
_argument = argument;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
var current = root.GetCurrentNode(this.Node);
var newNode = _modifier(current, generator, _argument);
return generator.ReplaceNode(root, current, newNode);
}
}
private class InsertChange : Change
{
private readonly List<SyntaxNode> _newNodes;
private readonly bool _isBefore;
public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore)
: base(node)
{
_newNodes = newNodes.ToList();
_isBefore = isBefore;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
if (_isBefore)
{
return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes);
}
else
{
return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes);
}
}
}
}
}
| |
using System;
using System.Data;
using System.ComponentModel;
namespace Provider.VistaDB
{
/// <summary>
/// Command object.
/// </summary>
[DesignTimeVisible(true)]
public class VistaDBCommand: Component, IDbCommand
{
private VistaDBConnection connection;
private VistaDBTransaction vistaDBTransaction;
private string commandText;
private VistaDBSQLQuery sqlQuery;
private int commandTimeOut = 0;
/// <summary>
/// Gets or sets how command results are applied to the DataRow when used by the Update method of the VistaDBDataAdapter.
/// </summary>
public UpdateRowSource updatedRowSource = UpdateRowSource.None;
/// <summary>
/// Represents a collection of parameters relevant to a VistaDBCommand as well as their respective mappings to
/// columns in a DataSet. This class cannot be inherited.For a list of all members of this type,
/// see VistaDBParameterCollection Members.
/// </summary>
public VistaDBParameterCollection parameters = new VistaDBParameterCollection();
/// <summary>
/// Constructor.
/// </summary>
public VistaDBCommand()
{
InitClass();
commandText = "";
}
//' Implement other constructors here.
/// <summary>
/// Overloaded. Initializes a new instance of the VistaDBCommand class.
/// </summary>
public VistaDBCommand(string cmdText)
{
InitClass();
commandText = cmdText;
}
/// <summary>
/// Overloaded. Initializes a new instance of the VistaDBCommand class with a connection.
/// </summary>
public VistaDBCommand(string cmdText, VistaDBConnection connection)
{
InitClass();
commandText = cmdText;
this.connection = connection;
}
/// <summary>
/// Overloaded. Initializes a new instance of the VistaDBCommand class with a connection and transaction.
/// </summary>
public VistaDBCommand(string cmdText, VistaDBConnection connection, VistaDBTransaction txn)
{
InitClass();
commandText = cmdText;
this.connection = connection;
vistaDBTransaction = txn;
}
/// <summary>
/// VistaDBCommand destructor
/// </summary>
~VistaDBCommand()
{
Dispose(false);
}
/// <summary>
/// Used internally to initialize the object.
/// </summary>
public void InitClass()
{
VistaDBErrorMsgs.SetErrorFunc();
}
/// <summary>
/// Gets or sets the V-SQL statement to execute at the data source.
/// </summary>
[Browsable(true), Editor("VistaDB.Designer.VistaDBQueryEditor, VistaDB.Designer.VS2003", "System.Drawing.Design.UITypeEditor")]
public string CommandText//IDbCommand.CommandText
{
get
{
return commandText;
}
set
{
commandText = value;
}
}
/// <summary>
/// Gets or sets the wait time before terminating the attempt to execute a command and generating an error.
/// </summary>
public int CommandTimeout//IDbCommand.CommandTimeout
{
get
{
return commandTimeOut;
}
set
{
commandTimeOut = value;
}
}
/// <summary>
/// Gets or sets a value indicating how the CommandText property is to be interpreted.
/// </summary>
public CommandType CommandType//IDbCommand.CommandType
{
get
{
return CommandType.Text;
}
set
{
if(value != CommandType.Text)
throw new NotSupportedException();
}
}
IDbConnection IDbCommand.Connection
{
get
{
return (IDbConnection)connection;
}
set
{
if(connection != value)
{
connection = (VistaDBConnection)value;
sqlQuery = null;
}
}
}
/// <summary>
/// Gets or sets the VistaDBConnection used by this instance of the VistaDBCommand.
/// </summary>
[TypeConverter(typeof(ComponentConverter))]
public VistaDBConnection Connection
{
get
{
return connection;
}
set
{
if(connection != value)
{
connection = value;
sqlQuery = null;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
IDataParameterCollection IDbCommand.Parameters
{
get
{
return (VistaDBParameterCollection)parameters;
}
}
/// <summary>
/// Gets the VistaDBParameterCollection.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public VistaDBParameterCollection Parameters
{
get
{
return parameters;
}
}
[Browsable(false)]
IDbTransaction IDbCommand.Transaction
{
get
{
return vistaDBTransaction;
}
set
{
vistaDBTransaction = (VistaDBTransaction)value;
}
}
/// <summary>
/// Gets or sets the VistaDBTransaction within which the VistaDBCommand executes.
/// </summary>
[Browsable(false)]
public VistaDBTransaction Transaction
{
get
{
return vistaDBTransaction;
}
set
{
vistaDBTransaction = value;
}
}
/// <summary>
/// Gets or sets how command results are applied to the DataRow when used by the Update method of the VistaDBDataAdapter.
/// </summary>
public UpdateRowSource UpdatedRowSource//IDbCommand.UpdatedRowSource
{
get
{
return updatedRowSource;
}
set
{
updatedRowSource = value;
}
}
/// <summary>
/// Attempts to cancel the execution of a SqlCommand.
/// </summary>
public void Cancel()//IDbCommand.Cancel
{
throw new NotSupportedException();
}
IDbDataParameter IDbCommand.CreateParameter()//IDbCommand.CreateParameter
{
return new VistaDBParameter();
}
/// <summary>
/// Creates a new instance of a VistaDBParameter object.
/// </summary>
public VistaDBParameter CreateParameter()
{
return new VistaDBParameter();
}
/// <summary>
/// Overloaded. Releases the resources used by the component.
/// </summary>
/// <param name="disposing">True for external disposing</param>
protected override void Dispose(bool disposing)
{
if(sqlQuery != null)
sqlQuery.DropQuery();
sqlQuery = null;
base.Dispose(disposing);
}
/// <summary>
/// Executes a V-SQL statement against the connection and returns the number of rows affected.
/// </summary>
public int ExecuteNonQuery()//IDbCommand.ExecuteNonQuery
{
if((connection == null || connection.State != ConnectionState.Open)&&
(commandText.Substring(0, 6).ToUpper() != "CREATE"))
throw new VistaDBException(VistaDBErrorCodes.ConnectionInvalid);
if( sqlQuery == null )
sqlQuery = connection.VistaDBSQL.NewSQLQuery();
sqlQuery.SQL = commandText;
AddSQLParameter(sqlQuery);
sqlQuery.ExecSQL();
return sqlQuery.RowsAffected;
}
IDataReader IDbCommand.ExecuteReader()//IDbCommand.ExecuteReader
{
return this.ExecuteReader();
}
/// <summary>
/// Overloaded. Sends the CommandText to the Connection and builds a VistaDBDataReader object.
/// </summary>
public VistaDBDataReader ExecuteReader()
{
VistaDBSQLQuery query;
string s;
s = commandText.TrimStart(' ');
s = (s.Substring(0,6)).ToUpper();
if( s == "INSERT" || s == "UPDATE" || s == "DELETE" )
{
ExecuteNonQuery();
return null;
}
if(connection == null || connection.State != ConnectionState.Open)
throw new VistaDBException(VistaDBErrorCodes.ConnectionInvalid);
query = connection.VistaDBSQL.NewSQLQuery();
query.SQL = commandText;
AddSQLParameter(query);
query.Open();
return new VistaDBDataReader(query, true, null);
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)//IDbCommand.ExecuteReader
{
return this.ExecuteReader(behavior);
}
/// <summary>
/// Overloaded. Sends the CommandText to the Connection and builds a VistaDBDataReader object, passing in CommandBehavior.
/// </summary>
public VistaDBDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
VistaDBSQLQuery query;
string s;
VistaDBConnection conn;
bool fillData;
s = commandText.TrimStart(' ');
s = (s.Substring(0,6)).ToUpper();
if( s == "INSERT" || s == "UPDATE" || s == "DELETE" )
{
int rowsAffected = ExecuteNonQuery();
return new VistaDBDataReader(rowsAffected);
}
if(connection == null || connection.State != ConnectionState.Open)
throw new VistaDBException(VistaDBErrorCodes.ConnectionInvalid);
query = connection.VistaDBSQL.NewSQLQuery();
query.SQL = commandText;
AddSQLParameter(query);
query.Open();
conn = (int)(behavior & CommandBehavior.CloseConnection) != 0 ? this.connection: null;
fillData = ((int)(behavior & CommandBehavior.KeyInfo) == 0) && ((int)(behavior & CommandBehavior.SchemaOnly) == 0);
return new VistaDBDataReader(query, fillData, conn);
}
/// <summary>
/// Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.
/// </summary>
public object ExecuteScalar()//IDbCommand.ExecuteScalar
{
VistaDBSQLQuery query;
object res;
if(connection == null || connection.State != ConnectionState.Open)
throw new VistaDBException(VistaDBErrorCodes.ConnectionInvalid);
query = connection.VistaDBSQL.NewSQLQuery();
query.SQL = commandText;
AddSQLParameter(query);
query.Open();
if(!query.Opened || query.Eof)
return null;
res = query.GetValue(0);
query.Close();
query.DropQuery();
return res;
}
private void AddSQLParameter(VistaDBSQLQuery query)
{
VistaDBType vdbType;
foreach(VistaDBParameter vp in Parameters)
{
vdbType = vp.VistaDBType;
if( vp.Value == null || vp.Value == DBNull.Value )
{
query.SetParamNull(vp.ParameterName, vdbType);
}
else
{
switch(vdbType)
{
case VistaDBType.Character:
query.SetParameter(vp.ParameterName, VistaDBType.Character, (string)vp.Value);
break;
case VistaDBType.Date:
query.SetParameter(vp.ParameterName, VistaDBType.Date, (DateTime)vp.Value);
break;
case VistaDBType.DateTime:
query.SetParameter(vp.ParameterName, VistaDBType.DateTime, (DateTime)vp.Value);
break;
case VistaDBType.Int32:
query.SetParameter(vp.ParameterName, VistaDBType.Int32, (int)vp.Value);
break;
case VistaDBType.Int64:
query.SetParameter(vp.ParameterName, VistaDBType.Int64, (long)vp.Value);
break;
case VistaDBType.Boolean:
query.SetParameter(vp.ParameterName, VistaDBType.Boolean, (bool)vp.Value);
break;
case VistaDBType.Double:
query.SetParameter(vp.ParameterName, VistaDBType.Double, (double)vp.Value);
break;
case VistaDBType.Varchar:
query.SetParameter(vp.ParameterName, VistaDBType.Varchar, (string)vp.Value);
break;
case VistaDBType.Memo:
query.SetParameter(vp.ParameterName, VistaDBType.Memo, (string)vp.Value);
break;
case VistaDBType.Blob:
query.SetParameter(vp.ParameterName, VistaDBType.Blob, vp.Value);
break;
case VistaDBType.Picture:
query.SetParameter(vp.ParameterName, VistaDBType.Picture, vp.Value);
break;
case VistaDBType.Currency:
query.SetParameter(vp.ParameterName, VistaDBType.Currency, (decimal)vp.Value);
break;
case VistaDBType.Guid:
query.SetParameter(vp.ParameterName, VistaDBType.Guid, (Guid)vp.Value);
break;
}
}
}
}
/// <summary>
/// Creates a prepared version of the command on an instance of VistaDB.
/// </summary>
public void Prepare()
{
if(connection == null || connection.State != ConnectionState.Open)
throw new VistaDBException( VistaDBErrorCodes.ConnectionInvalid );
}
}
}
| |
// 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.Text;
using System.Globalization;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections;
using System.Text.RegularExpressions;
namespace System.Xml
{
// ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods
internal enum ExceptionType
{
ArgumentException,
XmlException,
}
// Options for serializing and deserializing DateTime
public enum XmlDateTimeSerializationMode
{
Local,
Utc,
Unspecified,
RoundtripKind,
}
/// <devdoc>
/// Encodes and decodes XML names according to
/// the "Encoding of arbitrary Unicode Characters in XML Names" specification.
/// </devdoc>
public static class XmlConvert
{
//
// Static fields with implicit initialization
//
private static XmlCharType s_xmlCharType = XmlCharType.Instance;
/// <devdoc>
/// <para>
/// Converts names, such
/// as DataTable or
/// DataColumn names, that contain characters that are not permitted in
/// XML names to valid names.</para>
/// </devdoc>
public static string EncodeName(string name)
{
return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/);
}
/// <devdoc>
/// <para> Verifies the name is valid
/// according to production [7] in the XML spec.</para>
/// </devdoc>
public static string EncodeNmToken(string name)
{
return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/);
}
/// <devdoc>
/// <para>Converts names, such as DataTable or DataColumn names, that contain
/// characters that are not permitted in XML names to valid names.</para>
/// </devdoc>
public static string EncodeLocalName(string name)
{
return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/);
}
/// <devdoc>
/// <para>
/// Transforms an XML name into an object name (such as DataTable or DataColumn).</para>
/// </devdoc>
public static string DecodeName(string name)
{
if (name == null || name.Length == 0)
return name;
StringBuilder bufBld = null;
int length = name.Length;
int copyPosition = 0;
int underscorePos = name.IndexOf('_');
MatchCollection mc = null;
IEnumerator en = null;
if (underscorePos >= 0)
{
if (s_decodeCharPattern == null)
{
s_decodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
}
mc = s_decodeCharPattern.Matches(name, underscorePos);
en = mc.GetEnumerator();
}
else
{
return name;
}
int matchPos = -1;
if (en != null && en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index;
}
for (int position = 0; position < length - s_encodedCharLength + 1; position++)
{
if (position == matchPos)
{
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index;
}
if (bufBld == null)
{
bufBld = new StringBuilder(length + 20);
}
bufBld.Append(name, copyPosition, position - copyPosition);
if (name[position + 6] != '_')
{ //_x1234_
Int32 u =
FromHex(name[position + 2]) * 0x10000000 +
FromHex(name[position + 3]) * 0x1000000 +
FromHex(name[position + 4]) * 0x100000 +
FromHex(name[position + 5]) * 0x10000 +
FromHex(name[position + 6]) * 0x1000 +
FromHex(name[position + 7]) * 0x100 +
FromHex(name[position + 8]) * 0x10 +
FromHex(name[position + 9]);
if (u >= 0x00010000)
{
if (u <= 0x0010ffff)
{ //convert to two chars
copyPosition = position + s_encodedCharLength + 4;
char lowChar, highChar;
XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar);
bufBld.Append(highChar);
bufBld.Append(lowChar);
}
//else bad ucs-4 char don't convert
}
else
{ //convert to single char
copyPosition = position + s_encodedCharLength + 4;
bufBld.Append((char)u);
}
position += s_encodedCharLength - 1 + 4; //just skip
}
else
{
copyPosition = position + s_encodedCharLength;
bufBld.Append((char)(
FromHex(name[position + 2]) * 0x1000 +
FromHex(name[position + 3]) * 0x100 +
FromHex(name[position + 4]) * 0x10 +
FromHex(name[position + 5])));
position += s_encodedCharLength - 1;
}
}
}
if (copyPosition == 0)
{
return name;
}
else
{
if (copyPosition < length)
{
bufBld.Append(name, copyPosition, length - copyPosition);
}
return bufBld.ToString();
}
}
private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local)
{
if (string.IsNullOrEmpty(name))
{
return name;
}
StringBuilder bufBld = null;
int length = name.Length;
int copyPosition = 0;
int position = 0;
int underscorePos = name.IndexOf('_');
MatchCollection mc = null;
IEnumerator en = null;
if (underscorePos >= 0)
{
if (s_encodeCharPattern == null)
{
s_encodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
}
mc = s_encodeCharPattern.Matches(name, underscorePos);
en = mc.GetEnumerator();
}
int matchPos = -1;
if (en != null && en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
if (first)
{
if ((!s_xmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) ||
matchPos == 0)
{
if (bufBld == null)
{
bufBld = new StringBuilder(length + 20);
}
bufBld.Append("_x");
if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1]))
{
int x = name[0];
int y = name[1];
Int32 u = XmlCharType.CombineSurrogateChar(y, x);
bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
position++;
copyPosition = 2;
}
else
{
bufBld.Append(((Int32)name[0]).ToString("X4", CultureInfo.InvariantCulture));
copyPosition = 1;
}
bufBld.Append('_');
position++;
if (matchPos == 0)
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
}
}
for (; position < length; position++)
{
if ((local && !s_xmlCharType.IsNCNameCharXml4e(name[position])) ||
(!local && !s_xmlCharType.IsNameCharXml4e(name[position])) ||
(matchPos == position))
{
if (bufBld == null)
{
bufBld = new StringBuilder(length + 20);
}
if (matchPos == position)
if (en.MoveNext())
{
Match m = (Match)en.Current;
matchPos = m.Index - 1;
}
bufBld.Append(name, copyPosition, position - copyPosition);
bufBld.Append("_x");
if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1]))
{
int x = name[position];
int y = name[position + 1];
Int32 u = XmlCharType.CombineSurrogateChar(y, x);
bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
copyPosition = position + 2;
position++;
}
else
{
bufBld.Append(((Int32)name[position]).ToString("X4", CultureInfo.InvariantCulture));
copyPosition = position + 1;
}
bufBld.Append('_');
}
}
if (copyPosition == 0)
{
return name;
}
else
{
if (copyPosition < length)
{
bufBld.Append(name, copyPosition, length - copyPosition);
}
return bufBld.ToString();
}
}
private static readonly int s_encodedCharLength = 7; // ("_xFFFF_".Length);
private static volatile Regex s_encodeCharPattern;
private static volatile Regex s_decodeCharPattern;
private static int FromHex(char digit)
{
return (digit <= '9')
? ((int)digit - (int)'0')
: (((digit <= 'F')
? ((int)digit - (int)'A')
: ((int)digit - (int)'a'))
+ 10);
}
internal static byte[] FromBinHexString(string s)
{
return FromBinHexString(s, true);
}
internal static byte[] FromBinHexString(string s, bool allowOddCount)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount);
}
internal static string ToBinHexString(byte[] inArray)
{
if (inArray == null)
{
throw new ArgumentNullException(nameof(inArray));
}
return BinHexEncoder.Encode(inArray, 0, inArray.Length);
}
//
// Verification methods for strings
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyName(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName);
}
// parse name
int endPos = ValidateNames.ParseNameNoNamespaces(name, 0);
if (endPos != name.Length)
{
// did not parse to the end -> there is invalid character at endPos
throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException);
}
return name;
}
internal static string VerifyQName(string name, ExceptionType exceptionType)
{
if (name == null || name.Length == 0)
{
throw new ArgumentNullException(nameof(name));
}
int colonPosition = -1;
int endPos = ValidateNames.ParseQName(name, 0, out colonPosition);
if (endPos != name.Length)
{
throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
}
return name;
}
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyNCName(string name)
{
return VerifyNCName(name, ExceptionType.XmlException);
}
internal static string VerifyNCName(string name, ExceptionType exceptionType)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName);
}
int end = ValidateNames.ParseNCName(name, 0);
if (end != name.Length)
{
// If the string is not a valid NCName, then throw or return false
throw CreateInvalidNameCharException(name, end, exceptionType);
}
return name;
}
/// <devdoc>
/// <para>
/// </para>
/// </devdoc>
public static string VerifyNMTOKEN(string name)
{
return VerifyNMTOKEN(name, ExceptionType.XmlException);
}
internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType);
}
int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0);
if (endPos != name.Length)
{
throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
}
return name;
}
// Verification method for XML characters as defined in XML spec production [2] Char.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyXmlChars(string content)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
VerifyCharData(content, ExceptionType.XmlException);
return content;
}
// Verification method for XML public ID characters as defined in XML spec production [13] PubidChar.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyPublicId(string publicId)
{
if (publicId == null)
{
throw new ArgumentNullException(nameof(publicId));
}
// returns the position of invalid character or -1
int pos = s_xmlCharType.IsPublicId(publicId);
if (pos != -1)
{
throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException);
}
return publicId;
}
// Verification method for XML whitespace characters as defined in XML spec production [3] S.
// Throws XmlException if invalid character is found, otherwise returns the input string.
public static string VerifyWhitespace(string content)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
// returns the position of invalid character or -1
int pos = s_xmlCharType.IsOnlyWhitespaceWithPos(content);
if (pos != -1)
{
throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1);
}
return content;
}
#if XML10_FIFTH_EDITION
public static bool IsStartNCNameSurrogatePair(char lowChar, char highChar)
{
return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
}
#endif
#if XML10_FIFTH_EDITION
public static bool IsNCNameSurrogatePair(char lowChar, char highChar)
{
return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
}
#endif
// Value converters:
//
// String representation of Base types in XML (xsd) sometimes differ from
// one common language runtime offer and for all types it has to be locale independent.
// o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo
// x -- means we doing something special to make a conversion.
//
// From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid
// ------------------------------------------------------------------------------
// Boolean x
// Char o
// SByte o
// Byte o
// Int16 o
// UInt16 o
// Int32 o
// UInt32 o
// Int64 o
// UInt64 o
// Single x
// Double x
// Decimal o
// DateTime x
// String x o o o o o o o o o o x x o o x
// Guid x
// -----------------------------------------------------------------------------
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Boolean value)
{
return value ? "true" : "false";
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Char value)
{
return value.ToString();
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Decimal value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(SByte value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int16 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int32 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Int64 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Byte value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt16 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString8"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt32 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static string ToString(UInt64 value)
{
return value.ToString(null, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString9"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Single value)
{
if (Single.IsNegativeInfinity(value)) return "-INF";
if (Single.IsPositiveInfinity(value)) return "INF";
if (IsNegativeZero((double)value))
{
return ("-0");
}
return value.ToString("R", NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString10"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Double value)
{
if (Double.IsNegativeInfinity(value)) return "-INF";
if (Double.IsPositiveInfinity(value)) return "INF";
if (IsNegativeZero(value))
{
return ("-0");
}
return value.ToString("R", NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString11"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(TimeSpan value)
{
return new XsdDuration(value).ToString();
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString14"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)
{
switch (dateTimeOption)
{
case XmlDateTimeSerializationMode.Local:
value = SwitchToLocalTime(value);
break;
case XmlDateTimeSerializationMode.Utc:
value = SwitchToUtcTime(value);
break;
case XmlDateTimeSerializationMode.Unspecified:
value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
break;
case XmlDateTimeSerializationMode.RoundtripKind:
break;
default:
throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
}
XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime);
return xsdDateTime.ToString();
}
public static string ToString(DateTimeOffset value)
{
XsdDateTime xsdDateTime = new XsdDateTime(value);
return xsdDateTime.ToString();
}
public static string ToString(DateTimeOffset value, string format)
{
return value.ToString(format, DateTimeFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(Guid value)
{
return value.ToString();
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToBoolean"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Boolean ToBoolean(string s)
{
s = TrimString(s);
if (s == "1" || s == "true") return true;
if (s == "0" || s == "false") return false;
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean"));
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToChar"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Char ToChar(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (s.Length != 1)
{
throw new FormatException(SR.XmlConvert_NotOneCharString);
}
return s[0];
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDecimal"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Decimal ToDecimal(string s)
{
return Decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSByte"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static SByte ToSByte(string s)
{
return SByte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int16 ToInt16(string s)
{
return Int16.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt32"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int32 ToInt32(string s)
{
return Int32.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt64"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Int64 ToInt64(string s)
{
return Int64.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToByte"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Byte ToByte(string s)
{
return Byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt16 ToUInt16(string s)
{
return UInt16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt32"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt32 ToUInt32(string s)
{
return UInt32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt64"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public static UInt64 ToUInt64(string s)
{
return UInt64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSingle"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Single ToSingle(string s)
{
s = TrimString(s);
if (s == "-INF") return Single.NegativeInfinity;
if (s == "INF") return Single.PositiveInfinity;
float f = Single.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo);
if (f == 0 && s[0] == '-')
{
return -0f;
}
return f;
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDouble"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Double ToDouble(string s)
{
s = TrimString(s);
if (s == "-INF") return Double.NegativeInfinity;
if (s == "INF") return Double.PositiveInfinity;
double dVal = Double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
if (dVal == 0 && s[0] == '-')
{
return -0d;
}
return dVal;
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static TimeSpan ToTimeSpan(string s)
{
XsdDuration duration;
TimeSpan timeSpan;
try
{
duration = new XsdDuration(s);
}
catch (Exception)
{
// Remap exception for v1 compatibility
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "TimeSpan"));
}
timeSpan = duration.ToTimeSpan();
return timeSpan;
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)
{
XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
DateTime dt = (DateTime)xsdDateTime;
switch (dateTimeOption)
{
case XmlDateTimeSerializationMode.Local:
dt = SwitchToLocalTime(dt);
break;
case XmlDateTimeSerializationMode.Utc:
dt = SwitchToUtcTime(dt);
break;
case XmlDateTimeSerializationMode.Unspecified:
dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified);
break;
case XmlDateTimeSerializationMode.RoundtripKind:
break;
default:
throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
}
return dt;
}
public static DateTimeOffset ToDateTimeOffset(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime;
return dateTimeOffset;
}
public static DateTimeOffset ToDateTimeOffset(string s, string format)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
}
public static DateTimeOffset ToDateTimeOffset(string s, string[] formats)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
}
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToGuid"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Guid ToGuid(string s)
{
return new Guid(s);
}
private static DateTime SwitchToLocalTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Local:
return value;
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Local);
case DateTimeKind.Utc:
return value.ToLocalTime();
}
return value;
}
private static DateTime SwitchToUtcTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Utc:
return value;
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Utc);
case DateTimeKind.Local:
return value.ToUniversalTime();
}
return value;
}
internal static Uri ToUri(string s)
{
if (s != null && s.Length > 0)
{ //string.Empty is a valid uri but not " "
s = TrimString(s);
if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1)
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri"));
}
}
Uri uri;
if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri"));
}
return uri;
}
// Compares the given character interval and string and returns true if the characters are identical
internal static bool StrEqual(char[] chars, int strPos1, int strLen1, string str2)
{
if (strLen1 != str2.Length)
{
return false;
}
int i = 0;
while (i < strLen1 && chars[strPos1 + i] == str2[i])
{
i++;
}
return i == strLen1;
}
// XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec>
internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
// Trim a string using XML whitespace characters
internal static string TrimString(string value)
{
return value.Trim(WhitespaceChars);
}
// Trim beginning of a string using XML whitespace characters
internal static string TrimStringStart(string value)
{
return value.TrimStart(WhitespaceChars);
}
// Trim end of a string using XML whitespace characters
internal static string TrimStringEnd(string value)
{
return value.TrimEnd(WhitespaceChars);
}
// Split a string into a whitespace-separated list of tokens
internal static string[] SplitString(string value)
{
return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries);
}
internal static string[] SplitString(string value, StringSplitOptions splitStringOptions)
{
return value.Split(WhitespaceChars, splitStringOptions);
}
internal static bool IsNegativeZero(double value)
{
// Simple equals function will report that -0 is equal to +0, so compare bits instead
if (value == 0 && DoubleToInt64Bits(value) == DoubleToInt64Bits(-0e0))
{
return true;
}
return false;
}
#if !SILVERLIGHT_DISABLE_SECURITY
[System.Security.SecuritySafeCritical]
#endif
private static unsafe long DoubleToInt64Bits(double value)
{
// NOTE: BitConverter.DoubleToInt64Bits is missing in Silverlight
return *((long*)&value);
}
internal static void VerifyCharData(string data, ExceptionType exceptionType)
{
VerifyCharData(data, exceptionType, exceptionType);
}
internal static void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType)
{
if (data == null || data.Length == 0)
{
return;
}
int i = 0;
int len = data.Length;
for (; ;)
{
while (i < len && s_xmlCharType.IsCharData(data[i]))
{
i++;
}
if (i == len)
{
return;
}
char ch = data[i];
if (XmlCharType.IsHighSurrogate(ch))
{
if (i + 1 == len)
{
throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1);
}
ch = data[i + 1];
if (XmlCharType.IsLowSurrogate(ch))
{
i += 2;
continue;
}
else
{
throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1);
}
}
throw CreateInvalidCharException(data, i, invCharExceptionType);
}
}
internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType)
{
if (data == null || len == 0)
{
return;
}
int i = offset;
int endPos = offset + len;
for (; ;)
{
while (i < endPos && s_xmlCharType.IsCharData(data[i]))
{
i++;
}
if (i == endPos)
{
return;
}
char ch = data[i];
if (XmlCharType.IsHighSurrogate(ch))
{
if (i + 1 == endPos)
{
throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1);
}
ch = data[i + 1];
if (XmlCharType.IsLowSurrogate(ch))
{
i += 2;
continue;
}
else
{
throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1);
}
}
throw CreateInvalidCharException(data, len, i, exceptionType);
}
}
internal static Exception CreateException(string res, ExceptionType exceptionType)
{
return CreateException(res, exceptionType, 0, 0);
}
internal static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos)
{
switch (exceptionType)
{
case ExceptionType.ArgumentException:
return new ArgumentException(res);
case ExceptionType.XmlException:
default:
return new XmlException(res, string.Empty, lineNo, linePos);
}
}
internal static Exception CreateException(string res, string arg, ExceptionType exceptionType)
{
return CreateException(res, arg, exceptionType, 0, 0);
}
internal static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos)
{
switch (exceptionType)
{
case ExceptionType.ArgumentException:
return new ArgumentException(SR.Format(res, arg));
case ExceptionType.XmlException:
default:
return new XmlException(res, arg, lineNo, linePos);
}
}
internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType)
{
return CreateException(res, args, exceptionType, 0, 0);
}
internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos)
{
switch (exceptionType)
{
case ExceptionType.ArgumentException:
return new ArgumentException(SR.Format(res, args));
case ExceptionType.XmlException:
default:
return new XmlException(res, args, lineNo, linePos);
}
}
internal static Exception CreateInvalidSurrogatePairException(char low, char hi)
{
return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType)
{
return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0);
}
internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos)
{
string[] args = new string[] {
((uint)hi).ToString( "X", CultureInfo.InvariantCulture ),
((uint)low).ToString( "X", CultureInfo.InvariantCulture )
};
return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos);
}
internal static Exception CreateInvalidHighSurrogateCharException(char hi)
{
return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType)
{
return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0);
}
internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos)
{
return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos);
}
internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos)
{
return CreateInvalidCharException(data, length, invCharPos, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType)
{
return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1);
}
internal static Exception CreateInvalidCharException(string data, int invCharPos)
{
return CreateInvalidCharException(data, invCharPos, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType)
{
return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1);
}
internal static Exception CreateInvalidCharException(char invChar, char nextChar)
{
return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException);
}
internal static Exception CreateInvalidCharException(char invChar, char nextChar, ExceptionType exceptionType)
{
return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType);
}
internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType)
{
return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1);
}
internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName)
{
return (name == null) ? new ArgumentNullException(argumentName) : new ArgumentException(SR.Xml_EmptyName, argumentName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class SslStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
protected abstract bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream);
[Fact]
[ActiveIssue(16516, TestPlatforms.Windows)]
public void SslStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var server = new SslStream(serverStream))
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Assert.True(DoHandshake(client, server), "Handshake completed in the allotted time");
}
}
[Fact]
public void SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream))
using (var server = new SslStream(serverStream))
using (var certificate = Configuration.Certificates.GetServerCertificate())
{
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync("incorrectServer");
auth[1] = server.AuthenticateAsServerAsync(certificate);
Assert.Throws<AuthenticationException>(() =>
{
auth[0].GetAwaiter().GetResult();
});
auth[1].GetAwaiter().GetResult();
}
}
[Fact]
public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(_sampleMsg);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Fact]
public void SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(Array.Empty<byte>());
clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
clientSslStream.Write(_sampleMsg);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
clientSslStream.Write(Array.Empty<byte>());
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData)
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");
byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
if (randomizedData)
{
new Random().NextBytes(largeMsg); // not very compressible
}
else
{
for (int i = 0; i < largeMsg.Length; i++)
{
largeMsg[i] = unchecked((byte)i); // very compressible
}
}
byte[] receivedLargeMsg = new byte[largeMsg.Length];
// First do a large write and read blocks at a time
clientSslStream.Write(largeMsg);
int bytesRead = 0, totalRead = 0;
while (totalRead < largeMsg.Length &&
(bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
{
totalRead += bytesRead;
}
Assert.Equal(receivedLargeMsg.Length, totalRead);
Assert.Equal(largeMsg, receivedLargeMsg);
// Then write again and read bytes at a time
clientSslStream.Write(largeMsg);
foreach (byte b in largeMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
[Fact]
public async Task SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Fact]
[ActiveIssue(16516, TestPlatforms.Windows)]
public void SslStream_StreamToStream_Write_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
for (int i = 0; i < 3; i++)
{
clientSslStream.Write(_sampleMsg);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
[Fact]
public async Task SslStream_StreamToStream_WriteAsync_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
for (int i = 0; i < 3; i++)
{
await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length).ConfigureAwait(false);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
[Fact]
public async Task SslStream_StreamToStream_WriteAsync_ReadAsync_Pending_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new NotifyReadVirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
var serverBuffer = new byte[1];
var tcs = new TaskCompletionSource<object>();
serverStream.OnRead += (buffer, offset, count) =>
{
tcs.TrySetResult(null);
};
Task readTask = serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length);
// Since the sequence of calls that ends in serverStream.Read() is sync, by now
// the read task will have acquired the semaphore shared by Stream.BeginReadInternal()
// and Stream.BeginWriteInternal().
// But to be sure, we wait until we know we're inside Read().
await tcs.Task.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
// Should not hang
await serverSslStream.WriteAsync(new byte[] { 1 }, 0, 1)
.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
// Read in client
var clientBuffer = new byte[1];
await clientSslStream.ReadAsync(clientBuffer, 0, clientBuffer.Length);
Assert.Equal(1, clientBuffer[0]);
// Complete server read task
await clientSslStream.WriteAsync(new byte[] { 2 }, 0, 1);
await readTask;
Assert.Equal(2, serverBuffer[0]);
}
}
[Fact]
public void SslStream_StreamToStream_Flush_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
{
Assert.False(stream.HasBeenSyncFlushed);
sslStream.Flush();
Assert.True(stream.HasBeenSyncFlushed);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")]
public void SslStream_StreamToStream_FlushAsync_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
{
Task task = sslStream.FlushAsync();
Assert.False(task.IsCompleted);
stream.CompleteAsyncFlush();
Assert.True(task.IsCompleted);
}
}
private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer)
{
return expectedBuffer.SequenceEqual(actualBuffer);
}
private bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;
if (!Capability.IsTrustedRootCertificateInstalled())
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
}
Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);
if (sslPolicyErrors == expectedSslPolicyErrors)
{
return true;
}
else
{
return false;
}
}
}
public sealed class SslStreamStreamToStreamTest_Async : SslStreamStreamToStreamTest
{
protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
Task t2 = serverSslStream.AuthenticateAsServerAsync(certificate);
return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds);
}
}
}
public sealed class SslStreamStreamToStreamTest_BeginEnd : SslStreamStreamToStreamTest
{
protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
IAsyncResult a1 = clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null);
IAsyncResult a2 = serverSslStream.BeginAuthenticateAsServer(certificate, null, null);
if (WaitHandle.WaitAll(new[] { a1.AsyncWaitHandle, a2.AsyncWaitHandle }, TestConfiguration.PassingTestTimeoutMilliseconds))
{
clientSslStream.EndAuthenticateAsClient(a1);
serverSslStream.EndAuthenticateAsServer(a2);
return true;
}
return false;
}
}
}
public sealed class SslStreamStreamToStreamTest_Sync : SslStreamStreamToStreamTest
{
protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFeedItemSetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetFeedItemSetRequestObject()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet response = client.GetFeedItemSet(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemSetRequestObjectAsync()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet responseCallSettings = await client.GetFeedItemSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemSet responseCancellationToken = await client.GetFeedItemSetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeedItemSet()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet response = client.GetFeedItemSet(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemSetAsync()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet responseCallSettings = await client.GetFeedItemSetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemSet responseCancellationToken = await client.GetFeedItemSetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeedItemSetResourceNames()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet response = client.GetFeedItemSet(request.ResourceNameAsFeedItemSetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemSetResourceNamesAsync()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemSetRequest request = new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
};
gagvr::FeedItemSet expectedResponse = new gagvr::FeedItemSet
{
ResourceNameAsFeedItemSetName = gagvr::FeedItemSetName.FromCustomerFeedFeedItemSet("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_SET_ID]"),
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
FeedItemSetId = 2017070211045731158L,
DisplayName = "display_name137f65c2",
DynamicLocationSetFilter = new gagvc::DynamicLocationSetFilter(),
DynamicAffiliateLocationSetFilter = new gagvc::DynamicAffiliateLocationSetFilter(),
Status = gagve::FeedItemSetStatusEnum.Types.FeedItemSetStatus.Enabled,
};
mockGrpcClient.Setup(x => x.GetFeedItemSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemSet>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemSet responseCallSettings = await client.GetFeedItemSetAsync(request.ResourceNameAsFeedItemSetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemSet responseCancellationToken = await client.GetFeedItemSetAsync(request.ResourceNameAsFeedItemSetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeedItemSetsRequestObject()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemSetsRequest request = new MutateFeedItemSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateFeedItemSetsResponse expectedResponse = new MutateFeedItemSetsResponse
{
Results =
{
new MutateFeedItemSetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateFeedItemSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemSetsResponse response = client.MutateFeedItemSets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedItemSetsRequestObjectAsync()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemSetsRequest request = new MutateFeedItemSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemSetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateFeedItemSetsResponse expectedResponse = new MutateFeedItemSetsResponse
{
Results =
{
new MutateFeedItemSetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateFeedItemSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemSetsResponse responseCallSettings = await client.MutateFeedItemSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedItemSetsResponse responseCancellationToken = await client.MutateFeedItemSetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeedItemSets()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemSetsRequest request = new MutateFeedItemSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemSetOperation(),
},
};
MutateFeedItemSetsResponse expectedResponse = new MutateFeedItemSetsResponse
{
Results =
{
new MutateFeedItemSetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateFeedItemSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemSetsResponse response = client.MutateFeedItemSets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedItemSetsAsync()
{
moq::Mock<FeedItemSetService.FeedItemSetServiceClient> mockGrpcClient = new moq::Mock<FeedItemSetService.FeedItemSetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemSetsRequest request = new MutateFeedItemSetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemSetOperation(),
},
};
MutateFeedItemSetsResponse expectedResponse = new MutateFeedItemSetsResponse
{
Results =
{
new MutateFeedItemSetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateFeedItemSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemSetServiceClient client = new FeedItemSetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemSetsResponse responseCallSettings = await client.MutateFeedItemSetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedItemSetsResponse responseCancellationToken = await client.MutateFeedItemSetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using J2N;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace YAF.Lucene.Net.Util.Automaton
{
/// <summary>
/// Construction of basic automata.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class BasicAutomata
{
private BasicAutomata()
{
}
/// <summary>
/// Returns a new (deterministic) automaton with the empty language.
/// </summary>
public static Automaton MakeEmpty()
{
Automaton a = new Automaton();
State s = new State();
a.initial = s;
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts only the empty string.
/// </summary>
public static Automaton MakeEmptyString()
{
Automaton a = new Automaton();
a.singleton = "";
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts all strings.
/// </summary>
public static Automaton MakeAnyString()
{
Automaton a = new Automaton();
State s = new State();
a.initial = s;
s.accept = true;
s.AddTransition(new Transition(Character.MinCodePoint, Character.MaxCodePoint, s));
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts any single codepoint.
/// </summary>
public static Automaton MakeAnyChar()
{
return MakeCharRange(Character.MinCodePoint, Character.MaxCodePoint);
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts a single codepoint of
/// the given value.
/// </summary>
public static Automaton MakeChar(int c)
{
Automaton a = new Automaton();
a.singleton = new string(Character.ToChars(c));
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts a single codepoint whose
/// value is in the given interval (including both end points).
/// </summary>
public static Automaton MakeCharRange(int min, int max)
{
if (min == max)
{
return MakeChar(min);
}
Automaton a = new Automaton();
State s1 = new State();
State s2 = new State();
a.initial = s1;
s2.accept = true;
if (min <= max)
{
s1.AddTransition(new Transition(min, max, s2));
}
a.deterministic = true;
return a;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of length
/// <c>x.Substring(n).Length</c>.
/// </summary>
private static State AnyOfRightLength(string x, int n)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
s.AddTransition(new Transition('0', '9', AnyOfRightLength(x, n + 1)));
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value at least
/// <c>x.Substring(n)</c> and length <c>x.Substring(n).Length</c>.
/// </summary>
private static State AtLeast(string x, int n, ICollection<State> initials, bool zeros)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
if (zeros)
{
initials.Add(s);
}
char c = x[n];
s.AddTransition(new Transition(c, AtLeast(x, n + 1, initials, zeros && c == '0')));
if (c < '9')
{
s.AddTransition(new Transition((char)(c + 1), '9', AnyOfRightLength(x, n + 1)));
}
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value at most
/// <c>x.Substring(n)</c> and length <c>x.Substring(n).Length</c>.
/// </summary>
private static State AtMost(string x, int n)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
char c = x[n];
s.AddTransition(new Transition(c, AtMost(x, (char)n + 1)));
if (c > '0')
{
s.AddTransition(new Transition('0', (char)(c - 1), AnyOfRightLength(x, n + 1)));
}
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value between
/// <c>x.Substring(n)</c> and <c>y.Substring(n)</c> and of length <c>x.Substring(n).Length</c>
/// (which must be equal to <c>y.Substring(n).Length</c>).
/// </summary>
private static State Between(string x, string y, int n, ICollection<State> initials, bool zeros)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
if (zeros)
{
initials.Add(s);
}
char cx = x[n];
char cy = y[n];
if (cx == cy)
{
s.AddTransition(new Transition(cx, Between(x, y, n + 1, initials, zeros && cx == '0')));
}
else // cx<cy
{
s.AddTransition(new Transition(cx, AtLeast(x, n + 1, initials, zeros && cx == '0')));
s.AddTransition(new Transition(cy, AtMost(y, n + 1)));
if (cx + 1 < cy)
{
s.AddTransition(new Transition((char)(cx + 1), (char)(cy - 1), AnyOfRightLength(x, n + 1)));
}
}
}
return s;
}
/// <summary>
/// Returns a new automaton that accepts strings representing decimal
/// non-negative integers in the given interval.
/// </summary>
/// <param name="min"> Minimal value of interval. </param>
/// <param name="max"> Maximal value of interval (both end points are included in the
/// interval). </param>
/// <param name="digits"> If > 0, use fixed number of digits (strings must be prefixed
/// by 0's to obtain the right length) - otherwise, the number of
/// digits is not fixed. </param>
/// <exception cref="ArgumentException"> If min > max or if numbers in the
/// interval cannot be expressed with the given fixed number of
/// digits. </exception>
public static Automaton MakeInterval(int min, int max, int digits)
{
Automaton a = new Automaton();
string x = Convert.ToString(min, CultureInfo.InvariantCulture);
string y = Convert.ToString(max, CultureInfo.InvariantCulture);
if (min > max || (digits > 0 && y.Length > digits))
{
throw new System.ArgumentException();
}
int d;
if (digits > 0)
{
d = digits;
}
else
{
d = y.Length;
}
StringBuilder bx = new StringBuilder();
for (int i = x.Length; i < d; i++)
{
bx.Append('0');
}
bx.Append(x);
x = bx.ToString();
StringBuilder by = new StringBuilder();
for (int i = y.Length; i < d; i++)
{
by.Append('0');
}
by.Append(y);
y = by.ToString();
ICollection<State> initials = new List<State>();
a.initial = Between(x, y, 0, initials, digits <= 0);
if (digits <= 0)
{
List<StatePair> pairs = new List<StatePair>();
foreach (State p in initials)
{
if (a.initial != p)
{
pairs.Add(new StatePair(a.initial, p));
}
}
BasicOperations.AddEpsilons(a, pairs);
a.initial.AddTransition(new Transition('0', a.initial));
a.deterministic = false;
}
else
{
a.deterministic = true;
}
a.CheckMinimizeAlways();
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts the single given
/// string.
/// </summary>
public static Automaton MakeString(string s)
{
Automaton a = new Automaton();
a.singleton = s;
a.deterministic = true;
return a;
}
public static Automaton MakeString(int[] word, int offset, int length)
{
Automaton a = new Automaton();
a.IsDeterministic = true;
State s = new State();
a.initial = s;
for (int i = offset; i < offset + length; i++)
{
State s2 = new State();
s.AddTransition(new Transition(word[i], s2));
s = s2;
}
s.accept = true;
return a;
}
/// <summary>
/// Returns a new (deterministic and minimal) automaton that accepts the union
/// of the given collection of <see cref="BytesRef"/>s representing UTF-8 encoded
/// strings.
/// </summary>
/// <param name="utf8Strings">
/// The input strings, UTF-8 encoded. The collection must be in sorted
/// order.
/// </param>
/// <returns> An <see cref="Automaton"/> accepting all input strings. The resulting
/// automaton is codepoint based (full unicode codepoints on
/// transitions). </returns>
public static Automaton MakeStringUnion(ICollection<BytesRef> utf8Strings)
{
if (utf8Strings.Count == 0)
{
return MakeEmpty();
}
else
{
return DaciukMihovAutomatonBuilder.Build(utf8Strings);
}
}
}
}
| |
#region Apache License, Version 2.0
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
/// Author: Leopoldo Lee Agdeppa III
namespace NPanday.ProjectImporter.Parser.VisualStudioProjectTypes
{
public class VisualStudioProjectType
{
static Dictionary<string, VisualStudioProjectTypeEnum> __visualStudioProjectTypes;
static Dictionary<VisualStudioProjectTypeEnum, string> __visualStudioProjectTypeGuids;
static Dictionary<string, bool> __visualStudioProjectTypeSupported; // TODO: should remove, and just rely on the converter registrations
static VisualStudioProjectType()
{
__visualStudioProjectTypes = new Dictionary<string, VisualStudioProjectTypeEnum>();
__visualStudioProjectTypeGuids = new Dictionary<VisualStudioProjectTypeEnum, string>();
__visualStudioProjectTypeSupported = new Dictionary<string, bool>();
//Windows (C#) {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
__visualStudioProjectTypes.Add("FAE04EC0-301F-11D3-BF4B-00C04F79EFBC", VisualStudioProjectTypeEnum.Windows__CSharp);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Windows__CSharp, "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC");
__visualStudioProjectTypeSupported.Add("FAE04EC0-301F-11D3-BF4B-00C04F79EFBC", true);
//Windows (VB.NET) {F184B08F-C81C-45F6-A57F-5ABD9991F28F}
__visualStudioProjectTypes.Add("F184B08F-C81C-45F6-A57F-5ABD9991F28F", VisualStudioProjectTypeEnum.Windows__VbDotNet);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Windows__VbDotNet, "F184B08F-C81C-45F6-A57F-5ABD9991F28F");
__visualStudioProjectTypeSupported.Add("F184B08F-C81C-45F6-A57F-5ABD9991F28F", true);
//Windows (Visual C++) {8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}
__visualStudioProjectTypes.Add("8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942", VisualStudioProjectTypeEnum.Windows__VCpp);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Windows__VCpp, "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942");
__visualStudioProjectTypeSupported.Add("8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942", false);
//Web Application {349C5851-65DF-11DA-9384-00065B846F21}
__visualStudioProjectTypes.Add("349C5851-65DF-11DA-9384-00065B846F21", VisualStudioProjectTypeEnum.Web_Application);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Web_Application, "349C5851-65DF-11DA-9384-00065B846F21");
__visualStudioProjectTypeSupported.Add("349C5851-65DF-11DA-9384-00065B846F21", true);
//Web Site {E24C65DC-7377-472B-9ABA-BC803B73C61A}
__visualStudioProjectTypes.Add("E24C65DC-7377-472B-9ABA-BC803B73C61A", VisualStudioProjectTypeEnum.Web_Site);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Web_Site, "E24C65DC-7377-472B-9ABA-BC803B73C61A");
__visualStudioProjectTypeSupported.Add("E24C65DC-7377-472B-9ABA-BC803B73C61A", true);
//Distributed System {F135691A-BF7E-435D-8960-F99683D2D49C}
__visualStudioProjectTypes.Add("F135691A-BF7E-435D-8960-F99683D2D49C", VisualStudioProjectTypeEnum.Distributed_System);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Distributed_System, "F135691A-BF7E-435D-8960-F99683D2D49C");
__visualStudioProjectTypeSupported.Add("F135691A-BF7E-435D-8960-F99683D2D49C", false);
//Windows Communication Foundation (WCF) {3D9AD99F-2412-4246-B90B-4EAA41C64699}
__visualStudioProjectTypes.Add("3D9AD99F-2412-4246-B90B-4EAA41C64699", VisualStudioProjectTypeEnum.Windows_Communication_Foundation__WCF);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Windows_Communication_Foundation__WCF, "3D9AD99F-2412-4246-B90B-4EAA41C64699");
__visualStudioProjectTypeSupported.Add("3D9AD99F-2412-4246-B90B-4EAA41C64699", true);
//Windows Presentation Foundation (WPF) {60DC8134-EBA5-43B8-BCC9-BB4BC16C2548}
__visualStudioProjectTypes.Add("60DC8134-EBA5-43B8-BCC9-BB4BC16C2548", VisualStudioProjectTypeEnum.Windows_Presentation_Foundation__WPF);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Windows_Presentation_Foundation__WPF, "60DC8134-EBA5-43B8-BCC9-BB4BC16C2548");
__visualStudioProjectTypeSupported.Add("60DC8134-EBA5-43B8-BCC9-BB4BC16C2548", true);
//Visual Database Tools {C252FEB5-A946-4202-B1D4-9916A0590387}
__visualStudioProjectTypes.Add("C252FEB5-A946-4202-B1D4-9916A0590387", VisualStudioProjectTypeEnum.Visual_Database_Tools);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Visual_Database_Tools, "C252FEB5-A946-4202-B1D4-9916A0590387");
__visualStudioProjectTypeSupported.Add("C252FEB5-A946-4202-B1D4-9916A0590387", false);
//Database {A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124}
__visualStudioProjectTypes.Add("A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124", VisualStudioProjectTypeEnum.Database);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Database, "A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124");
__visualStudioProjectTypeSupported.Add("A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124", false);
//Database (other project types) {4F174C21-8C12-11D0-8340-0000F80270F8}
__visualStudioProjectTypes.Add("4F174C21-8C12-11D0-8340-0000F80270F8", VisualStudioProjectTypeEnum.Database__other_project_types);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Database__other_project_types, "4F174C21-8C12-11D0-8340-0000F80270F8");
__visualStudioProjectTypeSupported.Add("4F174C21-8C12-11D0-8340-0000F80270F8", false);
//Test {3AC096D0-A1C2-E12C-1390-A8335801FDAB}
__visualStudioProjectTypes.Add("3AC096D0-A1C2-E12C-1390-A8335801FDAB", VisualStudioProjectTypeEnum.Test);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Test, "3AC096D0-A1C2-E12C-1390-A8335801FDAB");
__visualStudioProjectTypeSupported.Add("3AC096D0-A1C2-E12C-1390-A8335801FDAB", true);
//Legacy (2003) Smart Device (C#) {20D4826A-C6FA-45DB-90F4-C717570B9F32}
__visualStudioProjectTypes.Add("20D4826A-C6FA-45DB-90F4-C717570B9F32", VisualStudioProjectTypeEnum.Legacy__2003_Smart_Device__CSharp);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Legacy__2003_Smart_Device__CSharp, "20D4826A-C6FA-45DB-90F4-C717570B9F32");
__visualStudioProjectTypeSupported.Add("20D4826A-C6FA-45DB-90F4-C717570B9F32", false);
//Legacy (2003) Smart Device (VB.NET) {CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8}
__visualStudioProjectTypes.Add("CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8", VisualStudioProjectTypeEnum.Legacy__2003_Smart_Device__VbDotNet);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Legacy__2003_Smart_Device__VbDotNet, "CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8");
__visualStudioProjectTypeSupported.Add("CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8", false);
//Smart Device (C#) {4D628B5B-2FBC-4AA6-8C16-197242AEB884}
__visualStudioProjectTypes.Add("4D628B5B-2FBC-4AA6-8C16-197242AEB884", VisualStudioProjectTypeEnum.Smart_Device__CSharp);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Smart_Device__CSharp, "4D628B5B-2FBC-4AA6-8C16-197242AEB884");
__visualStudioProjectTypeSupported.Add("4D628B5B-2FBC-4AA6-8C16-197242AEB884", false);
//Smart Device (VB.NET) {68B1623D-7FB9-47D8-8664-7ECEA3297D4F}
__visualStudioProjectTypes.Add("68B1623D-7FB9-47D8-8664-7ECEA3297D4F", VisualStudioProjectTypeEnum.Smart_Device__VbDotNet);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Smart_Device__VbDotNet, "68B1623D-7FB9-47D8-8664-7ECEA3297D4F");
__visualStudioProjectTypeSupported.Add("68B1623D-7FB9-47D8-8664-7ECEA3297D4F", false);
//Workflow (C#) {14822709-B5A1-4724-98CA-57A101D1B079}
__visualStudioProjectTypes.Add("14822709-B5A1-4724-98CA-57A101D1B079", VisualStudioProjectTypeEnum.Workflow__CSharp);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Workflow__CSharp, "14822709-B5A1-4724-98CA-57A101D1B079");
__visualStudioProjectTypeSupported.Add("14822709-B5A1-4724-98CA-57A101D1B079", false);
//Workflow (VB.NET) {D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8}
__visualStudioProjectTypes.Add("D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8", VisualStudioProjectTypeEnum.Workflow__VbDotNet);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Workflow__VbDotNet, "D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8");
__visualStudioProjectTypeSupported.Add("D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8", false);
//Workflow 4.0+ {32F31D43-81CC-4C15-9DE6-3FC5453562B6}
__visualStudioProjectTypes.Add("32F31D43-81CC-4C15-9DE6-3FC5453562B6", VisualStudioProjectTypeEnum.Workflow);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Workflow, "32F31D43-81CC-4C15-9DE6-3FC5453562B6");
__visualStudioProjectTypeSupported.Add("32F31D43-81CC-4C15-9DE6-3FC5453562B6", false);
//Deployment Merge Module {06A35CCD-C46D-44D5-987B-CF40FF872267}
__visualStudioProjectTypes.Add("06A35CCD-C46D-44D5-987B-CF40FF872267", VisualStudioProjectTypeEnum.Deployment_Merge_Module);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Deployment_Merge_Module, "06A35CCD-C46D-44D5-987B-CF40FF872267");
__visualStudioProjectTypeSupported.Add("06A35CCD-C46D-44D5-987B-CF40FF872267", false);
//Deployment Cab {3EA9E505-35AC-4774-B492-AD1749C4943A}
__visualStudioProjectTypes.Add("3EA9E505-35AC-4774-B492-AD1749C4943A", VisualStudioProjectTypeEnum.Deployment_Cab);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Deployment_Cab, "3EA9E505-35AC-4774-B492-AD1749C4943A");
__visualStudioProjectTypeSupported.Add("3EA9E505-35AC-4774-B492-AD1749C4943A", false);
//Deployment Setup {978C614F-708E-4E1A-B201-565925725DBA}
__visualStudioProjectTypes.Add("978C614F-708E-4E1A-B201-565925725DBA", VisualStudioProjectTypeEnum.Deployment_Setup);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Deployment_Setup, "978C614F-708E-4E1A-B201-565925725DBA");
__visualStudioProjectTypeSupported.Add("978C614F-708E-4E1A-B201-565925725DBA", false);
//Deployment Smart Device Cab {AB322303-2255-48EF-A496-5904EB18DA55}
__visualStudioProjectTypes.Add("AB322303-2255-48EF-A496-5904EB18DA55", VisualStudioProjectTypeEnum.Deployment_Smart_Device_Cab);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Deployment_Smart_Device_Cab, "AB322303-2255-48EF-A496-5904EB18DA55");
__visualStudioProjectTypeSupported.Add("AB322303-2255-48EF-A496-5904EB18DA55", false);
//Visual Studio Tools for Applications (VSTA) {A860303F-1F3F-4691-B57E-529FC101A107}
__visualStudioProjectTypes.Add("A860303F-1F3F-4691-B57E-529FC101A107", VisualStudioProjectTypeEnum.Visual_Studio_Tools_for_Applications__VSTA);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Visual_Studio_Tools_for_Applications__VSTA, "A860303F-1F3F-4691-B57E-529FC101A107");
__visualStudioProjectTypeSupported.Add("A860303F-1F3F-4691-B57E-529FC101A107", false);
//Visual Studio Tools for Office (VSTO) {BAA0C2D2-18E2-41B9-852F-F413020CAA33}
__visualStudioProjectTypes.Add("BAA0C2D2-18E2-41B9-852F-F413020CAA33", VisualStudioProjectTypeEnum.Visual_Studio_Tools_for_Office__VSTO);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Visual_Studio_Tools_for_Office__VSTO, "BAA0C2D2-18E2-41B9-852F-F413020CAA33");
__visualStudioProjectTypeSupported.Add("BAA0C2D2-18E2-41B9-852F-F413020CAA33", false);
//SharePoint Workflow {F8810EC1-6754-47FC-A15F-DFABD2E3FA90}
__visualStudioProjectTypes.Add("F8810EC1-6754-47FC-A15F-DFABD2E3FA90", VisualStudioProjectTypeEnum.SharePoint_Workflow);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.SharePoint_Workflow, "F8810EC1-6754-47FC-A15F-DFABD2E3FA90");
__visualStudioProjectTypeSupported.Add("F8810EC1-6754-47FC-A15F-DFABD2E3FA90", false);
//Microsoft Installer {54435603-DBB4-11D2-8724-00A0C9A8B90C}
__visualStudioProjectTypes.Add("54435603-DBB4-11D2-8724-00A0C9A8B90C", VisualStudioProjectTypeEnum.Microsoft_Installer);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Microsoft_Installer, "54435603-DBB4-11D2-8724-00A0C9A8B90C");
__visualStudioProjectTypeSupported.Add("54435603-DBB4-11D2-8724-00A0C9A8B90C", false);
//Website_MVC {603C0E0B-DB56-11DC-BE95-000D561079B0}
__visualStudioProjectTypes.Add("603C0E0B-DB56-11DC-BE95-000D561079B0", VisualStudioProjectTypeEnum.Website_MVC);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Website_MVC, "603C0E0B-DB56-11DC-BE95-000D561079B0");
__visualStudioProjectTypeSupported.Add("603C0E0B-DB56-11DC-BE95-000D561079B0", true);
//Model View Controller (MVC) {F85E285D-A4E0-4152-9332-AB1D724D3325}
__visualStudioProjectTypes.Add("F85E285D-A4E0-4152-9332-AB1D724D3325", VisualStudioProjectTypeEnum.Model_View_Controller_MVC);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Model_View_Controller_MVC, "F85E285D-A4E0-4152-9332-AB1D724D3325");
__visualStudioProjectTypeSupported.Add("F85E285D-A4E0-4152-9332-AB1D724D3325", true);
//Model View Controller (MVC) {E53F8FEA-EAE0-44A6-8774-FFD645390401}
__visualStudioProjectTypes.Add("E53F8FEA-EAE0-44A6-8774-FFD645390401", VisualStudioProjectTypeEnum.Model_View_Controller_MVC3);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Model_View_Controller_MVC3, "E53F8FEA-EAE0-44A6-8774-FFD645390401");
__visualStudioProjectTypeSupported.Add("E53F8FEA-EAE0-44A6-8774-FFD645390401", true);
//Model View Controller (MVC) {E3E379DF-F4C6-4180-9B81-6769533ABE47}
__visualStudioProjectTypes.Add("E3E379DF-F4C6-4180-9B81-6769533ABE47", VisualStudioProjectTypeEnum.Model_View_Controller_MVC4);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Model_View_Controller_MVC4, "E3E379DF-F4C6-4180-9B81-6769533ABE47");
__visualStudioProjectTypeSupported.Add("E3E379DF-F4C6-4180-9B81-6769533ABE47", true);
//Windows Azure Project {CC5FD16D-436D-48AD-A40C-5A424C6E3E79}
__visualStudioProjectTypes.Add("CC5FD16D-436D-48AD-A40C-5A424C6E3E79", VisualStudioProjectTypeEnum.WindowsAzure_CloudService);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.WindowsAzure_CloudService, "CC5FD16D-436D-48AD-A40C-5A424C6E3E79");
__visualStudioProjectTypeSupported.Add("CC5FD16D-436D-48AD-A40C-5A424C6E3E79", true);
//Silverlight Project {A1591282-1198-4647-A2B1-27E5FF5F6F3B}
__visualStudioProjectTypes.Add("A1591282-1198-4647-A2B1-27E5FF5F6F3B", VisualStudioProjectTypeEnum.Silverlight);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.Silverlight, "A1591282-1198-4647-A2B1-27E5FF5F6F3B");
__visualStudioProjectTypeSupported.Add("A1591282-1198-4647-A2B1-27E5FF5F6F3B", true);
//Portable Class Library {786C8304-07A1-408B-BD7F-6EE04809D6DB}
__visualStudioProjectTypes.Add("786C830F-07A1-408B-BD7F-6EE04809D6DB", VisualStudioProjectTypeEnum.PortableClassLibrary);
__visualStudioProjectTypeGuids.Add(VisualStudioProjectTypeEnum.PortableClassLibrary, "786C830F-07A1-408B-BD7F-6EE04809D6DB");
__visualStudioProjectTypeSupported.Add("786C830F-07A1-408B-BD7F-6EE04809D6DB", true);
}
/// <summary>
/// Gets the VisualStudioProjectTypeEnum of the given GUID (Global Unique Identifier)
/// </summary>
/// <param name="guid">VisualStudio Project Type GUID</param>
/// <returns>VisualStudioProjectTypeEnum equivalent of the GUID</returns>
public static VisualStudioProjectTypeEnum GetVisualStudioProjectType(string guid)
{
string strGuid = guid.Replace("{", "");
strGuid = strGuid.Replace("}", "");
VisualStudioProjectTypeEnum projectType = 0;
foreach (string guidItem in strGuid.Split(';'))
{
string upperGuid = guidItem.ToUpper();
if (!__visualStudioProjectTypes.ContainsKey(upperGuid))
{
throw new NotSupportedException("Unknown project type GUID: " + guidItem);
}
projectType |= __visualStudioProjectTypes[upperGuid];
if (!__visualStudioProjectTypeSupported[upperGuid])
{
throw new NotSupportedException("NPanday does not support projects with type GUID: " + guidItem);
}
}
return projectType;
}
public static string GetVisualStudioProjectTypeGuid(VisualStudioProjectTypeEnum visualStudioProjectTypeEnum)
{
List<string> list = new List<string>();
foreach (VisualStudioProjectTypeEnum value in Enum.GetValues(typeof(VisualStudioProjectTypeEnum)))
{
if ((visualStudioProjectTypeEnum & value) == value)
{
list.Add("{" + __visualStudioProjectTypeGuids[value] + "}");
}
}
return string.Join(";", list.ToArray());
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
namespace HookActions
{
[Guid("0E620D8D-7B63-49ed-A3BF-55530A95B34F")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("HookActions.hookActionLabel")]
public sealed class hookActionsLabel : BaseCommand
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GMxCommands.Register(regKey);
MxCommands.Register(regKey);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GMxCommands.Unregister(regKey);
MxCommands.Unregister(regKey);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
private IHookHelper m_hookHelper = null;
private IGlobeHookHelper m_globeHookHelper = null;
public hookActionsLabel()
{
base.m_category = "HookActions";
base.m_caption = "Create labels";
base.m_message = "Create labels";
base.m_toolTip = "Create labels";
base.m_name = "HookActions_Label";
}
public override void OnCreate(object hook)
{
// Test the hook that calls this command and disable if nothing valid
try
{
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
if (m_hookHelper.ActiveView == null)
{
m_hookHelper = null;
}
}
catch
{
m_hookHelper = null;
}
if (m_hookHelper == null)
{
//Can be globe
try
{
m_globeHookHelper = new GlobeHookHelperClass();
m_globeHookHelper.Hook = hook;
if (m_globeHookHelper.ActiveViewer == null)
{
//Nothing valid!
m_globeHookHelper = null;
}
}
catch
{
m_globeHookHelper = null;
}
}
if (m_globeHookHelper == null && m_hookHelper == null)
base.m_enabled = false;
else
base.m_enabled = true;
}
public override bool Enabled
{
get
{
IHookActions hookActions = null;
IBasicMap basicMap = null;
//Get basic map and set hook actions
if (m_hookHelper != null)
{
basicMap = m_hookHelper.FocusMap as IBasicMap;
hookActions = m_hookHelper as IHookActions;
}
else if (m_globeHookHelper != null)
{
basicMap = m_globeHookHelper.Globe as IBasicMap;
hookActions = m_globeHookHelper as IHookActions;
}
//Disable if no features selected
IEnumFeature enumFeature = basicMap.FeatureSelection as IEnumFeature;
IFeature feature = enumFeature.Next();
if (feature == null) return false;
//Enable if action supported on first selected feature
if (hookActions.get_ActionSupported(feature.Shape, esriHookActions.esriHookActionsLabel))
return true;
else
return false;
}
}
public override void OnClick()
{
IHookActions hookActions = null;
IBasicMap basicMap = null;
//Get basic map and set hook actions
if (m_hookHelper != null)
{
basicMap = m_hookHelper.FocusMap as IBasicMap;
hookActions = m_hookHelper as IHookActions;
}
else if (m_globeHookHelper != null)
{
basicMap = m_globeHookHelper.Globe as IBasicMap;
hookActions = m_globeHookHelper as IHookActions;
}
//Get feature selection
ISelection selection = basicMap.FeatureSelection;
//Get enumerator
IEnumFeature enumFeature = selection as IEnumFeature;
enumFeature.Reset();
//Set first feature
IFeature feature;
feature = enumFeature.Next();
//Loop though the features
IArray array = new ESRI.ArcGIS.esriSystem.Array();
IStringArray sArray = new StrArray();
while (feature != null)
{
//Add feature to array
array.Add(feature.Shape);
//Add the value of the first field to the string array
sArray.Add(feature.get_Value(0).ToString());
//Set next feature
feature = enumFeature.Next();
}
//If the action is supported perform the action
if (hookActions.get_ActionSupportedOnMultiple(array, esriHookActions.esriHookActionsLabel))
hookActions.DoActionWithNameOnMultiple(array, sArray, esriHookActions.esriHookActionsLabel);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public sealed class MSBuildTask_Tests : IDisposable
{
public MSBuildTask_Tests()
{
ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
}
public void Dispose()
{
ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
}
/// <summary>
/// If we pass in an item spec that is over the max path but it can be normalized down to something under the max path, we should still work and not
/// throw a path too long exception
/// </summary>
[Fact]
[ActiveIssue("https://github.com/Microsoft/msbuild/issues/4247")]
public void ProjectItemSpecTooLong()
{
string currentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Path.GetTempPath());
string tempPath = Path.GetTempPath();
string tempProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB; TargetC` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`TargetA` Outputs=`a1.dll`/>
<Target Name=`TargetB` Outputs=`b1.dll; b2.dll`/>
<Target Name=`TargetC` Outputs=`@(C_Outputs)`>
<CreateItem Include=`c1.dll` AdditionalMetadata=`MSBuildSourceProjectFile=birch; MSBuildSourceTargetName=oak`>
<Output ItemName=`C_Outputs` TaskParameter=`Include`/>
</CreateItem>
</Target>
</Project>
");
string fileName = Path.GetFileName(tempProject);
string projectFile1 = null;
for (int i = 0; i < 250; i++)
{
projectFile1 += "..\\";
}
int rootLength = Path.GetPathRoot(tempPath).Length;
string tempPathNoRoot = tempPath.Substring(rootLength);
projectFile1 += Path.Combine(tempPathNoRoot, fileName);
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<MSBuild Projects=`" + projectFile1 + @"` />
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
bool success = p.Build();
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
}
finally
{
File.Delete(tempProject);
}
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
}
}
/// <summary>
/// Ensure that the MSBuild task tags any output items with two pieces of metadata -- MSBuildSourceProjectFile and
/// MSBuildSourceTargetName -- that give an indication of where the items came from.
/// </summary>
[Fact]
public void OutputItemsAreTaggedWithProjectFileAndTargetName()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB; TargetC` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`TargetA` Outputs=`a1.dll`/>
<Target Name=`TargetB` Outputs=`b1.dll; b2.dll`/>
<Target Name=`TargetC` Outputs=`@(C_Outputs)`>
<CreateItem Include=`c1.dll`>
<Output ItemName=`C_Outputs` TaskParameter=`Include`/>
</CreateItem>
</Target>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`TargetG` Outputs=`g1.dll; g2.dll`/>
<Target Name=`TargetH` Outputs=`h1.dll`/>
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"` />
<Projects Include=`" + projectFile2 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
b2.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
c1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetC
g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG
g2.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG
h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(7, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Ensures that it is possible to call the MSBuild task with an empty Projects parameter, and it
/// shouldn't error, and it shouldn't try to build itself.
/// </summary>
[Fact]
public void EmptyProjectsParameterResultsInNoop()
{
string projectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=` @(empty) ` />
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents, logger);
bool success = project.Build();
Assert.True(success); // "Build failed. See Standard Out tab for details"
}
/// <summary>
/// Verifies that nonexistent projects aren't normally skipped
/// </summary>
[Fact]
public void NormallyDoNotSkipNonexistentProjects()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"SkipNonexistentProjectsMain.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=`this_project_does_not_exist.csproj` />
</Target>
</Project>
");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"SkipNonexistentProjectsMain.csproj");
string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj");
Assert.Contains(error, logger.FullLog);
}
/// <summary>
/// Verifies that nonexistent projects aren't normally skipped
/// </summary>
[Fact]
public void NormallyDoNotSkipNonexistentProjectsBuildInParallel()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"SkipNonexistentProjectsMain.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=`this_project_does_not_exist.csproj` BuildInParallel=`true`/>
</Target>
</Project>
");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"SkipNonexistentProjectsMain.csproj");
string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj");
Assert.Equal(0, logger.WarningCount);
Assert.Equal(1, logger.ErrorCount);
Assert.Contains(error, logger.FullLog);
}
/// <summary>
/// Verifies that nonexistent projects are skipped when requested
/// </summary>
[Fact]
public void SkipNonexistentProjects()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"SkipNonexistentProjectsMain.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=`this_project_does_not_exist.csproj;foo.csproj` SkipNonexistentProjects=`true` />
</Target>
</Project>
");
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"foo.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<Message Text=`Hello from foo.csproj`/>
</Target>
</Project>
");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"SkipNonexistentProjectsMain.csproj");
logger.AssertLogContains("Hello from foo.csproj");
string message = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFoundMessage"), "this_project_does_not_exist.csproj");
string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj");
Assert.Equal(0, logger.WarningCount);
Assert.Equal(0, logger.ErrorCount);
Assert.Contains(message, logger.FullLog); // for the missing project
Assert.DoesNotContain(error, logger.FullLog);
}
/// <summary>
/// Verifies that nonexistent projects are skipped when requested when building in parallel.
/// DDB # 125831
/// </summary>
[Fact]
public void SkipNonexistentProjectsBuildingInParallel()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"SkipNonexistentProjectsMain.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=`this_project_does_not_exist.csproj;foo.csproj` SkipNonexistentProjects=`true` BuildInParallel=`true` />
</Target>
</Project>
");
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"foo.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<Message Text=`Hello from foo.csproj`/>
</Target>
</Project>
");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"SkipNonexistentProjectsMain.csproj");
logger.AssertLogContains("Hello from foo.csproj");
string message = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFoundMessage"), "this_project_does_not_exist.csproj");
string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectFileNotFound"), "this_project_does_not_exist.csproj");
Assert.Equal(0, logger.WarningCount);
Assert.Equal(0, logger.ErrorCount);
Assert.Contains(message, logger.FullLog); // for the missing project
Assert.DoesNotContain(error, logger.FullLog);
}
[Fact]
public void LogErrorWhenBuildingVCProj()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"BuildingVCProjMain.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<MSBuild Projects=`blah.vcproj;foo.csproj` StopOnFirstFailure=`false` />
</Target>
</Project>
");
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"foo.csproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`t` >
<Message Text=`Hello from foo.csproj`/>
</Target>
</Project>
");
ObjectModelHelpers.CreateFileInTempProjectDirectory(
"blah.vcproj",
@"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<NotWellFormedMSBuildFormatTag />
<Target Name=`t` >
<Message Text=`Hello from blah.vcproj`/>
</Target>
</Project>
");
MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectFailure(@"BuildingVCProjMain.csproj");
logger.AssertLogContains("Hello from foo.csproj");
string error = String.Format(AssemblyResources.GetString("MSBuild.ProjectUpgradeNeededToVcxProj"), "blah.vcproj");
Assert.Equal(0, logger.WarningCount);
Assert.Equal(1, logger.ErrorCount);
Assert.Contains(error, logger.FullLog);
}
#if FEATURE_COMPILE_IN_TESTS
/// <summary>
/// Regression test for bug 533369. Calling the MSBuild task, passing in a property
/// in the Properties parameter that has a special character in its value, such as semicolon.
/// However, it's a situation where the project author doesn't have control over the
/// property value and so he can't escape it himself.
/// </summary>
[Fact]
public void PropertyOverridesContainSemicolon()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// -------------------------------------------------------
// ConsoleApplication1.csproj
// -------------------------------------------------------
// Just a normal console application project.
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"bug'533'369\Sub;Dir\ConsoleApplication1\ConsoleApplication1.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Exe</OutputType>
<AssemblyName>ConsoleApplication1</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Reference Include=`System.Data` />
<Reference Include=`System.Xml` />
</ItemGroup>
<ItemGroup>
<Compile Include=`Program.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// -------------------------------------------------------
// Program.cs
// -------------------------------------------------------
// Just a normal console application project.
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"bug'533'369\Sub;Dir\ConsoleApplication1\Program.cs", @"
using System;
namespace ConsoleApplication32
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(`Hello world`);
}
}
}
");
// -------------------------------------------------------
// TeamBuild.proj
// -------------------------------------------------------
// Attempts to build the above ConsoleApplication1.csproj by calling the MSBuild task,
// and overriding the OutDir property. However, the value being passed into OutDir
// is coming from another property which is produced by CreateProperty and has
// some special characters in it.
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"bug'533'369\Sub;Dir\TeamBuild.proj", @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<CreateProperty Value=`$(MSBuildProjectDirectory)\binaries\`>
<Output PropertyName=`MasterOutDir` TaskParameter=`Value`/>
</CreateProperty>
<MSBuild Projects=`ConsoleApplication1\ConsoleApplication1.csproj`
Properties=`OutDir=$(MasterOutDir)`
Targets=`Rebuild`/>
</Target>
</Project>
");
ObjectModelHelpers.BuildTempProjectFileExpectSuccess(@"bug'533'369\Sub;Dir\TeamBuild.proj");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bug'533'369\Sub;Dir\binaries\ConsoleApplication1.exe");
}
#endif
/// <summary>
/// Check if passing different global properties via metadata works
/// </summary>
[Fact]
public void DifferentGlobalPropertiesWithDefault()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"` />
<Projects Include=`" + projectFile1 + @"`>
<Properties>MyProp=1</Properties>
</Projects>
<Projects Include=`" + projectFile2 + @"` />
<Projects Include=`" + projectFile2 + @"`>
<Properties>MyProp=1</Properties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Properties=`MyProp=0`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG
h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(4, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check if passing different global properties via metadata works
/// </summary>
[Fact]
public void DifferentGlobalPropertiesWithoutDefault()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"` />
<Projects Include=`" + projectFile1 + @"`>
<Properties>MyProp=1</Properties>
</Projects>
<Projects Include=`" + projectFile2 + @"` />
<Projects Include=`" + projectFile2 + @"`>
<Properties>MyProp=1</Properties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(2, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check trailing semicolons are ignored
/// </summary>
[Fact]
public void VariousPropertiesToMSBuildTask()
{
string projectFile = null;
try
{
projectFile = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<PR Include='$(MSBuildProjectFullPath)'>
<Properties>a=a;b=b;</Properties>
<AdditionalProperties>e=e;g=1;f=f;</AdditionalProperties>
<UndefineProperties>g;h;</UndefineProperties>
</PR>
</ItemGroup>
<Target Name='a'>
<MSBuild Projects='@(PR)' Properties='c=c;d=d;' RemoveProperties='i;c;' Targets='b'/>
</Target>
<Target Name='b'>
<Message Text='a=[$(a)]' Importance='High' />
<Message Text='b=[$(b)]' Importance='High' />
<Message Text='c=[$(c)]' Importance='High' />
<Message Text='d=[$(d)]' Importance='High' />
<Message Text='e=[$(e)]' Importance='High' />
<Message Text='f=[$(f)]' Importance='High' />
<Message Text='g=[$(g)]' Importance='High' />
</Target>
</Project>
");
var logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess(projectFile);
Console.WriteLine(logger.FullLog);
logger.AssertLogContains("a=[a]");
logger.AssertLogContains("b=[b]");
logger.AssertLogContains("c=[]");
logger.AssertLogContains("d=[]");
logger.AssertLogContains("e=[e]");
logger.AssertLogContains("f=[f]");
logger.AssertLogContains("g=[]");
}
finally
{
File.Delete(projectFile);
}
}
/// <summary>
/// Check if passing different global properties via metadata works
/// </summary>
[Fact]
public void DifferentGlobalPropertiesWithBlanks()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"` />
<Projects Include=`" + projectFile1 + @"`>
<Properties></Properties>
</Projects>
<Projects Include=`" + projectFile2 + @"` />
<Projects Include=`" + projectFile2 + @"`>
<Properties>MyProp=1</Properties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
h1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetH
", projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Single(targetOutputs["Build"].Items);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check if passing different global properties via metadata works
/// </summary>
[Fact]
public void DifferentGlobalPropertiesInvalid()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyProp)'=='0'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyProp)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyProp)'=='0'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyProp)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"` />
<Projects Include=`" + projectFile1 + @"`>
<Properties>=1</Properties>
</Projects>
<Projects Include=`" + projectFile2 + @"` />
<Projects Include=`" + projectFile2 + @"`>
<Properties>=;1</Properties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
bool success = p.Build();
Assert.False(success); // "Build succeeded. See 'Standard Out' tab for details."
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check if passing additional global properties via metadata works
/// </summary>
[Fact]
public void DifferentAdditionalPropertiesWithDefault()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='1'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='1'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"`>
<AdditionalProperties>MyPropA=1</AdditionalProperties>
</Projects>
<Projects Include=`" + projectFile2 + @"`>
<AdditionalProperties>MyPropA=0</AdditionalProperties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Properties=`MyPropG=1`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
a1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetA
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(3, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check if passing additional global properties via metadata works
/// </summary>
[Fact]
public void DifferentAdditionalPropertiesWithGlobalProperties()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='0'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='0'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"`>
<Properties>MyPropG=1</Properties>
<AdditionalProperties>MyPropA=1</AdditionalProperties>
</Projects>
<Projects Include=`" + projectFile2 + @"`>
<Properties>MyPropG=0</Properties>
<AdditionalProperties>MyPropA=1</AdditionalProperties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Properties=`MyPropG=1`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
g1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetG
h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(3, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Check if passing additional global properties via metadata works
/// </summary>
[Fact]
public void DifferentAdditionalPropertiesWithoutDefault()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetA; TargetB` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetA` Outputs=`a1.dll` Condition=`'$(MyPropG)'=='1'`/>
<Target Name=`TargetB` Outputs=`b1.dll` Condition=`'$(MyPropA)'=='1'`/>
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`TargetG; TargetH` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`TargetG` Outputs=`g1.dll` Condition=`'$(MyPropG)'=='1'` />
<Target Name=`TargetH` Outputs=`h1.dll` Condition=`'$(MyPropA)'=='1'` />
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile1 + @"`>
<AdditionalProperties>MyPropA=1</AdditionalProperties>
</Projects>
<Projects Include=`" + projectFile2 + @"`>
<AdditionalProperties>MyPropA=1</AdditionalProperties>
</Projects>
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
string expectedItemOutputs = string.Format(@"
b1.dll : MSBuildSourceProjectFile={0} ; MSBuildSourceTargetName=TargetB
h1.dll : MSBuildSourceProjectFile={1} ; MSBuildSourceTargetName=TargetH
", projectFile1, projectFile2);
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(2, targetOutputs["Build"].Items.Length);
ObjectModelHelpers.AssertItemsMatch(expectedItemOutputs, targetOutputs["Build"].Items, false /* order of items not enforced */);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Properties and Targets that use non-standard separation chars
/// </summary>
[Fact]
public void TargetsWithSeparationChars()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<Target Name=`Clean` />
<Target Name=`Build` />
<Target Name=`BuildAgain` />
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<PropertyGroup>
<Targets>Clean%3BBuild%3CBuildAgain</Targets>
</PropertyGroup>
<ItemGroup>
<ProjectFile Include=`" + projectFile1 + @"` />
</ItemGroup>
<Target Name=`Build` Outputs=`$(SomeOutputs)`>
<MSBuild Projects=`@(ProjectFile)` Targets=`$(Targets)` TargetAndPropertyListSeparators=`%3B;%3C` />
</Target>
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile2 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
bool success = p.Build();
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Verify stopOnFirstFailure with BuildInParallel override message are correctly logged
/// Also verify stop on first failure will not build the second project if the first one failed
/// The Aardvark tests which also test StopOnFirstFailure are at:
/// qa\md\wd\DTP\MSBuild\ShippingExtensions\ShippingTasks\MSBuild\_Tst\MSBuild.StopOnFirstFailure
/// </summary>
[Fact]
public void StopOnFirstFailureandBuildInParallelSingleNode()
{
string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Error Text='Error'/>
</Target>
</Project>
");
string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Message Text='SecondProject'/>
</Target>
</Project>
");
try
{
ITaskItem[] projects = new ITaskItem[]
{
new TaskItem(project1), new TaskItem(project2)
};
// Test the various combinations of BuildInParallel and StopOnFirstFailure when the msbuild task is told there are not multiple nodes
// running in the system
for (int i = 0; i < 4; i++)
{
bool buildInParallel = false;
bool stopOnFirstFailure = false;
// first set up the project being built.
switch (i)
{
case 0:
buildInParallel = true;
stopOnFirstFailure = true;
break;
case 1:
buildInParallel = true;
stopOnFirstFailure = false;
break;
case 2:
buildInParallel = false;
stopOnFirstFailure = true;
break;
case 3:
buildInParallel = false;
stopOnFirstFailure = false;
break;
}
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + project1 + @"` />
<Projects Include=`" + project2 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`" + buildInParallel.ToString() + @"` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
MockLogger logger = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents, logger);
bool success = p.Build(logger);
switch (i)
{
case 0:
// Verify setting BuildInParallel and StopOnFirstFailure to
// true will cause the msbuild task to set BuildInParallel to false during the execute
// Verify build did not build second project which has the message SecondProject
logger.AssertLogDoesntContain("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 1:
// Verify setting BuildInParallel to true and StopOnFirstFailure to
// false will cause no change in BuildInParallel
// Verify build did build second project which has the message SecondProject
logger.AssertLogContains("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 2:
// Verify build did not build second project which has the message SecondProject
logger.AssertLogDoesntContain("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 3:
// Verify setting BuildInParallel to false and StopOnFirstFailure to
// false will cause no change in BuildInParallel
// Verify build did build second project which has the message SecondProject
logger.AssertLogContains("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
}
// The build should fail as the first project has an error
Assert.False(success, "Iteration of i " + i + " Build Succeeded. See 'Standard Out' tab for details.");
}
}
finally
{
File.Delete(project1);
File.Delete(project2);
}
}
#if FEATURE_APPDOMAIN
/// <summary>
/// Verify stopOnFirstFailure with BuildInParallel override message are correctly logged when there are multiple nodes
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void StopOnFirstFailureandBuildInParallelMultipleNode()
{
string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Error Text='Error'/>
</Target>
</Project>
");
string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Message Text='SecondProject'/>
</Target>
</Project>
");
try
{
// Test the various combinations of BuildInParallel and StopOnFirstFailure when the msbuild task is told there are multiple nodes
// running in the system
for (int i = 0; i < 4; i++)
{
bool buildInParallel = false;
bool stopOnFirstFailure = false;
// first set up the project being built.
switch (i)
{
case 0:
buildInParallel = true;
stopOnFirstFailure = true;
break;
case 1:
buildInParallel = true;
stopOnFirstFailure = false;
break;
case 2:
buildInParallel = false;
stopOnFirstFailure = true;
break;
case 3:
buildInParallel = false;
stopOnFirstFailure = false;
break;
}
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + project1 + @"` />
<Projects Include=`" + project2 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`" + buildInParallel.ToString() + @"` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
MockLogger logger = new MockLogger();
ProjectCollection pc = new ProjectCollection(null, new List<ILogger> { logger }, null, ToolsetDefinitionLocations.Default, 2, false);
Project p = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger);
bool success = p.Build();
switch (i)
{
case 0:
// Verify build did build second project which has the message SecondProject
logger.AssertLogContains("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 1:
// Verify setting BuildInParallel to true and StopOnFirstFailure to
// false will cause no change in BuildInParallel
// Verify build did build second project which has the message SecondProject
logger.AssertLogContains("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 2:
// Verify setting BuildInParallel to false and StopOnFirstFailure to
// true will cause no change in BuildInParallel
// Verify build did not build second project which has the message SecondProject
logger.AssertLogDoesntContain("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
case 3:
// Verify setting BuildInParallel to false and StopOnFirstFailure to
// false will cause no change in BuildInParallel
// Verify build did build second project which has the message SecondProject
logger.AssertLogContains("SecondProject");
// Verify the correct msbuild task messages are in the log
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NoStopOnFirstFailure"));
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.NotBuildingInParallel"));
break;
}
// The build should fail as the first project has an error
Assert.False(success, "Iteration of i " + i + " Build Succeeded. See 'Standard Out' tab for details.");
}
}
finally
{
File.Delete(project1);
File.Delete(project2);
}
}
#endif
/// <summary>
/// Test the skipping of the remaining projects. Verify the skip message is only displayed when there are projects to skip.
/// </summary>
[Fact]
public void SkipRemainingProjects()
{
string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Error Text='Error'/>
</Target>
</Project>
");
string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='msbuild'>
<Message Text='SecondProject'/>
</Target>
</Project>
");
try
{
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + project1 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`false` StopOnFirstFailure=`true`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
MockLogger logger = new MockLogger();
ProjectCollection pc = new ProjectCollection(null, new List<ILogger> { logger }, null, ToolsetDefinitionLocations.Default, 2, false);
Project p = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger);
bool success = p.Build();
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
Assert.False(success); // "Build Succeeded. See 'Standard Out' tab for details."
parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + project2 + @"` />
<Projects Include=`" + project1 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Targets=`msbuild` BuildInParallel=`false` StopOnFirstFailure=`true`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
MockLogger logger2 = new MockLogger();
Project p2 = ObjectModelHelpers.CreateInMemoryProject(pc, parentProjectContents, logger2);
bool success2 = p2.Build();
logger2.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingProjects"));
Assert.False(success2); // "Build Succeeded. See 'Standard Out' tab for details."
}
finally
{
File.Delete(project1);
File.Delete(project2);
}
}
/// <summary>
/// Verify the behavior of Target execution with StopOnFirstFailure
/// </summary>
[Fact]
public void TargetStopOnFirstFailureBuildInParallel()
{
string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name='T1'>
<Message Text='Proj2 T1 message'/>
</Target>
<Target Name='T2'>
<Message Text='Proj2 T2 message'/>
</Target>
<Target Name='T3'>
<Error Text='Error'/>
</Target>
</Project>
");
try
{
ITaskItem[] projects = new ITaskItem[]
{
new TaskItem(project1)
};
for (int i = 0; i < 6; i++)
{
bool stopOnFirstFailure = false;
bool runEachTargetSeparately = false;
string target1 = String.Empty;
string target2 = String.Empty;
string target3 = String.Empty;
switch (i)
{
case 0:
stopOnFirstFailure = true;
runEachTargetSeparately = true;
target1 = "T1";
target2 = "T2";
target3 = "T3";
break;
case 1:
stopOnFirstFailure = true;
runEachTargetSeparately = true;
target1 = "T1";
target2 = "T3";
target3 = "T2";
break;
case 2:
stopOnFirstFailure = false;
runEachTargetSeparately = true;
target1 = "T1";
target2 = "T3";
target3 = "T2";
break;
case 3:
stopOnFirstFailure = true;
target1 = "T1";
target2 = "T2";
target3 = "T3";
break;
case 4:
stopOnFirstFailure = true;
target1 = "T1";
target2 = "T3";
target3 = "T2";
break;
case 5:
stopOnFirstFailure = false;
target1 = "T1";
target2 = "T3";
target3 = "T2";
break;
}
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + project1 + @"` />
</ItemGroup>
<ItemGroup>
<Targets Include=`" + target1 + @"` />
<Targets Include=`" + target2 + @"` />
<Targets Include=`" + target3 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)` Targets=`@(Targets)` StopOnFirstFailure=`" + stopOnFirstFailure.ToString() + @"` RunEachTargetSeparately=`" + runEachTargetSeparately.ToString() + @"`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
MockLogger logger = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents, logger);
bool success = p.Build();
switch (i)
{
case 0:
// Test the case where the error is in the last project and RunEachTargetSeparately = true
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogContains("Proj2 T2 message");
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
break;
case 1:
// Test the case where the error is in the second target out of 3.
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogContains(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
logger.AssertLogDoesntContain("Proj2 T2 message");
// The build should fail as the first project has an error
break;
case 2:
// Test case where error is in second last target but stopOnFirstFailure is false
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogContains("Proj2 T2 message");
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
break;
// Test the cases where RunEachTargetSeparately is false. In these cases all of the targets should be submitted at once
case 3:
// Test the case where the error is in the last project and RunEachTargetSeparately = true
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogContains("Proj2 T2 message");
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
// The build should fail as the first project has an error
break;
case 4:
// Test the case where the error is in the second target out of 3.
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogDoesntContain("Proj2 T2 message");
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
// The build should fail as the first project has an error
break;
case 5:
// Test case where error is in second last target but stopOnFirstFailure is false
logger.AssertLogContains("Proj2 T1 message");
logger.AssertLogDoesntContain("Proj2 T2 message");
logger.AssertLogDoesntContain(AssemblyResources.GetString("MSBuild.SkippingRemainingTargets"));
break;
}
// The build should fail as the first project has an error
Assert.False(success, "Iteration of i:" + i + "Build Succeeded. See 'Standard Out' tab for details.");
}
}
finally
{
File.Delete(project1);
}
}
/// <summary>
/// Properties and Targets that use non-standard separation chars
/// </summary>
[Fact]
public void PropertiesWithSeparationChars()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`Build` Outputs=`|$(a)|$(b)|$(C)|$(D)|` />
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<PropertyGroup>
<AValues>a%3BA</AValues>
<BValues>b;B</BValues>
<CValues>c;C</CValues>
<DValues>d%3BD</DValues>
</PropertyGroup>
<ItemGroup>
<ProjectFile Include=`" + projectFile1 + @"`>
<AdditionalProperties>C=$(CValues)%3BD=$(DValues)</AdditionalProperties>
</ProjectFile>
</ItemGroup>
<Target Name=`Build` Outputs=`$(SomeOutputs)`>
<MSBuild Projects=`@(ProjectFile)` Targets=`Build` Properties=`a=$(AValues)%3Bb=$(BValues)` TargetAndPropertyListSeparators=`%3B`>
<Output TaskParameter=`TargetOutputs` PropertyName=`SomeOutputs`/>
</MSBuild>
</Target>
</Project>
");
string parentProjectContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<ItemGroup>
<Projects Include=`" + projectFile2 + @"` />
</ItemGroup>
<Target Name=`Build` Returns=`@(Outputs)`>
<MSBuild Projects=`@(Projects)`>
<Output TaskParameter=`TargetOutputs` ItemName=`Outputs` />
</MSBuild>
</Target>
</Project>";
try
{
ITaskItem[] projects = new ITaskItem[]
{
new TaskItem(projectFile2)
};
Project p = ObjectModelHelpers.CreateInMemoryProject(parentProjectContents);
ProjectInstance pi = p.CreateProjectInstance();
IDictionary<string, TargetResult> targetOutputs;
bool success = pi.Build(null, null, null, out targetOutputs);
Assert.True(success); // "Build failed. See 'Standard Out' tab for details."
Assert.True(targetOutputs.ContainsKey("Build"));
Assert.Equal(5, targetOutputs["Build"].Items.Length);
Assert.Equal("|a", targetOutputs["Build"].Items[0].ItemSpec);
Assert.Equal("A|b", targetOutputs["Build"].Items[1].ItemSpec);
Assert.Equal("B|c", targetOutputs["Build"].Items[2].ItemSpec);
Assert.Equal("C|d", targetOutputs["Build"].Items[3].ItemSpec);
Assert.Equal("D|", targetOutputs["Build"].Items[4].ItemSpec);
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
/// <summary>
/// Orcas had a bug that if the target casing specified was not correct, we would still build it,
/// but not return any target outputs!
/// </summary>
[Fact]
public void TargetNameIsCaseInsensitive()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`Build` xmlns=`msbuildnamespace` ToolsVersion='msbuilddefaulttoolsversion'>
<Target Name=`bUiLd` Outputs=`foo.out` />
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project DefaultTargets=`t` xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<Target Name=`t`>
<MSBuild Projects=`" + projectFile1 + @"` Targets=`BUILD`>
<Output TaskParameter=`TargetOutputs` ItemName=`out`/>
</MSBuild>
<Message Text=`[@(out)]`/>
</Target>
</Project>
");
try
{
Project project = new Project(projectFile2);
MockLogger logger = new MockLogger();
Assert.True(project.Build(logger));
logger.AssertLogContains("[foo.out]");
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
[Fact]
public void ProjectFileWithoutNamespaceBuilds()
{
string projectFile1 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project>
<Target Name=`Build` Outputs=`foo.out` />
</Project>
");
string projectFile2 = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project>
<Target Name=`t`>
<MSBuild Projects=`" + projectFile1 + @"` Targets=`Build`>
<Output TaskParameter=`TargetOutputs` ItemName=`out`/>
</MSBuild>
<Message Text=`[@(out)]`/>
</Target>
</Project>
");
try
{
Project project = new Project(projectFile2);
MockLogger logger = new MockLogger();
Assert.True(project.Build(logger));
logger.AssertLogContains("[foo.out]");
}
finally
{
File.Delete(projectFile1);
File.Delete(projectFile2);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace ProCharts
{
public partial class LineChart : UserControl, ISupportInitialize
{
private Color m_BackGroundColor = Color.FromArgb(24, 24, 24);
private bool m_bIsInitializing = false;
private Rectangle rcentre;
public LineChart()
{
InitializeComponent();
}
void ISupportInitialize.BeginInit()
{
this.m_bIsInitializing = true;
}
void ISupportInitialize.EndInit()
{
this.m_bIsInitializing = false;
base.Invalidate();
}
[Browsable(true), Category("LinearGauge"), Description("Set the gauge background color"), DefaultValue(typeof(Color), "System.Drawing.Color.Black")]
public Color BackGroundColor
{
get { return m_BackGroundColor; }
set
{
m_BackGroundColor = value;
base.Invalidate();
}
}
private Color m_BevelLineColor = Color.Gray;
[Browsable(true), Category("LinearGauge"), Description("Set the gauge bevel color"), DefaultValue(typeof(Color), "System.Drawing.Color.Gray")]
public Color BevelLineColor
{
get { return m_BevelLineColor; }
set
{
m_BevelLineColor = value;
base.Invalidate();
}
}
private ChannelCollection m_channelCollection = new ChannelCollection();
public void AddPointCollection(PointCollection pc)
{
foreach (PointHelper p in pc)
{
bool foundchannel = false;
foreach (ChannelHelper ch in m_channelCollection)
{
if (ch.ChannelName == p.Channelname)
{
ch.PointCollection.Add(p);
if (p.DateTimeValue > m_MaxDateTime) m_MaxDateTime = p.DateTimeValue;
if (p.DateTimeValue < m_MinDateTime) m_MinDateTime = p.DateTimeValue;
if (p.Pointvalue < ch.MinValue) ch.MinValue = p.Pointvalue;
if (p.Pointvalue > ch.MaxValue) ch.MaxValue = p.Pointvalue;
foundchannel = true;
}
}
if (!foundchannel)
{
ChannelHelper nch = new ChannelHelper();
nch.ChannelName = p.Channelname;
nch.PointCollection.Add(p);
nch.ChannelColor = Color.FromArgb(m_channelCollection.Count * 10, 255 - (m_channelCollection.Count * 10), 128);
if (p.DateTimeValue > m_MaxDateTime) m_MaxDateTime = p.DateTimeValue;
if (p.DateTimeValue < m_MinDateTime) m_MinDateTime = p.DateTimeValue;
if (p.Pointvalue < nch.MinValue) nch.MinValue = p.Pointvalue;
if (p.Pointvalue > nch.MaxValue) nch.MaxValue = p.Pointvalue;
m_channelCollection.Add(nch);
}
}
Console.WriteLine("mindate: "+ m_MinDateTime.ToString() + " maxdate: " + m_MaxDateTime.ToString());
this.Invalidate(true);
}
private DateTime m_MinDateTime = DateTime.MaxValue;
private DateTime m_MaxDateTime = DateTime.MinValue;
private void DrawLines(Graphics g)
{
// draw each line in the linecollection
// use the x_axis scale (time!)
TimeSpan ts = new TimeSpan(m_MaxDateTime.Ticks - m_MinDateTime.Ticks);
double totalmilliseconds = ts.TotalMilliseconds;
foreach (ChannelHelper ch in m_channelCollection)
{
// First sort the points in the collection!!!
Pen p = new Pen(ch.ChannelColor);
//ch.PointCollection.SortColumn =;
//ch.PointCollection.Sort();
// then plot them
bool first = true;
int previous_x = 0;
int previous_y = 0;
foreach (PointHelper ph in ch.PointCollection)
{
if (ph.DateTimeValue >= m_MinDateTime && ph.DateTimeValue <= m_MaxDateTime)
{
// determine where to plot
TimeSpan tsp = new TimeSpan(ph.DateTimeValue.Ticks - m_MinDateTime.Ticks);
int x_offset = (int)((((float)tsp.TotalMilliseconds / (float)totalmilliseconds)) * (float)splitContainer2.Panel1.ClientRectangle.Width);
int y_offset = (int)((ph.Pointvalue - ch.MinValue) * splitContainer2.Panel1.ClientRectangle.Height / (ch.MaxValue - ch.MinValue));
int x = x_offset;
int y = splitContainer2.Panel1.ClientRectangle.Height - y_offset;
//g.DrawEllipse(p , x , y -10, 3, 3);
if (!first)
{
g.DrawLine(p, previous_x, previous_y, x, y);
}
previous_x = x;
previous_y = y;
}
first = false;
}
p.Dispose();
}
}
private void DrawScale(Graphics g)
{
// draw x scale and y scale(s)
TimeSpan ts = new TimeSpan(m_MaxDateTime.Ticks - m_MinDateTime.Ticks);
for (int t = 0; t < 10; t++)
{
}
}
private void DrawText(Graphics g)
{
}
private void DrawNumbers(Graphics g)
{
}
private bool m_bShowHighlight = true;
[Browsable(true), Category("LinearGauge"), Description("Switches highlighting of the gauge on and off"), DefaultValue(typeof(bool), "true")]
public bool ShowHighlight
{
get { return m_bShowHighlight; }
set
{
if (m_bShowHighlight != value)
{
m_bShowHighlight = value;
base.Invalidate();
}
}
}
private byte m_nHighlightOpaqueEnd = 30;
[DefaultValue(50), Browsable(true), Category("LinearGauge"), Description("Set the opaque value of the highlight")]
public byte HighlightOpaqueEnd
{
get
{
return this.m_nHighlightOpaqueEnd;
}
set
{
if (value > 100)
{
throw new ArgumentException("This value should be between 0 and 50");
}
if (this.m_nHighlightOpaqueEnd != value)
{
this.m_nHighlightOpaqueEnd = value;
//if (!this.m_bIsInitializing)
//{
base.Invalidate();
//}
}
}
}
private byte m_nHighlightOpaqueStart = 100;
[DefaultValue(100), Browsable(true), Category("LinearGauge"), Description("Set the opaque start value of the highlight")]
public byte HighlightOpaqueStart
{
get
{
return this.m_nHighlightOpaqueStart;
}
set
{
if (value > 255)
{
throw new ArgumentException("This value should be between 0 and 50");
}
if (this.m_nHighlightOpaqueStart != value)
{
this.m_nHighlightOpaqueStart = value;
//if (!this.m_bIsInitializing)
//{
base.Invalidate();
//}
}
}
}
private void DrawHighlight(Graphics g)
{
if (this.m_bShowHighlight)
{
Rectangle clientRectangle = splitContainer2.Panel1.ClientRectangle;
clientRectangle.Height = clientRectangle.Height >> 1;
clientRectangle.Inflate(-2, -2);
Color color = Color.FromArgb(this.m_nHighlightOpaqueStart, 0xff, 0xff, 0xff);
Color color2 = Color.FromArgb(this.m_nHighlightOpaqueEnd, 0xff, 0xff, 0xff);
this.DrawRoundRect(g, clientRectangle, /*((this.m_nCornerRadius - 1) > 1) ? ((float)(this.m_nCornerRadius - 1)) :*/ ((float)1), color, color2, Color.Empty, 0, true, false);
}
else
{
/*Rectangle clientRectangle = base.ClientRectangle;
clientRectangle.Height = clientRectangle.Height >> 1;
clientRectangle.Inflate(-2, -2);
Color color = Color.FromArgb(100, 0xff, 0xff, 0xff);
Color color2 = Color.FromArgb(this.m_nHighlightOpaque, 0xff, 0xff, 0xff);
Brush backGroundBrush = new SolidBrush(Color.FromArgb(120, Color.Silver));
g.FillEllipse(backGroundBrush, clientRectangle);*/
}
}
private void DrawRoundRect(Graphics g, Rectangle rect, float radius, Color col1, Color col2, Color colBorder, int nBorderWidth, bool bGradient, bool bDrawBorder)
{
GraphicsPath path = new GraphicsPath();
float width = radius + radius;
RectangleF ef = new RectangleF(0f, 0f, width, width);
Brush brush = null;
ef.X = rect.Left;
ef.Y = rect.Top;
path.AddArc(ef, 180f, 90f);
ef.X = (rect.Right - 1) - width;
path.AddArc(ef, 270f, 90f);
ef.Y = (rect.Bottom - 1) - width;
path.AddArc(ef, 0f, 90f);
ef.X = rect.Left;
path.AddArc(ef, 90f, 90f);
path.CloseFigure();
if (bGradient)
{
brush = new LinearGradientBrush(rect, col1, col2, 90f, false);
}
else
{
brush = new SolidBrush(col1);
}
//g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillPath(brush, path);
if (/*bDrawBorder*/ true)
{
Pen pen = new Pen(colBorder);
pen.Width = nBorderWidth;
g.DrawPath(pen, path);
pen.Dispose();
}
g.SmoothingMode = SmoothingMode.None;
brush.Dispose();
path.Dispose();
}
private void LineChart_Resize(object sender, EventArgs e)
{
base.Invalidate();
}
private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
{
if (!this.IsDisposed)
{
Graphics g = e.Graphics;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.AntiAlias;
this.DrawBackground(g);
if ((base.ClientRectangle.Height >= 85) && (base.ClientRectangle.Width >= 85))
{
this.DrawNumbers(g);
this.DrawText(g);
}
this.DrawScale(g);
this.DrawLines(g);
this.DrawHighlight(g);
} //g.Dispose();
}
private void GetCenterRectangle()
{
rcentre = new Rectangle(splitContainer2.Panel1.ClientRectangle.X + splitContainer2.Panel1.ClientRectangle.Width / 8, splitContainer2.Panel1.ClientRectangle.Y + (splitContainer2.Panel1.ClientRectangle.Height * 3) / 8, (splitContainer2.Panel1.ClientRectangle.Width * 6) / 8, (splitContainer2.Panel1.ClientRectangle.Height * 2) / 8);
}
private void DrawBackground(Graphics g)
{
SolidBrush b = new SolidBrush(m_BackGroundColor);
g.FillRectangle(b, splitContainer2.Panel1.ClientRectangle);
RectangleF r = splitContainer2.Panel1.ClientRectangle;
r.Inflate(-3, -3);
Pen p = new Pen(m_BevelLineColor, 2);
g.DrawRectangle(p, new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height));
//g.DrawRectangle(Pens.DimGray, rcentre);
b.Dispose();
p.Dispose();
}
private void splitContainer2_Panel1_Resize(object sender, EventArgs e)
{
GetCenterRectangle();
}
private int m_numberOfDivisions = 10;
/* private void GetCenterRectangle()
{
rcentre = new Rectangle(this.ClientRectangle.X + this.ClientRectangle.Width / 8, this.ClientRectangle.Y + (this.ClientRectangle.Height * 3) / 8, (this.ClientRectangle.Width * 6) / 8, (this.ClientRectangle.Height * 2) / 8);
}*/
private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
{
SolidBrush b = new SolidBrush(m_BackGroundColor);
e.Graphics.FillRectangle(b, splitContainer2.Panel2.ClientRectangle);
b.Dispose();
// paint all x axis stuff
if (m_channelCollection.Count > 0)
{
// background
// values
TimeSpan ts = new TimeSpan(m_MaxDateTime.Ticks - m_MinDateTime.Ticks);
double totalmilliseconds = ts.TotalMilliseconds;
int sizex = splitContainer2.Panel2.ClientRectangle.Width;
float sizeperdivision = (float)sizex / (float)m_numberOfDivisions;
for (int xscale = 1; xscale < m_numberOfDivisions; xscale++)
{
float xpos = (float)xscale * sizeperdivision;
float doutstr = (float)totalmilliseconds * ((float)xscale/ (float)m_numberOfDivisions);
string outstr = doutstr.ToString("F1");
SizeF textSize = e.Graphics.MeasureString(outstr, this.Font);
float xpostext = xpos - textSize.Width / 2;
e.Graphics.DrawString(outstr, this.Font, Brushes.Wheat, xpostext, 10F);
e.Graphics.DrawLine(Pens.Wheat, xpos, 0, xpos, 8);
}
}
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
SolidBrush b = new SolidBrush(m_BackGroundColor);
e.Graphics.FillRectangle(b, splitContainer1.Panel1.ClientRectangle);
b.Dispose();
// draw y scales
// one scale for every channel
int channelnumber = 0;
foreach (ChannelHelper ch in m_channelCollection)
{
// determine x position for text
SolidBrush sb = new SolidBrush(ch.ChannelColor);
double totalscale = ch.MaxValue - ch.MinValue;
int sizey = splitContainer2.Panel1.ClientRectangle.Height;
float sizeperdivision = (float)sizey / (float)m_numberOfDivisions;
for (int yscale = 1; yscale < m_numberOfDivisions; yscale++)
{
float ypos = (float)yscale * sizeperdivision;
float doutstr = (float)totalscale * ((float)(m_numberOfDivisions - yscale) / (float)m_numberOfDivisions) + ch.MinValue;
string outstr = doutstr.ToString("F1");
SizeF textSize = e.Graphics.MeasureString(outstr, this.Font);
float ypostext = ypos - textSize.Width / 2;
e.Graphics.DrawString(outstr, this.Font, sb, channelnumber * (65), ypostext);
}
string text = ch.ChannelName;
float width = e.Graphics.MeasureString(text, this.Font).Width;
float height = e.Graphics.MeasureString(text, this.Font).Height;
double angle = Math.PI/2;
float rotationAngle = -90;
e.Graphics.TranslateTransform((channelnumber * 65) + 10, splitContainer1.Panel1.ClientRectangle.Height - 100);
//(splitContainer1.Panel1.ClientRectangle.Width + (float)(height * Math.Sin(angle)) - (float)(width * Math.Cos(angle))) / 2,
//(splitContainer1.Panel1.ClientRectangle.Height - (float)(height * Math.Cos(angle)) - (float)(width * Math.Sin(angle))) / 6);
e.Graphics.RotateTransform((float)rotationAngle);
e.Graphics.DrawString(text, this.Font, sb, 0, 0);
e.Graphics.ResetTransform();
sb.Dispose();
channelnumber++;
}
}
}
}
| |
using Discord.Audio;
using Discord.Rest;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ChannelModel = Discord.API.Channel;
using EmojiUpdateModel = Discord.API.Gateway.GuildEmojiUpdateEvent;
using ExtendedModel = Discord.API.Gateway.ExtendedGuild;
using GuildSyncModel = Discord.API.Gateway.GuildSyncEvent;
using MemberModel = Discord.API.GuildMember;
using Model = Discord.API.Guild;
using PresenceModel = Discord.API.Presence;
using RoleModel = Discord.API.Role;
using UserModel = Discord.API.User;
using VoiceStateModel = Discord.API.VoiceState;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based guild object.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketGuild : SocketEntity<ulong>, IGuild, IDisposable
{
#pragma warning disable IDISP002, IDISP006
private readonly SemaphoreSlim _audioLock;
private TaskCompletionSource<bool> _syncPromise, _downloaderPromise;
private TaskCompletionSource<AudioClient> _audioConnectPromise;
private ConcurrentHashSet<ulong> _channels;
private ConcurrentDictionary<ulong, SocketGuildUser> _members;
private ConcurrentDictionary<ulong, SocketRole> _roles;
private ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
private ImmutableArray<GuildEmote> _emotes;
private ImmutableArray<string> _features;
private AudioClient _audioClient;
#pragma warning restore IDISP002, IDISP006
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public int AFKTimeout { get; private set; }
/// <inheritdoc />
public bool IsEmbeddable { get; private set; }
/// <inheritdoc />
public VerificationLevel VerificationLevel { get; private set; }
/// <inheritdoc />
public MfaLevel MfaLevel { get; private set; }
/// <inheritdoc />
public DefaultMessageNotifications DefaultMessageNotifications { get; private set; }
/// <inheritdoc />
public ExplicitContentFilterLevel ExplicitContentFilter { get; private set; }
/// <summary>
/// Gets the number of members.
/// </summary>
/// <remarks>
/// This property retrieves the number of members returned by Discord.
/// <note type="tip">
/// <para>
/// Due to how this property is returned by Discord instead of relying on the WebSocket cache, the
/// number here is the most accurate in terms of counting the number of users within this guild.
/// </para>
/// <para>
/// Use this instead of enumerating the count of the
/// <see cref="Discord.WebSocket.SocketGuild.Users" /> collection, as you may see discrepancy
/// between that and this property.
/// </para>
/// </note>
/// </remarks>
public int MemberCount { get; internal set; }
/// <summary> Gets the number of members downloaded to the local guild cache. </summary>
public int DownloadedMemberCount { get; private set; }
internal bool IsAvailable { get; private set; }
/// <summary> Indicates whether the client is connected to this guild. </summary>
public bool IsConnected { get; internal set; }
/// <inheritdoc />
public ulong? ApplicationId { get; internal set; }
internal ulong? AFKChannelId { get; private set; }
internal ulong? EmbedChannelId { get; private set; }
internal ulong? SystemChannelId { get; private set; }
/// <inheritdoc />
public ulong OwnerId { get; private set; }
/// <summary> Gets the user that owns this guild. </summary>
public SocketGuildUser Owner => GetUser(OwnerId);
/// <inheritdoc />
public string VoiceRegionId { get; private set; }
/// <inheritdoc />
public string IconId { get; private set; }
/// <inheritdoc />
public string SplashId { get; private set; }
/// <inheritdoc />
public PremiumTier PremiumTier { get; private set; }
/// <inheritdoc />
public string BannerId { get; private set; }
/// <inheritdoc />
public string VanityURLCode { get; private set; }
/// <inheritdoc />
public SystemChannelMessageDeny SystemChannelFlags { get; private set; }
/// <inheritdoc />
public string Description { get; private set; }
/// <inheritdoc />
public int PremiumSubscriptionCount { get; private set; }
/// <inheritdoc />
public string PreferredLocale { get; private set; }
/// <inheritdoc />
public CultureInfo PreferredCulture { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public string IconUrl => CDN.GetGuildIconUrl(Id, IconId);
/// <inheritdoc />
public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId);
/// <inheritdoc />
public string BannerUrl => CDN.GetGuildBannerUrl(Id, BannerId);
/// <summary> Indicates whether the client has all the members downloaded to the local guild cache. </summary>
public bool HasAllMembers => MemberCount == DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted;
/// <summary> Indicates whether the guild cache is synced to this guild. </summary>
public bool IsSynced => _syncPromise.Task.IsCompleted;
public Task SyncPromise => _syncPromise.Task;
public Task DownloaderPromise => _downloaderPromise.Task;
/// <summary>
/// Gets the <see cref="IAudioClient" /> associated with this guild.
/// </summary>
public IAudioClient AudioClient => _audioClient;
/// <summary>
/// Gets the default channel in this guild.
/// </summary>
/// <remarks>
/// This property retrieves the first viewable text channel for this guild.
/// <note type="warning">
/// This channel does not guarantee the user can send message to it, as it only looks for the first viewable
/// text channel.
/// </note>
/// </remarks>
/// <returns>
/// A <see cref="SocketTextChannel"/> representing the first viewable channel that the user has access to.
/// </returns>
public SocketTextChannel DefaultChannel => TextChannels
.Where(c => CurrentUser.GetPermissions(c).ViewChannel)
.OrderBy(c => c.Position)
.FirstOrDefault();
/// <summary>
/// Gets the AFK voice channel in this guild.
/// </summary>
/// <returns>
/// A <see cref="SocketVoiceChannel" /> that the AFK users will be moved to after they have idled for too
/// long; <c>null</c> if none is set.
/// </returns>
public SocketVoiceChannel AFKChannel
{
get
{
var id = AFKChannelId;
return id.HasValue ? GetVoiceChannel(id.Value) : null;
}
}
/// <summary>
/// Gets the embed channel (i.e. the channel set in the guild's widget settings) in this guild.
/// </summary>
/// <returns>
/// A channel set within the server's widget settings; <c>null</c> if none is set.
/// </returns>
public SocketGuildChannel EmbedChannel
{
get
{
var id = EmbedChannelId;
return id.HasValue ? GetChannel(id.Value) : null;
}
}
/// <summary>
/// Gets the system channel where randomized welcome messages are sent in this guild.
/// </summary>
/// <returns>
/// A text channel where randomized welcome messages will be sent to; <c>null</c> if none is set.
/// </returns>
public SocketTextChannel SystemChannel
{
get
{
var id = SystemChannelId;
return id.HasValue ? GetTextChannel(id.Value) : null;
}
}
/// <summary>
/// Gets a collection of all text channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of message channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketTextChannel> TextChannels
=> Channels.OfType<SocketTextChannel>().ToImmutableArray();
/// <summary>
/// Gets a collection of all voice channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of voice channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketVoiceChannel> VoiceChannels
=> Channels.OfType<SocketVoiceChannel>().ToImmutableArray();
/// <summary>
/// Gets a collection of all category channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of category channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketCategoryChannel> CategoryChannels
=> Channels.OfType<SocketCategoryChannel>().ToImmutableArray();
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public SocketGuildUser CurrentUser => _members.TryGetValue(Discord.CurrentUser.Id, out SocketGuildUser member) ? member : null;
/// <summary>
/// Gets the built-in role containing all users in this guild.
/// </summary>
/// <returns>
/// A role object that represents an <c>@everyone</c> role in this guild.
/// </returns>
public SocketRole EveryoneRole => GetRole(Id);
/// <summary>
/// Gets a collection of all channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of generic channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketGuildChannel> Channels
{
get
{
var channels = _channels;
var state = Discord.State;
return channels.Select(x => state.GetChannel(x) as SocketGuildChannel).Where(x => x != null).ToReadOnlyCollection(channels);
}
}
/// <inheritdoc />
public IReadOnlyCollection<GuildEmote> Emotes => _emotes;
/// <inheritdoc />
public IReadOnlyCollection<string> Features => _features;
/// <summary>
/// Gets a collection of users in this guild.
/// </summary>
/// <remarks>
/// This property retrieves all users found within this guild.
/// <note type="warning">
/// <para>
/// This property may not always return all the members for large guilds (i.e. guilds containing
/// 100+ users). If you are simply looking to get the number of users present in this guild,
/// consider using <see cref="MemberCount"/> instead.
/// </para>
/// <para>
/// Otherwise, you may need to enable <see cref="DiscordSocketConfig.AlwaysDownloadUsers"/> to fetch
/// the full user list upon startup, or use <see cref="DownloadUsersAsync"/> to manually download
/// the users.
/// </para>
/// </note>
/// </remarks>
/// <returns>
/// A collection of guild users found within this guild.
/// </returns>
public IReadOnlyCollection<SocketGuildUser> Users => _members.ToReadOnlyCollection();
/// <summary>
/// Gets a collection of all roles in this guild.
/// </summary>
/// <returns>
/// A read-only collection of roles found within this guild.
/// </returns>
public IReadOnlyCollection<SocketRole> Roles => _roles.ToReadOnlyCollection();
internal SocketGuild(DiscordSocketClient client, ulong id)
: base(client, id)
{
_audioLock = new SemaphoreSlim(1, 1);
_emotes = ImmutableArray.Create<GuildEmote>();
_features = ImmutableArray.Create<string>();
}
internal static SocketGuild Create(DiscordSocketClient discord, ClientState state, ExtendedModel model)
{
var entity = new SocketGuild(discord, model.Id);
entity.Update(state, model);
return entity;
}
internal void Update(ClientState state, ExtendedModel model)
{
IsAvailable = !(model.Unavailable ?? false);
if (!IsAvailable)
{
if (_channels == null)
_channels = new ConcurrentHashSet<ulong>();
if (_members == null)
_members = new ConcurrentDictionary<ulong, SocketGuildUser>();
if (_roles == null)
_roles = new ConcurrentDictionary<ulong, SocketRole>();
/*if (Emojis == null)
_emojis = ImmutableArray.Create<Emoji>();
if (Features == null)
_features = ImmutableArray.Create<string>();*/
_syncPromise = new TaskCompletionSource<bool>();
_downloaderPromise = new TaskCompletionSource<bool>();
return;
}
Update(state, model as Model);
var channels = new ConcurrentHashSet<ulong>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Channels.Length * 1.05));
{
for (int i = 0; i < model.Channels.Length; i++)
{
var channel = SocketGuildChannel.Create(this, state, model.Channels[i]);
state.AddChannel(channel);
channels.TryAdd(channel.Id);
}
}
_channels = channels;
var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
{
for (int i = 0; i < model.Members.Length; i++)
{
var member = SocketGuildUser.Create(this, state, model.Members[i]);
members.TryAdd(member.Id, member);
}
DownloadedMemberCount = members.Count;
for (int i = 0; i < model.Presences.Length; i++)
{
if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
member.Update(state, model.Presences[i], true);
}
}
_members = members;
MemberCount = model.MemberCount;
var voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.VoiceStates.Length * 1.05));
{
for (int i = 0; i < model.VoiceStates.Length; i++)
{
SocketVoiceChannel channel = null;
if (model.VoiceStates[i].ChannelId.HasValue)
channel = state.GetChannel(model.VoiceStates[i].ChannelId.Value) as SocketVoiceChannel;
var voiceState = SocketVoiceState.Create(channel, model.VoiceStates[i]);
voiceStates.TryAdd(model.VoiceStates[i].UserId, voiceState);
}
}
_voiceStates = voiceStates;
_syncPromise = new TaskCompletionSource<bool>();
_downloaderPromise = new TaskCompletionSource<bool>();
var _ = _syncPromise.TrySetResultAsync(true);
/*if (!model.Large)
_ = _downloaderPromise.TrySetResultAsync(true);*/
}
internal void Update(ClientState state, Model model)
{
AFKChannelId = model.AFKChannelId;
EmbedChannelId = model.EmbedChannelId;
SystemChannelId = model.SystemChannelId;
AFKTimeout = model.AFKTimeout;
IsEmbeddable = model.EmbedEnabled;
IconId = model.Icon;
Name = model.Name;
OwnerId = model.OwnerId;
VoiceRegionId = model.Region;
SplashId = model.Splash;
VerificationLevel = model.VerificationLevel;
MfaLevel = model.MfaLevel;
DefaultMessageNotifications = model.DefaultMessageNotifications;
ExplicitContentFilter = model.ExplicitContentFilter;
ApplicationId = model.ApplicationId;
PremiumTier = model.PremiumTier;
VanityURLCode = model.VanityURLCode;
BannerId = model.Banner;
SystemChannelFlags = model.SystemChannelFlags;
Description = model.Description;
PremiumSubscriptionCount = model.PremiumSubscriptionCount.GetValueOrDefault();
PreferredLocale = model.PreferredLocale;
PreferredCulture = new CultureInfo(PreferredLocale);
if (model.Emojis != null)
{
var emojis = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
for (int i = 0; i < model.Emojis.Length; i++)
emojis.Add(model.Emojis[i].ToEntity());
_emotes = emojis.ToImmutable();
}
else
_emotes = ImmutableArray.Create<GuildEmote>();
if (model.Features != null)
_features = model.Features.ToImmutableArray();
else
_features = ImmutableArray.Create<string>();
var roles = new ConcurrentDictionary<ulong, SocketRole>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Roles.Length * 1.05));
if (model.Roles != null)
{
for (int i = 0; i < model.Roles.Length; i++)
{
var role = SocketRole.Create(this, state, model.Roles[i]);
roles.TryAdd(role.Id, role);
}
}
_roles = roles;
}
internal void Update(ClientState state, GuildSyncModel model)
{
var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
{
for (int i = 0; i < model.Members.Length; i++)
{
var member = SocketGuildUser.Create(this, state, model.Members[i]);
members.TryAdd(member.Id, member);
}
DownloadedMemberCount = members.Count;
for (int i = 0; i < model.Presences.Length; i++)
{
if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
member.Update(state, model.Presences[i], true);
}
}
_members = members;
var _ = _syncPromise.TrySetResultAsync(true);
/*if (!model.Large)
_ = _downloaderPromise.TrySetResultAsync(true);*/
}
internal void Update(ClientState state, EmojiUpdateModel model)
{
var emotes = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
for (int i = 0; i < model.Emojis.Length; i++)
emotes.Add(model.Emojis[i].ToEntity());
_emotes = emotes.ToImmutable();
}
//General
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> GuildHelper.DeleteAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyEmbedAsync(this, Discord, func, options);
/// <inheritdoc />
public Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
=> GuildHelper.ReorderChannelsAsync(this, Discord, args, options);
/// <inheritdoc />
public Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
=> GuildHelper.ReorderRolesAsync(this, Discord, args, options);
/// <inheritdoc />
public Task LeaveAsync(RequestOptions options = null)
=> GuildHelper.LeaveAsync(this, Discord, options);
//Bans
/// <summary>
/// Gets a collection of all users banned in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// ban objects that this guild currently possesses, with each object containing the user banned and reason
/// behind the ban.
/// </returns>
public Task<IReadOnlyCollection<RestBan>> GetBansAsync(RequestOptions options = null)
=> GuildHelper.GetBansAsync(this, Discord, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="user">The banned user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, user.Id, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="userId">The snowflake identifier for the banned user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, userId, options);
/// <inheritdoc />
public Task AddBanAsync(IUser user, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, user.Id, pruneDays, reason, options);
/// <inheritdoc />
public Task AddBanAsync(ulong userId, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, userId, pruneDays, reason, options);
/// <inheritdoc />
public Task RemoveBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, user.Id, options);
/// <inheritdoc />
public Task RemoveBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, userId, options);
//Channels
/// <summary>
/// Gets a channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the channel.</param>
/// <returns>
/// A generic channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketGuildChannel GetChannel(ulong id)
{
var channel = Discord.State.GetChannel(id) as SocketGuildChannel;
if (channel?.Guild.Id == Id)
return channel;
return null;
}
/// <summary>
/// Gets a text channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the text channel.</param>
/// <returns>
/// A text channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketTextChannel GetTextChannel(ulong id)
=> GetChannel(id) as SocketTextChannel;
/// <summary>
/// Gets a voice channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the voice channel.</param>
/// <returns>
/// A voice channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketVoiceChannel GetVoiceChannel(ulong id)
=> GetChannel(id) as SocketVoiceChannel;
/// <summary>
/// Gets a category channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the category channel.</param>
/// <returns>
/// A category channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketCategoryChannel GetCategoryChannel(ulong id)
=> GetChannel(id) as SocketCategoryChannel;
/// <summary>
/// Creates a new text channel in this guild.
/// </summary>
/// <example>
/// The following example creates a new text channel under an existing category named <c>Wumpus</c> with a set topic.
/// <code language="cs">
/// var categories = await guild.GetCategoriesAsync();
/// var targetCategory = categories.FirstOrDefault(x => x.Name == "wumpus");
/// if (targetCategory == null) return;
/// await Context.Guild.CreateTextChannelAsync(name, x =>
/// {
/// x.CategoryId = targetCategory.Id;
/// x.Topic = $"This channel was created at {DateTimeOffset.UtcNow} by {user}.";
/// });
/// </code>
/// </example>
/// <param name="name">The new name for the text channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// text channel.
/// </returns>
public Task<RestTextChannel> CreateTextChannelAsync(string name, Action<TextChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateTextChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a new voice channel in this guild.
/// </summary>
/// <param name="name">The new name for the voice channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// voice channel.
/// </returns>
public Task<RestVoiceChannel> CreateVoiceChannelAsync(string name, Action<VoiceChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateVoiceChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a new channel category in this guild.
/// </summary>
/// <param name="name">The new name for the category.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// category channel.
/// </returns>
public Task<RestCategoryChannel> CreateCategoryChannelAsync(string name, Action<GuildChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateCategoryChannelAsync(this, Discord, name, options, func);
internal SocketGuildChannel AddChannel(ClientState state, ChannelModel model)
{
var channel = SocketGuildChannel.Create(this, state, model);
_channels.TryAdd(model.Id);
state.AddChannel(channel);
return channel;
}
internal SocketGuildChannel RemoveChannel(ClientState state, ulong id)
{
if (_channels.TryRemove(id))
return state.RemoveChannel(id) as SocketGuildChannel;
return null;
}
//Voice Regions
/// <summary>
/// Gets a collection of all the voice regions this guild can access.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// voice regions the guild can access.
/// </returns>
public Task<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
=> GuildHelper.GetVoiceRegionsAsync(this, Discord, options);
//Integrations
public Task<IReadOnlyCollection<RestGuildIntegration>> GetIntegrationsAsync(RequestOptions options = null)
=> GuildHelper.GetIntegrationsAsync(this, Discord, options);
public Task<RestGuildIntegration> CreateIntegrationAsync(ulong id, string type, RequestOptions options = null)
=> GuildHelper.CreateIntegrationAsync(this, Discord, id, type, options);
//Invites
/// <summary>
/// Gets a collection of all invites in this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// invite metadata, each representing information for an invite found within this guild.
/// </returns>
public Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
=> GuildHelper.GetInvitesAsync(this, Discord, options);
/// <summary>
/// Gets the vanity invite URL of this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the partial metadata of
/// the vanity invite found within this guild; <c>null</c> if none is found.
/// </returns>
public Task<RestInviteMetadata> GetVanityInviteAsync(RequestOptions options = null)
=> GuildHelper.GetVanityInviteAsync(this, Discord, options);
//Roles
/// <summary>
/// Gets a role in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the role.</param>
/// <returns>
/// A role that is associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public SocketRole GetRole(ulong id)
{
if (_roles.TryGetValue(id, out SocketRole value))
return value;
return null;
}
/// <inheritdoc />
public Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
bool isHoisted = false, RequestOptions options = null)
=> GuildHelper.CreateRoleAsync(this, Discord, name, permissions, color, isHoisted, false, options);
/// <summary>
/// Creates a new role with the provided name.
/// </summary>
/// <param name="name">The new name for the role.</param>
/// <param name="permissions">The guild permission that the role should possess.</param>
/// <param name="color">The color of the role.</param>
/// <param name="isHoisted">Whether the role is separated from others on the sidebar.</param>
/// <param name="isMentionable">Whether the role can be mentioned.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// role.
/// </returns>
public Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
bool isHoisted = false, bool isMentionable = false, RequestOptions options = null)
=> GuildHelper.CreateRoleAsync(this, Discord, name, permissions, color, isHoisted, isMentionable, options);
internal SocketRole AddRole(RoleModel model)
{
var role = SocketRole.Create(this, Discord.State, model);
_roles[model.Id] = role;
return role;
}
internal SocketRole RemoveRole(ulong id)
{
if (_roles.TryRemove(id, out SocketRole role))
return role;
return null;
}
//Users
/// <inheritdoc />
public Task<RestGuildUser> AddGuildUserAsync(ulong id, string accessToken, Action<AddGuildUserProperties> func = null, RequestOptions options = null)
=> GuildHelper.AddGuildUserAsync(this, Discord, id, accessToken, func, options);
/// <summary>
/// Gets a user from this guild.
/// </summary>
/// <remarks>
/// This method retrieves a user found within this guild.
/// <note>
/// This may return <c>null</c> in the WebSocket implementation due to incomplete user collection in
/// large guilds.
/// </note>
/// </remarks>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A guild user associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public SocketGuildUser GetUser(ulong id)
{
if (_members.TryGetValue(id, out SocketGuildUser member))
return member;
return null;
}
/// <inheritdoc />
public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null)
=> GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options);
internal SocketGuildUser AddOrUpdateUser(UserModel model)
{
if (_members.TryGetValue(model.Id, out SocketGuildUser member))
member.GlobalUser?.Update(Discord.State, model);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
return member;
}
internal SocketGuildUser AddOrUpdateUser(MemberModel model)
{
if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
member.Update(Discord.State, model);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
if (member == null)
throw new InvalidOperationException("SocketGuildUser.Create failed to produce a member"); // TODO 2.2rel: delete this
if (member.GlobalUser == null)
throw new InvalidOperationException("Member was created without global user"); // TODO 2.2rel: delete this
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
if (member == null)
throw new InvalidOperationException("AddOrUpdateUser failed to produce a user"); // TODO 2.2rel: delete this
return member;
}
internal SocketGuildUser AddOrUpdateUser(PresenceModel model)
{
if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
member.Update(Discord.State, model, false);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
return member;
}
internal SocketGuildUser RemoveUser(ulong id)
{
if (_members.TryRemove(id, out SocketGuildUser member))
{
DownloadedMemberCount--;
member.GlobalUser.RemoveRef(Discord);
return member;
}
return null;
}
/// <inheritdoc />
public async Task DownloadUsersAsync()
{
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
}
internal void CompleteDownloadUsers()
{
_downloaderPromise.TrySetResultAsync(true);
}
//Audit logs
/// <summary>
/// Gets the specified number of audit log entries for this guild.
/// </summary>
/// <param name="limit">The number of audit log entries to fetch.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <param name="beforeId">The audit log entry ID to filter entries before.</param>
/// <param name="actionType">The type of actions to filter.</param>
/// <param name="userId">The user ID to filter entries for.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of the requested audit log entries.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestAuditLogEntry>> GetAuditLogsAsync(int limit, RequestOptions options = null, ulong? beforeId = null, ulong? userId = null, ActionType? actionType = null)
=> GuildHelper.GetAuditLogsAsync(this, Discord, beforeId, limit, options, userId: userId, actionType: actionType);
//Webhooks
/// <summary>
/// Gets a webhook found within this guild.
/// </summary>
/// <param name="id">The identifier for the webhook.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the webhook with the
/// specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetWebhookAsync(this, Discord, id, options);
/// <summary>
/// Gets a collection of all webhook from this guild.
/// </summary>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of webhooks found within the guild.
/// </returns>
public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null)
=> GuildHelper.GetWebhooksAsync(this, Discord, options);
//Emotes
/// <inheritdoc />
public Task<GuildEmote> GetEmoteAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetEmoteAsync(this, Discord, id, options);
/// <inheritdoc />
public Task<GuildEmote> CreateEmoteAsync(string name, Image image, Optional<IEnumerable<IRole>> roles = default(Optional<IEnumerable<IRole>>), RequestOptions options = null)
=> GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task<GuildEmote> ModifyEmoteAsync(GuildEmote emote, Action<EmoteProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options);
/// <inheritdoc />
public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null)
=> GuildHelper.DeleteEmoteAsync(this, Discord, emote.Id, options);
//Voice States
internal async Task<SocketVoiceState> AddOrUpdateVoiceStateAsync(ClientState state, VoiceStateModel model)
{
var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
var before = GetVoiceState(model.UserId) ?? SocketVoiceState.Default;
var after = SocketVoiceState.Create(voiceChannel, model);
_voiceStates[model.UserId] = after;
if (_audioClient != null && before.VoiceChannel?.Id != after.VoiceChannel?.Id)
{
if (model.UserId == CurrentUser.Id)
{
if (after.VoiceChannel != null && _audioClient.ChannelId != after.VoiceChannel?.Id)
{
_audioClient.ChannelId = after.VoiceChannel.Id;
await RepopulateAudioStreamsAsync().ConfigureAwait(false);
}
}
else
{
await _audioClient.RemoveInputStreamAsync(model.UserId).ConfigureAwait(false); //User changed channels, end their stream
if (CurrentUser.VoiceChannel != null && after.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id)
await _audioClient.CreateInputStreamAsync(model.UserId).ConfigureAwait(false);
}
}
return after;
}
internal SocketVoiceState? GetVoiceState(ulong id)
{
if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
return voiceState;
return null;
}
internal async Task<SocketVoiceState?> RemoveVoiceStateAsync(ulong id)
{
if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
{
if (_audioClient != null)
await _audioClient.RemoveInputStreamAsync(id).ConfigureAwait(false); //User changed channels, end their stream
return voiceState;
}
return null;
}
//Audio
internal AudioInStream GetAudioStream(ulong userId)
{
return _audioClient?.GetInputStream(userId);
}
internal async Task<IAudioClient> ConnectAudioAsync(ulong channelId, bool selfDeaf, bool selfMute, bool external)
{
TaskCompletionSource<AudioClient> promise;
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
promise = new TaskCompletionSource<AudioClient>();
_audioConnectPromise = promise;
if (external)
{
#pragma warning disable IDISP001
var _ = promise.TrySetResultAsync(null);
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
return null;
#pragma warning restore IDISP001
}
if (_audioClient == null)
{
var audioClient = new AudioClient(this, Discord.GetAudioId(), channelId);
audioClient.Disconnected += async ex =>
{
if (!promise.Task.IsCompleted)
{
try
{ audioClient.Dispose(); }
catch { }
_audioClient = null;
if (ex != null)
await promise.TrySetExceptionAsync(ex);
else
await promise.TrySetCanceledAsync();
return;
}
};
audioClient.Connected += () =>
{
#pragma warning disable IDISP001
var _ = promise.TrySetResultAsync(_audioClient);
#pragma warning restore IDISP001
return Task.Delay(0);
};
#pragma warning disable IDISP003
_audioClient = audioClient;
#pragma warning restore IDISP003
}
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
}
catch
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
throw;
}
finally
{
_audioLock.Release();
}
try
{
var timeoutTask = Task.Delay(15000);
if (await Task.WhenAny(promise.Task, timeoutTask).ConfigureAwait(false) == timeoutTask)
throw new TimeoutException();
return await promise.Task.ConfigureAwait(false);
}
catch
{
await DisconnectAudioAsync().ConfigureAwait(false);
throw;
}
}
internal async Task DisconnectAudioAsync()
{
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
finally
{
_audioLock.Release();
}
}
private async Task DisconnectAudioInternalAsync()
{
_audioConnectPromise?.TrySetCanceledAsync(); //Cancel any previous audio connection
_audioConnectPromise = null;
if (_audioClient != null)
await _audioClient.StopAsync().ConfigureAwait(false);
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, null, false, false).ConfigureAwait(false);
_audioClient?.Dispose();
_audioClient = null;
}
internal async Task FinishConnectAudio(string url, string token)
{
//TODO: Mem Leak: Disconnected/Connected handlers arent cleaned up
var voiceState = GetVoiceState(Discord.CurrentUser.Id).Value;
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
if (_audioClient != null)
{
await RepopulateAudioStreamsAsync().ConfigureAwait(false);
await _audioClient.StartAsync(url, Discord.CurrentUser.Id, voiceState.VoiceSessionId, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
catch (Exception e)
{
await _audioConnectPromise.SetExceptionAsync(e).ConfigureAwait(false);
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
finally
{
_audioLock.Release();
}
}
internal async Task RepopulateAudioStreamsAsync()
{
await _audioClient.ClearInputStreamsAsync().ConfigureAwait(false); //We changed channels, end all current streams
if (CurrentUser.VoiceChannel != null)
{
foreach (var pair in _voiceStates)
{
if (pair.Value.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id && pair.Key != CurrentUser.Id)
await _audioClient.CreateInputStreamAsync(pair.Key).ConfigureAwait(false);
}
}
}
/// <summary>
/// Gets the name of the guild.
/// </summary>
/// <returns>
/// A string that resolves to <see cref="Discord.WebSocket.SocketGuild.Name"/>.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id})";
internal SocketGuild Clone() => MemberwiseClone() as SocketGuild;
//IGuild
/// <inheritdoc />
ulong? IGuild.AFKChannelId => AFKChannelId;
/// <inheritdoc />
IAudioClient IGuild.AudioClient => null;
/// <inheritdoc />
bool IGuild.Available => true;
/// <inheritdoc />
ulong IGuild.DefaultChannelId => DefaultChannel?.Id ?? 0;
/// <inheritdoc />
ulong? IGuild.EmbedChannelId => EmbedChannelId;
/// <inheritdoc />
ulong? IGuild.SystemChannelId => SystemChannelId;
/// <inheritdoc />
IRole IGuild.EveryoneRole => EveryoneRole;
/// <inheritdoc />
IReadOnlyCollection<IRole> IGuild.Roles => Roles;
/// <inheritdoc />
async Task<IReadOnlyCollection<IBan>> IGuild.GetBansAsync(RequestOptions options)
=> await GetBansAsync(options).ConfigureAwait(false);
/// <inheritdoc/>
async Task<IBan> IGuild.GetBanAsync(IUser user, RequestOptions options)
=> await GetBanAsync(user, options).ConfigureAwait(false);
/// <inheritdoc/>
async Task<IBan> IGuild.GetBanAsync(ulong userId, RequestOptions options)
=> await GetBanAsync(userId, options).ConfigureAwait(false);
/// <inheritdoc />
Task<IReadOnlyCollection<IGuildChannel>> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IGuildChannel>>(Channels);
/// <inheritdoc />
Task<IGuildChannel> IGuild.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildChannel>(GetChannel(id));
/// <inheritdoc />
Task<IReadOnlyCollection<ITextChannel>> IGuild.GetTextChannelsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<ITextChannel>>(TextChannels);
/// <inheritdoc />
Task<ITextChannel> IGuild.GetTextChannelAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<ITextChannel>(GetTextChannel(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IVoiceChannel>> IGuild.GetVoiceChannelsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IVoiceChannel>>(VoiceChannels);
/// <inheritdoc />
Task<IReadOnlyCollection<ICategoryChannel>> IGuild.GetCategoriesAsync(CacheMode mode , RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<ICategoryChannel>>(CategoryChannels);
/// <inheritdoc />
Task<IVoiceChannel> IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IVoiceChannel>(GetVoiceChannel(id));
/// <inheritdoc />
Task<IVoiceChannel> IGuild.GetAFKChannelAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IVoiceChannel>(AFKChannel);
/// <inheritdoc />
Task<ITextChannel> IGuild.GetDefaultChannelAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<ITextChannel>(DefaultChannel);
/// <inheritdoc />
Task<IGuildChannel> IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildChannel>(EmbedChannel);
/// <inheritdoc />
Task<ITextChannel> IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<ITextChannel>(SystemChannel);
/// <inheritdoc />
async Task<ITextChannel> IGuild.CreateTextChannelAsync(string name, Action<TextChannelProperties> func, RequestOptions options)
=> await CreateTextChannelAsync(name, func, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IVoiceChannel> IGuild.CreateVoiceChannelAsync(string name, Action<VoiceChannelProperties> func, RequestOptions options)
=> await CreateVoiceChannelAsync(name, func, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<ICategoryChannel> IGuild.CreateCategoryAsync(string name, Action<GuildChannelProperties> func, RequestOptions options)
=> await CreateCategoryChannelAsync(name, func, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IVoiceRegion>> IGuild.GetVoiceRegionsAsync(RequestOptions options)
=> await GetVoiceRegionsAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IGuildIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options)
=> await GetIntegrationsAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IGuildIntegration> IGuild.CreateIntegrationAsync(ulong id, string type, RequestOptions options)
=> await CreateIntegrationAsync(id, type, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options)
=> await GetInvitesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IInviteMetadata> IGuild.GetVanityInviteAsync(RequestOptions options)
=> await GetVanityInviteAsync(options).ConfigureAwait(false);
/// <inheritdoc />
IRole IGuild.GetRole(ulong id)
=> GetRole(id);
/// <inheritdoc />
async Task<IRole> IGuild.CreateRoleAsync(string name, GuildPermissions? permissions, Color? color, bool isHoisted, RequestOptions options)
=> await CreateRoleAsync(name, permissions, color, isHoisted, false, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IRole> IGuild.CreateRoleAsync(string name, GuildPermissions? permissions, Color? color, bool isHoisted, bool isMentionable, RequestOptions options)
=> await CreateRoleAsync(name, permissions, color, isHoisted, isMentionable, options).ConfigureAwait(false);
/// <inheritdoc />
Task<IReadOnlyCollection<IGuildUser>> IGuild.GetUsersAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IGuildUser>>(Users);
/// <inheritdoc />
async Task<IGuildUser> IGuild.AddGuildUserAsync(ulong userId, string accessToken, Action<AddGuildUserProperties> func, RequestOptions options)
=> await AddGuildUserAsync(userId, accessToken, func, options);
/// <inheritdoc />
Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(GetUser(id));
/// <inheritdoc />
Task<IGuildUser> IGuild.GetCurrentUserAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(CurrentUser);
/// <inheritdoc />
Task<IGuildUser> IGuild.GetOwnerAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(Owner);
/// <inheritdoc />
async Task<IReadOnlyCollection<IAuditLogEntry>> IGuild.GetAuditLogsAsync(int limit, CacheMode cacheMode, RequestOptions options,
ulong? beforeId, ulong? userId, ActionType? actionType)
{
if (cacheMode == CacheMode.AllowDownload)
return (await GetAuditLogsAsync(limit, options, beforeId: beforeId, userId: userId, actionType: actionType).FlattenAsync().ConfigureAwait(false)).ToImmutableArray();
else
return ImmutableArray.Create<IAuditLogEntry>();
}
/// <inheritdoc />
async Task<IWebhook> IGuild.GetWebhookAsync(ulong id, RequestOptions options)
=> await GetWebhookAsync(id, options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IReadOnlyCollection<IWebhook>> IGuild.GetWebhooksAsync(RequestOptions options)
=> await GetWebhooksAsync(options).ConfigureAwait(false);
void IDisposable.Dispose()
{
DisconnectAudioAsync().GetAwaiter().GetResult();
_audioLock?.Dispose();
_audioClient?.Dispose();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2014 Paul Louth
//
// 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 Monad.Utility;
using System;
using System.Collections.Generic;
namespace Monad
{
/// <summary>
/// Either constructor methods
/// </summary>
public class EitherStrict
{
/// <summary>
/// Construct an Either Left monad
/// </summary>
public static EitherStrict<L, R> Left<L, R>(L left)
{
return new EitherStrict<L, R>(left);
}
/// <summary>
/// Construct an Either Right monad
/// </summary>
public static EitherStrict<L, R> Right<L, R>(R right)
{
return new EitherStrict<L, R>(right);
}
/// <summary>
/// Monadic zero
/// </summary>
public static EitherStrict<L, R> Mempty<L, R>()
{
return new EitherStrict<L, R>(default(R));
}
}
/// <summary>
/// The Either monad represents values with two possibilities: a value of Left or Right
/// Either is sometimes used to represent a value which is either correct or an error,
/// by convention, 'Left' is used to hold an error value 'Right' is used to hold a
/// correct value.
/// So you can see that Either has a very close relationship to the Error monad. However,
/// the Either monad won't capture exceptions. Either would primarily be used for
/// known error values rather than exceptional ones.
/// Once the Either monad is in the Left state it cancels the monad bind function and
/// returns immediately.
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
public struct EitherStrict<L, R> : IEquatable<EitherStrict<L, R>>
{
static readonly string TypeOfR = typeof(R).ToString();
static readonly bool IsAppendable = typeof(IAppendable<R>).IsAssignableFrom(typeof(R));
readonly L left;
readonly R right;
/// <summary>
/// Returns true if the monad object is in the Left state
/// </summary>
public readonly bool IsLeft;
/// <summary>
/// Left constructor
/// </summary>
internal EitherStrict(L left)
{
IsLeft = true;
this.left = left;
this.right = default(R);
}
/// <summary>
/// Right constructor
/// </summary>
internal EitherStrict(R right)
{
IsLeft = false;
this.right = right;
this.left = default(L);
}
/// <summary>
/// Returns true if the monad object is in the Right state
/// </summary>
public bool IsRight
{
get
{
return !IsLeft;
}
}
/// <summary>
/// Get the Left value
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Right state
/// </summary>
public L Left
{
get
{
if (!IsLeft)
throw new InvalidOperationException("Not in the left state");
return left;
}
}
/// <summary>
/// Get the Right value
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Left state
/// </summary>
public R Right
{
get
{
if (!IsRight)
throw new InvalidOperationException("Not in the right state");
return right;
}
}
/// <summary>
/// Pattern matching method for a branching expression
/// </summary>
/// <param name="Right">Action to perform if the monad is in the Right state</param>
/// <param name="Left">Action to perform if the monad is in the Left state</param>
/// <returns>T</returns>
public T Match<T>(Func<R, T> Right, Func<L, T> Left)
{
if (Right == null) throw new ArgumentNullException("Right");
if (Left == null) throw new ArgumentNullException("Left");
return IsLeft
? Left(this.Left)
: Right(this.Right);
}
/// <summary>
/// Pattern matching method for a branching expression
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Left state
/// </summary>
/// <param name="right">Action to perform if the monad is in the Right state</param>
/// <returns>T</returns>
public T MatchRight<T>(Func<R, T> right)
{
if (right == null) throw new ArgumentNullException("right");
return right(this.Right);
}
/// <summary>
/// Pattern matching method for a branching expression
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Right state
/// </summary>
/// <param name="left">Action to perform if the monad is in the Left state</param>
/// <returns>T</returns>
public T MatchLeft<T>(Func<L, T> left)
{
if (left == null) throw new ArgumentNullException("left");
return left(this.Left);
}
/// <summary>
/// Pattern matching method for a branching expression
/// Returns the defaultValue if the monad is in the Left state
/// </summary>
/// <param name="right">Action to perform if the monad is in the Right state</param>
/// <returns>T</returns>
public T MatchRight<T>(Func<R, T> right, T defaultValue)
{
if (right == null) throw new ArgumentNullException("right");
if (IsLeft)
return defaultValue;
return right(this.Right);
}
/// <summary>
/// Pattern matching method for a branching expression
/// Returns the defaultValue if the monad is in the Right state
/// </summary>
/// <param name="left">Action to perform if the monad is in the Left state</param>
/// <returns>T</returns>
public T MatchLeft<T>(Func<L, T> left, T defaultValue)
{
if (left == null) throw new ArgumentNullException("left");
if (IsRight)
return defaultValue;
return left(this.Left);
}
/// <summary>
/// Pattern matching method for a branching expression
/// </summary>
/// <param name="Right">Action to perform if the monad is in the Right state</param>
/// <param name="Left">Action to perform if the monad is in the Left state</param>
/// <returns>Unit</returns>
public Unit Match(Action<R> Right, Action<L> Left)
{
if (Right == null) throw new ArgumentNullException("Right");
if (Left == null) throw new ArgumentNullException("Left");
var self = this;
return Unit.Return(() =>
{
if (self.IsLeft)
Left(self.Left);
else
Right(self.Right);
});
}
/// <summary>
/// Pattern matching method for a branching expression
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Left state
/// </summary>
/// <param name="right">Action to perform if the monad is in the Right state</param>
/// <returns>Unit</returns>
public Unit MatchRight(Action<R> right)
{
if (right == null) throw new ArgumentNullException("right");
var self = this;
return Unit.Return(() => right(self.Right));
}
/// <summary>
/// Pattern matching method for a branching expression
/// NOTE: This throws an InvalidOperationException if the object is in the
/// Right state
/// </summary>
/// <param name="left">Action to perform if the monad is in the Left state</param>
/// <returns>Unit</returns>
public Unit MatchLeft(Action<L> left)
{
if (left == null) throw new ArgumentNullException("left");
var self = this;
return Unit.Return(() => left(self.Left));
}
/// <summary>
/// Monadic append
/// If the left-hand side or right-hand side are in a Left state, then Left propogates
/// </summary>
public static EitherStrict<L, R> operator +(EitherStrict<L, R> lhs, EitherStrict<L, R> rhs)
{
return lhs.Mappend(rhs);
}
/// <summary>
/// Left coalescing operator
/// Returns the left-hand operand if the operand is not Left; otherwise it returns the right hand operand.
/// In other words it returns the first valid option in the operand sequence.
/// </summary>
public static EitherStrict<L, R> operator |(EitherStrict<L, R> lhs, EitherStrict<L, R> rhs)
{
return lhs.IsRight
? lhs
: rhs;
}
/// <summary>
/// Returns the right-hand side if the left-hand and right-hand side are not Left.
/// In order words every operand must hold a value for the result to be Right.
/// In the case where all operands return Left, then the last operand will provide
/// its value.
/// </summary>
public static EitherStrict<L, R> operator &(EitherStrict<L, R> lhs, EitherStrict<L, R> rhs)
{
return lhs.IsRight && rhs.IsRight
? rhs
: lhs.IsRight
? rhs
: lhs;
}
/// <summary>
/// Monadic append
/// If the left-hand side or right-hand side are in a Left state, then Left propagates
/// </summary>
public EitherStrict<L, R> Mappend(EitherStrict<L, R> rhs)
{
if (IsLeft)
{
return this;
}
else
{
if (rhs.IsLeft)
{
return rhs.Left;
}
else
{
if (IsAppendable)
{
var lhs = this.Right as IAppendable<R>;
return new EitherStrict<L, R>(lhs.Append(rhs.Right));
}
else
{
// TODO: Consider replacing this with a static Reflection.Emit which does this job efficiently.
switch (TypeOfR)
{
case "System.Int64":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToInt64(right) + Convert.ToInt64(rhs.right)), typeof(R)));
case "System.UInt64":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToUInt64(right) + Convert.ToUInt64(rhs.right)), typeof(R)));
case "System.Int32":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToInt32(right) + Convert.ToInt32(rhs.right)), typeof(R)));
case "System.UInt32":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToUInt32(right) + Convert.ToUInt32(rhs.right)), typeof(R)));
case "System.Int16":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToInt16(right) + Convert.ToInt16(rhs.right)), typeof(R)));
case "System.UInt16":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToUInt16(right) + Convert.ToUInt16(rhs.right)), typeof(R)));
case "System.Decimal":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToDecimal(right) + Convert.ToDecimal(rhs.right)), typeof(R)));
case "System.Double":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToDouble(right) + Convert.ToDouble(rhs.right)), typeof(R)));
case "System.Single":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToSingle(right) + Convert.ToSingle(rhs.right)), typeof(R)));
case "System.Char":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToChar(right) + Convert.ToChar(rhs.right)), typeof(R)));
case "System.Byte":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToByte(right) + Convert.ToByte(rhs.right)), typeof(R)));
case "System.String":
return new EitherStrict<L, R>((R)Convert.ChangeType((Convert.ToString(right) + Convert.ToString(rhs.right)), typeof(R)));
default:
throw new InvalidOperationException("Type " + typeof(R).Name + " is not appendable. Consider implementing the IAppendable interface.");
}
}
}
}
}
/// <summary>
/// Converts the Either to an enumerable of R
/// </summary>
/// <returns>
/// Right: A list with one R in
/// Left: An empty list
/// </returns>
public IEnumerable<R> AsEnumerable()
{
if (IsRight)
yield return Right;
else
yield break;
}
/// <summary>
/// Converts the Either to an infinite enumerable
/// </summary>
/// <returns>
/// Just: An infinite list of R
/// Nothing: An empty list
/// </returns>
public IEnumerable<R> AsEnumerableInfinte()
{
if (IsRight)
while (true) yield return Right;
else
yield break;
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator ==(EitherStrict<L, R> lhs, EitherStrict<L, R> rhs)
{
return lhs.Equals(rhs);
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator !=(EitherStrict<L, R> lhs, EitherStrict<L, R> rhs)
{
return !lhs.Equals(rhs);
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator ==(EitherStrict<L, R> lhs, L rhs)
{
return lhs.Equals(new EitherStrict<L, R>(rhs));
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator !=(EitherStrict<L, R> lhs, L rhs)
{
return !lhs.Equals(new EitherStrict<L, R>(rhs));
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator ==(EitherStrict<L, R> lhs, R rhs)
{
return lhs.Equals(new EitherStrict<L, R>(rhs));
}
/// <summary>
/// Monadic equality
/// </summary>
public static bool operator !=(EitherStrict<L, R> lhs, R rhs)
{
return !lhs.Equals(new EitherStrict<L, R>(rhs));
}
/// <summary>
/// Implicit left operator conversion
/// </summary>
public static implicit operator EitherStrict<L, R>(L left)
{
return new EitherStrict<L, R>(left);
}
/// <summary>
/// Implicit right operator conversion
/// </summary>
public static implicit operator EitherStrict<L, R>(R right)
{
return new EitherStrict<L, R>(right);
}
public override int GetHashCode()
{
return IsLeft
? Left == null ? 0 : Left.GetHashCode()
: Right == null ? 0 : Right.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
else
{
if (obj is EitherStrict<L, R>)
{
var rhs = (EitherStrict<L, R>)obj;
return IsRight && rhs.IsRight
? Right.Equals(rhs.Right)
: IsLeft && rhs.IsLeft
? true
: false;
}
else if (obj is R)
{
var rhs = (R)obj;
return IsRight
? Right.Equals(rhs)
: false;
}
else if (obj is L)
{
var rhs = (L)obj;
return IsLeft
? Left.Equals(rhs)
: false;
}
else
{
return false;
}
}
}
public bool Equals(EitherStrict<L, R> rhs)
{
return Equals((object)rhs);
}
public bool Equals(L rhs)
{
return Equals((object)rhs);
}
public bool Equals(R rhs)
{
return Equals((object)rhs);
}
}
/// <summary>
/// Either extension methods
/// </summary>
public static class EitherStrictExt
{
/// <summary>
/// Select
/// </summary>
public static EitherStrict<L, UR> Select<L, TR, UR>(
this EitherStrict<L, TR> self,
Func<TR, UR> selector)
{
if (selector == null) throw new ArgumentNullException("selector");
if (self.IsLeft)
return EitherStrict.Left<L, UR>(self.Left);
return EitherStrict.Right<L, UR>(selector(self.Right));
}
/// <summary>
/// SelectMany
/// </summary>
public static EitherStrict<L, VR> SelectMany<L, TR, UR, VR>(
this EitherStrict<L, TR> self,
Func<TR, EitherStrict<L, UR>> selector,
Func<TR, UR, VR> projector)
{
if (selector == null) throw new ArgumentNullException("selector");
if (projector == null) throw new ArgumentNullException("projector");
if (self.IsLeft)
return EitherStrict.Left<L, VR>(self.Left);
var res = selector(self.Right);
if (res.IsLeft)
return EitherStrict.Left<L, VR>(res.Left);
return EitherStrict.Right<L, VR>(projector(self.Right, res.Right));
}
/// <summary>
/// Mconcat
/// </summary>
public static EitherStrict<L, R> Mconcat<L, R>(this IEnumerable<EitherStrict<L, R>> ms)
{
var value = ms.Head();
foreach (var m in ms.Tail())
{
if (value.IsLeft)
return value;
value = value.Mappend(m);
}
return value;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// THIS FILE IS NOT INTENDED TO BE EDITED.
//
// This file can be updated in-place using the Package Manager Console. To check for updates, run the following command:
//
// PM> Get-Package -Updates
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp.RuntimeBinder;
namespace Its.Recipes
{
/// <summary>
/// Supports chaining of expressions when intermediate values may be null, to support a fluent API style using common .NET types.
/// </summary>
#if !RecipesProject
[System.Diagnostics.DebuggerStepThrough]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
#endif
internal static partial class MaybeExtensions
{
/// <summary>
/// Returns either a value or, if it's null, the result of a function that provides an alternate value.
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="value"> The primary value. </param>
/// <param name="otherValue">
/// A function to provide an alternate value if <paramref name="value" /> is null.
/// </param>
/// <returns>
/// The value of parameter <paramref name="value" /> , unless it's null, in which case the result of calling
/// <paramref
/// name="otherValue" />
/// .
/// </returns>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfNotNull().Else(() => ...)")]
public static T Else<T>(this T value, Func<T> otherValue)
where T : class
{
if (value == null)
{
return otherValue();
}
return value;
}
/// <summary>
/// Specifies a function that will be evaluated if the source <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
/// <param name="maybe">The source maybe.</param>
/// <param name="otherValue">The value to be returned if the <see cref="Recipes.Maybe{T}" /> has no value.</param>
/// <returns>
/// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />.
/// </returns>
public static T Else<T>(this Maybe<T> maybe, Func<T> otherValue)
{
if (maybe.HasValue)
{
return maybe.Value;
}
return otherValue();
}
/// <summary>
/// Specifies a function that will be evaluated if the source <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
/// <param name="maybe">The source maybe.</param>
/// <param name="other">The value to be returned if the <see cref="Recipes.Maybe{T}" /> has no value.</param>
/// <returns>
/// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="other" />.
/// </returns>
public static Maybe<T> Else<T>(this Maybe<T> maybe, Maybe<T> other)
{
return maybe.HasValue
? maybe
: other;
}
/// <summary>
/// Specifies a function that will be evaluated if the source <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
/// <param name="maybe">The source maybe.</param>
/// <param name="otherValue">The value to be returned if the <see cref="Recipes.Maybe{T}" /> has no value.</param>
/// <returns>
/// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />.
/// </returns>
public static T Else<T>(this Maybe<Maybe<T>> maybe, Func<T> otherValue)
{
if (maybe.HasValue)
{
return maybe.Value.Else(otherValue);
}
return otherValue();
}
/// <summary>
/// Specifies a function that will be evaluated if the source <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
/// <param name="maybe">The source maybe.</param>
/// <param name="otherValue">The value to be returned if the <see cref="Recipes.Maybe{T}" /> has no value.</param>
/// <returns>
/// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />.
/// </returns>
public static T Else<T>(this Maybe<Maybe<Maybe<T>>> maybe, Func<T> otherValue)
{
if (maybe.HasValue)
{
return maybe.Value.Else(otherValue);
}
return otherValue();
}
/// <summary>
/// Specifies a function that will be evaluated if the source <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
/// <param name="maybe">The source maybe.</param>
/// <param name="otherValue">The value to be returned if the <see cref="Recipes.Maybe{T}" /> has no value.</param>
/// <returns>
/// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />.
/// </returns>
public static T Else<T>(this Maybe<Maybe<Maybe<Maybe<T>>>> maybe, Func<T> otherValue)
{
if (maybe.HasValue)
{
return maybe.Value.Else(otherValue);
}
return otherValue();
}
/// <summary>
/// Executes an action if the value of a condition is false.
/// </summary>
/// <param name="condition">
/// if set to <c>true</c> execute <paramref name="action" /> .
/// </param>
/// <param name="action">
/// The action to be executed it <paramref name="condition" /> is false..
/// </param>
/// <exception cref="ArgumentNullException">action</exception>
[Obsolete("This will be removed in v2.0.0.")]
public static void Else(
this bool condition,
Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (!condition)
{
action();
}
}
/// <summary>
/// Returns the default value for <typeparamref name="T" /> if the <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static T ElseDefault<T>(this Maybe<T> maybe)
{
return maybe.Else(() => default(T));
}
/// <summary>
/// Returns the default value for <typeparamref name="T" /> if the <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static T ElseDefault<T>(this Maybe<Maybe<T>> maybe)
{
return maybe.Else(() => default(T));
}
/// <summary>
/// Returns the default value for <typeparamref name="T" /> if the <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static T ElseDefault<T>(this Maybe<Maybe<Maybe<T>>> maybe)
{
return maybe.Else(() => default(T));
}
/// <summary>
/// Returns the default value for <typeparamref name="T" /> if the <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static T ElseDefault<T>(this Maybe<Maybe<Maybe<Maybe<T>>>> maybe)
{
return maybe.Else(() => default(T));
}
/// <summary>
/// Returns null if the source has no value.
/// </summary>
/// <typeparam name="T">The type held by the <see cref="Recipes.Maybe{T}" />.</typeparam>
public static T? ElseNull<T>(this Maybe<T> maybe)
where T : struct
{
if (maybe.HasValue)
{
return maybe.Value;
}
return null;
}
/// <summary>
/// Performs an action if the <see cref="Recipes.Maybe{T}" /> has no value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static void ElseDo<T>(this Maybe<T> maybe, Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (!maybe.HasValue)
{
action();
}
}
/// <summary>
/// If the dictionary contains a value for a specified key, executes an action passing the corresponding value.
/// </summary>
/// <typeparam name="TKey"> The type of the key. </typeparam>
/// <typeparam name="TValue"> The type of the value. </typeparam>
/// <param name="dictionary"> The dictionary. </param>
/// <param name="key"> The key. </param>
/// <param name="then">
/// An action to be invoked with the value corresponding to <paramref name="key" /> .
/// </param>
/// <exception cref="ArgumentNullException">dictionary</exception>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfContains(\"key\").ThenDo(value => ...)")]
public static void IfContains<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
Action<TValue> then)
{
TValue value;
if (dictionary != null && dictionary.TryGetValue(key, out value))
{
then(value);
}
}
/// <summary>
/// If the dictionary contains a value for a specified key, executes an action passing the corresponding value.
/// </summary>
/// <typeparam name="TKey"> The type of the key. </typeparam>
/// <typeparam name="TValue"> The type of the value. </typeparam>
/// <param name="dictionary"> The dictionary. </param>
/// <param name="key"> The key. </param>
/// <exception cref="ArgumentNullException">dictionary</exception>
public static Maybe<TValue> IfContains<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key)
{
TValue value;
if (dictionary != null && dictionary.TryGetValue(key, out value))
{
return Recipes.Maybe<TValue>.Yes(value);
}
return Recipes.Maybe<TValue>.No();
}
/// <summary>that
/// Allows two maybes to be combined.
/// </summary>
public static T1 And<T1>(
this Maybe<T1> first)
{
if (first.HasValue)
{
return first.Value;
}
return default(T1);
}
/// <summary>
/// Attempts to retrieve a value dynamically.
/// </summary>
/// <typeparam name="T">The type of the value expected to be returned.</typeparam>
/// <param name="source">The source object.</param>
/// <param name="getValue">A delegate that attempts to return a value via a dynamic invocation on the source object.</param>
/// <remarks>This method will not cast the result value to <typeparamref name="T" />. If the returned value is not of this type, then a negative <see cref="Recipes.Maybe{T}" /> will be returned.</remarks>
public static Maybe<T> IfHas<T>(
this object source,
Func<dynamic, T> getValue)
{
try
{
var value = getValue(source);
return value.IfTypeIs<T>();
}
catch (RuntimeBinderException)
{
return Recipes.Maybe<T>.No();
}
}
/// <summary>
/// Attempts to perform a series of calls depending on whether the previous calls returned non-null values.
/// </summary>
public static Maybe<T3> IfNoneNull<T1, T2, T3>(
this T1 source,
Func<T1, T2> first,
Func<T2, T3> second)
where T1 : class
where T2 : class
where T3 : class
{
return source.IfNotNull()
.Then(v => first(v).IfNotNull()
.Then(second)
.IfNotNull())
.Else(Recipes.Maybe<T3>.No);
}
/// <summary>
/// Attempts to perform a series of calls depending on whether the previous calls returned non-null values.
/// </summary>
public static Maybe<T4> IfNoneNull<T1, T2, T3, T4>(
this T1 source,
Func<T1, T2> first,
Func<T2, T3> second,
Func<T3, T4> third)
where T1 : class
where T2 : class
where T3 : class
where T4 : class
{
return source.IfNoneNull(first, second)
.Then(third)
.IfNotNull();
}
/// <summary>
/// Creates a <see cref="Recipes.Maybe{T}" />, allowing <see cref="Then" /> and <see cref="Else" /> operations to be chained and evaluated conditionally based on whether source is null.
/// </summary>
/// <typeparam name="T">The type of the instance wrapped by the <see cref="Recipes.Maybe{T}" />.</typeparam>
/// <param name="source">The source instance, which may be null.</param>
/// <remarks>This method is equivalent to <see cref="Maybe{T}(T)" />.</remarks>
public static Maybe<T> IfNotNull<T>(this T source) where T : class
{
if (source != null)
{
return Recipes.Maybe<T>.Yes(source);
}
return Recipes.Maybe<T>.No();
}
public static Maybe<T> IfNotNull<T>(this Maybe<T> source) where T : class
{
if (source.HasValue && source.Value != null)
{
return source;
}
return Recipes.Maybe<T>.No();
}
/// <summary>
/// Creates a <see cref="Recipes.Maybe{T}" />, allowing <see cref="Then" /> and <see cref="Else" /> operations to be chained and evaluated conditionally based on whether source is null.
/// </summary>
/// <typeparam name="T">The type of the instance wrapped by the <see cref="Recipes.Maybe{T}" />.</typeparam>
/// <param name="source">The source instance, which may be null.</param>
public static Maybe<T> IfNotNull<T>(this T? source)
where T : struct
{
if (source.HasValue)
{
return Recipes.Maybe<T>.Yes(source.Value);
}
return Recipes.Maybe<T>.No();
}
/// <summary>
/// Determines whether a string is null, empty, or consists entirely of whitespace.
/// </summary>
/// <param name="value">The string.</param>
public static Maybe<string> IfNotNullOrEmptyOrWhitespace(this string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
return Recipes.Maybe<string>.Yes(value);
}
return Recipes.Maybe<string>.No();
}
/// <summary>
/// Executes a specified action only if the <paramref name="source" /> object is of type <typeparamref name="T" />.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The object.</param>
/// <param name="action">
/// The action to be executed against the specified object, cast to type <typeparamref name="T" />.
/// </param>
/// <returns>
/// True if the object is of type <typeparamref name="T" />; otherwise, false.
/// </returns>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfTypeIs<T>().ThenDo(s => ...)")]
public static bool IfTypeIs<T>(
this object source,
Action<T> action)
{
if (source is T)
{
action((T) source);
return true;
}
return false;
}
/// <summary>
/// Returns a Maybe.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <returns></returns>
public static Maybe<T> IfTypeIs<T>(
this object source)
{
if (source is T)
{
return Recipes.Maybe<T>.Yes((T) source);
}
return Recipes.Maybe<T>.No();
}
/// <summary>
/// Returns the value of <paramref name="getValue" /> if <paramref name="source" /> is not null. Otherwise, returns null.
/// </summary>
/// <typeparam name="T"> The type of the source object. </typeparam>
/// <typeparam name="TResult"> The type of the result. </typeparam>
/// <param name="source"> The source object. </param>
/// <param name="getValue">
/// A delegate specifying a value to retrieve if <paramref name="source" /> is not null.
/// </param>
/// <returns>
/// If <paramref name="source" /> is not null, the value produced by <paramref name="getValue" /> ; otherwise, null.
/// </returns>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfNotNull().Then(s => ...)")]
public static TResult Maybe<T, TResult>(
this T source,
Func<T, TResult> getValue)
where T : class
where TResult : class
{
return source == null
? null
: getValue(source);
}
/// <summary>
/// Executes an action of <paramref name="action" /> if <paramref name="source" /> is not null. Otherwise, do nothing.
/// </summary>
/// <typeparam name="T"> The type of the source object. </typeparam>
/// <param name="source"> The source object. </param>
/// <param name="action">
/// A delegate specifying an action to take if <paramref name="source" /> is not null.
/// </param>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfNotNull().ThenDo(s => ...)")]
public static void Maybe<T>(this T source, Action<T> action) where T : class
{
if (source != null)
{
action(source);
}
}
/// <summary>
/// Creates a <see cref="Recipes.Maybe{T}" />, allowing <see cref="Then" /> and <see cref="Else" /> operations to be chained and evaluated conditionally based on whether source is null.
/// </summary>
/// <typeparam name="T">The type of the instance wrapped by the <see cref="Recipes.Maybe{T}" />.</typeparam>
/// <param name="source">The source instance, which may be null.</param>
/// <remarks>This method is equivalent to <see cref="IfNotNull{T}" />.</remarks>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfNotNull()")]
public static Maybe<T> Maybe<T>(this T source) where T : class
{
return source.IfNotNull();
}
/// <summary>
/// Creates a <see cref="Recipes.Maybe{T}" />, allowing <see cref="Then" /> and <see cref="Else" /> operations to be chained and evaluated conditionally based on whether source is null.
/// </summary>
/// <typeparam name="T">The type of the instance wrapped by the <see cref="Recipes.Maybe{T}" />.</typeparam>
/// <param name="source">The source instance, which may be null.</param>
[Obsolete("This will be removed in v2.0.0. Instead, do this: source.IfNotNull()")]
public static Maybe<T> Maybe<T>(this T? source)
where T : struct
{
return source.IfNotNull();
}
/// <summary>
/// Returns either the source or, if it is null, an empty <see cref="IEnumerable{T}" /> sequence.
/// </summary>
/// <typeparam name="T"> The type of the objects in the sequence. </typeparam>
/// <param name="source"> The source sequence. </param>
/// <returns> The source sequence or, if it is null, an empty sequence. </returns>
public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
/// <summary>
/// Attempts to get the value of a Try* method with an out parameter, for example <see cref="Dictionary{TKey,TValue}.TryGetValue" /> or <see cref="ConcurrentQueue{T}.TryDequeue" />.
/// </summary>
/// <typeparam name="T">The type of the source object.</typeparam>
/// <typeparam name="TOut">The type the out parameter.</typeparam>
/// <param name="source">The source object exposing the Try* method.</param>
/// <param name="tryTryGetValue">A delegate to call the Try* method.</param>
/// <returns></returns>
public static Maybe<TOut> Out<T, TOut>(this T source, TryGetOutParameter<T, TOut> tryTryGetValue)
{
TOut result;
if (tryTryGetValue(source, out result))
{
return Recipes.Maybe<TOut>.Yes(result);
}
return Recipes.Maybe<TOut>.No();
}
/// <summary>
/// Executes a function and returns its value if the value of a condition is true.
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="condition">
/// if set to <c>true</c> execute <paramref name="getValue" /> and return its result.
/// </param>
/// <param name="getValue">
/// A function that will be executed and whose value will be returned if <paramref name="condition" /> is true.
/// </param>
/// <returns>
/// The value returned by getValue or, if <paramref name="condition" /> is false, null.
/// </returns>
/// <exception cref="ArgumentNullException">getValue</exception>
[Obsolete("This will be removed in v2.0.0.")]
public static T Then<T>(
this bool condition,
Func<T> getValue)
where T : class
{
if (getValue == null)
{
throw new ArgumentNullException("getValue");
}
return condition
? getValue()
: null;
}
/// <summary>
/// Invokes an action if the source condition is true, otherwise does nothing.
/// </summary>
/// <param name="condition">
/// if set to <c>true</c> , then <paramref name="action" /> is executed.
/// </param>
/// <param name="action">
/// The action to be invoked if <paramref name="condition" /> is true.\
/// </param>
/// <exception cref="ArgumentNullException">action</exception>
public static void Then(
this bool condition,
Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (condition)
{
action();
}
}
/// <summary>
/// Specifies the result of a <see cref="Recipes.Maybe{T}" /> if the <see cref="Recipes.Maybe{T}" /> has a value.
/// </summary>
/// <typeparam name="TIn">The type of source object.</typeparam>
/// <typeparam name="TOut">The type of result.</typeparam>
/// <param name="maybe">The maybe.</param>
/// <param name="getValue">A delegate to get the value from the source object.</param>
/// <returns></returns>
public static Maybe<TOut> Then<TIn, TOut>(
this Maybe<TIn> maybe,
Func<TIn, TOut> getValue)
{
return maybe.HasValue
? Recipes.Maybe<TOut>.Yes(getValue(maybe.Value))
: Recipes.Maybe<TOut>.No();
}
/// <summary>
/// Performs an action if the <see cref="Recipes.Maybe{T}" /> has a value.
/// </summary>
/// <typeparam name="T">
/// The type held by the <see cref="Recipes.Maybe{T}" />.
/// </typeparam>
public static Maybe<Unit> ThenDo<T>(this Maybe<T> maybe, Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (maybe.HasValue)
{
action(maybe.Value);
return Recipes.Maybe<Unit>.Yes(Unit.Default);
}
return Recipes.Maybe<Unit>.No();
}
/// <summary>
/// Tries to call the specified method and catches exceptions if they occur.
/// </summary>
/// <typeparam name="TIn">The type of source object.</typeparam>
/// <typeparam name="TOut">The type of result.</typeparam>
/// <param name="source">The source object.</param>
/// <param name="getValue">A delegate to get the value from the source object.</param>
/// <param name="ignore">A predicate to determine whether the exception should be ignored. If this is not specified, all exceptions are ignored. If it is specified and an exception is thrown that matches the predicate, the exception is ignored and a <see cref="Recipes.Maybe{TOut}" /> having no value is returned. If it is specified and an exception is thrown that does not match the predicate, the exception is allowed to propagate.</param>
/// <returns></returns>
public static Maybe<TOut> Try<TIn, TOut>(
this TIn source,
Func<TIn, TOut> getValue,
Func<Exception, bool> ignore)
{
if (getValue == null)
{
throw new ArgumentNullException("getValue");
}
if (ignore == null)
{
throw new ArgumentNullException("ignore");
}
try
{
return Recipes.Maybe<TOut>.Yes(getValue(source));
}
catch (Exception ex)
{
if (!ignore(ex))
{
throw;
}
}
return Recipes.Maybe<TOut>.No();
}
}
/// <summary>
/// Represents an object that may or may not contain a value, allowing optional chained results to be specified for both possibilities.
/// </summary>
/// <typeparam name="T">The type of the possible value.</typeparam>
#if !RecipesProject
[System.Diagnostics.DebuggerStepThrough]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
#endif
internal struct Maybe<T>
{
private static readonly Maybe<T> no = new Maybe<T>
{
HasValue = false
};
private T value;
/// <summary>
/// Returns a <see cref="Recipes.Maybe{T}" /> that contains a value.
/// </summary>
/// <param name="value">The value.</param>
public static Maybe<T> Yes(T value)
{
return new Maybe<T>
{
HasValue = true,
value = value
};
}
/// <summary>
/// Returns a <see cref="Recipes.Maybe{T}" /> that does not contain a value.
/// </summary>
public static Maybe<T> No()
{
return no;
}
/// <summary>
/// Gets the value contained by the <see cref="Recipes.Maybe{T}" />.
/// </summary>
/// <value>
/// The value.
/// </value>
public T Value
{
get
{
if (!HasValue)
{
throw new InvalidOperationException("The Maybe does not contain a value.");
}
return value;
}
}
/// <summary>
/// Gets a value indicating whether this instance has a value.
/// </summary>
/// <value>
/// <c>true</c> if this instance has value; otherwise, <c>false</c>.
/// </value>
public bool HasValue { get; private set; }
}
/// <summary>
/// A delegate used to return an out parameter from a Try* method that indicates success via a boolean return value.
/// </summary>
/// <typeparam name="T">The type of the source object.</typeparam>
/// <typeparam name="TOut">The type of the out parameter.</typeparam>
/// <param name="source">The source.</param>
/// <param name="outValue">The out parameter's value.</param>
/// <returns>true if the out parameter was set; otherwise, false.</returns>
internal delegate bool TryGetOutParameter<in T, TOut>(T source, out TOut outValue);
/// <summary>
/// A type representing a void return type.
/// </summary>
#if !RecipesProject
[System.Diagnostics.DebuggerStepThrough]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
#endif
internal struct Unit
{
/// <summary>
/// The default instance.
/// </summary>
public static readonly Unit Default = new Unit();
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using Encog.Engine.Network.Activation;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Train;
using Encog.MathUtil.Error;
namespace Encog.Neural.Freeform.Training
{
/// <summary>
/// Provides basic propagation functions to other trainers.
/// </summary>
[Serializable]
public abstract class FreeformPropagationTraining : BasicTraining
{
/// <summary>
/// The constant to use to fix the flat spot problem.
/// </summary>
public static double FlatSpotConst = 0.1;
/// <summary>
/// The network that we are training.
/// </summary>
private readonly FreeformNetwork _network;
/// <summary>
/// The training set to use.
/// </summary>
private readonly IMLDataSet _training;
/// <summary>
/// The number of iterations.
/// </summary>
private int _iterationCount = 0;
/// <summary>
/// The error at the beginning of the last iteration.
/// </summary>
public override double Error { get; set; }
/// <summary>
/// The neurons that have been visited.
/// </summary>
private readonly HashSet<IFreeformNeuron> _visited = new HashSet<IFreeformNeuron>();
/// <summary>
/// Are we fixing the flat spot problem? (default = true)
/// </summary>
public bool FixFlatSopt { get; set; }
/// <summary>
/// The batch size. Specify 1 for pure online training. Specify 0 for pure
/// batch training (complete training set in one batch). Otherwise specify
/// the batch size for batch training.
/// </summary>
public int BatchSize { get; set; }
/// <summary>
/// Don't use this constructor, it is for serialization only.
/// </summary>
public FreeformPropagationTraining(): base(TrainingImplementationType.Iterative) {
_network = null;
_training = null;
FixFlatSopt = true;
}
/// <summary>
/// Construct the trainer.
/// </summary>
/// <param name="theNetwork">The network to train.</param>
/// <param name="theTraining">The training data.</param>
public FreeformPropagationTraining(FreeformNetwork theNetwork,
IMLDataSet theTraining):
base(TrainingImplementationType.Iterative)
{
_network = theNetwork;
_training = theTraining;
FixFlatSopt = true;
}
/// <summary>
/// Calculate the gradient for a neuron.
/// </summary>
/// <param name="toNeuron">The neuron to calculate for.</param>
private void CalculateNeuronGradient(IFreeformNeuron toNeuron) {
// Only calculate if layer has inputs, because we've already handled the
// output
// neurons, this means a hidden layer.
if (toNeuron.InputSummation != null) {
// between the layer deltas between toNeuron and the neurons that
// feed toNeuron.
// also calculate all inbound gradeints to toNeuron
foreach (IFreeformConnection connection in toNeuron
.InputSummation.List) {
// calculate the gradient
double gradient = connection.Source.Activation
* toNeuron.GetTempTraining(0);
connection.AddTempTraining(0, gradient);
// calculate the next layer delta
IFreeformNeuron fromNeuron = connection.Source;
double sum = fromNeuron.Outputs.Sum(toConnection => toConnection.Target.GetTempTraining(0)*toConnection.Weight);
double neuronOutput = fromNeuron.Activation;
double neuronSum = fromNeuron.Sum;
double deriv = toNeuron.InputSummation
.ActivationFunction
.DerivativeFunction(neuronSum, neuronOutput);
if (FixFlatSopt
&& (toNeuron.InputSummation
.ActivationFunction is ActivationSigmoid)) {
deriv += FlatSpotConst;
}
double layerDelta = sum * deriv;
fromNeuron.SetTempTraining(0, layerDelta);
}
// recurse to the next level
foreach (IFreeformConnection connection in toNeuron
.InputSummation.List) {
IFreeformNeuron fromNeuron = connection.Source;
CalculateNeuronGradient(fromNeuron);
}
}
}
/// <summary>
/// Calculate the output delta for a neuron, given its difference.
/// Only used for output neurons.
/// </summary>
/// <param name="neuron">The neuron.</param>
/// <param name="diff">The difference.</param>
private void CalculateOutputDelta(IFreeformNeuron neuron,
double diff) {
double neuronOutput = neuron.Activation;
double neuronSum = neuron.InputSummation.Sum;
double deriv = neuron.InputSummation.ActivationFunction
.DerivativeFunction(neuronSum, neuronOutput);
if (FixFlatSopt
&& (neuron.InputSummation.ActivationFunction is ActivationSigmoid)) {
deriv += FlatSpotConst;
}
double layerDelta = deriv * diff;
neuron.SetTempTraining(0, layerDelta);
}
/// <inheritdoc/>
public override bool CanContinue {
get
{
return false;
}
}
/// <inheritdoc/>
public override void FinishTraining() {
_network.TempTrainingClear();
}
/// <inheritdoc/>
public override TrainingImplementationType ImplementationType {
get
{
return TrainingImplementationType.Iterative;
}
}
/// <inheritdoc/>
public override IMLMethod Method {
get
{
return _network;
}
}
/// <inheritdoc/>
public override IMLDataSet Training {
get
{
return _training;
}
}
/// <inheritdoc/>
public override void Iteration() {
PreIteration();
_iterationCount++;
_network.ClearContext();
if (BatchSize == 0) {
ProcessPureBatch();
} else {
ProcessBatches();
}
PostIteration();
}
/// <inheritdoc/>
public override void Iteration(int count) {
for (int i = 0; i < count; i++) {
Iteration();
}
}
/// <summary>
/// Process training for pure batch mode (one single batch).
/// </summary>
protected void ProcessPureBatch() {
var errorCalc = new ErrorCalculation();
_visited.Clear();
foreach (IMLDataPair pair in _training) {
var input = pair.Input;
var ideal = pair.Ideal;
var actual = _network.Compute(input);
var sig = pair.Significance;
errorCalc.UpdateError(actual, ideal, sig);
for (int i = 0; i < _network.OutputCount; i++) {
var diff = (ideal[i] - actual[i])
* sig;
IFreeformNeuron neuron = _network.OutputLayer.Neurons[i];
CalculateOutputDelta(neuron, diff);
CalculateNeuronGradient(neuron);
}
}
// Set the overall error.
Error = errorCalc.Calculate();
// Learn for all data.
Learn();
}
/// <summary>
/// Process training batches.
/// </summary>
protected void ProcessBatches() {
int lastLearn = 0;
var errorCalc = new ErrorCalculation();
_visited.Clear();
foreach (IMLDataPair pair in _training) {
var input = pair.Input;
var ideal = pair.Ideal;
var actual = _network.Compute(input);
var sig = pair.Significance;
errorCalc.UpdateError(actual, ideal, sig);
for (int i = 0; i < _network.OutputCount; i++) {
double diff = (ideal[i] - actual[i])
* sig;
IFreeformNeuron neuron = _network.OutputLayer.Neurons[i];
CalculateOutputDelta(neuron, diff);
CalculateNeuronGradient(neuron);
}
// Are we at the end of a batch.
lastLearn++;
if( lastLearn>=BatchSize ) {
lastLearn = 0;
Learn();
}
}
// Handle any remaining data.
if( lastLearn>0 ) {
Learn();
}
// Set the overall error.
Error = errorCalc.Calculate();
}
/// <summary>
/// Learn for the entire network.
/// </summary>
protected void Learn() {
_network.PerformConnectionTask(c=>{
LearnConnection(c);
c.SetTempTraining(0, 0);
}
);
}
/// <summary>
/// Learn for a single connection.
/// </summary>
/// <param name="connection">The connection to learn from.</param>
protected abstract void LearnConnection(IFreeformConnection connection);
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban
{
/// <summary>
/// Rewriter context used to write an AST/<see cref="ScriptNode"/> tree back to a text.
/// </summary>
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptPrinter
{
private readonly IScriptOutput _output;
private readonly bool _isScriptOnly;
private bool _isInCode;
private bool _expectSpace;
private bool _expectEndOfStatement;
// Gets a boolean indicating whether the last character written has a whitespace.
private bool _previousHasSpace;
private bool _hasEndOfStatement;
private bool _hasComma;
private FastStack<bool> _isWhileLoop;
public ScriptPrinter(IScriptOutput output, ScriptPrinterOptions options = default(ScriptPrinterOptions))
{
_isWhileLoop = new FastStack<bool>(4);
Options = options;
if (options.Mode != ScriptMode.Default && options.Mode != ScriptMode.ScriptOnly)
{
throw new ArgumentException($"The rendering mode `{options.Mode}` is not supported. Only `ScriptMode.Default` or `ScriptMode.ScriptOnly` are currently supported");
}
_isScriptOnly = options.Mode == ScriptMode.ScriptOnly;
_isInCode = _isScriptOnly || (options.Mode == ScriptMode.FrontMatterOnly || options.Mode == ScriptMode.FrontMatterAndContent);
_output = output;
_hasEndOfStatement = true; // We start as if we were on a new line
}
/// <summary>
/// Gets the options for rendering
/// </summary>
public readonly ScriptPrinterOptions Options;
public bool PreviousHasSpace => _previousHasSpace;
public bool IsInWhileLoop => _isWhileLoop.Count > 0 && _isWhileLoop.Peek();
public ScriptPrinter Write(ScriptNode node)
{
if (node != null)
{
bool pushedWhileLoop = false;
if (node is ScriptLoopStatementBase)
{
_isWhileLoop.Push(node is ScriptWhileStatement);
pushedWhileLoop = true;
}
try
{
WriteBegin(node);
// Reset comma before node
if (node is IScriptTerminal) _hasComma = false;
node.PrintTo(this);
WriteEnd(node);
}
finally
{
if (pushedWhileLoop)
{
_isWhileLoop.Pop();
}
}
}
return this;
}
public ScriptPrinter Write(string text)
{
_previousHasSpace = text.Length > 0 && char.IsWhiteSpace(text[text.Length - 1]);
_output.Write(text);
return this;
}
public ScriptPrinter Write(ScriptStringSlice slice)
{
_previousHasSpace = slice.Length > 0 && char.IsWhiteSpace(slice[slice.Length - 1]);
_output.Write(slice);
return this;
}
public ScriptPrinter ExpectEos()
{
if (!_hasEndOfStatement)
{
_expectEndOfStatement = true;
}
return this;
}
public ScriptPrinter ExpectSpace()
{
_expectSpace = true;
return this;
}
public ScriptPrinter WriteListWithCommas<T>(IList<T> list) where T : ScriptNode
{
if (list == null)
{
return this;
}
for(int i = 0; i < list.Count; i++)
{
var value = list[i];
// If the value didn't have any Comma Trivia, we can emit it
if (i > 0 && !_hasComma)
{
Write(",");
_hasComma = true;
}
Write(value);
}
return this;
}
public ScriptPrinter WriteEnterCode(int escape = 0)
{
Write("{");
for (int i = 0; i < escape; i++)
{
Write("%");
}
Write("{");
_expectEndOfStatement = false;
_expectSpace = false;
_hasEndOfStatement = true;
_isInCode = true;
return this;
}
public ScriptPrinter WriteExitCode(int escape = 0)
{
Write("}");
for (int i = 0; i < escape; i++)
{
Write("%");
}
Write("}");
_expectEndOfStatement = false;
_expectSpace = false;
_hasEndOfStatement = false;
_isInCode = false;
return this;
}
private void WriteBegin(ScriptNode node)
{
WriteTrivias(node, true);
HandleEos(node);
if (_hasEndOfStatement)
{
_hasEndOfStatement = false;
_expectEndOfStatement = false;
}
// Add a space if this is required and no trivia are providing it
if (node.CanHaveLeadingTrivia())
{
if (_expectSpace && !_previousHasSpace)
{
Write(" ");
}
_expectSpace = false;
}
}
private void WriteEnd(ScriptNode node)
{
WriteTrivias(node, false);
if (node is ScriptPage)
{
if (_isInCode && !_isScriptOnly)
{
WriteExitCode();
}
}
}
private static bool IsFrontMarker(ScriptNode node) => node is ScriptToken token && token.TokenType == TokenType.FrontMatterMarker;
private void HandleEos(ScriptNode node)
{
var isFrontMarker = IsFrontMarker(node);
if ((node is ScriptStatement || isFrontMarker) && !IsBlockOrPage(node) && _isInCode && _expectEndOfStatement)
{
if (!_hasEndOfStatement)
{
if (!(node is ScriptEscapeStatement))
{
Write(isFrontMarker ? "\n" : "; ");
}
}
_expectEndOfStatement = false; // We expect always a end of statement before and after
_hasEndOfStatement = false;
_hasComma = false;
}
}
private static bool IsBlockOrPage(ScriptNode node)
{
return node is ScriptBlockStatement || node is ScriptPage;
}
private void WriteTrivias(ScriptNode node, bool before)
{
if (!(node is IScriptTerminal terminal)) return;
var trivias = terminal.Trivias;
if (trivias != null)
{
foreach (var trivia in (before ? trivias.Before : trivias.After))
{
trivia.Write(this);
if (trivia.Type == ScriptTriviaType.NewLine || trivia.Type == ScriptTriviaType.SemiColon)
{
_hasEndOfStatement = true;
if (trivia.Type == ScriptTriviaType.SemiColon)
{
_hasComma = false;
}
// If expect a space and we have a NewLine or SemiColon, we can safely discard the required space
if (_expectSpace)
{
_expectSpace = false;
}
}
if (trivia.Type == ScriptTriviaType.Comma)
{
_hasComma = true;
}
}
}
}
}
}
| |
using System;
using System.Text;
namespace HTLib2
{
public partial class SelftestData
{
public static string[] lines_1L2Y_xyz
{
get
{
return new string[]
{
" 304",
" 1 NH3 -8.901000 4.127000 -0.555000 65 2 5 6 7",
" 2 CT1 -8.608000 3.135000 -1.618000 24 1 3 8 9",
" 3 C -7.117000 2.964000 -1.897000 20 2 4 17",
" 4 O -6.634000 1.849000 -1.758000 74 3",
" 5 HC -8.330000 3.957000 0.261000 6 1",
" 6 HC -8.740000 5.068000 -0.889000 6 1",
" 7 HC -9.877000 4.041000 -0.293000 6 1",
" 8 HB -8.930000 2.162000 -1.239000 5 2",
" 9 CT2 -9.437000 3.396000 -2.889000 26 2 10 13 14",
" 10 CC -10.915000 3.130000 -2.611000 49 9 11 12",
" 11 O -11.269000 2.700000 -1.524000 75 10",
" 12 NH2 -11.806000 3.406000 -3.543000 64 10 15 16",
" 13 HA -9.310000 4.417000 -3.193000 1 9",
" 14 HA -9.108000 2.719000 -3.679000 1 9",
" 15 H -11.572000 3.791000 -4.444000 3 12",
" 16 H -12.757000 3.183000 -3.294000 3 12",
" 17 NH1 -6.379000 4.031000 -2.228000 63 3 18 21",
" 18 CT1 -4.923000 4.002000 -2.452000 23 17 19 22 23",
" 19 C -4.136000 3.187000 -1.404000 20 18 20 36",
" 20 O -3.391000 2.274000 -1.760000 74 19",
" 21 H -6.821000 4.923000 -2.394000 3 17",
" 22 HB -4.750000 3.494000 -3.403000 4 18",
" 23 CT2 -4.411000 5.450000 -2.619000 26 18 24 27 28",
" 24 CT1 -4.795000 6.450000 -1.495000 25 23 25 26 29",
" 25 CT3 -3.612000 6.803000 -0.599000 27 24 30 31 32",
" 26 CT3 -5.351000 7.748000 -2.084000 27 24 33 34 35",
" 27 HA -3.340000 5.414000 -2.672000 1 23",
" 28 HA -4.813000 5.817000 -3.564000 1 23",
" 29 HA -5.568000 6.022000 -0.858000 1 24",
" 30 HA -3.207000 5.905000 -0.146000 1 25",
" 31 HA -2.841000 7.304000 -1.183000 1 25",
" 32 HA -3.929000 7.477000 0.197000 1 25",
" 33 HA -4.607000 8.209000 -2.736000 1 26",
" 34 HA -6.255000 7.544000 -2.657000 1 26",
" 35 HA -5.592000 8.445000 -1.281000 1 26",
" 36 NH1 -4.354000 3.455000 -0.111000 63 19 37 40",
" 37 CT1 -3.690000 2.738000 0.981000 23 36 38 41 42",
" 38 C -4.102000 1.256000 1.074000 20 37 39 57",
" 39 O -3.291000 0.409000 1.442000 74 38",
" 40 H -4.934000 4.245000 0.120000 3 36",
" 41 HB -2.615000 2.768000 0.796000 4 37",
" 42 CT2 -3.964000 3.472000 2.302000 26 37 43 50 51",
" 43 CA -2.824000 3.339000 3.290000 47 42 44 45",
" 44 CA -2.746000 2.217000 4.138000 21 43 46 52",
" 45 CA -1.820000 4.326000 3.332000 21 43 47 53",
" 46 CA -1.657000 2.076000 5.018000 21 44 48 54",
" 47 CA -0.725000 4.185000 4.205000 21 45 48 55",
" 48 CA -0.639000 3.053000 5.043000 48 46 47 49",
" 49 OH1 0.433000 2.881000 5.861000 77 48 56",
" 50 HA -4.117000 4.513000 2.091000 1 42",
" 51 HA -4.886000 3.096000 2.750000 1 42",
" 52 HP -3.513000 1.456000 4.101000 2 44",
" 53 HP -1.877000 5.200000 2.695000 2 45",
" 54 HP -1.576000 1.221000 5.669000 2 46",
" 55 HP 0.033000 4.952000 4.233000 2 47",
" 56 H 1.187000 3.395000 5.567000 8 49",
" 57 NH1 -5.342000 0.925000 0.689000 63 38 58 61",
" 58 CT1 -5.857000 -0.449000 0.613000 23 57 59 62 63",
" 59 C -5.089000 -1.221000 -0.470000 20 58 60 76",
" 60 O -4.621000 -2.334000 -0.226000 74 59",
" 61 H -5.906000 1.656000 0.283000 3 57",
" 62 HB -5.670000 -0.941000 1.568000 4 58",
" 63 CT1 -7.386000 -0.466000 0.343000 25 58 64 65 67",
" 64 CT2 -8.197000 0.540000 1.197000 26 63 66 68 69",
" 65 CT3 -7.959000 -1.884000 0.501000 27 63 70 71 72",
" 66 CT3 -8.019000 0.412000 2.715000 27 64 73 74 75",
" 67 HA -7.554000 -0.192000 -0.697000 1 63",
" 68 HA -7.900000 1.531000 0.912000 1 64",
" 69 HA -9.257000 0.424000 0.964000 1 64",
" 70 HA -7.509000 -2.555000 -0.232000 1 65",
" 71 HA -7.759000 -2.271000 1.501000 1 65",
" 72 HA -9.036000 -1.871000 0.332000 1 65",
" 73 HA -8.306000 -0.585000 3.049000 1 66",
" 74 HA -6.983000 0.606000 2.995000 1 66",
" 75 HA -8.656000 1.144000 3.213000 1 66",
" 76 NH1 -4.907000 -0.601000 -1.645000 63 59 77 80",
" 77 CT1 -4.122000 -1.167000 -2.743000 23 76 78 81 82",
" 78 C -2.629000 -1.321000 -2.390000 20 77 79 93",
" 79 O -1.986000 -2.240000 -2.884000 74 78",
" 80 H -5.327000 0.318000 -1.763000 3 76",
" 81 HB -4.517000 -2.162000 -2.940000 4 77",
" 82 CT2 -4.292000 -0.313000 -4.013000 26 77 83 87 88",
" 83 CT2 -4.244000 -1.171000 -5.290000 26 82 84 89 90",
" 84 CC -5.576000 -1.860000 -5.585000 49 83 85 86",
" 85 O -5.769000 -3.044000 -5.335000 75 84",
" 86 NH2 -6.532000 -1.146000 -6.152000 64 84 91 92",
" 87 HA -5.238000 0.191000 -3.969000 1 82",
" 88 HA -3.492000 0.429000 -4.053000 1 82",
" 89 HA -3.993000 -0.539000 -6.120000 1 83",
" 90 HA -3.458000 -1.923000 -5.205000 1 83",
" 91 H -6.389000 -0.184000 -6.408000 3 86",
" 92 H -7.392000 -1.635000 -6.335000 3 86",
" 93 NH1 -2.074000 -0.459000 -1.528000 63 78 94 97",
" 94 CT1 -0.716000 -0.631000 -0.993000 23 93 95 98 99",
" 95 C -0.631000 -1.766000 0.044000 20 94 96 117",
" 96 O 0.295000 -2.579000 -0.004000 74 95",
" 97 H -2.624000 0.343000 -1.242000 3 93",
" 98 HB -0.052000 -0.908000 -1.813000 4 94",
" 99 CT2 -0.221000 0.703000 -0.417000 26 94 100 109 110",
" 100 CY 1.148000 0.652000 0.194000 50 99 101 102",
" 101 CA 2.319000 0.664000 -0.482000 51 100 103 111",
" 102 CPT 1.508000 0.564000 1.606000 52 100 104 105",
" 103 NY 3.371000 0.560000 0.411000 71 101 104 112",
" 104 CPT 2.928000 0.515000 1.710000 53 102 103 106",
" 105 CA 0.779000 0.524000 2.812000 21 102 107 113",
" 106 CA 3.599000 0.445000 2.938000 21 104 108 114",
" 107 CA 1.439000 0.433000 4.053000 21 105 108 115",
" 108 CA 2.842000 0.407000 4.120000 21 106 107 116",
" 109 HA -0.206000 1.425000 -1.211000 1 99",
" 110 HA -0.921000 1.044000 0.344000 1 99",
" 111 HP 2.412000 0.733000 -1.558000 2 101",
" 112 H 4.360000 0.536000 0.156000 9 103",
" 113 HP -0.299000 0.571000 2.773000 2 105",
" 114 HP 4.679000 0.418000 2.961000 2 106",
" 115 HP 0.862000 0.400000 4.966000 2 107",
" 116 HP 3.334000 0.360000 5.081000 2 108",
" 117 NH1 -1.600000 -1.860000 0.967000 63 95 118 121",
" 118 CT1 -1.641000 -2.932000 1.963000 23 117 119 122 123",
" 119 C -1.847000 -4.319000 1.342000 20 118 120 136",
" 120 O -1.144000 -5.248000 1.742000 74 119",
" 121 H -2.316000 -1.137000 0.994000 3 117",
" 122 HB -0.666000 -2.978000 2.445000 4 118",
" 123 CT2 -2.710000 -2.645000 3.033000 26 118 124 127 128",
" 124 CT1 -2.301000 -1.579000 4.069000 25 123 125 126 129",
" 125 CT3 -3.475000 -1.323000 5.018000 27 124 130 131 132",
" 126 CT3 -1.093000 -2.007000 4.914000 27 124 133 134 135",
" 127 HA -3.600000 -2.308000 2.537000 1 123",
" 128 HA -2.921000 -3.571000 3.572000 1 123",
" 129 HA -2.061000 -0.649000 3.560000 1 124",
" 130 HA -4.343000 -0.992000 4.449000 1 125",
" 131 HA -3.725000 -2.237000 5.560000 1 125",
" 132 HA -3.211000 -0.549000 5.739000 1 125",
" 133 HA -1.270000 -2.989000 5.354000 1 126",
" 134 HA -0.195000 -2.045000 4.300000 1 126",
" 135 HA -0.922000 -1.286000 5.712000 1 126",
" 136 NH1 -2.753000 -4.481000 0.360000 63 119 137 140",
" 137 CT1 -3.024000 -5.791000 -0.269000 23 136 138 141 142",
" 138 C -1.796000 -6.427000 -0.937000 20 137 139 158",
" 139 O -1.719000 -7.648000 -1.030000 74 138",
" 140 H -3.321000 -3.675000 0.097000 3 136",
" 141 HB -3.309000 -6.478000 0.529000 4 137",
" 142 CT2 -4.224000 -5.697000 -1.232000 26 137 143 147 148",
" 143 CT2 -3.930000 -5.009000 -2.577000 26 142 144 149 150",
" 144 CT2 -3.682000 -5.986000 -3.736000 26 143 145 151 152",
" 145 CT2 -3.494000 -5.199000 -5.039000 58 144 146 153 154",
" 146 NH3 -4.563000 -5.483000 -6.023000 65 145 155 156 157",
" 147 HA -4.565000 -6.694000 -1.436000 1 142",
" 148 HA -5.019000 -5.143000 -0.731000 1 142",
" 149 HA -4.769000 -4.390000 -2.830000 1 143",
" 150 HA -3.062000 -4.368000 -2.469000 1 143",
" 151 HA -2.799000 -6.562000 -3.536000 1 144",
" 152 HA -4.524000 -6.674000 -3.818000 1 144",
" 153 HA -3.502000 -4.150000 -4.813000 17 145",
" 154 HA -2.511000 -5.439000 -5.457000 17 145",
" 155 HC -4.621000 -6.474000 -6.211000 6 146",
" 156 HC -5.442000 -5.124000 -5.657000 6 146",
" 157 HC -4.382000 -4.983000 -6.881000 6 146",
" 158 NH1 -0.828000 -5.607000 -1.355000 63 138 159 162",
" 159 CT1 0.466000 -6.016000 -1.905000 23 158 160 163 164",
" 160 C 1.481000 -6.464000 -0.832000 20 159 161 170",
" 161 O 2.545000 -6.971000 -1.194000 74 160",
" 162 H -1.010000 -4.616000 -1.291000 3 158",
" 163 HB 0.319000 -6.867000 -2.574000 4 159",
" 164 CT2 1.033000 -4.839000 -2.724000 54 159 165 168 169",
" 165 CC 0.672000 -4.906000 -4.210000 55 164 166 167",
" 166 OC -0.532000 -5.051000 -4.522000 78 165",
" 167 OC 1.627000 -4.815000 -5.017000 78 165",
" 168 HA 0.644000 -3.924000 -2.320000 1 164",
" 169 HA 2.116000 -4.837000 -2.650000 1 164",
" 170 NH1 1.185000 -6.278000 0.464000 63 160 171 174",
" 171 CT2 2.060000 -6.618000 1.593000 28 170 172 175 176",
" 172 C 2.628000 -5.412000 2.353000 20 171 173 177",
" 173 O 3.496000 -5.594000 3.208000 74 172",
" 174 H 0.265000 -5.908000 0.693000 3 170",
" 175 HB 1.486000 -7.214000 2.304000 4 171",
" 176 HB 2.897000 -7.228000 1.252000 4 171",
" 177 NH1 2.172000 -4.187000 2.055000 63 172 178 181",
" 178 CT2 2.626000 -2.967000 2.723000 28 177 179 182 183",
" 179 C 4.157000 -2.802000 2.654000 20 178 180 184",
" 180 O 4.710000 -2.829000 1.551000 74 179",
" 181 H 1.481000 -4.089000 1.319000 3 177",
" 182 HB 2.164000 -2.109000 2.237000 4 178",
" 183 HB 2.280000 -2.997000 3.753000 4 178",
" 184 N 4.871000 -2.651000 3.794000 66 179 185 191",
" 185 CP1 6.333000 -2.533000 3.806000 30 184 186 188 189",
" 186 C 7.058000 -3.729000 3.165000 20 185 187 198",
" 187 O 8.139000 -3.562000 2.601000 74 186",
" 188 HB 6.611000 -1.626000 3.267000 4 185",
" 189 CP2 6.740000 -2.387000 5.279000 31 185 190 192 193",
" 190 CP2 5.460000 -1.952000 5.987000 31 189 191 194 195",
" 191 CP3 4.362000 -2.615000 5.160000 32 184 190 196 197",
" 192 HA 7.091000 -3.323000 5.670000 1 189",
" 193 HA 7.531000 -1.647000 5.403000 1 189",
" 194 HA 5.443000 -2.302000 7.001000 1 190",
" 195 HA 5.358000 -0.867000 5.929000 1 190",
" 196 HA 4.173000 -3.609000 5.516000 1 191",
" 197 HA 3.440000 -2.042000 5.246000 1 191",
" 198 NH1 6.463000 -4.929000 3.205000 63 186 199 202",
" 199 CT1 7.049000 -6.179000 2.704000 23 198 200 203 204",
" 200 C 6.897000 -6.369000 1.185000 20 199 201 209",
" 201 O 7.025000 -7.488000 0.697000 74 200",
" 202 H 5.535000 -4.999000 3.613000 3 198",
" 203 HB 8.121000 -6.159000 2.903000 4 199",
" 204 CT2 6.458000 -7.371000 3.472000 35 199 205 206 207",
" 205 OH1 6.763000 -7.264000 4.850000 76 204 208",
" 206 HA 5.393000 -7.382000 3.344000 1 204",
" 207 HA 6.880000 -8.302000 3.093000 1 204",
" 208 H 7.707000 -7.394000 4.970000 8 205",
" 209 NH1 6.637000 -5.290000 0.434000 63 200 210 213",
" 210 CT1 6.389000 -5.315000 -1.015000 23 209 211 214 215",
" 211 C 7.332000 -4.405000 -1.823000 20 210 212 220",
" 212 O 7.082000 -4.123000 -2.993000 74 211",
" 213 H 6.509000 -4.415000 0.930000 3 209",
" 214 HB 6.562000 -6.329000 -1.378000 4 210",
" 215 CT2 4.914000 -4.993000 -1.265000 35 210 216 217 218",
" 216 OH1 4.431000 -5.743000 -2.358000 76 215 219",
" 217 HA 4.344000 -5.236000 -0.389000 1 215",
" 218 HA 4.778000 -3.934000 -1.457000 1 215",
" 219 H 3.714000 -6.324000 -1.987000 8 216",
" 220 NH1 8.419000 -3.920000 -1.202000 63 211 221 224",
" 221 CT2 9.451000 -3.116000 -1.870000 28 220 222 225 226",
" 222 C 8.984000 -1.725000 -2.316000 20 221 223 227",
" 223 O 9.539000 -1.177000 -3.267000 74 222",
" 224 H 8.573000 -4.210000 -0.246000 3 220",
" 225 HB 10.297000 -2.987000 -1.194000 4 221",
" 226 HB 9.805000 -3.652000 -2.752000 4 221",
" 227 NH1 7.956000 -1.164000 -1.660000 63 222 228 231",
" 228 CT1 7.289000 0.084000 -2.054000 23 227 229 232 233",
" 229 C 6.855000 0.916000 -0.829000 20 228 230 251",
" 230 O 6.222000 0.366000 0.076000 74 229",
" 231 H 7.579000 -1.676000 -0.874000 3 227",
" 232 HB 8.009000 0.663000 -2.630000 4 228",
" 233 CT2 6.110000 -0.243000 -2.994000 26 228 234 240 241",
" 234 CT2 5.046000 -1.171000 -2.378000 26 233 235 242 243",
" 235 CT2 3.923000 -1.592000 -3.338000 59 234 236 244 245",
" 236 NC2 4.251000 -2.811000 -4.100000 72 235 237 246",
" 237 C 4.859000 -2.914000 -5.274000 60 236 238 239",
" 238 NC2 5.289000 -1.864000 -5.937000 73 237 247 248",
" 239 NC2 5.035000 -4.095000 -5.809000 73 237 249 250",
" 240 HA 5.634000 0.678000 -3.269000 1 233",
" 241 HA 6.524000 -0.720000 -3.880000 1 233",
" 242 HA 5.538000 -2.059000 -2.031000 1 234",
" 243 HA 4.579000 -0.652000 -1.549000 1 234",
" 244 HA 3.033000 -1.774000 -2.766000 1 235",
" 245 HA 3.669000 -0.765000 -4.003000 1 235",
" 246 HC 3.963000 -3.694000 -3.698000 18 236",
" 247 HC 5.150000 -0.962000 -5.521000 19 238",
" 248 HC 5.761000 -1.962000 -6.815000 19 238",
" 249 HC 4.649000 -4.894000 -5.327000 19 239",
" 250 HC 5.508000 -4.205000 -6.684000 19 239",
" 251 N 7.156000 2.230000 -0.780000 66 229 252 258",
" 252 CP1 6.782000 3.088000 0.345000 30 251 253 255 256",
" 253 C 5.261000 3.331000 0.395000 20 252 254 265",
" 254 O 4.586000 3.165000 -0.624000 74 253",
" 255 HB 7.107000 2.628000 1.279000 4 252",
" 256 CP2 7.554000 4.394000 0.119000 31 252 257 259 260",
" 257 CP2 7.677000 4.474000 -1.401000 31 256 258 261 262",
" 258 CP3 7.820000 3.010000 -1.816000 32 251 257 263 264",
" 259 HA 7.009000 5.234000 0.505000 1 256",
" 260 HA 8.548000 4.308000 0.561000 1 256",
" 261 HA 6.800000 4.914000 -1.836000 1 257",
" 262 HA 8.540000 5.066000 -1.707000 1 257",
" 263 HA 7.349000 2.844000 -2.766000 1 258",
" 264 HA 8.876000 2.739000 -1.855000 1 258",
" 265 N 4.710000 3.739000 1.555000 66 253 266 272",
" 266 CP1 3.287000 4.031000 1.686000 30 265 267 269 270",
" 267 C 2.901000 5.305000 0.913000 20 266 268 279",
" 268 O 3.684000 6.256000 0.871000 74 267",
" 269 HB 2.719000 3.181000 1.316000 4 266",
" 270 CP2 3.035000 4.190000 3.187000 31 266 271 273 274",
" 271 CP2 4.385000 4.655000 3.729000 31 270 272 275 276",
" 272 CP3 5.393000 3.949000 2.823000 32 265 271 277 278",
" 273 HA 2.274000 4.924000 3.372000 1 270",
" 274 HA 2.781000 3.223000 3.618000 1 270",
" 275 HA 4.482000 5.721000 3.654000 1 271",
" 276 HA 4.518000 4.377000 4.775000 1 271",
" 277 HA 6.262000 4.562000 2.682000 1 272",
" 278 HA 5.662000 2.983000 3.253000 1 272",
" 279 N 1.688000 5.360000 0.336000 66 267 280 286",
" 280 CP1 1.185000 6.543000 -0.353000 30 279 281 283 284",
" 281 C 0.715000 7.607000 0.655000 20 280 282 293",
" 282 O -0.124000 7.324000 1.513000 74 281",
" 283 HB 1.961000 6.966000 -0.991000 4 280",
" 284 CP2 0.048000 6.014000 -1.229000 31 280 285 287 288",
" 285 CP2 -0.519000 4.852000 -0.412000 31 284 286 289 290",
" 286 CP3 0.716000 4.275000 0.272000 32 279 285 291 292",
" 287 HA -0.697000 6.770000 -1.389000 1 284",
" 288 HA 0.463000 5.630000 -2.162000 1 284",
" 289 HA -1.232000 5.201000 0.310000 1 285",
" 290 HA -1.019000 4.114000 -1.041000 1 285",
" 291 HA 0.470000 3.937000 1.260000 1 286",
" 292 HA 1.121000 3.461000 -0.329000 1 286",
" 293 NH1 1.271000 8.822000 0.549000 63 281 294 297",
" 294 CT1 0.852000 10.027000 1.285000 23 293 295 298 299",
" 295 CC -0.406000 10.657000 0.683000 22 294 296 304",
" 296 OC -0.387000 10.916000 -0.540000 79 295",
" 297 H 1.969000 8.961000 -0.165000 3 293",
" 298 HB 0.601000 9.760000 2.310000 4 294",
" 299 CT2 1.972000 11.071000 1.284000 35 294 300 301 302",
" 300 OH1 3.120000 10.541000 1.911000 76 299 303",
" 301 HA 2.210000 11.338000 0.272000 1 299",
" 302 HA 1.636000 11.959000 1.824000 1 299",
" 303 H 2.831000 10.040000 2.676000 8 300",
" 304 OC -1.341000 10.903000 1.473000 79 295",
};
}
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation 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.
#endregion // License
using Bam.Core;
namespace Publisher
{
/// <summary>
/// Abstract base class for any collated object
/// </summary>
abstract class CollatedObject :
Bam.Core.Module,
ICollatedObject
{
/// <summary>
/// Path key to the file copied
/// </summary>
public const string CopiedFileKey = "Copied file";
/// <summary>
/// Path key to the directory copied
/// </summary>
public const string CopiedDirectoryKey = "Copied directory";
/// <summary>
/// Path key to the renamed directory copied
/// </summary>
public const string CopiedRenamedDirectoryKey = "Copied renamed directory";
/// <summary>
/// Path key to the macOS framework copied
/// </summary>
public const string CopiedFrameworkKey = "Copied framework";
private Bam.Core.Module sourceModule;
private string sourcePathKey;
private Bam.Core.TokenizedString publishingDirectory;
private ICollatedObject anchor = null;
private readonly System.Collections.Generic.Dictionary<System.Tuple<Bam.Core.Module, string>, ICollatedObject> dependents = new System.Collections.Generic.Dictionary<System.Tuple<Bam.Core.Module, string>, ICollatedObject>();
Bam.Core.Module ICollatedObject.SourceModule => this.sourceModule;
/// <summary>
/// Set the source module
/// </summary>
public Bam.Core.Module SourceModule
{
set
{
this.sourceModule = value;
}
}
string ICollatedObject.SourcePathKey => this.sourcePathKey;
/// <summary>
/// Set the source path key
/// </summary>
public string SourcePathKey
{
set
{
this.sourcePathKey = value;
}
}
Bam.Core.TokenizedString ICollatedObject.PublishingDirectory => this.publishingDirectory;
ICollatedObject ICollatedObject.Anchor => this.anchor;
/// <summary>
/// Set the relative anchor point
/// </summary>
public ICollatedObject Anchor
{
set
{
this.anchor = value;
if (null != value)
{
// anchor should exist first
this.DependsOn(anchor as Bam.Core.Module);
}
}
}
/// <summary>
/// Get or set whether to ignore collating this object
/// </summary>
public bool Ignore { get; set; }
/// <summary>
/// Helper function to determine if this is an anchor
/// (as an anchor cannot have an anchor)
/// </summary>
public bool IsAnchor => null == this.anchor;
/// <summary>
/// Helper function for XcodeBuilder, to determine if this collated object
/// is in the same package as the anchor
/// </summary>
public bool IsInAnchorPackage
{
get
{
if (null == this.anchor)
{
return true;
}
var srcModule = (this as ICollatedObject).SourceModule;
if (null == srcModule)
{
return false;
}
return (srcModule.PackageDefinition == (this.anchor as ICollatedObject).SourceModule.PackageDefinition);
}
}
/// <summary>
/// Query if the anchor is a macOS application bundle
/// </summary>
public bool IsAnchorAnApplicationBundle
{
get
{
if (!this.IsAnchor)
{
throw new Bam.Core.Exception("Only available on anchors");
}
var isAppBundle = this.publishingDirectory.ToString().Contains(".app");
return isAppBundle;
}
}
/// <summary>
/// Set the publishing directory for this collated object
/// </summary>
/// <param name="original">Original path</param>
/// <param name="positional">With any positional arguments</param>
public void
SetPublishingDirectory(
string original,
params Bam.Core.TokenizedString[] positional)
{
if (null == this.publishingDirectory)
{
this.publishingDirectory = this.CreateTokenizedString(original, positional);
}
else
{
this.publishingDirectory.Set(original, positional);
}
}
// TODO: add accessors, rather than direct to the field
/// <summary>
/// Get the dependent collations on this collated object
/// </summary>
public System.Collections.Generic.Dictionary<System.Tuple<Bam.Core.Module, string>, ICollatedObject> DependentCollations => this.dependents;
/// <summary>
/// Get the source path of this collated object
/// </summary>
public Bam.Core.TokenizedString SourcePath => this.sourceModule.GeneratedPaths[this.sourcePathKey];
/// <summary>
/// Initialize this module
/// </summary>
protected override void
Init()
{
base.Init();
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
{
this.Tool = Bam.Core.Graph.Instance.FindReferencedModule<CopyFileWin>();
}
else
{
this.Tool = Bam.Core.Graph.Instance.FindReferencedModule<CopyFilePosix>();
}
if (null == this.publishingDirectory)
{
if (null != this.sourceModule)
{
throw new Bam.Core.Exception(
$"The publishing directory for module '{this.sourceModule.ToString()}', pathkey '{this.sourcePathKey.ToString()}' has yet to be set"
);
}
else
{
// TODO: this may result in a not-yet-parsed TokenizedString exception
// but what is the alternative for identifying the path?
throw new Bam.Core.Exception(
$"The publishing directory for '{this.SourcePath}' has yet to be set"
);
}
}
if (null != this.sourceModule)
{
this.Requires(this.sourceModule);
if (!this.sourceModule.GeneratedPaths.ContainsKey(this.sourcePathKey))
{
// this shouldn't happen, but just in case, a sensible error...
throw new Bam.Core.Exception(
$"Unable to locate generated path '{this.sourcePathKey.ToString()}' in module '{this.sourceModule.ToString()}' for collation"
);
}
}
if (this is CollatedFile)
{
this.RegisterGeneratedFile(
CopiedFileKey,
this.CreateTokenizedString(
"$(0)/@filename($(1))",
new[]
{
this.publishingDirectory,
this.SourcePath
}
)
);
}
else if (this is CollatedDirectory)
{
if (this.Macros.Contains("RenameLeaf"))
{
this.RegisterGeneratedFile(
CopiedRenamedDirectoryKey,
this.CreateTokenizedString(
"$(0)/$(RenameLeaf)",
new[]
{
this.publishingDirectory
}
)
);
}
else
{
this.RegisterGeneratedFile(
CopiedDirectoryKey,
this.CreateTokenizedString(
"$(0)/@filename($(1))",
new[]
{
this.publishingDirectory,
this.SourcePath
}
)
);
}
}
else if (this is CollatedOSXFramework)
{
this.RegisterGeneratedFile(
CopiedFrameworkKey,
this.CreateTokenizedString(
"$(0)/@filename($(1))",
new[]
{
this.publishingDirectory,
this.SourcePath
}
)
);
}
else
{
throw new System.NotSupportedException();
}
this.Ignore = false;
}
/// <summary>
/// Execute the tool on this module
/// </summary>
/// <param name="context">in this context</param>
protected override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
switch (Bam.Core.Graph.Instance.Mode)
{
#if D_PACKAGE_MAKEFILEBUILDER
case "MakeFile":
MakeFileBuilder.Support.Add(this);
break;
#endif
#if D_PACKAGE_NATIVEBUILDER
case "Native":
{
if (this.Ignore)
{
return;
}
NativeBuilder.Support.RunCommandLineTool(this, context);
}
break;
#endif
#if D_PACKAGE_VSSOLUTIONBUILDER
case "VSSolution":
VSSolutionSupport.CollateObject(this);
break;
#endif
#if D_PACKAGE_XCODEBUILDER
case "Xcode":
XcodeSupport.CollateObject(this);
break;
#endif
default:
throw new System.NotImplementedException();
}
}
/// <summary>
/// /copydoc Bam.Core.Module.InputModulePaths
/// </summary>
public override System.Collections.Generic.IEnumerable<(Bam.Core.Module module, string pathKey)> InputModulePaths
{
get
{
yield return (this.sourceModule, this.sourcePathKey);
}
}
}
}
| |
/*
* Copyright 2014 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.
*/
using System;
using System.Text;
namespace FlatBuffers
{
/// <summary>
/// Responsible for building up and accessing a flatbuffer formatted byte
/// array (via ByteBuffer)
/// </summary>
public class FlatBufferBuilder
{
private int _space;
private ByteBuffer _bb;
private int _minAlign = 1;
// The vtable for the current table (if _vtableSize >= 0)
private int[] _vtable = new int[16];
// The size of the vtable. -1 indicates no vtable
private int _vtableSize = -1;
// Starting offset of the current struct/table.
private int _objectStart;
// List of offsets of all vtables.
private int[] _vtables = new int[16];
// Number of entries in `vtables` in use.
private int _numVtables = 0;
// For the current vector being built.
private int _vectorNumElems = 0;
public FlatBufferBuilder(int initialSize)
{
if (initialSize <= 0)
throw new ArgumentOutOfRangeException("initialSize",
initialSize, "Must be greater than zero");
_space = initialSize;
_bb = new ByteBuffer(new byte[initialSize]);
}
public void Clear()
{
_space = _bb.Length;
_bb.Reset();
_minAlign = 1;
while (_vtableSize > 0) _vtable[--_vtableSize] = 0;
_vtableSize = -1;
_objectStart = 0;
_numVtables = 0;
_vectorNumElems = 0;
}
public int Offset { get { return _bb.Length - _space; } }
public void Pad(int size)
{
_bb.PutByte(_space -= size, 0, size);
}
// Doubles the size of the ByteBuffer, and copies the old data towards
// the end of the new buffer (since we build the buffer backwards).
void GrowBuffer()
{
var oldBuf = _bb.Data;
var oldBufSize = oldBuf.Length;
if ((oldBufSize & 0xC0000000) != 0)
throw new Exception(
"FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
var newBufSize = oldBufSize << 1;
var newBuf = new byte[newBufSize];
Buffer.BlockCopy(oldBuf, 0, newBuf, newBufSize - oldBufSize,
oldBufSize);
_bb = new ByteBuffer(newBuf, newBufSize);
}
// Prepare to write an element of `size` after `additional_bytes`
// have been written, e.g. if you write a string, you need to align
// such the int length field is aligned to SIZEOF_INT, and the string
// data follows it directly.
// If all you need to do is align, `additional_bytes` will be 0.
public void Prep(int size, int additionalBytes)
{
// Track the biggest thing we've ever aligned to.
if (size > _minAlign)
_minAlign = size;
// Find the amount of alignment needed such that `size` is properly
// aligned after `additional_bytes`
var alignSize =
((~((int)_bb.Length - _space + additionalBytes)) + 1) &
(size - 1);
// Reallocate the buffer if needed.
while (_space < alignSize + size + additionalBytes)
{
var oldBufSize = (int)_bb.Length;
GrowBuffer();
_space += (int)_bb.Length - oldBufSize;
}
if (alignSize > 0)
Pad(alignSize);
}
public void PutBool(bool x)
{
_bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0));
}
public void PutSbyte(sbyte x)
{
_bb.PutSbyte(_space -= sizeof(sbyte), x);
}
public void PutByte(byte x)
{
_bb.PutByte(_space -= sizeof(byte), x);
}
public void PutShort(short x)
{
_bb.PutShort(_space -= sizeof(short), x);
}
public void PutUshort(ushort x)
{
_bb.PutUshort(_space -= sizeof(ushort), x);
}
public void PutInt(int x)
{
_bb.PutInt(_space -= sizeof(int), x);
}
public void PutUint(uint x)
{
_bb.PutUint(_space -= sizeof(uint), x);
}
public void PutLong(long x)
{
_bb.PutLong(_space -= sizeof(long), x);
}
public void PutUlong(ulong x)
{
_bb.PutUlong(_space -= sizeof(ulong), x);
}
public void PutFloat(float x)
{
_bb.PutFloat(_space -= sizeof(float), x);
}
public void PutDouble(double x)
{
_bb.PutDouble(_space -= sizeof(double), x);
}
// Adds a scalar to the buffer, properly aligned, and the buffer grown
// if needed.
public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); }
public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); }
public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); }
public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); }
public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); }
public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); }
public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); }
public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); }
public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); }
public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); }
public void AddDouble(double x) { Prep(sizeof(double), 0);
PutDouble(x); }
// Adds on offset, relative to where it will be written.
public void AddOffset(int off)
{
Prep(sizeof(int), 0); // Ensure alignment is already done.
if (off > Offset)
throw new ArgumentException();
off = Offset - off + sizeof(int);
PutInt(off);
}
public void StartVector(int elemSize, int count, int alignment)
{
NotNested();
_vectorNumElems = count;
Prep(sizeof(int), elemSize * count);
Prep(alignment, elemSize * count); // Just in case alignment > int.
}
public VectorOffset EndVector()
{
PutInt(_vectorNumElems);
return new VectorOffset(Offset);
}
public void Nested(int obj)
{
// Structs are always stored inline, so need to be created right
// where they are used. You'll get this assert if you created it
// elsewhere.
if (obj != Offset)
throw new Exception(
"FlatBuffers: struct must be serialized inline.");
}
public void NotNested()
{
// You should not be creating any other objects or strings/vectors
// while an object is being constructed
if (_vtableSize >= 0)
throw new Exception(
"FlatBuffers: object serialization must not be nested.");
}
public void StartObject(int numfields)
{
if (numfields < 0)
throw new ArgumentOutOfRangeException("Flatbuffers: invalid numfields");
NotNested();
if (_vtable.Length < numfields)
_vtable = new int[numfields];
_vtableSize = numfields;
_objectStart = Offset;
}
// Set the current vtable at `voffset` to the current location in the
// buffer.
public void Slot(int voffset)
{
if (voffset >= _vtableSize)
throw new IndexOutOfRangeException("Flatbuffers: invalid voffset");
_vtable[voffset] = Offset;
}
// Add a scalar to a table at `o` into its vtable, with value `x` and default `d`
public void AddBool(int o, bool x, bool d) { if (x != d) { AddBool(x); Slot(o); } }
public void AddSbyte(int o, sbyte x, sbyte d) { if (x != d) { AddSbyte(x); Slot(o); } }
public void AddByte(int o, byte x, byte d) { if (x != d) { AddByte(x); Slot(o); } }
public void AddShort(int o, short x, int d) { if (x != d) { AddShort(x); Slot(o); } }
public void AddUshort(int o, ushort x, ushort d) { if (x != d) { AddUshort(x); Slot(o); } }
public void AddInt(int o, int x, int d) { if (x != d) { AddInt(x); Slot(o); } }
public void AddUint(int o, uint x, uint d) { if (x != d) { AddUint(x); Slot(o); } }
public void AddLong(int o, long x, long d) { if (x != d) { AddLong(x); Slot(o); } }
public void AddUlong(int o, ulong x, ulong d) { if (x != d) { AddUlong(x); Slot(o); } }
public void AddFloat(int o, float x, double d) { if (x != d) { AddFloat(x); Slot(o); } }
public void AddDouble(int o, double x, double d) { if (x != d) { AddDouble(x); Slot(o); } }
public void AddOffset(int o, int x, int d) { if (x != d) { AddOffset(x); Slot(o); } }
public StringOffset CreateString(string s)
{
NotNested();
AddByte(0);
var utf8StringLen = Encoding.UTF8.GetByteCount(s);
StartVector(1, utf8StringLen, 1);
Encoding.UTF8.GetBytes(s, 0, s.Length, _bb.Data, _space -= utf8StringLen);
return new StringOffset(EndVector().Value);
}
// Structs are stored inline, so nothing additional is being added.
// `d` is always 0.
public void AddStruct(int voffset, int x, int d)
{
if (x != d)
{
Nested(x);
Slot(voffset);
}
}
public int EndObject()
{
if (_vtableSize < 0)
throw new InvalidOperationException(
"Flatbuffers: calling endObject without a startObject");
AddInt((int)0);
var vtableloc = Offset;
// Write out the current vtable.
for (int i = _vtableSize - 1; i >= 0 ; i--) {
// Offset relative to the start of the table.
short off = (short)(_vtable[i] != 0
? vtableloc - _vtable[i]
: 0);
AddShort(off);
// clear out written entry
_vtable[i] = 0;
}
const int standardFields = 2; // The fields below:
AddShort((short)(vtableloc - _objectStart));
AddShort((short)((_vtableSize + standardFields) *
sizeof(short)));
// Search for an existing vtable that matches the current one.
int existingVtable = 0;
for (int i = 0; i < _numVtables; i++) {
int vt1 = _bb.Length - _vtables[i];
int vt2 = _space;
short len = _bb.GetShort(vt1);
if (len == _bb.GetShort(vt2)) {
for (int j = sizeof(short); j < len; j += sizeof(short)) {
if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) {
goto endLoop;
}
}
existingVtable = _vtables[i];
break;
}
endLoop: { }
}
if (existingVtable != 0) {
// Found a match:
// Remove the current vtable.
_space = _bb.Length - vtableloc;
// Point table to existing vtable.
_bb.PutInt(_space, existingVtable - vtableloc);
} else {
// No match:
// Add the location of the current vtable to the list of
// vtables.
if (_numVtables == _vtables.Length)
{
// Arrays.CopyOf(vtables num_vtables * 2);
var newvtables = new int[ _numVtables * 2];
Array.Copy(_vtables, newvtables, _vtables.Length);
_vtables = newvtables;
};
_vtables[_numVtables++] = Offset;
// Point table to current vtable.
_bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc);
}
_vtableSize = -1;
return vtableloc;
}
// This checks a required field has been set in a given table that has
// just been constructed.
public void Required(int table, int field)
{
int table_start = _bb.Length - table;
int vtable_start = table_start - _bb.GetInt(table_start);
bool ok = _bb.GetShort(vtable_start + field) != 0;
// If this fails, the caller will show what field needs to be set.
if (!ok)
throw new InvalidOperationException("FlatBuffers: field " + field +
" must be set");
}
public void Finish(int rootTable)
{
Prep(_minAlign, sizeof(int));
AddOffset(rootTable);
_bb.Position = _space;
}
public ByteBuffer DataBuffer { get { return _bb; } }
// Utility function for copying a byte array that starts at 0.
public byte[] SizedByteArray()
{
var newArray = new byte[_bb.Data.Length - _bb.Position];
Buffer.BlockCopy(_bb.Data, _bb.Position, newArray, 0,
_bb.Data.Length - _bb.Position);
return newArray;
}
public void Finish(int rootTable, string fileIdentifier)
{
Prep(_minAlign, sizeof(int) +
FlatBufferConstants.FileIdentifierLength);
if (fileIdentifier.Length !=
FlatBufferConstants.FileIdentifierLength)
throw new ArgumentException(
"FlatBuffers: file identifier must be length " +
FlatBufferConstants.FileIdentifierLength,
"fileIdentifier");
for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0;
i--)
{
AddByte((byte)fileIdentifier[i]);
}
Finish(rootTable);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2007 Novell Inc., www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
// Authors:
// Thomas Wiest (twiest@novell.com)
// Rusty Howell (rhowell@novell.com)
//
// (C) Novell Inc.
using System;
using System.Collections;
using System.Text;
using System.Management.Internal.BaseDataTypes;
namespace System.Management.Internal
{
/// <summary>
/// Holds an collection of CimProperty objects
/// </summary>
internal class CimPropertyList : BaseDataTypeList<CimProperty>
{
#region Constructors
/// <summary>
/// Creates an empty CimPropertyList
/// </summary>
public CimPropertyList()
{
}
/// <summary>
/// Creates a new CimPropertyList with the given CimProperties
/// </summary>
/// <param name="properties"></param>
public CimPropertyList(params CimProperty[] properties)
: base(properties)
{
}
#endregion
#region Properties
/// <summary>
/// Gets a CimProperty based on the name
/// </summary>
/// <param name="name">Name of the CimProperty</param>
/// <returns>CimProperty or null if not found</returns>
public CimProperty this[string name]
{
get { return FindItem(new CimName(name)); }
}
/// <summary>
/// Gets a CimProperty based on the name
/// </summary>
/// <param name="name">Name of the CimProperty</param>
/// <returns>CimProperty or null if not found</returns>
public CimProperty this[CimName name]
{
get { return FindItem(name); }
}
/// <summary>
/// Returns true if the list has at least one key property
/// </summary>
public bool HasKeyProperty
{
get
{
//Changed for MONO
for (int i = 0; i < this.Count; i++)
{
if (this[i].IsKeyProperty)
return true;
}
return false;
}
}
#endregion
#region Methods
/// <summary>
/// Removes a CimProperty from the collection, based the the name
/// </summary>
/// <param name="name">Name of the property to remove</param>
public bool Remove(string name)
{
return Remove(new CimName(name));
}
/// <summary>
/// Removes a CimProperty from the collection, based the the name
/// </summary>
/// <param name="name">Name of the property to remove</param>
public bool Remove(CimName name)
{
CimProperty prop = FindItem(name);
if (prop != null)
{
items.Remove(prop);
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private CimProperty FindItem(CimName name)
{
foreach (CimProperty curItem in items)
{
if (curItem.Name == name)
return curItem;
}
return null;
}
public bool Contains(CimName propertyName)
{
return (FindItem(propertyName) != null);
}
#region Equals, operator== , operator!=
public override bool Equals(object obj)
{
if ((obj == null) || !(obj is CimPropertyList))
{
return false;
}
return (this == (CimPropertyList)obj);
}
/// <summary>
/// Shallow compare two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if both lists have the same elements with the same names</returns>
public static bool operator ==(CimPropertyList list1, CimPropertyList list2)
{
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count != list2.Count)
return false;
//Changing to for loops for MONO
//check that all A's exist in B
for(int i = 0; i < list1.Count; i++)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
//check that all B's exist in A
for(int i = 0; i < list2.Count; i++)
{
if (list1.FindItem(list2[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Shallow compare of two CimPropertyLists
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns>Returns true if the lists do not have the same elements</returns>
public static bool operator !=(CimPropertyList list1, CimPropertyList list2)
{
return !(list1 == list2);
}
#endregion
#region Operator <,>,<=,>=
/*
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Subset list</param>
/// <param name="list2">Superset list</param>
/// <returns>Returns true if list1 is a subset of list2</returns>
public static bool operator <(CimPropertyList list1, CimPropertyList list2)
{
if (!(list1 <= list2))
return false;
//list1 is a subset of list2
return !(list1 == list2);//return true if the two lists are not equal
}
public static bool operator >(CimPropertyList list1, CimPropertyList list2)
{
return (list2 < list1);
}
* */
/// <summary>
/// Determines whether a list is a subset of another list (shallow compare)
/// </summary>
/// <param name="list1">Subset list</param>
/// <param name="list2">Superset list</param>
/// <returns>Returns true if list1 is a subset of list2</returns>
public static bool operator <=(CimPropertyList list1, CimPropertyList list2)
{
//return ((list1 < list2) || (list1 == list2));
if (((object)list1 == null) || ((object)list2 == null))
{
if (((object)list1 == null) && ((object)list2 == null))
{
return true;
}
return false;
}
if (list1.Count > list2.Count)
return false;
//Changing to for loop for MONO
for (int i = 0; i < list1.Count; ++i)
{
if (list2.FindItem(list1[i].Name) == null)
return false;
}
return true;
}
/// <summary>
/// Determines whether a list is a superset of another list (shallow compare)
/// </summary>
/// <param name="list1">superset list</param>
/// <param name="list2">subset list</param>
/// <returns>Returns true if list1 is a superset of list2</returns>
public static bool operator >=(CimPropertyList list1, CimPropertyList list2)
{
return (list2 <= list1);
}
#endregion
/// <summary>
/// Performes a deep compare of two CimPropertyLists
/// </summary>
/// <param name="list">CimPropertyList to compare</param>
/// <returns>Returns true if the lists have the same properties and values</returns>
public bool IsEqualTo(CimPropertyList list)
{
if (this != list)//do shallow compare first
return false;
//changing to for loop for MONO
for(int i = 0; i < this.Count; i++)
{
CimProperty p = list.FindItem(this[i].Name);
if ((p == null)||(p != this[i]))
return false;
}
return true;
}
/// <summary>
/// Finds all key properties in the list
/// </summary>
/// <returns>A list of all the key properties</returns>
public CimPropertyList GetKeyProperties()
{
CimPropertyList list = new CimPropertyList();
//Changing to for loop for MONO
for (int i = 0; i < this.Count; ++i)
{
if (this[i].IsKeyProperty)
list.Add(this[i]);
}
return list;
}
/// <summary>
/// Finds all required properties in the list
/// </summary>
/// <returns>A list of all the required properties</returns>
public CimPropertyList GetRequiredProperties()
{
CimPropertyList list = new CimPropertyList();
//Changing to for loop for MONO
for (int i = 0; i < this.Count; ++i)
{
if (this[i].IsRequiredProperty)
list.Add(this[i]);
}
return list;
}
#endregion
}
}
| |
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Text;
namespace Dna.Web.Core
{
/// <summary>
/// A basic HTTP server that will listen and serve files based on URLs
/// </summary>
public class LiveServer : IDisposable
{
#region Protected Members
/// <summary>
/// The URL query string that if appended to a request should then just hang until there are file changes
/// </summary>
protected const string SignalNewContentQuery = "?newcontent";
/// <summary>
/// The Http Listener for this server
/// </summary>
protected HttpListener mListener;
/// <summary>
/// The folder watcher that listens out for file changes
/// </summary>
protected FolderWatcher mFolderWatcher;
/// <summary>
/// Lock for locking the Listen call so it doesn't run twice
/// </summary>
protected object mListenLock = new object();
/// <summary>
/// Lock for locking the Stop call so it doesn't run twice
/// </summary>
protected string mStopLock = "HttpListenerStopLock";
/// <summary>
/// The reset event that gets set when contents observed in the <see cref="ServingDirectory"/> change
/// </summary>
protected ManualResetEvent mContentChangedResetEvent = new ManualResetEvent(false);
/// <summary>
/// The special URL that requests the auto-reload script
/// </summary>
protected const string AutoReloadRequestQueryUrl = "?autoreload";
/// <summary>
/// The Javascript to return when requesting the auto-reload script
/// </summary>
protected const string AutoReloadJavascript = @"
// Checks for any changes to this file and reloads
function checkForChanges()
{
// New XHR call
var xhttp = new XMLHttpRequest();
// On timeout, repeat
xhttp.onTimeout = function ()
{
// Call again
checkForChanges();
}
// On state change...
xhttp.onreadystatechange = function()
{
// If we are successful...
if (this.readyState == 4)
{
if (this.status == 200)
{
// Reload page
// NOTE: Contents of response is this.responseText
window.location.reload(true);
}
}
};
// Open connection (removing any # data after the URL)
xhttp.open(""GET"", location.href.replace(location.hash,"""").replace('#', '') + ""?newcontent"", true);
// Make sure the response is not cached
xhttp.setRequestHeader('Cache-Control', 'no-cache');
// Send
xhttp.send();
}
// Check for changes to the file
window.onload = checkForChanges;";
#endregion
#region Public Properties
/// <summary>
/// The port to listen on. If left as 0, an available port will be chosen
/// </summary>
public int Port { get; set; }
/// <summary>
/// Flag indicating if we are disposing
/// </summary>
public bool Disposing { get; private set; }
/// <summary>
/// Flag indicating if we are stopping listening
/// </summary>
public bool Stopping { get; private set; }
/// <summary>
/// Flag indicating if we are listening
/// </summary>
public bool Listening { get; private set; }
/// <summary>
/// The directory that files should be served from
/// </summary>
public string ServingDirectory { get; set; }
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public LiveServer() { }
#endregion
#region Public Static Helpers
/// <summary>
/// Finds the next available TCP port
/// </summary>
/// <returns></returns>
public static int NextAvailablePort()
{
// Create a listener, and have it find an empty port
var tcpListener = new TcpListener(IPAddress.Loopback, 0);
// Start it
tcpListener.Start();
// Get the port it is listening on
var port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
// Stop it
tcpListener.Stop();
return port;
}
#endregion
#region Listen / Stop Methods
/// <summary>
/// Stop listening
/// </summary>
public async Task StopAsync()
{
// Log it
CoreLogger.Log($"LiveServer '{ServingDirectory}' stopping...", type: LogType.Warning);
// Lock call
await AsyncAwaitor.AwaitAsync(mStopLock, async () =>
{
try
{
// Stop listener
mListener.Stop();
}
catch (Exception ex)
{
// Log it
Debugger.Break();
CoreLogger.Log($"Failed to stop LiveServer listener. {ex.Message}", type: LogType.Warning);
}
// Set stopping flag to true
Stopping = true;
// Dispose folder watcher
mFolderWatcher?.Dispose();
mFolderWatcher = null;
// Set it so any blocked calls pass on
mContentChangedResetEvent.Set();
mContentChangedResetEvent.Reset();
// Flag that we are no longer listening
while (Listening)
await Task.Delay(100);
// Log it
CoreLogger.Log($"LiveServer {ServingDirectory} stopped", type: LogType.Attention);
});
}
/// <summary>
/// Starts listening on the specified <see cref="Port"/>
/// </summary>
/// <returns>Returns the URL that is being listened on</returns>
public string Listen()
{
lock (mListenLock)
{
// If we are already listening...
if (Listening)
// Ignore
return null;
#region Get Port
try
{
// Get port if one is not specified
if (Port <= 0)
{
// Log it
CoreLogger.Log("LiveServer getting available port...");
// Get next available port
Port = NextAvailablePort();
}
}
catch (Exception ex)
{
// Log it
Debugger.Break();
CoreLogger.Log($"LiveServer failed to find an available port. {ex.Message}", type: LogType.Error);
// Go no further
return null;
}
// Log port to be used
CoreLogger.Log($"LiveServer will listen on port {Port}");
#endregion
// Expected listen URL
var listenUrl = $"http://localhost:{Port}/";
#region Listen
try
{
// Create new Http Listener
mListener = new HttpListener();
// Set port number
mListener.Prefixes.Add(listenUrl);
// Start listening
mListener.Start();
// Run new thread listening for content
// until we call Stop or Dispose
SafeTask.Run(() => ListenForContent());
// Set Listening flag
Listening = true;
// Log it
CoreLogger.Log($"LiveServer listening on http://localhost:{Port}, directory '{ServingDirectory}'", type: LogType.Information);
}
catch (Exception ex)
{
// Log it
Debugger.Break();
CoreLogger.Log($"LiveServer failed to start on port {Port}, directory '{ServingDirectory}'. {ex.Message}", type: LogType.Error);
// Go no further
return null;
}
#endregion
#region File Change Watcher
mFolderWatcher = new FolderWatcher
{
Filter = "*",
Path = ServingDirectory,
UpdateDelay = 100
};
// Listen for file changes
mFolderWatcher.FileChanged += FolderWatcher_FileChanged;
mFolderWatcher.Start();
#endregion
// Return URL we are now listening on
return listenUrl;
}
}
/// <summary>
/// Fired when a file has changed in the <see cref="ServingDirectory"/>
/// </summary>
/// <param name="obj"></param>
private void FolderWatcher_FileChanged(string filePath)
{
// Make sure we have a path
if (string.IsNullOrEmpty(filePath))
return;
// Make it lower case for quick checking of file extension
var lowerString = filePath?.ToLower();
// TODO: We could check the served files real references
// and only refresh if they change
//
// However for now its perfectly fine to just refresh
// the page if any file changes in the folder that could
// be a file in the webpage
//
// Check if the file is a file that may be served to the browser
if (lowerString.EndsWith(".htm") ||
lowerString.EndsWith(".html") ||
lowerString.EndsWith(".css") ||
lowerString.EndsWith(".js") ||
lowerString.EndsWith(".png") ||
lowerString.EndsWith(".gif") ||
lowerString.EndsWith(".jpg") ||
lowerString.EndsWith(".jpeg"))
{
// Let listeners know
mContentChangedResetEvent.Set();
mContentChangedResetEvent.Reset();
}
}
/// <summary>
/// Listens forever for requests until the thread is terminated
/// </summary>
private void ListenForContent()
{
try
{
// Start new
while (!Stopping && !Disposing)
{
CoreLogger.Log($"LiveServer waiting for next response '{ServingDirectory}'...");
// Note: The GetContext method blocks while waiting for a request.
var result = mListener.BeginGetContext(new AsyncCallback((callback) =>
{
try
{
// See if we are stopping
if (Stopping || Disposing)
return;
// Get context from result
var context = ((HttpListener)callback.AsyncState).EndGetContext(callback);
// Process it
Process(context);
}
catch (Exception ex)
{
// Log it
CoreLogger.Log($"LiveServer response failed. {ex.Message}", type: LogType.Warning);
}
}), mListener);
// Wait for result or stopping before moving to next loop
while (!Stopping && !Disposing && !result.AsyncWaitHandle.WaitOne(10)) ;
}
}
finally
{
// Make sure regardless of errors, we stop listening once done
Listening = false;
}
}
#endregion
/// <summary>
/// Processes the HTTP request
/// </summary>
/// <param name="context">The Http Context</param>
private void Process(HttpListenerContext context)
{
// Log it
CoreLogger.Log($"LiveServer Processing request {context.Request.Url.OriginalString}...");
// Get the URL information after the hostname
// i.e. http://localhost:8080/ would be /
// http://localhost:8080/some/path would be /some/path
var url = context.Request.Url.AbsolutePath;
// Get query string
var query = context.Request.Url.Query;
// If this is a request for the auto-reload script...
if (query.EqualsIgnoreCase(AutoReloadRequestQueryUrl))
{
// Serve the Javascript script
ServeString(AutoReloadJavascript, MimeTypes.GetExtension("file.js"), context);
// Done
return;
}
// If this is a request to return once there are changes...
if (query.EqualsIgnoreCase(SignalNewContentQuery))
{
// Pass off this request to simply return successful once it get's told there is a file change
HangUntilFileChange(context);
return;
}
else
{
// If the URL is just / (root)
if (string.IsNullOrWhiteSpace(url) || url == "/")
// Look for index by default
url = "index";
// Otherwise...
else
// Remove leading slash
url = url.Substring(1);
// Now look in the watch directory for a file with this name...
var filePath = DnaConfiguration.ResolveFullPath(ServingDirectory, url, false, out bool wasRelative);
// If this file exists...
if (File.Exists(filePath))
{
// Serve it
ServeFile(filePath, context);
// Done
return;
}
// If the file has no extension, try adding .htm
if (!Path.HasExtension(filePath) && File.Exists(filePath + ".htm"))
{
// Serve it
ServeFile(filePath + ".htm", context);
// Done
return;
}
// If the file has no extension, try adding .html
if (!Path.HasExtension(filePath) && File.Exists(filePath + ".html"))
{
// Serve it
ServeFile(filePath + ".html", context);
// Done
return;
}
// Let client know the file is not found
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
// Close the response
context.Response.OutputStream.Close();
}
}
private void HangUntilFileChange(HttpListenerContext context)
{
SafeTask.Run(() =>
{
// Log it
CoreLogger.Log("Waiting for file change signal...");
// Wait here until files change
mContentChangedResetEvent.WaitOne();
// If we are stopping, just return
if (Stopping)
return;
// Log it
CoreLogger.LogInformation("Refreshing web page request...");
// Response code OK (200)
context.Response.StatusCode = (int)HttpStatusCode.OK;
// End stream
context.Response.OutputStream.Close();
});
}
/// <summary>
/// Writes a files contents to the response stream
/// </summary>
/// <param name="filePath">The absolute file path</param>
/// <param name="context">The Http context</param>
private void ServeFile(string filePath, HttpListenerContext context)
{
try
{
// Get file info
var fileInfo = new FileInfo(filePath);
// Adding http response headers
context.Response.ContentType = MimeTypes.GetExtension(filePath);
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
// NOTE: Use last-modified date to now as MS Edge doesn't refresh CSS if the HTML page hasn't changed
// So instead of fileInfo.LastAccessTime.ToString("r") use the date now
context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("r"));
// If it is a HTML file just read it all in
if (filePath.ToLower().EndsWith(".htm") || filePath.ToLower().EndsWith(".html"))
{
// Don't cache HTML
context.Response.AddHeader("Cache-Control", "no-cache");
// Read all the HTML
var htmlContents = File.ReadAllText(filePath);
// Inject the javascript auto-reload script
var headIndex = htmlContents.ToLower().IndexOf("<head>");
// If we found a head... inject JS
if (headIndex > 0)
{
// Find location just after the opening <head> tag
var injectHeader = headIndex + "<head>".Length;
// Inject the javascript src
htmlContents = htmlContents.Insert(injectHeader, $"<script type=\"text/javascript\" src=\"/{AutoReloadRequestQueryUrl}\" charset=\"UTF-8\"></script>");
}
// Get bytes for content
var bytes = Encoding.UTF8.GetBytes(htmlContents);
// Set content length
context.Response.ContentLength64 = bytes.Length;
// Write to response
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
}
else
{
// Open file
using (var input = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Set content length
context.Response.ContentLength64 = fileInfo.Length;
// Create 16kb buffer
var buffer = new byte[1024 * 16];
int nbytes;
// Read file into output stream in chunks until done
while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
context.Response.OutputStream.Write(buffer, 0, nbytes);
}
}
// Response code OK (200)
context.Response.StatusCode = (int)HttpStatusCode.OK;
// Flush stream so everything is written
context.Response.OutputStream.Flush();
// Log it
CoreLogger.Log($"LiveServer Served File {filePath} ({Math.Round(fileInfo.Length / 1024f, 2)}kb)");
}
catch (Exception ex)
{
// Log it
CoreLogger.Log($"LiveServer Unexpected Error Serving File {filePath}. {ex.Message}", type: LogType.Error);
// Let browser know internal error
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
finally
{
// Close the response
context.Response.OutputStream.Close();
}
}
/// <summary>
/// Writes a string contents to the response stream
/// </summary>
/// <param name="contents">The contents to write</param>
/// <param name="mimeType">The Mime type of this content</param>
/// <param name="context">The Http context</param>
private void ServeString(string contents, string mimeType, HttpListenerContext context)
{
// Adding http response headers
context.Response.ContentType = mimeType;
context.Response.ContentLength64 = contents.Length;
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("r"));
// Get bytes for content
var bytes = Encoding.UTF8.GetBytes(contents);
// Write to response
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
// Response code OK (200)
context.Response.StatusCode = (int)HttpStatusCode.OK;
// Flush stream so everything is written
context.Response.OutputStream.Flush();
}
#region Dispose
/// <summary>
/// Dispose
/// </summary>
public async void Dispose()
{
// Let threads know to exit
Disposing = true;
await StopAsync();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class AddStrStrStringDictionaryTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
StringDictionary sd;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
string ind; // key
// initialize IntStrings
intl = new IntlStrings();
// [] StringDictionary is constructed as expected
//-----------------------------------------------------------------
sd = new StringDictionary();
// [] Add() simple strings
//
for (int i = 0; i < values.Length; i++)
{
cnt = sd.Count;
sd.Add(keys[i], values[i]);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (!sd.ContainsValue(values[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
}
if (!sd.ContainsKey(keys[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(sd[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[keys[i]], values[i]));
}
}
//
// Intl strings
// [] Add() Intl strings
//
int len = values.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = sd.Count;
sd.Add(intlValues[i + len], intlValues[i]);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (!sd.ContainsValue(intlValues[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
}
if (!sd.ContainsKey(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
ind = intlValues[i + len];
if (String.Compare(sd[ind], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
sd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = sd.Count;
sd.Add(intlValues[i + len], intlValues[i]);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (!sd.ContainsValue(intlValues[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
}
if (!sd.ContainsKey(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i]))
{
Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i));
}
// key is case insensitive
if (!sd.ContainsKey(intlValuesLower[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i));
}
}
//
// [] Add (string, null)
//
cnt = sd.Count;
sd.Add("keykey", null);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt + 1));
}
// verify that collection contains null
//
if (!sd.ContainsValue(null))
{
Assert.False(true, string.Format("Error, collection doesn't contain null"));
}
// access item-null
//
if (sd["keykey"] != null)
{
Assert.False(true, string.Format("Error, returned non-null on place of null"));
}
//
// Add item with null key - ArgumentNullException expected
// [] Add (null, string)
//
Assert.Throws<ArgumentNullException>(() => { sd.Add(null, "item"); });
//
// Add duplicate key item - ArgumentException expected
// [] Add duplicate key item
//
// generate key
string k = intl.GetRandomString(MAX_LEN);
if (!sd.ContainsKey(k))
{
sd.Add(k, "newItem");
}
if (!sd.ContainsKey(k))
{
Assert.False(true, string.Format("Error,failed to add item"));
}
else
{
Assert.Throws<ArgumentException>(() => { sd.Add(k, "itemitemitem"); });
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
namespace fyiReporting.RDL
{
///<summary>
/// A collection of rows.
///</summary>
internal class Rows : System.Collections.Generic.IComparer<Row>
{
List<Row> _Data; // array of Row object;
List<RowsSortExpression> _SortBy; // array of expressions used to sort the data
GroupEntry[] _CurrentGroups; // group
Report _Rpt;
internal Rows(Report rpt)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
}
// Constructor that takes existing Rows; a start, end and bitArray with the rows wanted
internal Rows(Report rpt, Rows r, int start, int end, BitArray ba)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
if (end - start < 0) // null set?
{
_Data = new List<Row>(1);
_Data.TrimExcess();
return;
}
_Data = new List<Row>(end - start + 1);
for (int iRow = start; iRow <= end; iRow++)
{
if (ba == null || ba.Get(iRow))
{
Row or = r.Data[iRow];
Row nr = new Row(this, or);
nr.RowNumber = or.RowNumber;
_Data.Add(nr);
}
}
_Data.TrimExcess();
}
// Constructor that takes existing Rows
internal Rows(Report rpt, Rows r)
{
_Rpt = rpt;
_SortBy = null;
_CurrentGroups = null;
if (r.Data == null || r.Data.Count <= 0) // null set?
{
_Data = new List<Row>(1);
_Data.TrimExcess();
return;
}
_Data = new List<Row>(r.Data.Count);
for (int iRow = 0; iRow < r.Data.Count; iRow++)
{
Row or = r.Data[iRow];
Row nr = new Row(this, or);
nr.RowNumber = or.RowNumber;
_Data.Add(nr);
}
_Data.TrimExcess();
}
// Constructor that creates exactly one row and one column
static internal Rows CreateOneRow(Report rpt)
{
Rows or = new Rows(rpt);
or._Data = new List<Row>(1);
Row nr = new Row(or, 1);
nr.RowNumber = 0;
or._Data.Add(nr);
or._Data.TrimExcess();
return or;
}
internal Rows(Report rpt, TableGroups tg, Grouping g, Sorting s)
{
_Rpt = rpt;
_SortBy = new List<RowsSortExpression>();
// Pull all the sort expression together
if (tg != null)
{
foreach(TableGroup t in tg.Items)
{
foreach(GroupExpression ge in t.Grouping.GroupExpressions.Items)
{
_SortBy.Add(new RowsSortExpression(ge.Expression));
}
// TODO what to do with the sort expressions!!!!
}
}
if (g != null)
{
if (g.ParentGroup != null)
_SortBy.Add(new RowsSortExpression(g.ParentGroup));
else if (g.GroupExpressions != null)
{
foreach (GroupExpression ge in g.GroupExpressions.Items)
{
_SortBy.Add(new RowsSortExpression(ge.Expression));
}
}
}
if (s != null)
{
foreach (SortBy sb in s.Items)
{
_SortBy.Add(new RowsSortExpression(sb.SortExpression, sb.Direction == SortDirectionEnum.Ascending));
}
}
if (_SortBy.Count > 0)
{
_SortBy.TrimExcess();
}
else
{
_SortBy = null;
}
}
internal Report Report
{
get {return this._Rpt;}
}
internal void Sort()
{
// sort the data array by the data.
_Data.Sort(this);
}
internal List<Row> Data
{
get { return _Data; }
set
{
_Data = value; // Assign the new value
foreach(Row r in _Data) // Updata all rows
{
r.R = this;
}
}
}
internal List<RowsSortExpression> SortBy
{
get { return _SortBy; }
set { _SortBy = value; }
}
internal GroupEntry[] CurrentGroups
{
get { return _CurrentGroups; }
set { _CurrentGroups = value; }
}
#region IComparer Members
public int Compare(Row r1, Row r2)
{
if (r1 == r2) // why does the sort routine do this??
return 0;
object o1=null,o2=null;
TypeCode tc = TypeCode.Object;
int rc;
try
{
foreach (RowsSortExpression se in _SortBy)
{
o1 = se.expr.Evaluate(this._Rpt, r1);
o2 = se.expr.Evaluate(this._Rpt, r2);
tc = se.expr.GetTypeCode();
rc = Filter.ApplyCompare(tc, o1, o2);
if (rc != 0)
return se.bAscending? rc: -rc;
}
}
catch (Exception e) // this really shouldn't happen
{
_Rpt.rl.LogError(8,
string.Format("Sort rows exception\r\nArguments: {0} {1}\r\nTypecode: {2}\r\n{3}\r\n{4}",
o1, o2, tc.ToString(), e.Message, e.StackTrace));
}
return r1.RowNumber - r2.RowNumber; // in case of tie use original row number
}
#endregion
}
class RowsSortExpression
{
internal Expression expr;
internal bool bAscending;
internal RowsSortExpression(Expression e, bool asc)
{
expr = e;
bAscending = asc;
}
internal RowsSortExpression(Expression e)
{
expr = e;
bAscending = true;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Microsoft.Identity.Json.Linq;
using Microsoft.Identity.Json.Utilities;
using System.Xml;
using Microsoft.Identity.Json.Converters;
using Microsoft.Identity.Json.Serialization;
using System.Text;
using System.Diagnostics;
#if HAVE_XLINQ
using System.Xml.Linq;
#endif
namespace Microsoft.Identity.Json
{
/// <summary>
/// Provides methods for converting between .NET types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Microsoft.Identity.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
internal static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings> DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value <c>true</c> as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value <c>false</c> as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's <c>null</c> as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's <c>undefined</c> as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's <c>NaN</c> as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#endif
/// <summary>
/// Converts the <see cref="bool"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="bool"/>.</returns>
public static string ToString(bool value)
{
return value ? True : False;
}
/// <summary>
/// Converts the <see cref="char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="int"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="int"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="short"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="short"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="ushort"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="ushort"/>.</returns>
// [ClsCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="uint"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="uint"/>.</returns>
// [ClsCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="long"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="long"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if HAVE_BIG_INTEGER
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#endif
/// <summary>
/// Converts the <see cref="ulong"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="ulong"/>.</returns>
// [ClsCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="float"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="float"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
{
return text;
}
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
{
return (!nullable) ? "0.0" : Null;
}
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || text.IndexOf("E", StringComparison.OrdinalIgnoreCase) != -1 || text.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
{
return text;
}
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
{
return text;
}
return text + ".0";
}
/// <summary>
/// Converts the <see cref="byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="sbyte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="sbyte"/>.</returns>
// [ClsCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="sbyte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text;
string qc;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
qc = quoteChar.ToString(CultureInfo.InvariantCulture);
#else
#pragma warning disable CA1305 // Specify IFormatProvider
text = value.ToString("D");
qc = quoteChar.ToString();
#pragma warning restore CA1305 // Specify IFormatProvider
#endif
return qc + text + qc;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
{
return Null;
}
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.OriginalString, quoteChar);
}
/// <summary>
/// Converts the <see cref="string"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="string"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="string"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="string"/>.</returns>
public static string ToString(string value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
/// <summary>
/// Converts the <see cref="string"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <param name="stringEscapeHandling">The string escape handling.</param>
/// <returns>A JSON string representation of the <see cref="string"/>.</returns>
public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
{
throw new ArgumentException("Delimiter must be a single or double quote.", nameof(delimiter));
}
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
/// <summary>
/// Converts the <see cref="object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
{
return Null;
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string)value);
case PrimitiveTypeCode.Char:
return ToString((char)value);
case PrimitiveTypeCode.Boolean:
return ToString((bool)value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte)value);
case PrimitiveTypeCode.Int16:
return ToString((short)value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort)value);
case PrimitiveTypeCode.Int32:
return ToString((int)value);
case PrimitiveTypeCode.Byte:
return ToString((byte)value);
case PrimitiveTypeCode.UInt32:
return ToString((uint)value);
case PrimitiveTypeCode.Int64:
return ToString((long)value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong)value);
case PrimitiveTypeCode.Single:
return ToString((float)value);
case PrimitiveTypeCode.Double:
return ToString((double)value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime)value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal)value);
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
return Null;
#endif
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset)value);
#endif
case PrimitiveTypeCode.Guid:
return ToString((Guid)value);
case PrimitiveTypeCode.Uri:
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value)
{
return SerializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
return SerializeObjectInternal(value, type, jsonSerializer);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
{
jsonSerializer.CheckAdditionalContent = true;
}
using (JsonTextReader reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
#endregion
#region Populate
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
[DebuggerStepThrough]
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (settings != null && settings.CheckAdditionalContent)
{
while (jsonReader.Read())
{
if (jsonReader.TokenType != JsonToken.Comment)
{
throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
}
}
}
}
}
#endregion
#region Xml
#if HAVE_XML_DOCUMENT
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter
{
DeserializeRootElementName = deserializeRootElementName,
WriteArrayAttribute = writeArrayAttribute,
EncodeSpecialCharacters = encodeSpecialCharacters
};
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if HAVE_XLINQ
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter
{
DeserializeRootElementName = deserializeRootElementName,
WriteArrayAttribute = writeArrayAttribute,
EncodeSpecialCharacters = encodeSpecialCharacters
};
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Tests
{
[TestFixture]
public class DHTest
: SimpleTest
{
private static readonly IBigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
private static readonly IBigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
private static readonly IBigInteger g768 = new BigInteger("7c240073c1316c621df461b71ebb0cdcc90a6e5527e5e126633d131f87461c4dc4afc60c2cb0f053b6758871489a69613e2a8b4c8acde23954c08c81cbd36132cfd64d69e4ed9f8e51ed6e516297206672d5c0a69135df0a5dcf010d289a9ca1", 16);
private static readonly IBigInteger p768 = new BigInteger("8c9dd223debed1b80103b8b309715be009d48860ed5ae9b9d5d8159508efd802e3ad4501a7f7e1cfec78844489148cd72da24b21eddd01aa624291c48393e277cfc529e37075eccef957f3616f962d15b44aeab4039d01b817fde9eaa12fd73f", 16);
private static readonly IBigInteger g1024 = new BigInteger("1db17639cdf96bc4eabba19454f0b7e5bd4e14862889a725c96eb61048dcd676ceb303d586e30f060dbafd8a571a39c4d823982117da5cc4e0f89c77388b7a08896362429b94a18a327604eb7ff227bffbc83459ade299e57b5f77b50fb045250934938efa145511166e3197373e1b5b1e52de713eb49792bedde722c6717abf", 16);
private static readonly IBigInteger p1024 = new BigInteger("a00e283b3c624e5b2b4d9fbc2653b5185d99499b00fd1bf244c6f0bb817b4d1c451b2958d62a0f8a38caef059fb5ecd25d75ed9af403f5b5bdab97a642902f824e3c13789fed95fa106ddfe0ff4a707c85e2eb77d49e68f2808bcea18ce128b178cd287c6bc00efa9a1ad2a673fe0dceace53166f75b81d6709d5f8af7c66bb7", 16);
// public key with mismatched oid/parameters
private byte[] oldPubEnc = Base64.Decode(
"MIIBnzCCARQGByqGSM4+AgEwggEHAoGBAPxSrN417g43VAM9sZRf1dt6AocAf7D6" +
"WVCtqEDcBJrMzt63+g+BNJzhXVtbZ9kp9vw8L/0PHgzv0Ot/kOLX7Khn+JalOECW" +
"YlkyBhmOVbjR79TY5u2GAlvG6pqpizieQNBCEMlUuYuK1Iwseil6VoRuA13Zm7uw" +
"WO1eZmaJtY7LAoGAQaPRCFKM5rEdkMrV9FNzeSsYRs8m3DqPnnJHpuySpyO9wUcX" +
"OOJcJY5qvHbDO5SxHXu/+bMgXmVT6dXI5o0UeYqJR7fj6pR4E6T0FwG55RFr5Ok4" +
"3C4cpXmaOu176SyWuoDqGs1RDGmYQjwbZUi23DjaaTFUly9LCYXMliKrQfEDgYQA" +
"AoGAQUGCBN4TaBw1BpdBXdTvTfCU69XDB3eyU2FOBE3UWhpx9D8XJlx4f5DpA4Y6" +
"6sQMuCbhfmjEph8W7/sbMurM/awR+PSR8tTY7jeQV0OkmAYdGK2nzh0ZSifMO1oE" +
"NNhN2O62TLs67msxT28S4/S89+LMtc98mevQ2SX+JF3wEVU=");
// bogus key with full PKCS parameter set
private byte[] oldFullParams = Base64.Decode(
"MIIBIzCCARgGByqGSM4+AgEwggELAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E" +
"AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f" +
"6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv" +
"8iIDGZ3RSAHHAoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlX" +
"jrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6j" +
"fwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqAgFk" +
"AwUAAgIH0A==");
private byte[] samplePubEnc = Base64.Decode(
"MIIBpjCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YRt1I8" +
"70QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWk" +
"n5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HX" +
"Ku/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdR" +
"WVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWR" +
"bqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoC" +
"AgIAA4GEAAKBgEIiqxoUW6E6GChoOgcfNbVFclW91ITf5MFSUGQwt2R0RHoOhxvO" +
"lZhNs++d0VPATLAyXovjfgENT9SGCbuZttYcqqLdKTbMXBWPek+rfnAl9E4iEMED" +
"IDd83FJTKs9hQcPAm7zmp0Xm1bGF9CbUFjP5G02265z7eBmHDaT0SNlB");
private byte[] samplePrivEnc = Base64.Decode(
"MIIBZgIBADCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YR" +
"t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZ" +
"UKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOu" +
"K2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0H" +
"gmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuz" +
"pnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7P" +
"SSoCAgIABEICQAZYXnBHazxXUUdFP4NIf2Ipu7du0suJPZQKKff81wymi2zfCfHh" +
"uhe9gQ9xdm4GpzeNtrQ8/MzpTy+ZVrtd29Q=");
public override string Name
{
get { return "DH"; }
}
private void doTestGP(
string algName,
int size,
int privateValueSize,
IBigInteger g,
IBigInteger p)
{
IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName);
DHParameters dhParams = new DHParameters(p, g, null, privateValueSize);
KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParams);
keyGen.Init(kgp);
//
// a side
//
IAsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();
IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);
checkKeySize(privateValueSize, aKeyPair);
aKeyAgreeBasic.Init(aKeyPair.Private);
//
// b side
//
IAsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();
IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);
checkKeySize(privateValueSize, bKeyPair);
bKeyAgreeBasic.Init(bKeyPair.Private);
//
// agreement
//
// aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
// bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
// IBigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
// IBigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);
if (!k1.Equals(k2))
{
Fail(size + " bit 2-way test failed");
}
//
// public key encoding test
//
// byte[] pubEnc = aKeyPair.Public.GetEncoded();
byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();
// KeyFactory keyFac = KeyFactory.getInstance(algName);
// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
// DHPublicKey pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
DHPublicKeyParameters pubKey = (DHPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
// DHParameterSpec spec = pubKey.Parameters;
DHParameters spec = pubKey.Parameters;
if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
{
Fail(size + " bit public key encoding/decoding test failed on parameters");
}
if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
{
Fail(size + " bit public key encoding/decoding test failed on y value");
}
//
// public key serialisation test
//
// TODO Put back in
// MemoryStream bOut = new MemoryStream();
// ObjectOutputStream oOut = new ObjectOutputStream(bOut);
//
// oOut.WriteObject(aKeyPair.Public);
//
// MemoryStream bIn = new MemoryStream(bOut.ToArray(), false);
// ObjectInputStream oIn = new ObjectInputStream(bIn);
//
// pubKey = (DHPublicKeyParameters)oIn.ReadObject();
spec = pubKey.Parameters;
if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
{
Fail(size + " bit public key serialisation test failed on parameters");
}
if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
{
Fail(size + " bit public key serialisation test failed on y value");
}
//
// private key encoding test
//
// byte[] privEnc = aKeyPair.Private.GetEncoded();
byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
// DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);
DHPrivateKeyParameters privKey = (DHPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
spec = privKey.Parameters;
if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
{
Fail(size + " bit private key encoding/decoding test failed on parameters");
}
if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
{
Fail(size + " bit private key encoding/decoding test failed on y value");
}
//
// private key serialisation test
//
// TODO Put back in
// bOut = new MemoryStream();
// oOut = new ObjectOutputStream(bOut);
//
// oOut.WriteObject(aKeyPair.Private);
//
// bIn = new MemoryStream(bOut.ToArray(), false);
// oIn = new ObjectInputStream(bIn);
//
// privKey = (DHPrivateKeyParameters)oIn.ReadObject();
spec = privKey.Parameters;
if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
{
Fail(size + " bit private key serialisation test failed on parameters");
}
if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
{
Fail(size + " bit private key serialisation test failed on y value");
}
//
// three party test
//
IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);
aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
IAsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair();
IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);
bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
IAsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair();
IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);
cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
IAsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair();
IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName);
aKeyAgree.Init(aPair.Private);
IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName);
bKeyAgree.Init(bPair.Private);
IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName);
cKeyAgree.Init(cPair.Private);
// Key ac = aKeyAgree.doPhase(cPair.Public, false);
// Key ba = bKeyAgree.doPhase(aPair.Public, false);
// Key cb = cKeyAgree.doPhase(bPair.Public, false);
//
// aKeyAgree.doPhase(cb, true);
// bKeyAgree.doPhase(ac, true);
// cKeyAgree.doPhase(ba, true);
//
// IBigInteger aShared = new BigInteger(aKeyAgree.generateSecret());
// IBigInteger bShared = new BigInteger(bKeyAgree.generateSecret());
// IBigInteger cShared = new BigInteger(cKeyAgree.generateSecret());
DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec);
DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec);
DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec);
IBigInteger aShared = aKeyAgree.CalculateAgreement(cb);
IBigInteger bShared = bKeyAgree.CalculateAgreement(ac);
IBigInteger cShared = cKeyAgree.CalculateAgreement(ba);
if (!aShared.Equals(bShared))
{
Fail(size + " bit 3-way test failed (a and b differ)");
}
if (!cShared.Equals(bShared))
{
Fail(size + " bit 3-way test failed (c and b differ)");
}
}
private void doTestExplicitWrapping(
int size,
int privateValueSize,
IBigInteger g,
IBigInteger p)
{
DHParameters dhParams = new DHParameters(p, g, null, privateValueSize);
IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));
//
// a side
//
IAsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();
IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("DH");
checkKeySize(privateValueSize, aKeyPair);
aKeyAgree.Init(aKeyPair.Private);
//
// b side
//
IAsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();
IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("DH");
checkKeySize(privateValueSize, bKeyPair);
bKeyAgree.Init(bKeyPair.Private);
//
// agreement
//
// aKeyAgree.doPhase(bKeyPair.Public, true);
// bKeyAgree.doPhase(aKeyPair.Public, true);
//
// SecretKey k1 = aKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);
// SecretKey k2 = bKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);
// TODO Does this really test the same thing as the above code?
IBigInteger b1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
IBigInteger b2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);
if (!b1.Equals(b2))
{
Fail("Explicit wrapping test failed");
}
}
private void checkKeySize(
int privateValueSize,
IAsymmetricCipherKeyPair aKeyPair)
{
if (privateValueSize != 0)
{
DHPrivateKeyParameters key = (DHPrivateKeyParameters)aKeyPair.Private;
if (key.X.BitLength != privateValueSize)
{
Fail("limited key check failed for key size " + privateValueSize);
}
}
}
// TODO Put back in
// private void doTestRandom(
// int size)
// {
// AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DH");
// a.init(size, new SecureRandom());
// AlgorithmParameters parameters = a.generateParameters();
//
// byte[] encodeParams = parameters.GetEncoded();
//
// AlgorithmParameters a2 = AlgorithmParameters.getInstance("DH");
// a2.init(encodeParams);
//
// // a and a2 should be equivalent!
// byte[] encodeParams_2 = a2.GetEncoded();
//
// if (!areEqual(encodeParams, encodeParams_2))
// {
// Fail("encode/Decode parameters failed");
// }
//
// DHParameterSpec dhP = (DHParameterSpec)parameters.getParameterSpec(DHParameterSpec.class);
//
// doTestGP("DH", size, 0, dhP.G, dhP.P);
// }
[Test]
public void TestECDH()
{
doTestECDH("ECDH");
}
[Test]
public void TestECDHC()
{
doTestECDH("ECDHC");
}
private void doTestECDH(
string algorithm)
{
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm);
// EllipticCurve curve = new EllipticCurve(
// new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
// new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
// new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECCurve curve = new FPCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECDomainParameters ecSpec = new ECDomainParameters(
curve,
// ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n
BigInteger.One); //1); // h
// g.initialize(ecSpec, new SecureRandom());
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
//
// a side
//
IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);
aKeyAgreeBasic.Init(aKeyPair.Private);
//
// b side
//
IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);
bKeyAgreeBasic.Init(bKeyPair.Private);
//
// agreement
//
// aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
// bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
// IBigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
// IBigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);
if (!k1.Equals(k2))
{
Fail(algorithm + " 2-way test failed");
}
//
// public key encoding test
//
// byte[] pubEnc = aKeyPair.Public.GetEncoded();
byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();
// KeyFactory keyFac = KeyFactory.getInstance(algorithm);
// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
ECDomainParameters ecDP = pubKey.Parameters;
// if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW()))
if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
{
// Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX());
// Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY());
// Fail(algorithm + " public key encoding (W test) failed");
Console.WriteLine(" expected " + pubKey.Q.X.ToBigInteger()
+ " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.X.ToBigInteger());
Console.WriteLine(" expected " + pubKey.Q.Y.ToBigInteger()
+ " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.Y.ToBigInteger());
Fail(algorithm + " public key encoding (Q test) failed");
}
// if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator()))
if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G))
{
Fail(algorithm + " public key encoding (G test) failed");
}
//
// private key encoding test
//
// byte[] privEnc = aKeyPair.Private.GetEncoded();
byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
// if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
{
// Fail(algorithm + " private key encoding (S test) failed");
Fail(algorithm + " private key encoding (D test) failed");
}
// if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator()))
if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G))
{
Fail(algorithm + " private key encoding (G test) failed");
}
}
[Test]
public void TestExceptions()
{
DHParameters dhParams = new DHParameters(p512, g512);
try
{
IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("DH");
// aKeyAgreeBasic.generateSecret("DES");
aKeyAgreeBasic.CalculateAgreement(null);
}
catch (InvalidOperationException)
{
// okay
}
catch (Exception e)
{
Fail("Unexpected exception: " + e, e);
}
}
private void doTestDesAndDesEde(
IBigInteger g,
IBigInteger p)
{
DHParameters dhParams = new DHParameters(p, g, null, 256);
IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));
IAsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair();
IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreement("DH");
keyAgreement.Init(kp.Private);
IBigInteger agreed = keyAgreement.CalculateAgreement(kp.Public);
byte[] agreedBytes = agreed.ToByteArrayUnsigned();
// TODO Figure out where the magic happens of choosing the right
// bytes from 'agreedBytes' for each key type - need C# equivalent?
// (see JCEDHKeyAgreement.engineGenerateSecret)
// SecretKey key = keyAgreement.generateSecret("DES");
//
// if (key.getEncoded().length != 8)
// {
// Fail("DES length wrong");
// }
//
// if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))
// {
// Fail("DES parity wrong");
// }
//
// key = keyAgreement.generateSecret("DESEDE");
//
// if (key.getEncoded().length != 24)
// {
// Fail("DESEDE length wrong");
// }
//
// if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))
// {
// Fail("DESEDE parity wrong");
// }
//
// key = keyAgreement.generateSecret("Blowfish");
//
// if (key.getEncoded().length != 16)
// {
// Fail("Blowfish length wrong");
// }
}
[Test]
public void TestFunction()
{
doTestGP("DH", 512, 0, g512, p512);
doTestGP("DiffieHellman", 768, 0, g768, p768);
doTestGP("DIFFIEHELLMAN", 1024, 0, g1024, p1024);
doTestGP("DH", 512, 64, g512, p512);
doTestGP("DiffieHellman", 768, 128, g768, p768);
doTestGP("DIFFIEHELLMAN", 1024, 256, g1024, p1024);
doTestExplicitWrapping(512, 0, g512, p512);
doTestDesAndDesEde(g768, p768);
// TODO Put back in
//doTestRandom(256);
}
[Test]
public void TestEnc()
{
// KeyFactory kFact = KeyFactory.getInstance("DH", "BC");
//
// Key k = kFact.generatePrivate(new PKCS8EncodedKeySpec(samplePrivEnc));
IAsymmetricKeyParameter k = PrivateKeyFactory.CreateKey(samplePrivEnc);
byte[] encoded = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k).GetEncoded();
if (!Arrays.AreEqual(samplePrivEnc, encoded))
{
Fail("private key re-encode failed");
}
// k = kFact.generatePublic(new X509EncodedKeySpec(samplePubEnc));
k = PublicKeyFactory.CreateKey(samplePubEnc);
encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded();
if (!Arrays.AreEqual(samplePubEnc, encoded))
{
Fail("public key re-encode failed");
}
// k = kFact.generatePublic(new X509EncodedKeySpec(oldPubEnc));
k = PublicKeyFactory.CreateKey(oldPubEnc);
encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded();
if (!Arrays.AreEqual(oldPubEnc, encoded))
{
Fail("old public key re-encode failed");
}
// k = kFact.generatePublic(new X509EncodedKeySpec(oldFullParams));
k = PublicKeyFactory.CreateKey(oldFullParams);
encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded();
if (!Arrays.AreEqual(oldFullParams, encoded))
{
Fail("old full public key re-encode failed");
}
}
public override void PerformTest()
{
TestEnc();
TestFunction();
TestECDH();
TestECDHC();
TestExceptions();
}
public static void Main(
string[] args)
{
RunTest(new DHTest());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
using System.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
namespace System
{
internal class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#region QCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser);
#endregion
public SafeTypeNameParserHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
_ReleaseTypeNameParser(handle);
handle = IntPtr.Zero;
return true;
}
}
internal sealed class TypeNameParser : IDisposable
{
#region QCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString);
#endregion
#region Static Members
internal static Type GetType(
string typeName,
Func<AssemblyName, Assembly> assemblyResolver,
Func<Assembly, string, bool, Type> typeResolver,
bool throwOnError,
bool ignoreCase,
ref StackCrawlMark stackMark)
{
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
if (typeName.Length > 0 && typeName[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
Contract.EndContractBlock();
Type ret = null;
SafeTypeNameParserHandle handle = CreateTypeNameParser(typeName, throwOnError);
if (handle != null)
{
// If we get here the typeName must have been successfully parsed.
// Let's construct the Type object.
using (TypeNameParser parser = new TypeNameParser(handle))
{
ret = parser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark);
}
}
return ret;
}
#endregion
#region Private Data Members
private SafeTypeNameParserHandle m_NativeParser;
private static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; /* see typeparse.h */
#endregion
#region Constructor and Disposer
private TypeNameParser(SafeTypeNameParserHandle handle)
{
m_NativeParser = handle;
}
public void Dispose()
{
m_NativeParser.Dispose();
}
#endregion
#region private Members
private unsafe Type ConstructType(
Func<AssemblyName, Assembly> assemblyResolver,
Func<Assembly, string, bool, Type> typeResolver,
bool throwOnError,
bool ignoreCase,
ref StackCrawlMark stackMark)
{
// assembly name
Assembly assembly = null;
string asmName = GetAssemblyName();
// GetAssemblyName never returns null
Debug.Assert(asmName != null);
if (asmName.Length > 0)
{
assembly = ResolveAssembly(asmName, assemblyResolver, throwOnError, ref stackMark);
if (assembly == null)
{
// Cannot resolve the assembly. If throwOnError is true we should have already thrown.
return null;
}
}
string[] names = GetNames();
if (names == null)
{
// This can only happen if the type name is an empty string or if the first char is '\0'
if (throwOnError)
throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
return null;
}
Type baseType = ResolveType(assembly, names, typeResolver, throwOnError, ignoreCase, ref stackMark);
if (baseType == null)
{
// Cannot resolve the type. If throwOnError is true we should have already thrown.
Debug.Assert(throwOnError == false);
return null;
}
SafeTypeNameParserHandle[] typeArguments = GetTypeArguments();
Type[] types = null;
if (typeArguments != null)
{
types = new Type[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
Debug.Assert(typeArguments[i] != null);
using (TypeNameParser argParser = new TypeNameParser(typeArguments[i]))
{
types[i] = argParser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark);
}
if (types[i] == null)
{
// If throwOnError is true argParser.ConstructType should have already thrown.
Debug.Assert(throwOnError == false);
return null;
}
}
}
int[] modifiers = GetModifiers();
fixed (int* ptr = modifiers)
{
IntPtr intPtr = new IntPtr(ptr);
return RuntimeTypeHandle.GetTypeHelper(baseType, types, intPtr, modifiers == null ? 0 : modifiers.Length);
}
}
private static Assembly ResolveAssembly(string asmName, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark)
{
Contract.Requires(asmName != null && asmName.Length > 0);
Assembly assembly = null;
if (assemblyResolver == null)
{
if (throwOnError)
{
assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/);
}
else
{
// When throwOnError is false we should only catch FileNotFoundException.
// Other exceptions like BadImangeFormatException should still fly.
try
{
assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/);
}
catch (FileNotFoundException)
{
return null;
}
}
}
else
{
assembly = assemblyResolver(new AssemblyName(asmName));
if (assembly == null && throwOnError)
{
throw new FileNotFoundException(Environment.GetResourceString("FileNotFound_ResolveAssembly", asmName));
}
}
return assembly;
}
private static Type ResolveType(Assembly assembly, string[] names, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark)
{
Contract.Requires(names != null && names.Length > 0);
Type type = null;
// both the customer provided and the default type resolvers accept escaped type names
string OuterMostTypeName = EscapeTypeName(names[0]);
// Resolve the top level type.
if (typeResolver != null)
{
type = typeResolver(assembly, OuterMostTypeName, ignoreCase);
if (type == null && throwOnError)
{
string errorString = assembly == null ?
Environment.GetResourceString("TypeLoad_ResolveType", OuterMostTypeName) :
Environment.GetResourceString("TypeLoad_ResolveTypeFromAssembly", OuterMostTypeName, assembly.FullName);
throw new TypeLoadException(errorString);
}
}
else
{
if (assembly == null)
{
type = RuntimeType.GetType(OuterMostTypeName, throwOnError, ignoreCase, false, ref stackMark);
}
else
{
type = assembly.GetType(OuterMostTypeName, throwOnError, ignoreCase);
}
}
// Resolve nested types.
if (type != null)
{
BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public;
if (ignoreCase)
bindingFlags |= BindingFlags.IgnoreCase;
for (int i = 1; i < names.Length; i++)
{
type = type.GetNestedType(names[i], bindingFlags);
if (type == null)
{
if (throwOnError)
throw new TypeLoadException(Environment.GetResourceString("TypeLoad_ResolveNestedType", names[i], names[i-1]));
else
break;
}
}
}
return type;
}
private static string EscapeTypeName(string name)
{
if (name.IndexOfAny(SPECIAL_CHARS) < 0)
return name;
StringBuilder sb = StringBuilderCache.Acquire();
foreach (char c in name)
{
if (Array.IndexOf<char>(SPECIAL_CHARS, c) >= 0)
sb.Append('\\');
sb.Append(c);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
private static SafeTypeNameParserHandle CreateTypeNameParser(string typeName, bool throwOnError)
{
SafeTypeNameParserHandle retHandle = null;
_CreateTypeNameParser(typeName, JitHelpers.GetObjectHandleOnStack(ref retHandle), throwOnError);
return retHandle;
}
private string[] GetNames()
{
string[] names = null;
_GetNames(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref names));
return names;
}
private SafeTypeNameParserHandle[] GetTypeArguments()
{
SafeTypeNameParserHandle[] arguments = null;
_GetTypeArguments(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref arguments));
return arguments;
}
private int[] GetModifiers()
{
int[] modifiers = null;
_GetModifiers(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref modifiers));
return modifiers;
}
private string GetAssemblyName()
{
string assemblyName = null;
_GetAssemblyName(m_NativeParser, JitHelpers.GetStringHandleOnStack(ref assemblyName));
return assemblyName;
}
#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.
#if ENABLEDATABINDING
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
namespace System.Xml.XPath.DataBinding
{
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView"]/*' />
public sealed class XPathDocumentView : IBindingList, ITypedList {
ArrayList rows;
Shape rowShape;
XPathNode ndRoot;
XPathDocument document;
string xpath;
IXmlNamespaceResolver namespaceResolver;
IXmlNamespaceResolver xpathResolver;
//
// Constructors
//
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView"]/*' />
public XPathDocumentView(XPathDocument document)
: this(document, (IXmlNamespaceResolver)null) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView1"]/*' />
public XPathDocumentView(XPathDocument document, IXmlNamespaceResolver namespaceResolver) {
if (null == document)
throw new ArgumentNullException(nameof(document));
this.document = document;
this.ndRoot = document.Root;
if (null == this.ndRoot)
throw new ArgumentException(nameof(document));
this.namespaceResolver = namespaceResolver;
ArrayList rows = new ArrayList();
this.rows = rows;
Debug.Assert(XPathNodeType.Root == this.ndRoot.NodeType);
XPathNode nd = this.ndRoot.Child;
while (null != nd) {
if (XPathNodeType.Element == nd.NodeType)
rows.Add(nd);
nd = nd.Sibling;
}
DeriveShapeFromRows();
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView2"]/*' />
public XPathDocumentView(XPathDocument document, string xpath)
: this(document, xpath, null, true) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView3"]/*' />
public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver)
: this(document, xpath, namespaceResolver, false) {
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPathDocumentView4"]/*' />
public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver, bool showPrefixes) {
if (null == document)
throw new ArgumentNullException(nameof(document));
this.xpath = xpath;
this.document = document;
this.ndRoot = document.Root;
if (null == this.ndRoot)
throw new ArgumentException(nameof(document));
this.ndRoot = document.Root;
this.xpathResolver = namespaceResolver;
if (showPrefixes)
this.namespaceResolver = namespaceResolver;
ArrayList rows = new ArrayList();
this.rows = rows;
InitFromXPath(this.ndRoot, xpath);
}
internal XPathDocumentView(XPathNode root, ArrayList rows, Shape rowShape) {
this.rows = rows;
this.rowShape = rowShape;
this.ndRoot = root;
}
//
// public properties
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Document"]/*' />
public XPathDocument Document { get { return this.document; } }
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.XPath"]/*' />
public String XPath { get { return xpath; } }
//
// IEnumerable Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetEnumerator"]/*' />
public IEnumerator GetEnumerator() {
return new RowEnumerator(this);
}
//
// ICollection implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Count"]/*' />
public int Count {
get { return this.rows.Count; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsSynchronized"]/*' />
public bool IsSynchronized {
get { return false ; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SyncRoot"]/*' />
public object SyncRoot {
get { return null; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.CopyTo"]/*' />
public void CopyTo(Array array, int index) {
object o;
ArrayList rows = this.rows;
for (int i=0; i < rows.Count; i++)
o = this[i]; // force creation lazy of row object
rows.CopyTo(array, index);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.CopyTo2"]/*' />
/// <devdoc>
/// <para>strongly typed version of CopyTo, demanded by Fxcop.</para>
/// </devdoc>
public void CopyTo(XPathNodeView[] array, int index) {
object o;
ArrayList rows = this.rows;
for (int i=0; i < rows.Count; i++)
o = this[i]; // force creation lazy of row object
rows.CopyTo(array, index);
}
//
// IList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsReadOnly"]/*' />
bool IList.IsReadOnly {
get { return true; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsFixedSize"]/*' />
bool IList.IsFixedSize {
get { return true; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Contains"]/*' />
bool IList.Contains(object value) {
return this.rows.Contains(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Remove"]/*' />
void IList.Remove(object value) {
throw new NotSupportedException("IList.Remove");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveAt"]/*' />
void IList.RemoveAt(int index) {
throw new NotSupportedException("IList.RemoveAt");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Clear"]/*' />
void IList.Clear() {
throw new NotSupportedException("IList.Clear");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Add"]/*' />
int IList.Add(object value) {
throw new NotSupportedException("IList.Add");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Insert"]/*' />
void IList.Insert(int index, object value) {
throw new NotSupportedException("IList.Insert");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IndexOf"]/*' />
int IList.IndexOf( object value ) {
return this.rows.IndexOf(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.this"]/*' />
object IList.this[int index] {
get {
object val = this.rows[index];
if (val is XPathNodeView)
return val;
XPathNodeView xiv = FillRow((XPathNode)val, this.rowShape);
this.rows[index] = xiv;
return xiv;
}
set {
throw new NotSupportedException("IList.this[]");
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Contains2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Contains, demanded by Fxcop.</para>
/// </devdoc>
public bool Contains(XPathNodeView value) {
return this.rows.Contains(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Add2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Add, demanded by Fxcop.</para>
/// </devdoc>
public int Add(XPathNodeView value) {
throw new NotSupportedException("IList.Add");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Insert2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Insert, demanded by Fxcop.</para>
/// </devdoc>
public void Insert(int index, XPathNodeView value) {
throw new NotSupportedException("IList.Insert");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IndexOf2"]/*' />
/// <devdoc>
/// <para>strongly typed version of IndexOf, demanded by Fxcop.</para>
/// </devdoc>
public int IndexOf(XPathNodeView value) {
return this.rows.IndexOf(value);
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Remove2"]/*' />
/// <devdoc>
/// <para>strongly typed version of Remove, demanded by Fxcop.</para>
/// </devdoc>
public void Remove(XPathNodeView value) {
throw new NotSupportedException("IList.Remove");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Item"]/*' />
/// <devdoc>
/// <para>strongly typed version of Item, demanded by Fxcop.</para>
/// </devdoc>
public XPathNodeView this[int index] {
get {
object val = this.rows[index];
XPathNodeView nodeView;
nodeView = val as XPathNodeView;
if (nodeView != null) {
return nodeView;
}
nodeView = FillRow((XPathNode)val, this.rowShape);
this.rows[index] = nodeView;
return nodeView;
}
set {
throw new NotSupportedException("IList.this[]");
}
}
//
// IBindingList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowEdit"]/*' />
public bool AllowEdit {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowAdd"]/*' />
public bool AllowAdd {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowRemove"]/*' />
public bool AllowRemove {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AllowNew"]/*' />
public bool AllowNew {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AddNew"]/*' />
public object AddNew() {
throw new NotSupportedException("IBindingList.AddNew");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsChangeNotification"]/*' />
public bool SupportsChangeNotification {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.ListChanged"]/*' />
public event ListChangedEventHandler ListChanged {
add {
throw new NotSupportedException("IBindingList.ListChanged");
}
remove {
throw new NotSupportedException("IBindingList.ListChanged");
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsSearching"]/*' />
public bool SupportsSearching {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SupportsSorting"]/*' />
public bool SupportsSorting {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.IsSorted"]/*' />
public bool IsSorted {
get { return false; }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SortProperty"]/*' />
public PropertyDescriptor SortProperty {
get { throw new NotSupportedException("IBindingList.SortProperty"); }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.SortDirection"]/*' />
public ListSortDirection SortDirection {
get { throw new NotSupportedException("IBindingList.SortDirection"); }
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.AddIndex"]/*' />
public void AddIndex( PropertyDescriptor descriptor ) {
throw new NotSupportedException("IBindingList.AddIndex");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.ApplySort"]/*' />
public void ApplySort( PropertyDescriptor descriptor, ListSortDirection direction ) {
throw new NotSupportedException("IBindingList.ApplySort");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.Find"]/*' />
public int Find(PropertyDescriptor propertyDescriptor, object key) {
throw new NotSupportedException("IBindingList.Find");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveIndex"]/*' />
public void RemoveIndex(PropertyDescriptor propertyDescriptor) {
throw new NotSupportedException("IBindingList.RemoveIndex");
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.RemoveSort"]/*' />
public void RemoveSort() {
throw new NotSupportedException("IBindingList.RemoveSort");
}
//
// ITypedList Implementation
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetListName"]/*' />
public string GetListName(PropertyDescriptor[] listAccessors) {
if( listAccessors == null ) {
return this.rowShape.Name;
}
else {
return listAccessors[listAccessors.Length-1].Name;
}
}
/// <include file='doc\XPathDocumentView.uex' path='docs/doc[@for="XPathDocumentView.GetItemProperties"]/*' />
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) {
Shape shape = null;
if( listAccessors == null ) {
shape = this.rowShape;
}
else {
XPathNodeViewPropertyDescriptor propdesc = listAccessors[listAccessors.Length-1] as XPathNodeViewPropertyDescriptor;
if (null != propdesc)
shape = propdesc.Shape;
}
if (null == shape)
throw new ArgumentException(nameof(listAccessors));
return new PropertyDescriptorCollection(shape.PropertyDescriptors);
}
//
// Internal Implementation
internal Shape RowShape { get { return this.rowShape; } }
internal void SetRows(ArrayList rows) {
Debug.Assert(this.rows == null);
this.rows = rows;
}
XPathNodeView FillRow(XPathNode ndRow, Shape shape) {
object[] columns;
XPathNode nd;
switch (shape.BindingType) {
case BindingType.Text:
case BindingType.Attribute:
columns = new object[1];
columns[0] = ndRow;
return new XPathNodeView(this, ndRow, columns);
case BindingType.Repeat:
columns = new object[1];
nd = TreeNavigationHelper.GetContentChild(ndRow);
columns[0] = FillColumn(new ContentIterator(nd, shape), shape);
return new XPathNodeView(this, ndRow, columns);
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All:
int subShapesCount = shape.SubShapes.Count;
columns = new object[subShapesCount];
if (shape.BindingType == BindingType.Sequence
&& shape.SubShape(0).BindingType == BindingType.Attribute) {
FillAttributes(ndRow, shape, columns);
}
Shape lastSubShape = (Shape)shape.SubShapes[subShapesCount - 1];
if (lastSubShape.BindingType == BindingType.Text) { //Attributes followed by simpe content or mixed content
columns[subShapesCount - 1] = ndRow;
return new XPathNodeView(this, ndRow, columns);
}
else {
nd = TreeNavigationHelper.GetContentChild(ndRow);
return FillSubRow(new ContentIterator(nd, shape), shape, columns);
}
default:
// should not map to a row
#if DEBUG
throw new NotSupportedException("Unable to bind row to: "+shape.BindingType.ToString());
#else
throw new NotSupportedException();
#endif
}
}
void FillAttributes(XPathNode nd, Shape shape, object[] cols) {
int i = 0;
while (i < cols.Length) {
Shape attrShape = shape.SubShape(i);
if (attrShape.BindingType != BindingType.Attribute)
break;
XmlQualifiedName name = attrShape.AttributeName;
XPathNode ndAttr = nd.GetAttribute( name.Name, name.Namespace );
if (null != ndAttr)
cols[i] = ndAttr;
i++;
}
}
object FillColumn(ContentIterator iter, Shape shape) {
object val;
switch (shape.BindingType) {
case BindingType.Element:
val = iter.Node;
iter.Next();
break;
case BindingType.ElementNested: {
ArrayList rows = new ArrayList();
rows.Add(iter.Node);
iter.Next();
val = new XPathDocumentView(null, rows, shape.NestedShape);
break;
}
case BindingType.Repeat: {
ArrayList rows = new ArrayList();
Shape subShape = shape.SubShape(0);
if (subShape.BindingType == BindingType.ElementNested) {
Shape nestShape = subShape.NestedShape;
XPathDocumentView xivc = new XPathDocumentView(null, null, nestShape);
XPathNode nd;
while (null != (nd = iter.Node)
&& subShape.IsParticleMatch(iter.Particle)) {
rows.Add(nd);
iter.Next();
}
xivc.SetRows(rows);
val = xivc;
}
else {
XPathDocumentView xivc = new XPathDocumentView(null, null, subShape);
XPathNode nd;
while (null != (nd = iter.Node)
&& shape.IsParticleMatch(iter.Particle)) {
rows.Add(xivc.FillSubRow(iter, subShape, null));
}
xivc.SetRows(rows);
val = xivc;
}
break;
}
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All: {
XPathDocumentView docview = new XPathDocumentView(null, null, shape);
ArrayList rows = new ArrayList();
rows.Add(docview.FillSubRow(iter, shape, null));
docview.SetRows(rows);
val = docview;
break;
}
default:
case BindingType.Text:
case BindingType.Attribute:
throw new NotSupportedException();
}
return val;
}
XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns) {
if (null == columns) {
int colCount = shape.SubShapes.Count;
if (0 == colCount)
colCount = 1;
columns = new object[colCount];
}
switch (shape.BindingType) {
case BindingType.Element:
columns[0] = FillColumn(iter, shape);
break;
case BindingType.Sequence: {
int iPrev = -1;
int i;
while (null != iter.Node) {
i = shape.FindMatchingSubShape(iter.Particle);
if (i <= iPrev)
break;
columns[i] = FillColumn(iter, shape.SubShape(i));
iPrev = i;
}
break;
}
case BindingType.All: {
while (null != iter.Node) {
int i = shape.FindMatchingSubShape(iter.Particle);
if (-1 == i || null != columns[i])
break;
columns[i] = FillColumn(iter, shape.SubShape(i));
}
break;
}
case BindingType.Choice: {
int i = shape.FindMatchingSubShape(iter.Particle);
if (-1 != i) {
columns[i] = FillColumn(iter, shape.SubShape(i));
}
break;
}
case BindingType.Repeat:
default:
// should not map to a row
throw new NotSupportedException();
}
return new XPathNodeView(this, null, columns);
}
//
// XPath support
//
void InitFromXPath(XPathNode ndRoot, string xpath) {
XPathStep[] steps = ParseXPath(xpath, this.xpathResolver);
ArrayList rows = this.rows;
rows.Clear();
PopulateFromXPath(ndRoot, steps, 0);
DeriveShapeFromRows();
}
void DeriveShapeFromRows() {
object schemaInfo = null;
for (int i=0; (i<rows.Count) && (null==schemaInfo); i++) {
XPathNode nd = rows[i] as XPathNode;
Debug.Assert(null != nd && (XPathNodeType.Attribute == nd.NodeType || XPathNodeType.Element == nd.NodeType));
if (null != nd) {
if (XPathNodeType.Attribute == nd.NodeType)
schemaInfo = nd.SchemaAttribute;
else
schemaInfo = nd.SchemaElement;
}
}
if (0 == rows.Count) {
throw new NotImplementedException("XPath failed to match an elements");
}
if (null == schemaInfo) {
rows.Clear();
throw new XmlException(SR.XmlDataBinding_NoSchemaType, (string[])null);
}
ShapeGenerator shapeGen = new ShapeGenerator(this.namespaceResolver);
XmlSchemaElement xse = schemaInfo as XmlSchemaElement;
if (null != xse)
this.rowShape = shapeGen.GenerateFromSchema(xse);
else
this.rowShape = shapeGen.GenerateFromSchema((XmlSchemaAttribute)schemaInfo);
}
void PopulateFromXPath(XPathNode nd, XPathStep[] steps, int step) {
string ln = steps[step].name.Name;
string ns = steps[step].name.Namespace;
if (XPathNodeType.Attribute == steps[step].type) {
XPathNode ndAttr = nd.GetAttribute( ln, ns, true);
if (null != ndAttr) {
if (null != ndAttr.SchemaAttribute)
this.rows.Add(ndAttr);
}
}
else {
XPathNode ndChild = TreeNavigationHelper.GetElementChild(nd, ln, ns, true);
if (null != ndChild) {
int nextStep = step+1;
do {
if (steps.Length == nextStep) {
if (null != ndChild.SchemaType)
this.rows.Add(ndChild);
}
else {
PopulateFromXPath(ndChild, steps, nextStep);
}
ndChild = TreeNavigationHelper.GetElementSibling(ndChild, ln, ns, true);
} while (null != ndChild);
}
}
}
// This is the limited grammar we support
// Path ::= '/ ' ( Step '/')* ( QName | '@' QName )
// Step ::= '.' | QName
// This is encoded as an array of XPathStep structs
struct XPathStep {
internal XmlQualifiedName name;
internal XPathNodeType type;
}
// Parse xpath (limited to above grammar), using provided namespaceResolver
// to resolve prefixes.
XPathStep[] ParseXPath(string xpath, IXmlNamespaceResolver xnr) {
int pos;
int stepCount = 1;
for (pos=1; pos<(xpath.Length-1); pos++) {
if ( ('/' == xpath[pos]) && ('.' != xpath[pos+1]) )
stepCount++;
}
XPathStep[] steps = new XPathStep[stepCount];
pos = 0;
int i = 0;
for (;;) {
if (pos >= xpath.Length)
throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null);
if ('/' != xpath[pos])
throw new XmlException(SR.XmlDataBinding_XPathRequireSlash, (string[])null);
pos++;
char ch = xpath[pos];
if (ch == '.') {
pos++;
// again...
}
else if ('@' == ch) {
if (0 == i)
throw new XmlException(SR.XmlDataBinding_XPathAttrNotFirst, (string[])null);
pos++;
if (pos >= xpath.Length)
throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null);
steps[i].name = ParseQName(xpath, ref pos, xnr);
steps[i].type = XPathNodeType.Attribute;
i++;
if (pos != xpath.Length)
throw new XmlException(SR.XmlDataBinding_XPathAttrLast, (string[])null);
break;
}
else {
steps[i].name = ParseQName(xpath, ref pos, xnr);
steps[i].type = XPathNodeType.Element;
i++;
if (pos == xpath.Length)
break;
}
}
Debug.Assert(i == steps.Length);
return steps;
}
// Parse a QName from the string, and resolve prefix
XmlQualifiedName ParseQName(string xpath, ref int pos, IXmlNamespaceResolver xnr) {
string nm = ParseName(xpath, ref pos);
if (pos < xpath.Length && ':' == xpath[pos]) {
pos++;
string ns = (null==xnr) ? null : xnr.LookupNamespace(nm);
if (null == ns || 0 == ns.Length)
throw new XmlException(SR.Sch_UnresolvedPrefix, nm);
return new XmlQualifiedName(ParseName(xpath, ref pos), ns);
}
else {
return new XmlQualifiedName(nm);
}
}
// Parse a NCNAME from the string
string ParseName(string xpath, ref int pos) {
char ch;
int start = pos++;
while (pos < xpath.Length
&& '/' != (ch = xpath[pos])
&& ':' != ch)
pos++;
string nm = xpath.Substring(start, pos - start);
if (!XmlReader.IsName(nm))
throw new XmlException(SR.Xml_InvalidNameChars, (string[])null);
return this.document.NameTable.Add(nm);
}
//
// Helper classes
//
class ContentIterator {
XPathNode node;
ContentValidator contentValidator;
ValidationState currentState;
object currentParticle;
public ContentIterator(XPathNode nd, Shape shape) {
this.node = nd;
XmlSchemaElement xse = shape.XmlSchemaElement;
Debug.Assert(null != xse);
SchemaElementDecl decl = xse.ElementDecl;
Debug.Assert(null != decl);
this.contentValidator = decl.ContentValidator;
this.currentState = new ValidationState();
this.contentValidator.InitValidation(this.currentState);
this.currentState.ProcessContents = XmlSchemaContentProcessing.Strict;
if (nd != null)
Advance();
}
public XPathNode Node { get { return this.node; } }
public object Particle { get { return this.currentParticle; } }
public bool Next() {
if (null != this.node) {
this.node = TreeNavigationHelper.GetContentSibling(this.node, XPathNodeType.Element);
if (node != null)
Advance();
return null != this.node;
}
return false;
}
private void Advance() {
XPathNode nd = this.node;
int errorCode;
this.currentParticle = this.contentValidator.ValidateElement(new XmlQualifiedName(nd.LocalName, nd.NamespaceUri), this.currentState, out errorCode);
if (null == this.currentParticle || 0 != errorCode) {
this.node = null;
}
}
}
// Helper class to implement enumerator over rows
// We can't just use ArrayList enumerator because
// sometims rows may be lazily constructed
sealed class RowEnumerator : IEnumerator {
XPathDocumentView collection;
int pos;
internal RowEnumerator(XPathDocumentView collection) {
this.collection = collection;
this.pos = -1;
}
public object Current {
get {
if (this.pos < 0 || this.pos >= this.collection.Count)
return null;
return this.collection[this.pos];
}
}
public void Reset() {
this.pos = -1;
}
public bool MoveNext() {
this.pos++;
int max = this.collection.Count;
if (this.pos > max)
this.pos = max;
return this.pos < max;
}
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.