context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//! \file ArcABM.cs
//! \date Tue Aug 04 23:40:47 2015
//! \brief LiLiM/Le.Chocolat multi-frame compressed bitmaps.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Lilim
{
internal class AbmArchive : ArcFile
{
public readonly AbmImageData FrameInfo;
public AbmArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, AbmImageData info)
: base (arc, impl, dir)
{
FrameInfo = info;
}
}
internal class AbmImageData : ImageMetaData
{
public int Mode;
public uint BaseOffset;
public uint FrameOffset;
public AbmImageData Clone ()
{
return this.MemberwiseClone() as AbmImageData;
}
}
internal class AbmEntry : PackedEntry
{
public int Index;
}
[Export(typeof(ArchiveFormat))]
public class AbmOpener : ArchiveFormat
{
public override string Tag { get { return "ABM"; } }
public override string Description { get { return "LiLiM/Le.Chocolat multi-frame bitmap"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if ('B' != file.View.ReadByte (0) || 'M' != file.View.ReadByte (1))
return null;
int type = file.View.ReadSByte (0x1C);
if (type != 1 && type != 2)
return null;
int count = file.View.ReadInt16 (0x3A);
if (!IsSaneCount (count))
return null;
uint width = file.View.ReadUInt32 (0x12);
uint height = file.View.ReadUInt32 (0x16);
int pixel_size = 2 == type ? 4 : 3;
uint bitmap_data_size = width*height*(uint)pixel_size;
var dir = new List<Entry> (count);
long next_offset = file.View.ReadUInt32 (0x42);
uint current_offset = 0x46;
string base_name = Path.GetFileNameWithoutExtension (file.Name);
for (int i = 0; i < count; ++i)
{
var entry = new AbmEntry {
Name = string.Format ("{0}#{1:D4}", base_name, i),
Type = "image",
Offset = next_offset,
Index = i,
};
if (i + 1 != count)
{
next_offset = file.View.ReadUInt32 (current_offset);
current_offset += 4;
}
else
next_offset = file.MaxOffset;
if (next_offset <= entry.Offset)
return null;
entry.Size = (uint)(next_offset - entry.Offset);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
entry.UnpackedSize = 0x12 + bitmap_data_size;
dir.Add (entry);
}
var image_info = new AbmImageData
{
Width = (uint)width,
Height = (uint)height,
BPP = pixel_size * 8,
Mode = type,
BaseOffset = (uint)dir[0].Offset,
};
return new AbmArchive (file, this, dir, image_info);
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var abm = arc as AbmArchive;
var frame = entry as AbmEntry;
if (null == abm || null == frame)
return base.OpenImage (arc, entry);
var frame_info = abm.FrameInfo;
if (frame.Index != 0)
{
frame_info = frame_info.Clone();
frame_info.FrameOffset = (uint)frame.Offset;
}
var input = arc.File.CreateStream (0, (uint)arc.File.MaxOffset);
return new AbmReader (input, frame_info);
}
}
internal sealed class AbmReader : BinaryImageDecoder
{
byte[] m_output;
AbmImageData m_info;
int m_bpp;
public AbmReader (IBinaryStream file, AbmImageData info) : base (file, info)
{
m_info = info;
}
protected override ImageData GetImageData ()
{
switch (m_info.Mode)
{
case 8:
case -8:
m_input.Position = 0x36;
var palette = ImageFormat.ReadPalette (m_input.AsStream);
var bitmap_size = m_info.Width * m_info.Height;
m_output = new byte[bitmap_size];
m_input.Position = m_info.BaseOffset;
if (8 == m_info.Mode)
{
m_bpp = 8;
if (m_output.Length != m_input.Read (m_output, 0, m_output.Length))
throw new EndOfStreamException();
return ImageData.Create (m_info, PixelFormats.Indexed8, palette, m_output);
}
else
{
var alpha = new byte[bitmap_size];
UnpackStream8 (m_input, m_output, alpha);
m_output = ApplyAlpha (m_output, alpha, palette);
m_bpp = 32;
}
break;
case 2:
m_bpp = 32;
m_input.Position = m_info.FrameOffset;
m_output = UnpackV2 (m_input);
break;
case 1:
case 24:
case 32:
if (1 == m_info.Mode)
m_bpp = 24;
else
m_bpp = m_info.Mode;
int total_length = (int)(m_info.Width * m_info.Height * m_bpp / 8);
m_output = new byte[total_length];
m_input.Position = m_info.BaseOffset;
if (1 == m_info.Mode)
{
if (total_length != m_input.Read (m_output, 0, (total_length)))
throw new EndOfStreamException ();
}
else if (24 == m_bpp)
UnpackStream24 (m_input, m_output, total_length);
else
UnpackStream32 (m_input, m_output, total_length);
break;
default:
throw new NotImplementedException();
}
if (0 != m_info.FrameOffset)
m_output = Unpack();
PixelFormat format = 24 == m_bpp ? PixelFormats.Bgr24 : PixelFormats.Bgra32;
return ImageData.Create (m_info, format, null, m_output);
}
int frame_x;
int frame_y;
int frame_w;
int frame_h;
byte[] Unpack ()
{
m_input.Position = m_info.FrameOffset;
if (1 == m_info.Mode)
return UnpackStream24 (m_input, m_output, m_output.Length);
if (2 == m_info.Mode)
{
var frame = UnpackV2 (m_input);
CopyFrame (frame);
return m_output;
}
throw new NotImplementedException();
}
byte[] UnpackV2 (IBinaryStream input)
{
frame_x = input.ReadInt32();
frame_y = input.ReadInt32();
frame_w = input.ReadInt32();
frame_h = input.ReadInt32();
if (frame_x < 0 || frame_y < 0 || frame_w <= 0 || frame_h <= 0)
throw new InvalidFormatException();
int total_length = frame_w * frame_h * m_bpp / 8;
byte[] output = new byte[total_length];
input.ReadByte(); // position number
return UnpackStream32 (input, output, total_length);
}
byte[] UnpackStream24 (IBinaryStream input, byte[] output, int total_length)
{
int dst = 0;
while (dst < total_length)
{
int v = input.ReadUInt8();
if (0 == v)
{
int count = input.ReadUInt8();
if (0 == count)
continue;
dst += count;
}
else if (0xff == v)
{
int count = input.ReadUInt8();
if (0 == count)
continue;
count = Math.Min (count, total_length-dst);
input.Read (output, dst, count);
dst += count;
}
else
{
output[dst++] = input.ReadUInt8();
}
}
return output;
}
byte[] UnpackStream32 (IBinaryStream input, byte[] output, int total_length)
{
int dst = 0;
int component = 0;
while (dst < total_length)
{
byte v = input.ReadUInt8();
if (0 == v)
{
int count = input.ReadUInt8();
if (0 == count)
continue;
for (int i = 0; i < count; ++i)
{
++dst;
if (++component == 3)
{
++dst;
component = 0;
}
}
}
else if (0xff == v)
{
int count = input.ReadUInt8();
if (0 == count)
continue;
for (int i = 0; i < count && dst < total_length; ++i)
{
output[dst++] = input.ReadUInt8();
if (++component == 3)
{
output[dst++] = 0xff;
component = 0;
}
}
}
else
{
output[dst++] = input.ReadUInt8();
if (++component == 3)
{
output[dst++] = v;
component = 0;
}
}
}
return output;
}
void CopyFrame (byte[] frame)
{
if (frame_x >= m_info.Width || frame_y >= m_info.Height)
return;
int pixel_size = m_bpp / 8;
int line_size = Math.Min (frame_w, (int)m_info.Width-frame_x) * pixel_size;
int left = frame_x * pixel_size;
int bottom = Math.Min (frame_y+frame_h, (int)m_info.Height);
int stride = (int)m_info.Width * pixel_size;
int src = 0;
for (int y = frame_y; y < bottom; ++y)
{
int dst = stride * y + left;
Buffer.BlockCopy (frame, src, m_output, dst, line_size);
src += frame_w * pixel_size;
}
}
void UnpackStream8 (IBinaryStream input, byte[] output, byte[] alpha)
{
int alpha_dst = 0;
int dst = 0;
while (dst < output.Length)
{
byte rle = input.ReadUInt8();
if (0 == rle)
{
int skip = input.ReadUInt8();
dst += skip;
alpha_dst += skip;
}
else if (rle != 0xFF)
{
output[dst++] = input.ReadUInt8();
alpha[alpha_dst++] = rle;
}
else
{
int count = input.ReadUInt8();
input.Read (output, dst, count);
dst += count;
for (int i = 0; i < count; ++i)
alpha[alpha_dst++] = 0xFF;
}
}
}
byte[] ApplyAlpha (byte[] input, byte[] alpha, BitmapPalette palette)
{
var colors = palette.Colors;
var pixels = new byte[input.Length * 4];
int dst = 0;
for (int i = 0; i < input.Length; ++i)
{
var color = colors[input[i]];
pixels[dst++] = color.B;
pixels[dst++] = color.G;
pixels[dst++] = color.R;
pixels[dst++] = alpha[i];
}
return pixels;
}
}
}
| |
using System;
using System.Configuration;
using System.Threading;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Reflection;
using System.Security.Cryptography;
using System.Collections.Generic;
using MongoDB.Driver.GridFS;
using System.IO;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("2.0.0.*"), InternalsVisibleTo("DominionEnterprises.Mongo.Tests")]
namespace DominionEnterprises.Mongo
{
/// <summary>
/// Abstraction of mongo db collection as priority queue.
/// </summary>
/// <remarks>
/// Tied priorities are then ordered by time. So you may use a single priority for normal queuing (overloads exist for this purpose).
/// Using a random priority achieves random Get()
/// </remarks>
public sealed class Queue
{
internal const int ACK_MULTI_BATCH_SIZE = 1000;
private readonly MongoCollection collection;
private readonly MongoGridFS gridfs;
/// <summary>
/// Construct MongoQueue with url, db name and collection name from app settings keys mongoQueueUrl, mongoQueueDb and mongoQueueCollection
/// </summary>
public Queue()
: this(ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"], ConfigurationManager.AppSettings["mongoQueueCollection"])
{ }
/// <summary>
/// Construct MongoQueue
/// </summary>
/// <param name="url">mongo url like mongodb://localhost</param>
/// <param name="db">db name</param>
/// <param name="collection">collection name</param>
/// <exception cref="ArgumentNullException">url, db or collection is null</exception>
public Queue(string url, string db, string collection)
{
if (url == null) throw new ArgumentNullException("url");
if (db == null) throw new ArgumentNullException("db");
if (collection == null) throw new ArgumentNullException("collection");
this.collection = new MongoClient(url).GetServer().GetDatabase(db).GetCollection(collection);
this.gridfs = this.collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
}
/// <summary>
/// Construct MongoQueue
/// </summary>
/// <param name="collection">collection</param>
/// <exception cref="ArgumentNullException">collection is null</exception>
public Queue(MongoCollection collection)
{
if (collection == null) throw new ArgumentNullException("collection");
this.collection = collection;
this.gridfs = collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
}
#region EnsureGetIndex
/// <summary>
/// Ensure index for Get() method with no fields before or after sort fields
/// </summary>
public void EnsureGetIndex()
{
EnsureGetIndex(new IndexKeysDocument());
}
/// <summary>
/// Ensure index for Get() method with no fields after sort fields
/// </summary>
/// <param name="beforeSort">fields in Get() call that should be before the sort fields in the index</param>
/// <exception cref="ArgumentNullException">beforeSort is null</exception>
/// <exception cref="ArgumentException">beforeSort field value is not 1 or -1</exception>
public void EnsureGetIndex(IndexKeysDocument beforeSort)
{
EnsureGetIndex(beforeSort, new IndexKeysDocument());
}
/// <summary>
/// Ensure index for Get() method
/// </summary>
/// <param name="beforeSort">fields in Get() call that should be before the sort fields in the index</param>
/// <param name="afterSort">fields in Get() call that should be after the sort fields in the index</param>
/// <exception cref="ArgumentNullException">beforeSort or afterSort is null</exception>
/// <exception cref="ArgumentException">beforeSort or afterSort field value is not 1 or -1</exception>
public void EnsureGetIndex(IndexKeysDocument beforeSort, IndexKeysDocument afterSort)
{
if (beforeSort == null) throw new ArgumentNullException("beforeSort");
if (afterSort == null) throw new ArgumentNullException("afterSort");
//using general rule: equality, sort, range or more equality tests in that order for index
var completeIndex = new IndexKeysDocument("running", 1);
foreach (var field in beforeSort)
{
if (field.Value != 1 && field.Value != -1) throw new ArgumentException("field values must be 1 or -1 for ascending or descending", "beforeSort");
completeIndex.Add("payload." + field.Name, field.Value);
}
completeIndex.Add("priority", 1);
completeIndex.Add("created", 1);
foreach (var field in afterSort)
{
if (field.Value != -1 && field.Value != 1) throw new ArgumentException("field values must be 1 or -1 for ascending or descending", "afterSort");
completeIndex.Add("payload." + field.Name, field.Value);
}
completeIndex.Add("earliestGet", 1);
EnsureIndex(completeIndex);//main query in Get()
EnsureIndex(new IndexKeysDocument { { "running", 1 }, { "resetTimestamp", 1 } });//for the stuck messages query in Get()
}
#endregion
/// <summary>
/// Ensure index for Count() method
/// Is a no-op if the generated index is a prefix of an existing one. If you have a similar EnsureGetIndex call, call it first.
/// </summary>
/// <param name="index">fields in Count() call</param>
/// <param name="includeRunning">whether running was given to Count() or not</param>
/// <exception cref="ArgumentNullException">index was null</exception>
/// <exception cref="ArgumentException">index field value is not 1 or -1</exception>
public void EnsureCountIndex(IndexKeysDocument index, bool includeRunning)
{
if (index == null) throw new ArgumentNullException("index");
var completeFields = new IndexKeysDocument();
if (includeRunning)
completeFields.Add("running", 1);
foreach (var field in index)
{
if (field.Value != 1 && field.Value != -1) throw new ArgumentException("field values must be 1 or -1 for ascending or descending", "index");
completeFields.Add("payload." + field.Name, field.Value);
}
EnsureIndex(completeFields);
}
#region Get
/// <summary>
/// Get a non running message from queue with a wait of 3 seconds and poll of 200 milliseconds
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
/// <returns>message or null</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public Message Get(QueryDocument query, TimeSpan resetRunning)
{
return Get(query, resetRunning, TimeSpan.FromSeconds(3));
}
/// <summary>
/// Get a non running message from queue with a poll of 200 milliseconds
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
/// <param name="wait">duration to keep polling before returning null</param>
/// <returns>message or null</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public Message Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait)
{
return Get(query, resetRunning, wait, TimeSpan.FromMilliseconds(200));
}
/// <summary>
/// Get a non running message from queue with an approxiate wait.
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
/// <param name="wait">duration to keep polling before returning null</param>
/// <param name="poll">duration between poll attempts</param>
/// <returns>message or null</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public Message Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait, TimeSpan poll)
{
return Get(query, resetRunning, wait, poll, true);
}
/// <summary>
/// Get a non running message from queue
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
/// <param name="wait">duration to keep polling before returning null</param>
/// <param name="poll">duration between poll attempts</param>
/// <param name="approximateWait">whether to fluctuate the wait time randomly by +-10 percent. This ensures Get() calls seperate in time when multiple Queues are used in loops started at the same time</param>
/// <returns>message or null</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public Message Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait, TimeSpan poll, bool approximateWait)
{
if (query == null)
throw new ArgumentNullException ("query");
//reset stuck messages
collection.Update(
new QueryDocument { { "running", true }, { "resetTimestamp", new BsonDocument("$lte", DateTime.UtcNow) } },
new UpdateDocument("$set", new BsonDocument("running", false)),
UpdateFlags.Multi
);
var builtQuery = new QueryDocument("running", false);
foreach (var field in query)
builtQuery.Add("payload." + field.Name, field.Value);
builtQuery.Add("earliestGet", new BsonDocument("$lte", DateTime.UtcNow));
var resetTimestamp = DateTime.UtcNow;
try
{
resetTimestamp += resetRunning;
}
catch (ArgumentOutOfRangeException)
{
resetTimestamp = resetRunning > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
}
var sort = new SortByDocument { { "priority", 1 }, { "created", 1 } };
var update = new UpdateDocument("$set", new BsonDocument { { "running", true }, { "resetTimestamp", resetTimestamp } });
var fields = new FieldsDocument { { "payload", 1 }, { "streams", 1 } };
var end = DateTime.UtcNow;
try
{
if (approximateWait)
//fluctuate randomly by 10 percent
wait += TimeSpan.FromMilliseconds(wait.TotalMilliseconds * GetRandomDouble(-0.1, 0.1));
end += wait;
}
catch (Exception e)
{
if (!(e is OverflowException) && !(e is ArgumentOutOfRangeException))
throw e;//cant cover
end = wait > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
}
while (true)
{
var findModifyArgs = new FindAndModifyArgs { Query = builtQuery, SortBy = sort, Update = update, Fields = fields, Upsert = false };
var message = collection.FindAndModify(findModifyArgs).ModifiedDocument;
if (message != null)
{
var handleStreams = new List<KeyValuePair<BsonValue, Stream>>();
var messageStreams = new Dictionary<string, Stream>();
foreach (var streamId in message["streams"].AsBsonArray)
{
var fileInfo = gridfs.FindOneById(streamId);
var stream = fileInfo.OpenRead();
handleStreams.Add(new KeyValuePair<BsonValue, Stream>(streamId, stream));
messageStreams.Add(fileInfo.Name, stream);
}
var handle = new Handle(message["_id"].AsObjectId, handleStreams);
return new Message(handle, message["payload"].AsBsonDocument, messageStreams);
}
if (DateTime.UtcNow >= end)
return null;
try
{
Thread.Sleep(poll);
}
catch (ArgumentOutOfRangeException)
{
if (poll < TimeSpan.Zero)
poll = TimeSpan.Zero;
else
poll = TimeSpan.FromMilliseconds(int.MaxValue);
Thread.Sleep(poll);
}
if (DateTime.UtcNow >= end)
return null;
}
}
#endregion
#region Count
/// <summary>
/// Count in queue, running true or false
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <returns>count</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public long Count(QueryDocument query)
{
if (query == null) throw new ArgumentNullException("query");
var completeQuery = new QueryDocument();
foreach (var field in query)
completeQuery.Add("payload." + field.Name, field.Value);
return collection.Count(completeQuery);
}
/// <summary>
/// Count in queue
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="running">count running messages or not running</param>
/// <returns>count</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public long Count(QueryDocument query, bool running)
{
if (query == null) throw new ArgumentNullException("query");
var completeQuery = new QueryDocument("running", running);
foreach (var field in query)
completeQuery.Add("payload." + field.Name, field.Value);
return collection.Count(completeQuery);
}
#endregion
/// <summary>
/// Acknowledge a handle was processed and remove from queue.
/// </summary>
/// <param name="handle">handle received from Get()</param>
/// <exception cref="ArgumentNullException">handle is null</exception>
public void Ack(Handle handle)
{
if (handle == null) throw new ArgumentNullException("handle");
collection.Remove(new QueryDocument("_id", handle.Id));
foreach (var stream in handle.Streams)
{
stream.Value.Dispose();
gridfs.DeleteById(stream.Key);
}
}
/// <summary>
/// Acknowledge multiple handles were processed and remove from queue.
/// </summary>
/// <param name="handles">handles received from Get()</param>
/// <exception cref="ArgumentNullException">handles is null</exception>
public void AckMulti(IEnumerable<Handle> handles)
{
if (handles == null) throw new ArgumentNullException("handles");
var ids = new BsonArray();
foreach (var handle in handles)
{
ids.Add(handle.Id);
if (ids.Count != ACK_MULTI_BATCH_SIZE)
continue;
collection.Remove(new QueryDocument("_id", new BsonDocument("$in", ids)));
ids.Clear();
}
if (ids.Count > 0)
collection.Remove(new QueryDocument("_id", new BsonDocument("$in", ids)));
foreach (var handle in handles)
{
foreach (var stream in handle.Streams)
{
stream.Value.Dispose();
gridfs.DeleteById(stream.Key);
}
}
}
#region AckSend
/// <summary>
/// Ack handle and send payload to queue, atomically, with earliestGet as Now, 0.0 priority, new timestamp and no gridfs streams
/// </summary>
/// <param name="handle">handle to ack received from Get()</param>
/// <param name="payload">payload to send</param>
/// <exception cref="ArgumentNullException">handle or payload is null</exception>
public void AckSend(Handle handle, BsonDocument payload)
{
AckSend(handle, payload, DateTime.UtcNow);
}
/// <summary>
/// Ack handle and send payload to queue, atomically, with 0.0 priority, new timestamp and no gridfs streams
/// </summary>
/// <param name="handle">handle to ack received from Get()</param>
/// <param name="payload">payload to send</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <exception cref="ArgumentNullException">handle or payload is null</exception>
public void AckSend(Handle handle, BsonDocument payload, DateTime earliestGet)
{
AckSend(handle, payload, earliestGet, 0.0);
}
/// <summary>
/// Ack handle and send payload to queue, atomically, with new timestamp and no gridfs streams
/// </summary>
/// <param name="handle">handle to ack received from Get()</param>
/// <param name="payload">payload to send</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <param name="priority">priority for order out of Get(). 0 is higher priority than 1</param>
/// <exception cref="ArgumentNullException">handle or payload is null</exception>
/// <exception cref="ArgumentException">priority was NaN</exception>
public void AckSend(Handle handle, BsonDocument payload, DateTime earliestGet, double priority)
{
AckSend(handle, payload, earliestGet, priority, true);
}
/// <summary>
/// Ack handle and send payload to queue, atomically, with no gridfs streams
/// </summary>
/// <param name="handle">handle to ack received from Get()</param>
/// <param name="payload">payload to send</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <param name="priority">priority for order out of Get(). 0 is higher priority than 1</param>
/// <param name="newTimestamp">true to give the payload a new timestamp or false to use given message timestamp</param>
/// <exception cref="ArgumentNullException">handle or payload is null</exception>
/// <exception cref="ArgumentException">priority was NaN</exception>
public void AckSend(Handle handle, BsonDocument payload, DateTime earliestGet, double priority, bool newTimestamp)
{
AckSend(handle, payload, earliestGet, priority, newTimestamp, new KeyValuePair<string, Stream>[0]);
}
/// <summary>
/// Ack handle and send payload to queue, atomically.
/// </summary>
/// <param name="handle">handle to ack received from Get()</param>
/// <param name="payload">payload to send</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <param name="priority">priority for order out of Get(). 0 is higher priority than 1</param>
/// <param name="newTimestamp">true to give the payload a new timestamp or false to use given message timestamp</param>
/// <param name="streams">streams to upload into gridfs or null to forward handle's streams</param>
/// <exception cref="ArgumentNullException">handle or payload is null</exception>
/// <exception cref="ArgumentException">priority was NaN</exception>
public void AckSend(Handle handle, BsonDocument payload, DateTime earliestGet, double priority, bool newTimestamp, IEnumerable<KeyValuePair<string, Stream>> streams)
{
if (handle == null) throw new ArgumentNullException("handle");
if (payload == null) throw new ArgumentNullException("payload");
if (Double.IsNaN(priority)) throw new ArgumentException("priority was NaN", "priority");
var toSet = new BsonDocument
{
{"payload", payload},
{"running", false},
{"resetTimestamp", DateTime.MaxValue},
{"earliestGet", earliestGet},
{"priority", priority},
};
if (newTimestamp)
toSet["created"] = DateTime.UtcNow;
if (streams != null)
{
var streamIds = new BsonArray();
foreach (var stream in streams)
streamIds.Add(gridfs.Upload(stream.Value, stream.Key).Id);
toSet["streams"] = streamIds;
}
//using upsert because if no documents found then the doc was removed (SHOULD ONLY HAPPEN BY SOMEONE MANUALLY) so we can just send
collection.Update(new QueryDocument("_id", handle.Id), new UpdateDocument("$set", toSet), UpdateFlags.Upsert);
foreach (var existingStream in handle.Streams)
existingStream.Value.Dispose();
if (streams != null)
{
foreach (var existingStream in handle.Streams)
gridfs.DeleteById(existingStream.Key);
}
}
#endregion
#region Send
/// <summary>
/// Send message to queue with earliestGet as Now, 0.0 priority and no gridfs streams
/// </summary>
/// <param name="payload">payload</param>
/// <exception cref="ArgumentNullException">payload is null</exception>
public void Send(BsonDocument payload)
{
Send(payload, DateTime.UtcNow, 0.0);
}
/// <summary>
/// Send message to queue with 0.0 priority and no gridfs streams
/// </summary>
/// <param name="payload">payload</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <exception cref="ArgumentNullException">payload is null</exception>
public void Send(BsonDocument payload, DateTime earliestGet)
{
Send(payload, earliestGet, 0.0);
}
/// <summary>
/// Send message to queue with no gridfs streams
/// </summary>
/// <param name="payload">payload</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <param name="priority">priority for order out of Get(). 0 is higher priority than 1</param>
/// <exception cref="ArgumentNullException">payload is null</exception>
/// <exception cref="ArgumentException">priority was NaN</exception>
public void Send(BsonDocument payload, DateTime earliestGet, double priority)
{
Send(payload, earliestGet, priority, new List<KeyValuePair<string, Stream>>());
}
/// <summary>
/// Send message to queue.
/// </summary>
/// <param name="payload">payload</param>
/// <param name="earliestGet">earliest instant that a call to Get() can return message</param>
/// <param name="priority">priority for order out of Get(). 0 is higher priority than 1</param>
/// <param name="streams">streams to upload into gridfs</param>
/// <exception cref="ArgumentNullException">payload is null</exception>
/// <exception cref="ArgumentException">priority was NaN</exception>
/// <exception cref="ArgumentNullException">streams is null</exception>
public void Send(BsonDocument payload, DateTime earliestGet, double priority, IEnumerable<KeyValuePair<string, Stream>> streams)
{
if (payload == null) throw new ArgumentNullException("payload");
if (Double.IsNaN(priority)) throw new ArgumentException("priority was NaN", "priority");
if (streams == null) throw new ArgumentNullException("streams");
var streamIds = new BsonArray();
foreach (var stream in streams)
streamIds.Add(gridfs.Upload(stream.Value, stream.Key).Id);
var message = new BsonDocument
{
{"payload", payload},
{"running", false},
{"resetTimestamp", DateTime.MaxValue},
{"earliestGet", earliestGet},
{"priority", priority},
{"created", DateTime.UtcNow},
{"streams", streamIds},
};
collection.Insert(message);
}
#endregion
private void EnsureIndex(IndexKeysDocument index)
{
//if index is a prefix of any existing index we are good
foreach (var existingIndex in collection.GetIndexes())
{
var names = index.Names;
var values = index.Values;
var existingNamesPrefix = existingIndex.Key.Names.Take(names.Count());
var existingValuesPrefix = existingIndex.Key.Values.Take(values.Count());
if (Enumerable.SequenceEqual(names, existingNamesPrefix) && Enumerable.SequenceEqual(values, existingValuesPrefix))
return;
}
for (var i = 0; i < 5; ++i)
{
for (var name = Guid.NewGuid().ToString(); name.Length > 0; name = name.Substring(0, name.Length - 1))
{
//creating an index with the same name and different spec does nothing.
//creating an index with same spec and different name does nothing.
//so we use any generated name, and then find the right spec after we have called, and just go with that name.
try
{
collection.CreateIndex(index, new IndexOptionsDocument { {"name", name }, { "background", true } });
}
catch (MongoCommandException)
{
//this happens when the name was too long
}
foreach (var existingIndex in collection.GetIndexes())
{
if (existingIndex.Key == index)
return;
}
}
}
throw new Exception("couldnt create index after 5 attempts");
}
/// <summary>
/// Gets a random double between min and max using RNGCryptoServiceProvider
/// </summary>
/// <returns>
/// random double.
/// </returns>
internal static double GetRandomDouble(double min, double max)
{
if (Double.IsNaN(min)) throw new ArgumentException("min cannot be NaN");
if (Double.IsNaN(max)) throw new ArgumentException("max cannot be NaN");
if (max < min) throw new ArgumentException("max cannot be less than min");
var buffer = new byte[8];
new RNGCryptoServiceProvider().GetBytes(buffer);
var randomULong = BitConverter.ToUInt64(buffer, 0);
var fraction = (double)randomULong / (double)ulong.MaxValue;
var fractionOfNewRange = fraction * (max - min);
return min + fractionOfNewRange;
}
}
/// <summary>
/// Message to be given out of Get()
/// </summary>
public sealed class Message
{
public readonly Handle Handle;
public readonly BsonDocument Payload;
public readonly IDictionary<string, Stream> Streams;
/// <summary>
/// Construct Message
/// </summary>
/// <param name="handle">handle</param>
/// <param name="payload">payload</param>
/// <param name="streams">streams</param>
internal Message(Handle handle, BsonDocument payload, IDictionary<string, Stream> streams)
{
this.Handle = handle;
this.Payload = payload;
this.Streams = streams;
}
}
/// <summary>
/// Message handle to be given to Ack() and AckSend().
/// </summary>
public sealed class Handle
{
internal readonly BsonObjectId Id;
internal readonly IEnumerable<KeyValuePair<BsonValue, Stream>> Streams;
/// <summary>
/// Construct Handle
/// </summary>
/// <param name="id">id</param>
/// <param name="streams">streams</param>
internal Handle(BsonObjectId id, IEnumerable<KeyValuePair<BsonValue, Stream>> streams)
{
this.Id = id;
this.Streams = streams;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace PortalX_DCRM.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DowUtils;
namespace Factotum
{
public partial class GridEdit : Form, IEntityEditForm
{
private EGrid curGrid;
private EComponent curComponent;
private DataTable dsetAssignments;
private DataTable curMeasurements;
private GridDivider[] gridDividersUpExt, gridDividersUpMain, gridDividersDnMain, gridDividersDnExt,
gridDividersBranch, gridDividersBranchExt, gridDividersPost;
EGridSizeCollection gridSizes;
EGridComboItemCollection parentGrids;
private int curGridRows;
private bool savedInternally;
private bool newRecord;
// Used to prevent a tab-select triggered refresh if a checked-listbox
// triggered refresh is already in progress.
private bool refreshInProgress;
// This is set if the user checks any of the boxes in the checked listbox.
// We check to see if this is set when the user leaves the clb control.
private bool assignmentsChanged;
// This is set initially. The idea is that the user may want to open the grid
// and edit some parameters that don't require the grid to be filled or stats
// calculated. If this flag is set and the user then decides
// to click one of those tabs, we recalculate before displaying..
private bool gridAndStatsNotYetDisplayed;
// Flag whether to create a merged grid
private bool createMergedGrid = false;
// Allow the calling form to access the entity
public IEntity Entity
{
get { return curGrid; }
}
//---------------------------------------------------------
// Initialization
//---------------------------------------------------------
// If you are creating a new record, the ID should be null
// Normally in this case, you will want to provide a parentID
public GridEdit(Guid? ID)
: this(ID, null){}
public GridEdit(Guid? ID, Guid? inspectionID)
{
InitializeComponent();
curGrid = new EGrid();
curGrid.Load(ID);
if (inspectionID != null) curGrid.GridIspID = inspectionID;
curComponent = new EComponent(curGrid.ComponentID);
newRecord = (ID == null);
InitializeControls();
// Hook these up after the form data is initialized.
cboGridSize.SelectedIndexChanged += new System.EventHandler(cboGridSize_SelectedIndexChanged);
cboParentGrid.SelectedIndexChanged += new System.EventHandler(cboParentGrid_SelectedIndexChanged);
cboUpExtPreDivider.SelectedIndexChanged += new EventHandler(cboUpExtPreDivider_SelectedIndexChanged);
cboUpMainPreDivider.SelectedIndexChanged += new EventHandler(cboUpMainPreDivider_SelectedIndexChanged);
cboDnMainPreDivider.SelectedIndexChanged += new EventHandler(cboDnMainPreDivider_SelectedIndexChanged);
cboDnExtPreDivider.SelectedIndexChanged += new EventHandler(cboDnExtPreDivider_SelectedIndexChanged);
cboBranchPreDivider.SelectedIndexChanged += new EventHandler(cboBranchPreDivider_SelectedIndexChanged);
cboBranchExtPreDivider.SelectedIndexChanged += new EventHandler(cboBranchExtPreDivider_SelectedIndexChanged);
cboPostDivider.SelectedIndexChanged += new EventHandler(cboPostDivider_SelectedIndexChanged);
clbDatasets.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.clbDatasets_ItemCheck);
clbDatasets.Validated += new EventHandler(clbDatasets_Validated);
savedInternally = false;
}
private void GridEdit_FormClosed(object sender, FormClosedEventArgs e)
{
cboGridSize.SelectedIndexChanged -= new System.EventHandler(cboGridSize_SelectedIndexChanged);
cboParentGrid.SelectedIndexChanged -= new System.EventHandler(cboParentGrid_SelectedIndexChanged);
cboUpExtPreDivider.SelectedIndexChanged -= new System.EventHandler(cboUpExtPreDivider_SelectedIndexChanged);
cboUpMainPreDivider.SelectedIndexChanged -= new System.EventHandler(cboUpMainPreDivider_SelectedIndexChanged);
cboDnMainPreDivider.SelectedIndexChanged -= new System.EventHandler(cboDnMainPreDivider_SelectedIndexChanged);
cboDnExtPreDivider.SelectedIndexChanged -= new System.EventHandler(cboDnExtPreDivider_SelectedIndexChanged);
cboBranchPreDivider.SelectedIndexChanged -= new System.EventHandler(cboBranchPreDivider_SelectedIndexChanged);
cboBranchExtPreDivider.SelectedIndexChanged -= new System.EventHandler(cboBranchExtPreDivider_SelectedIndexChanged);
cboPostDivider.SelectedIndexChanged -= new System.EventHandler(cboPostDivider_SelectedIndexChanged);
clbDatasets.ItemCheck -= new System.Windows.Forms.ItemCheckEventHandler(this.clbDatasets_ItemCheck);
clbDatasets.Validated -= new EventHandler(clbDatasets_Validated);
}
// If the user is finished assigning datasets to the grid, try to save and rebuild the grid
// and refresh the statistics. Note: the validated event is triggered when the focus leaves
// the checked listbox whether or not any of the checkboxes were clicked.
void clbDatasets_Validated(object sender, EventArgs e)
{
if (assignmentsChanged)
{
// Update the database with the current dataset assignments to the current grid.
// This function will try to perform a silent save if this is a new record
if (!UpdateDsetAssignmentsToGrid()) return;
assignmentsChanged = false;
curGrid.UpdateSectionInfoVars();
TryToRebuildGridAndStats();
}
}
// Update the GridCells table, rebuild the datagridview, get the dataTable, add data from
// the dataTable to the datagridview, update the stats.
// This just needs to be done if: a) we just opened the form and clicked either the grid tab
// or the stats tab --- b) we changes the dataset assignments.
// It does NOT need to be done when the partition info changes.
void TryToRebuildGridAndStats()
{
// set this flag in case we need to prevent certain actions while we're refreshing...
refreshInProgress = true;
toolStripStatusLabel1.Text = "Refreshing Grid...";
toolStripProgressBar1.Value = 0;
toolStripProgressBar1.Value = 10;
// Update the table that is used to eliminate duplicate values for a given grid cell
// by using the higher priority Dset.
// We don't really need to do this when the form loads, but it's pretty fast...
curGrid.UpdateGridCellsDbTable();
toolStripProgressBar1.Value = 20;
// Rebuild the DataGridView, adding the right number of rows and columns and filling in
// row and column headings.
SetupDataGridView();
toolStripProgressBar1.Value = 30;
// Fill in the stats
GetStats();
// Get the curMeasurements DataTable. This takes awhile.
// when finished, it fills in the DataGridView
backgroundWorker1.RunWorkerAsync();
}
// If the user is finished changing partition info,
// try to save and update the section info variables in the EGrid
// which will be used for the conditional formatting.
// The validating event is triggered whenever the user leaves a control, whether they
// change anything or not.
void handlePartitionTextboxChange()
{
if (this.ActiveControl.Parent != this.Sections)
{
if (!performSilentSave()) return;
curGrid.UpdateSectionInfoVars();
// We need to update the stats because the number of mins may change by the new partitioning.
GetStats();
}
}
private void InitializeDividerCombo(ComboBox cbo, ref GridDivider[] div)
{
div = EGrid.GetGridDividerArray();
cbo.DataSource = div;
cbo.DisplayMember = "Name";
cbo.ValueMember = "ID";
}
// Initialize the form control values
private void InitializeControls()
{
// Grid Sizes combo box
gridSizes = EGridSize.ListByName(!newRecord, true);
cboGridSize.DataSource = gridSizes;
cboGridSize.DisplayMember = "GridSizeName";
cboGridSize.ValueMember = "ID";
// Radial Locations combo box
ERadialLocationCollection radialLocations = ERadialLocation.ListByName(!newRecord, true);
cboRadialLocation.DataSource = radialLocations;
cboRadialLocation.DisplayMember = "RadialLocationName";
cboRadialLocation.ValueMember = "ID";
// Parent grid combo box
parentGrids = EGridComboItem.ListEligibleParentGridsForReportByInspectionName(
(Guid)curGrid.InspectedComponentID, curGrid.ID, true);
cboParentGrid.DataSource = parentGrids;
cboParentGrid.DisplayMember = "GridName";
cboParentGrid.ValueMember = "ID";
// Divider combo boxes
InitializeDividerCombo(cboUpExtPreDivider, ref gridDividersUpExt);
InitializeDividerCombo(cboUpMainPreDivider, ref gridDividersUpMain);
InitializeDividerCombo(cboDnMainPreDivider, ref gridDividersDnMain);
InitializeDividerCombo(cboDnExtPreDivider, ref gridDividersDnExt);
InitializeDividerCombo(cboBranchPreDivider, ref gridDividersBranch);
InitializeDividerCombo(cboBranchExtPreDivider, ref gridDividersBranchExt);
InitializeDividerCombo(cboPostDivider, ref gridDividersPost);
// Dset CheckedListbox
dsetAssignments = EDset.GetWithGridAssignmentsForInspection((Guid)curGrid.GridIspID);
int rows = dsetAssignments.Rows.Count;
if (rows == 0)
{
clbDatasets.Visible = false;
}
else
{
for (int dmRow = 0; dmRow < dsetAssignments.Rows.Count; dmRow++)
{
string dsetName = (string)dsetAssignments.Rows[dmRow]["DsetName"];
bool isAssigned = Convert.ToBoolean(dsetAssignments.Rows[dmRow]["IsAssigned"]);
clbDatasets.Items.Add(dsetName, isAssigned);
}
}
// set a flag to force building the grid and stats the first time the user selects them
gridAndStatsNotYetDisplayed = true;
DisEnableRowTextboxesForComponent();
SetControlValues();
this.Text = newRecord ? "New Grid" : "Edit Grid";
if (newRecord)
{
EOutage curOutage = new EOutage(Globals.CurrentOutageID);
ckGridColumnLayoutCCW.Checked = curOutage.OutageGridColDefaultCCW;
}
}
// Todo: what if the user has set the thicknesses for the component, come here and entered
// values then cleared thicknesses for the component?...
private void DisEnableRowTextboxesForComponent()
{
// these three need to be enabled whether or not we have a downstream section or branch
txtUpExtStart.Enabled = txtUpExtEnd.Enabled = curComponent.UpMainThicknessesDefined;
txtUsMainStart.Enabled = txtUsMainEnd.Enabled = curComponent.UpMainThicknessesDefined;
txtDsExtStart.Enabled = txtDsExtEnd.Enabled = curComponent.UpMainThicknessesDefined;
txtDsMainStart.Enabled = txtDsMainEnd.Enabled = curComponent.DnMainThicknessesDefined;
cboDnMainPreDivider.Enabled = curComponent.DnMainThicknessesDefined;
txtBranchStart.Enabled = txtBranchEnd.Enabled = curComponent.BranchThicknessesDefined;
txtBranchExtStart.Enabled = txtBranchExtEnd.Enabled = curComponent.BranchThicknessesDefined;
cboBranchExtPreDivider.Enabled = cboBranchPreDivider.Enabled = curComponent.BranchThicknessesDefined;
}
//---------------------------------------------------------
// Event Handlers
//---------------------------------------------------------
// If the user cancels out, just close.
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
DialogResult = savedInternally ? DialogResult.OK : DialogResult.Cancel;
}
// If the user clicks OK, first validate and set the error text
// for any controls with invalid values.
// If it validates, try to save.
private void btnOK_Click(object sender, EventArgs e)
{
SaveAndClose();
}
// The user changed the selected Grid Size
// If they set it to "<No Selection>", I think it's best to clear the axial and radial dists.
// If they set it to a real Grid Size, we should fill in the axial and radial textboxes.
private void cboGridSize_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboGridSize.SelectedIndex == 0)
{
txtAxialDistance.Text = null;
txtRadialDistance.Text = null;
}
EGridSize gridSize = FindGridSizeForId((Guid?)cboGridSize.SelectedValue);
if (gridSize != null)
{
txtAxialDistance.Text = GetFormattedGridSize(gridSize.GridSizeAxialDistance);
txtRadialDistance.Text = GetFormattedGridSize(gridSize.GridSizeRadialDistance);
}
}
// If the user changed the parent grid combo selection, refresh the items in the
// ParentColRef and ParentRowRef combos.
private void cboParentGrid_SelectedIndexChanged(object sender, EventArgs e)
{
ManageParentRefCombos();
}
void cboPostDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboBranchExtPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboBranchPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboDnExtPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboDnMainPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboUpMainPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
void cboUpExtPreDivider_SelectedIndexChanged(object sender, EventArgs e)
{
}
// Whenever a grid column is added to the DataGridView, make it not sortable
private void dgvGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
// Get the curMeasurements DataTable. This takes awhile.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
curMeasurements = EMeasurement.GetForGrid(curGrid.ID);
}
// We're finished re-generating the curMeasurements DataTable, so fill in the DataGridView
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
toolStripStatusLabel1.Text = "Refreshing Grid...";
toolStripProgressBar1.Value = 90;
AddMeasurementsToGrid();
toolStripProgressBar1.Value = 100;
toolStripStatusLabel1.Text = "Ready";
toolStripProgressBar1.ProgressBar.Value = 0;
EInspectedComponent curReport = new EInspectedComponent(curGrid.InspectedComponentID);
curReport.UpdateMinCount();
curReport.Save();
gridAndStatsNotYetDisplayed = false;
refreshInProgress = false;
}
private bool performSilentSave()
{
// we need to do a 'silent save'
if (AnyControlErrors())
{
MessageBox.Show("Make sure all errors are cleared first", "Factotum");
return false;
}
// Set the entity values to match the form values
UpdateRecord();
// Try to validate
if (!curGrid.Valid())
{
setAllErrors();
MessageBox.Show("Make sure all errors are cleared first", "Factotum");
return false;
}
// The Save function returns a the Guid? of the record created or updated.
Guid? tmpID = curGrid.Save();
if (tmpID == null) return false;
savedInternally = true;
return true;
}
// If the user just clicked the grid or stats tab, build the grid and stats if
// they haven't been displayed yet unless there is already a refresh operation in progress
// Note: a refresh operation can be caused by the user clicking off of the checked listbox.
private void TabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
string tabName = e.TabPage.Name;
if (gridAndStatsNotYetDisplayed && !refreshInProgress &&
(tabName == "ViewGrid" || tabName == "Stats"))
{
// Update the database with the current dataset assignments to the current grid.
// This function will try to perform a silent save if this is a new record
if (!performSilentSave())
{
e.Cancel = true;
return;
}
curGrid.UpdateSectionInfoVars();
TryToRebuildGridAndStats();
}
}
// If the user checked to add or remove a dataset from the grid, set a flag
// We'll use this flag in the Validated event handler to regenerate the grid data.
private void clbDatasets_ItemCheck(object sender, ItemCheckEventArgs e)
{
assignmentsChanged = true;
}
private void dgvGrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
decimal val;
// Ignore empty cells
if (e.Value == null)
{
return;
}
// We don't care about the row and column headings
if (e.RowIndex >= 0 && e.ColumnIndex > 0)
{
bool sel = (e.State & DataGridViewElementStates.Selected) > 0;
// Special formatting for obstructed cells
if (e.Value.ToString() == "obst.")
{
paintCell(ref e, Brushes.Purple, Brushes.AliceBlue);
return;
}
// Some kind of mystery value...
if (!Decimal.TryParse(e.Value.ToString(), out val))
{
paintCell(ref e, Brushes.Magenta, Brushes.Yellow);
return;
}
ThicknessRange range = curGrid.GetThicknessRange(e.RowIndex, val);
switch (range)
{
case ThicknessRange.BelowTscreen:
paintCell(ref e, Brushes.Crimson, Brushes.Pink);
break;
case ThicknessRange.TscreenToTnom:
paintCell(ref e, Brushes.Green, Brushes.Pink);
break;
case ThicknessRange.TnomTo120pct:
paintCell(ref e, Brushes.Black, Brushes.Pink);
break;
case ThicknessRange.Above120pctTnom:
paintCell(ref e, Brushes.Blue, Brushes.Pink);
break;
case ThicknessRange.Unknown:
paintCell(ref e, Brushes.Magenta, Brushes.Yellow);
break;
}
}
}
// Paint a grid cell with the specified foreground color.
// The color depends on whether it's selected or not.
private void paintCell(ref DataGridViewCellPaintingEventArgs e, Brush regColor, Brush selColor)
{
bool sel = (e.State & DataGridViewElementStates.Selected) > 0;
e.PaintBackground(e.CellBounds, sel);
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
sel ? selColor : regColor, e.CellBounds.X + 2,
e.CellBounds.Y + 2, StringFormat.GenericDefault);
e.Handled = true;
}
// Each time the text changes, check to make sure its length is ok
// If not, set the error.
private void txtAxialDistance_TextChanged(object sender, EventArgs e)
{
curGrid.GridAxialDistanceLengthOk(txtAxialDistance.Text);
errorProvider1.SetError(txtAxialDistance, curGrid.GridAxialDistanceErrMsg);
}
private void txtRadialDistance_TextChanged(object sender, EventArgs e)
{
curGrid.GridRadialDistanceLengthOk(txtRadialDistance.Text);
errorProvider1.SetError(txtRadialDistance, curGrid.GridRadialDistanceErrMsg);
}
private void txtAxialLocationOverride_TextChanged(object sender, EventArgs e)
{
curGrid.GridAxialLocOverrideLengthOk(txtAxialLocationOverride.Text);
errorProvider1.SetError(txtAxialLocationOverride, curGrid.GridAxialLocOverrideErrMsg);
}
private void txtUpExtStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridUpExtStartRowLengthOk(txtUpExtStart.Text);
errorProvider1.SetError(txtUpExtStart, curGrid.GridUpExtStartRowErrMsg);
}
private void txtUpExtEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridUpExtEndRowLengthOk(txtUpExtEnd.Text);
errorProvider1.SetError(txtUpExtEnd, curGrid.GridUpExtEndRowErrMsg);
}
private void txtUsMainStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridUpMainStartRowLengthOk(txtUsMainStart.Text);
errorProvider1.SetError(txtUsMainStart, curGrid.GridUpMainStartRowErrMsg);
}
private void txtUsMainEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridUpMainEndRowLengthOk(txtUsMainEnd.Text);
errorProvider1.SetError(txtUsMainEnd, curGrid.GridUpMainEndRowErrMsg);
}
private void txtDsMainStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridDnMainStartRowLengthOk(txtDsMainStart.Text);
errorProvider1.SetError(txtDsMainStart, curGrid.GridDnMainStartRowErrMsg);
}
private void txtDsMainEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridDnMainEndRowLengthOk(txtDsMainEnd.Text);
errorProvider1.SetError(txtDsMainEnd, curGrid.GridDnMainEndRowErrMsg);
}
private void txtDsExtStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridDnExtStartRowLengthOk(txtDsExtStart.Text);
errorProvider1.SetError(txtDsExtStart, curGrid.GridDnExtStartRowErrMsg);
}
private void txtDsExtEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridDnExtEndRowLengthOk(txtDsExtEnd.Text);
errorProvider1.SetError(txtDsExtEnd, curGrid.GridDnExtEndRowErrMsg);
}
private void txtBranchStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridBranchStartRowLengthOk(txtBranchStart.Text);
errorProvider1.SetError(txtBranchStart, curGrid.GridBranchStartRowErrMsg);
}
private void txtBranchEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridBranchEndRowLengthOk(txtBranchEnd.Text);
errorProvider1.SetError(txtBranchEnd, curGrid.GridBranchEndRowErrMsg);
}
private void txtBranchExtStart_TextChanged(object sender, EventArgs e)
{
curGrid.GridBranchExtStartRowLengthOk(txtBranchExtStart.Text);
errorProvider1.SetError(txtBranchExtStart, curGrid.GridBranchExtStartRowErrMsg);
}
private void txtBranchExtEnd_TextChanged(object sender, EventArgs e)
{
curGrid.GridBranchExtEndRowLengthOk(txtBranchExtEnd.Text);
errorProvider1.SetError(txtBranchExtEnd, curGrid.GridBranchExtEndRowErrMsg);
}
// The validating event gets called when the user leaves the control.
// We handle it to perform all validation for the value.
private void txtAxialDistance_Validating(object sender, CancelEventArgs e)
{
curGrid.GridAxialDistanceValid(txtAxialDistance.Text);
errorProvider1.SetError(txtAxialDistance, curGrid.GridAxialDistanceErrMsg);
SetGridSizeComboForTextChange();
}
private void txtRadialDistance_Validating(object sender, CancelEventArgs e)
{
curGrid.GridRadialDistanceValid(txtRadialDistance.Text);
errorProvider1.SetError(txtRadialDistance, curGrid.GridRadialDistanceErrMsg);
SetGridSizeComboForTextChange();
}
private void txtAxialLocationOverride_Validating(object sender, CancelEventArgs e)
{
curGrid.GridAxialLocOverrideValid(txtAxialLocationOverride.Text);
errorProvider1.SetError(txtAxialLocationOverride, curGrid.GridAxialLocOverrideErrMsg);
}
private void txtUpExtStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridUpExtStartRowValid(txtUpExtStart.Text);
errorProvider1.SetError(txtUpExtStart, curGrid.GridUpExtStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtUpExtEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridUpExtEndRowValid(txtUpExtEnd.Text);
errorProvider1.SetError(txtUpExtEnd, curGrid.GridUpExtEndRowErrMsg);
handlePartitionTextboxChange();
}
private void txtUsMainStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridUpMainStartRowValid(txtUsMainStart.Text);
errorProvider1.SetError(txtUsMainStart, curGrid.GridUpMainStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtUsMainEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridUpMainEndRowValid(txtUsMainEnd.Text);
errorProvider1.SetError(txtUsMainEnd, curGrid.GridUpMainEndRowErrMsg);
handlePartitionTextboxChange();
}
private void txtDsMainStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridDnMainStartRowValid(txtDsMainStart.Text);
errorProvider1.SetError(txtDsMainStart, curGrid.GridDnMainStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtDsMainEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridDnMainEndRowValid(txtDsMainEnd.Text);
errorProvider1.SetError(txtDsMainEnd, curGrid.GridDnMainEndRowErrMsg);
handlePartitionTextboxChange();
}
private void txtDsExtStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridDnExtStartRowValid(txtDsExtStart.Text);
errorProvider1.SetError(txtDsExtStart, curGrid.GridDnExtStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtDsExtEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridDnExtEndRowValid(txtDsExtEnd.Text);
errorProvider1.SetError(txtDsExtEnd, curGrid.GridDnExtEndRowErrMsg);
handlePartitionTextboxChange();
}
private void txtBranchStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridBranchStartRowValid(txtBranchStart.Text);
errorProvider1.SetError(txtBranchStart, curGrid.GridBranchStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtBranchEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridBranchEndRowValid(txtBranchEnd.Text);
errorProvider1.SetError(txtBranchEnd, curGrid.GridBranchEndRowErrMsg);
handlePartitionTextboxChange();
}
private void txtBranchExtStart_Validating(object sender, CancelEventArgs e)
{
curGrid.GridBranchExtStartRowValid(txtBranchExtStart.Text);
errorProvider1.SetError(txtBranchExtStart, curGrid.GridBranchExtStartRowErrMsg);
handlePartitionTextboxChange();
}
private void txtBranchExtEnd_Validating(object sender, CancelEventArgs e)
{
curGrid.GridBranchExtEndRowValid(txtBranchExtEnd.Text);
errorProvider1.SetError(txtBranchExtEnd, curGrid.GridBranchExtEndRowErrMsg);
handlePartitionTextboxChange();
}
//---------------------------------------------------------
// Helper functions
//---------------------------------------------------------
// No prompting is performed. The user should understand the meanings of OK and Cancel.
private void SaveAndClose()
{
if (AnyControlErrors()) return;
// Set the entity values to match the form values
UpdateRecord();
// Try to validate
if (!curGrid.Valid())
{
setAllErrors();
return;
}
// The Save function returns a the Guid? of the record created or updated.
Guid? tmpID = curGrid.Save();
if (tmpID != null)
{
// We need to do these updates after saving because they require a valid Grid ID
// Update Inspectors table from checkboxes
for (int dmRow = 0; dmRow < dsetAssignments.Rows.Count; dmRow++)
{
dsetAssignments.Rows[dmRow]["IsAssigned"] = 0;
}
foreach (int idx in clbDatasets.CheckedIndices)
{
dsetAssignments.Rows[idx]["IsAssigned"] = 1;
}
EDset.UpdateAssignmentsToGrid((Guid)curGrid.ID, dsetAssignments);
Close();
DialogResult = DialogResult.OK;
}
}
// Set the form controls to the grid object values.
private void SetControlValues()
{
if (curGrid.GridIspID != null)
{
EInspection inspection = new EInspection((Guid?)curGrid.GridIspID);
EInspectedComponent inspectedComponent =
new EInspectedComponent(inspection.InspectionIscID);
lblSiteName.Text = "Grid for Inspection '" +
inspection.InspectionName + "' of Report '" + inspectedComponent.InspComponentName + "'";
}
else lblSiteName.Text = "Grid for Unknown Inspection";
DowUtils.Util.CenterControlHorizInForm(lblSiteName, this);
txtAxialDistance.Text = GetFormattedGridSize(curGrid.GridAxialDistance);
txtRadialDistance.Text = GetFormattedGridSize(curGrid.GridRadialDistance);
txtAxialLocationOverride.Text = curGrid.GridAxialLocOverride;
// User wants rows to start at 1
txtUpExtStart.Text = GetFormattedRow(curGrid.GridUpExtStartRow);
txtUpExtEnd.Text = GetFormattedRow(curGrid.GridUpExtEndRow);
txtUsMainStart.Text = GetFormattedRow(curGrid.GridUpMainStartRow);
txtUsMainEnd.Text = GetFormattedRow(curGrid.GridUpMainEndRow);
txtDsMainStart.Text = GetFormattedRow(curGrid.GridDnMainStartRow);
txtDsMainEnd.Text = GetFormattedRow(curGrid.GridDnMainEndRow);
txtDsExtStart.Text = GetFormattedRow(curGrid.GridDnExtStartRow);
txtDsExtEnd.Text = GetFormattedRow(curGrid.GridDnExtEndRow);
txtBranchStart.Text = GetFormattedRow(curGrid.GridBranchStartRow);
txtBranchEnd.Text = GetFormattedRow(curGrid.GridBranchEndRow);
txtBranchExtStart.Text = GetFormattedRow(curGrid.GridBranchExtStartRow);
txtBranchExtEnd.Text = GetFormattedRow(curGrid.GridBranchExtEndRow);
if (curGrid.GridGszID == null) cboGridSize.SelectedIndex = 0;
else cboGridSize.SelectedValue = curGrid.GridGszID;
if (curGrid.GridRdlID == null) cboRadialLocation.SelectedIndex = 0;
else cboRadialLocation.SelectedValue = curGrid.GridRdlID;
if (curGrid.GridParentID == null) cboParentGrid.SelectedIndex = 0;
else cboParentGrid.SelectedValue = curGrid.GridParentID;
// Set by default to N/A for new records
cboUpExtPreDivider.SelectedValue = curGrid.GridUpExtPreDivider;
cboUpMainPreDivider.SelectedValue = curGrid.GridUpMainPreDivider;
cboDnMainPreDivider.SelectedValue = curGrid.GridDnMainPreDivider;
cboDnExtPreDivider.SelectedValue = curGrid.GridDnExtPreDivider;
cboBranchPreDivider.SelectedValue = curGrid.GridBranchPreDivider;
cboBranchExtPreDivider.SelectedValue = curGrid.GridBranchExtPreDivider;
cboPostDivider.SelectedValue = curGrid.GridPostDivider;
ManageParentRefCombos();
if (curGrid.GridParentStartCol != null)
cboParentColRef.SelectedIndex = (int)curGrid.GridParentStartCol;
if (curGrid.GridParentStartRow != null)
cboParentRowRef.SelectedIndex = (int)curGrid.GridParentStartRow;
ckFullScan.Checked = curGrid.GridIsFullScan;
ckGridColumnLayoutCCW.Checked = curGrid.GridIsColumnCCW;
ckHideColumnLayoutGraphic.Checked = curGrid.GridHideColumnLayoutGraphic;
}
// Set the error provider text for all controls that use it.
private void setAllErrors()
{
errorProvider1.SetError(txtAxialDistance, curGrid.GridAxialDistanceErrMsg);
errorProvider1.SetError(txtRadialDistance, curGrid.GridRadialDistanceErrMsg);
errorProvider1.SetError(txtAxialLocationOverride, curGrid.GridAxialLocOverrideErrMsg);
errorProvider1.SetError(txtUpExtStart, curGrid.GridUpExtStartRowErrMsg);
errorProvider1.SetError(txtUpExtEnd, curGrid.GridUpExtEndRowErrMsg);
errorProvider1.SetError(txtUsMainStart, curGrid.GridUpMainStartRowErrMsg);
errorProvider1.SetError(txtUsMainEnd, curGrid.GridUpMainEndRowErrMsg);
errorProvider1.SetError(txtDsMainStart, curGrid.GridDnMainStartRowErrMsg);
errorProvider1.SetError(txtDsMainEnd, curGrid.GridDnMainEndRowErrMsg);
errorProvider1.SetError(txtDsExtStart, curGrid.GridDnExtStartRowErrMsg);
errorProvider1.SetError(txtDsExtEnd, curGrid.GridDnExtEndRowErrMsg);
errorProvider1.SetError(txtBranchStart, curGrid.GridBranchStartRowErrMsg);
errorProvider1.SetError(txtBranchEnd, curGrid.GridBranchEndRowErrMsg);
errorProvider1.SetError(txtBranchExtStart, curGrid.GridBranchExtStartRowErrMsg);
errorProvider1.SetError(txtBranchExtEnd, curGrid.GridBranchExtEndRowErrMsg);
}
// Check all controls to see if any have errors.
private bool AnyControlErrors()
{
return (errorProvider1.GetError(txtAxialDistance).Length > 0 ||
errorProvider1.GetError(txtRadialDistance).Length > 0 ||
errorProvider1.GetError(txtAxialLocationOverride).Length > 0 ||
errorProvider1.GetError(txtUpExtStart).Length > 0 ||
errorProvider1.GetError(txtUpExtEnd).Length > 0 ||
errorProvider1.GetError(txtUsMainStart).Length > 0 ||
errorProvider1.GetError(txtUsMainEnd).Length > 0 ||
errorProvider1.GetError(txtDsMainStart).Length > 0 ||
errorProvider1.GetError(txtDsMainEnd).Length > 0 ||
errorProvider1.GetError(txtDsExtStart).Length > 0 ||
errorProvider1.GetError(txtDsExtEnd).Length > 0 ||
errorProvider1.GetError(txtBranchStart).Length > 0 ||
errorProvider1.GetError(txtBranchEnd).Length > 0 ||
errorProvider1.GetError(txtBranchExtStart).Length > 0 ||
errorProvider1.GetError(txtBranchExtEnd).Length > 0
);
}
// Update the object values from the form control values.
private void UpdateRecord()
{
curGrid.GridAxialDistance = Util.GetNullableDecimalForString(txtAxialDistance.Text);
curGrid.GridRadialDistance = Util.GetNullableDecimalForString(txtRadialDistance.Text);
curGrid.GridAxialLocOverride = txtAxialLocationOverride.Text;
curGrid.GridUpExtStartRow = GetRowNumberForString(txtUpExtStart.Text);
curGrid.GridUpExtEndRow = GetRowNumberForString(txtUpExtEnd.Text);
curGrid.GridUpMainStartRow = GetRowNumberForString(txtUsMainStart.Text);
curGrid.GridUpMainEndRow = GetRowNumberForString(txtUsMainEnd.Text);
curGrid.GridDnMainStartRow = GetRowNumberForString(txtDsMainStart.Text);
curGrid.GridDnMainEndRow = GetRowNumberForString(txtDsMainEnd.Text);
curGrid.GridDnExtStartRow = GetRowNumberForString(txtDsExtStart.Text);
curGrid.GridDnExtEndRow = GetRowNumberForString(txtDsExtEnd.Text);
curGrid.GridBranchStartRow = GetRowNumberForString(txtBranchStart.Text);
curGrid.GridBranchEndRow = GetRowNumberForString(txtBranchEnd.Text);
curGrid.GridBranchExtStartRow = GetRowNumberForString(txtBranchExtStart.Text);
curGrid.GridBranchExtEndRow = GetRowNumberForString(txtBranchExtEnd.Text);
curGrid.GridGszID = (Guid?)cboGridSize.SelectedValue;
curGrid.GridRdlID = (Guid?)cboRadialLocation.SelectedValue;
curGrid.GridParentID = (Guid?)cboParentGrid.SelectedValue;
if (cboParentColRef.Items.Count > 0)
curGrid.GridParentStartCol = (short)cboParentColRef.SelectedIndex;
if (cboParentRowRef.Items.Count > 0)
curGrid.GridParentStartRow = (short)cboParentRowRef.SelectedIndex;
curGrid.GridUpExtPreDivider = (byte)cboUpExtPreDivider.SelectedValue;
curGrid.GridUpMainPreDivider = (byte)cboUpMainPreDivider.SelectedValue;
curGrid.GridDnMainPreDivider = (byte)cboDnMainPreDivider.SelectedValue;
curGrid.GridDnExtPreDivider = (byte)cboDnExtPreDivider.SelectedValue;
curGrid.GridBranchPreDivider = (byte)cboBranchPreDivider.SelectedValue;
curGrid.GridBranchExtPreDivider = (byte)cboBranchExtPreDivider.SelectedValue;
curGrid.GridPostDivider = (byte)cboPostDivider.SelectedValue;
curGrid.GridIsFullScan = ckFullScan.Checked;
curGrid.GridIsColumnCCW = ckGridColumnLayoutCCW.Checked;
curGrid.GridHideColumnLayoutGraphic = ckHideColumnLayoutGraphic.Checked;
}
// Update the database with the current dataset assignments to the current grid.
private bool UpdateDsetAssignmentsToGrid()
{
if (curGrid.ID == null)
{
if (!performSilentSave()) return false;
}
// We need to do these updates after saving because they require a valid Grid ID
// Update dataset assignments table from checkboxes
for (int dmRow = 0; dmRow < dsetAssignments.Rows.Count; dmRow++)
{
dsetAssignments.Rows[dmRow]["IsAssigned"] = 0;
}
foreach (int idx in clbDatasets.CheckedIndices)
{
dsetAssignments.Rows[idx]["IsAssigned"] = 1;
}
// Update the database from the assignments table
EDset.UpdateAssignmentsToGrid((Guid)curGrid.ID, dsetAssignments);
return true;
}
// Set up the DataGridView, adding the right number of rows and columns and filling in
// row and column headings.
private void SetupDataGridView()
{
int nRows;
int nCols;
short startRow;
short endRow;
short startCol;
short endCol;
dgvGrid.Columns.Clear();
// If no grid data, just clear the grid and return
if (curGrid.GridStartRow == null || curGrid.GridStartCol == null ||
curGrid.GridEndRow == null || curGrid.GridEndCol == null) return;
dgvGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
startRow = (short)curGrid.GridStartRow;
endRow = (short)curGrid.GridEndRow;
startCol = (short)curGrid.GridStartCol;
endCol = (short)curGrid.GridEndCol;
nRows = endRow - startRow + 1;
curGridRows = nRows;
dgvGrid.RowCount = nRows;
nCols = endCol - startCol + 1;
dgvGrid.ColumnCount = nCols + 1; // add an extra because column 1 is row headings
dgvGrid.Columns[0].HeaderText = "Row #";
for (short c = 0; c < nCols; c++)
dgvGrid.Columns[c + 1].HeaderText = EMeasurement.GetColLabel((short)(c+startCol));
for (short r = 0; r < nRows; r++)
dgvGrid.Rows[r].Cells[0].Value = r+startRow + 1;
}
// Add all measurements from the curMeasurements DataTable to the DataGridView
private void AddMeasurementsToGrid()
{
string sVal;
int row, col;
short startRow;
short startCol;
// If no grid data, just return
if (curGrid.GridStartRow == null || curGrid.GridStartCol == null ||
curGrid.GridEndRow == null || curGrid.GridEndCol == null) return;
startRow = (short)curGrid.GridStartRow;
startCol = (short)curGrid.GridStartCol;
decimal? thick;
bool obstr, error;
DataRow dr;
for (int r = 0; r < curMeasurements.Rows.Count; r++)
{
dr = curMeasurements.Rows[r];
row = Convert.ToInt32(dr[1]);
col = Convert.ToInt32(dr[2]);
if (dr[3] == DBNull.Value) thick = null;
else thick = Convert.ToDecimal(dr[3]);
obstr = (bool)dr[4];
error = (bool)dr[5];
if (thick == null)
{
if (obstr) sVal = "obst.";
else sVal = "empty";
}
else sVal = GetFormattedThickness(thick);
dgvGrid.Rows[row-startRow].Cells[col-startCol + 1].Value = sVal;
}
}
// Fill in the items in the ParentColRef and ParentRowRef combo boxes.
// These items depend on the currently selected parent grid if any.
private void ManageParentRefCombos()
{
if (cboParentGrid.SelectedIndex == 0)
{
cboParentColRef.Items.Clear();
cboParentRowRef.Items.Clear();
}
else
{
cboParentColRef.Items.Clear();
cboParentRowRef.Items.Clear();
EGrid grid = new EGrid((Guid?)cboParentGrid.SelectedValue);
int? endRow = grid.GridEndRow;
int? endCol = grid.GridEndCol;
if (endRow != null)
{
for (int i = 0; i <= endRow; i++)
cboParentRowRef.Items.Add((i + 1));
cboParentRowRef.SelectedIndex = 0;
}
if (endCol != null)
{
for (int i = 0; i <= endCol; i++)
cboParentColRef.Items.Add(EMeasurement.GetColLabel((short)i));
cboParentColRef.SelectedIndex = 0;
}
}
}
// Gets a GridSize from a collection with the specified id if it's there.
private EGridSize FindGridSizeForId(Guid? id)
{
if (id == null) return null;
foreach (EGridSize gridSize in gridSizes)
if (gridSize.ID == id)
return gridSize;
return null;
}
// Searches the gridsizes collection for a grid size that matches the specified axial
// and radial distances.
private Guid? GetGridSizeIdForAxialAndRadial(string axialDist, string radialDist)
{
decimal ad, rd;
if (decimal.TryParse(axialDist, out ad) && decimal.TryParse(radialDist, out rd))
{
foreach (EGridSize gridSize in gridSizes)
{
if (ad == gridSize.GridSizeAxialDistance && rd == gridSize.GridSizeRadialDistance)
{
return gridSize.ID;
}
}
}
return null;
}
// Test if a grid size object's axial and radial distances match the specified values.
private bool GridSizeMatchesAxialAndRadial(EGridSize gridSize, string axialDist, string radialDist)
{
if (gridSize == null) return false;
decimal ad, rd;
if (decimal.TryParse(axialDist, out ad) && decimal.TryParse(radialDist, out rd))
if (ad == gridSize.GridSizeAxialDistance && rd == gridSize.GridSizeRadialDistance)
return true;
return false;
}
// If there are errors for either textbox, set the combo to no selection.
// Otherwise, Check the current combo item to see if its distances match the textboxes.
// If it does, we're done.
// If not, check the grid size collection to see if a grid size that matches the
// current axial and radial distances exists. If it does, set the combo to that item.
// Otherwise, set it to no selection.
private void SetGridSizeComboForTextChange()
{
if (errorProvider1.GetError(txtAxialDistance).Length > 0 ||
errorProvider1.GetError(txtRadialDistance).Length > 0)
cboGridSize.SelectedIndex = 0;
else
{
EGridSize gridSize = FindGridSizeForId((Guid?)cboGridSize.SelectedValue);
if (!GridSizeMatchesAxialAndRadial(gridSize,
txtAxialDistance.Text, txtRadialDistance.Text))
{
Guid? gridSizeID = GetGridSizeIdForAxialAndRadial(txtAxialDistance.Text, txtRadialDistance.Text);
cboGridSize.SelectedIndexChanged -= new System.EventHandler(cboGridSize_SelectedIndexChanged);
if (gridSizeID == null) cboGridSize.SelectedIndex = 0;
else cboGridSize.SelectedValue = gridSizeID;
cboGridSize.SelectedIndexChanged += new System.EventHandler(cboGridSize_SelectedIndexChanged);
}
}
}
private void GetStats()
{
int? startRow = curGrid.GridStartRow;
int? endRow = curGrid.GridEndRow;
int? startCol = curGrid.GridStartCol;
int? endCol = curGrid.GridEndCol;
if (startRow != null && startCol != null && endRow != null && endCol != null)
{
lblColsIncluded.Text = EMeasurement.GetColLabel((short)startCol) + " to " + EMeasurement.GetColLabel((short)endCol);
lblRowsIncluded.Text = (startRow + 1) + " to " + (endRow + 1);
lblObstructions.Text = curGrid.GridObstructions.ToString();
lblEmpties.Text = curGrid.GridEmpties.ToString();
}
else
{
lblColsIncluded.Text = "N/A";
lblRowsIncluded.Text = "N/A";
lblObstructions.Text = "N/A";
lblEmpties.Text = "N/A";
}
if (curGrid.GridMeasurements != null)
lblTotalReadings.Text = curGrid.GridMeasurements.ToString();
else
lblTotalReadings.Text = "0";
if ((curGrid.GridTextFilePoints != null && curGrid.GridTextFilePoints != 0))
{
lblMaxInfo.Text = curGrid.GridMaxWall.ToString();
lblMinInfo.Text = curGrid.GridMinWall.ToString();
lblMean.Text = string.Format("{0:0.000}", curGrid.GridMeanWall);
lblStdDev.Text = string.Format("{0:0.000}", curGrid.GridStdevWall);
lblBelowTscr.Text = string.Format("{0:0}", curGrid.GridBelowTscr);
}
else
{
lblMaxInfo.Text = "N/A";
lblMinInfo.Text = "N/A";
lblMean.Text = "N/A";
lblStdDev.Text = "N/A";
lblBelowTscr.Text = "N/A";
}
}
// Given a string value which may contain a 1-based row value,
// try to return a 0-based short row value
public static short? GetRowNumberForString(string text)
{
return Util.IsNullOrEmpty(text) ? (short?)null : (short)((short.Parse(text) - 1));
}
// Format a grid size value for display
private string GetFormattedGridSize(decimal? number)
{
return number == null ? null :
string.Format("{0:0.000}", number);
}
// Format a thickness value for display
private string GetFormattedThickness(decimal? number)
{
return number == null ? null :
string.Format("{0:0.000}", number);
}
// Format a generic short for display
private string GetFormattedShort(short? number)
{
return number == null ? null :
string.Format("{0}", number);
}
// Format a row for display
private string GetFormattedRow(short? number)
{
return number == null ? null :
string.Format("{0}", number + 1);
}
private void dgvGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
int rowIdx = e.RowIndex;
int colIdx = e.ColumnIndex - 1;
Guid? measurementID = GetMeasurementIdForGridRowAndColumn(rowIdx, colIdx);
EMeasurement measurement = new EMeasurement(measurementID);
}
private Guid? GetMeasurementIdForGridRowAndColumn(int row, int column)
{
foreach (DataRow dr in curMeasurements.Rows)
{
if (Convert.ToInt32(dr[1]) == row && Convert.ToInt32(dr[2]) == column)
{
return (Guid?)dr[0];
}
}
return null;
}
private void btnExportToText_Click(object sender, EventArgs e)
{
if (clbDatasets.CheckedItems.Count == 0)
{
MessageBox.Show("Nothing to Export -- The current grid does not contain any datasets","Factotum");
return;
}
EInspection curInspection = new EInspection(curGrid.GridIspID);
EInspectedComponent curReport = new EInspectedComponent(curInspection.InspectionIscID);
saveFileDialog1.Filter = "Text files *.txt|*.txt";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.FileName = Globals.MeterDataFolder + "\\" +
curReport.InspComponentName + "_" + curInspection.InspectionName + ".txt";
saveFileDialog1.Title = "Export Grid to Panametrics Text File";
DialogResult rslt = saveFileDialog1.ShowDialog();
if (rslt != DialogResult.OK) return;
PanametricsExporter exporter =
new PanametricsExporter(saveFileDialog1.FileName, (Guid)curGrid.ID);
exporter.ExportGrid();
MessageBox.Show("Done!");
}
private void btnExportToExcel_Click(object sender, EventArgs e)
{
if (!performSilentSave()) return;
if (clbDatasets.CheckedItems.Count == 0)
{
MessageBox.Show("Nothing to Export -- The current grid does not contain any datasets", "Factotum");
return;
}
if (curGrid.GridAxialDistance == null || curGrid.GridRadialDistance == null)
{
MessageBox.Show("A Grid Size must be selected before the grid can be exported", "Factotum");
return;
}
EGridCollection childGrids = curGrid.GetAllChildGrids();
if (childGrids.Count > 0)
{
if (MessageBox.Show("Current grid contains child grids. Create a merged grid?",
"Factotum", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
createMergedGrid = true;
}
EInspection curInspection = new EInspection(curGrid.GridIspID);
EInspectedComponent curReport = new EInspectedComponent(curInspection.InspectionIscID);
saveFileDialog1.Filter = "Excel files *.xls|*.xls";
saveFileDialog1.DefaultExt = "xls";
saveFileDialog1.FileName = Globals.MeterDataFolder + "\\" +
curReport.InspComponentName + "_" + curInspection.InspectionName + ".xls";
saveFileDialog1.Title = "Export Grid to Excel file";
DialogResult rslt = saveFileDialog1.ShowDialog();
if (rslt != DialogResult.OK) return;
backgroundWorker2.RunWorkerAsync();
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
MergedGridExporter exporter = new MergedGridExporter((Guid)curGrid.ID, saveFileDialog1.FileName, backgroundWorker2, createMergedGrid);
exporter.CreateWorkbook();
exporter = null;
}
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done!");
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using Region = Apache.Geode.Client.IRegion<Object, Object>;
[TestFixture]
[Category("group4")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientHARegionTests : ThinClientRegionSteps
{
#region Private members
private UnitProcess m_client1, m_client2, m_client3;
private string[] m_regexes = { "Key.*1", "Key.*2", "Key.*3", "Key.*4" };
private static string QueryRegionName = "Portfolios";
#endregion
protected override string ExtraPropertiesFile
{
get
{
return "geode.properties.mixed";
}
}
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3 };
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
m_client3.Call(CacheHelper.Close);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Various steps for HA tests
public void InitClient_Pool(string locators, int redundancyLevel)
{
CacheHelper.CreatePool<object, object>("__TESTPOOL1_", locators, null, redundancyLevel, true);
}
public void InitClientForEventId_Pool(string locators, bool notification,
int redundancyLevel, TimeSpan ackInterval, TimeSpan dupCheckLife)
{
CacheHelper.Init();
CacheHelper.CreatePool<object, object>("__TESTPOOL1_", locators, null,
redundancyLevel, notification, ackInterval, dupCheckLife);
}
public void InitClientXml(string cacheXml)
{
CacheHelper.InitConfig(cacheXml);
}
public void InitClientXml(string cacheXml, int serverport1, int serverport2)
{
CacheHelper.HOST_PORT_1 = serverport1;
CacheHelper.HOST_PORT_2 = serverport2;
CacheHelper.InitConfig(cacheXml);
}
public void CreateEntriesForEventId(int sleep)
{
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region2 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
for (int value = 1; value <= 100; value++)
{
region1[m_keys[0]] = value;
Thread.Sleep(sleep);
region1[m_keys[1]] = value;
Thread.Sleep(sleep);
region1[m_keys[2]] = value;
Thread.Sleep(sleep);
region1[m_keys[3]] = value;
Thread.Sleep(sleep);
region2[m_keys[0]] = value;
Thread.Sleep(sleep);
region2[m_keys[1]] = value;
Thread.Sleep(sleep);
region2[m_keys[2]] = value;
Thread.Sleep(sleep);
region2[m_keys[3]] = value;
Thread.Sleep(sleep);
}
}
public void CheckClientForEventId()
{
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region2 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
DupListener<object, object> checker1 = region1.Attributes.CacheListener as DupListener<object, object>;
DupListener<object, object> checker2 = region2.Attributes.CacheListener as DupListener<object, object>;
Util.Log("Validating checker1 cachelistener");
checker1.validate();
Util.Log("Validating checker2 cachelistener");
checker2.validate();
}
public void InitDupListeners()
{
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region2 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region1.AttributesMutator.SetCacheListener(DupListener<object, object>.Create());
region2.AttributesMutator.SetCacheListener(DupListener<object, object>.Create());
Thread.Sleep(5000);
region1.GetSubscriptionService().RegisterAllKeys();
region2.GetSubscriptionService().RegisterAllKeys();
}
public void CreateHATCRegions(string[] regionNames, bool useList,
string locators, bool clientNotification, bool create)
{
if (create)
{
CacheHelper.CreateTCRegion_Pool<object, object>(regionNames[0], true, true,
null, locators, "__TESTPOOL1_", clientNotification);
CacheHelper.CreateTCRegion_Pool<object, object>(regionNames[1], false, true,
null, locators, "__TESTPOOL1_", clientNotification);
}
m_regionNames = regionNames;
}
/*
public void CreateCPPRegion(string regionName)
{
CacheHelper.CreateTCRegion(regionName, true, true,
null, "none", false);
}
* */
public void CreateMixedEntry(string regionName, string key, string val)
{
CreateEntry(regionName, key, val);
}
public void DoNetsearchMixed(string regionName, string key, string val, bool checkNoKey)
{
DoNetsearch(regionName, key, val, checkNoKey);
}
public void UpdateEntryMixed(string regionName, string key, string val, bool checkVal)
{
UpdateEntry(regionName, key, val, checkVal);
}
public void LocalDestroyEntry(string regionName, string key)
{
Util.Log("Locally Destroying entry -- key: {0} in region {1}",
key, regionName);
// Destroy entry, verify entry is destroyed
Region region = CacheHelper.GetVerifyRegion<object, object>(regionName);
Assert.IsTrue(region.ContainsKey(key), "Key should have been found in region.");
region.GetLocalView().Remove(key);
VerifyDestroyed(regionName, key);
}
public void Create2Vals(bool even)
{
if (even)
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
else
{
CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
}
public void CreateVals()
{
Create2Vals(true);
Create2Vals(false);
}
public void VerifyValCreations(bool even)
{
if (even)
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
}
else
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
}
}
public void VerifyTallies()
{
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region2 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
TallyLoader<object, object> loader1 = (TallyLoader<object, object>)region1.Attributes.CacheLoader;
TallyListener<object, object> listener1 = (TallyListener<object, object>) region1.Attributes.CacheListener;
TallyWriter<object, object> writer1 = (TallyWriter<object, object>)region1.Attributes.CacheWriter;
TallyResolver<object, object> resolver1 = (TallyResolver<object, object>) region1.Attributes.PartitionResolver;
TallyLoader<object, object> loader2 = (TallyLoader<object, object>)region2.Attributes.CacheLoader;
TallyListener<object, object> listener2 = (TallyListener<object, object>)region2.Attributes.CacheListener;
TallyWriter<object, object> writer2 = (TallyWriter<object, object>)region2.Attributes.CacheWriter;
TallyResolver<object, object> resolver2 = (TallyResolver<object, object>)region2.Attributes.PartitionResolver;
loader1.ShowTallies();
writer1.ShowTallies();
listener1.ShowTallies();
resolver1.ShowTallies();
loader2.ShowTallies();
writer2.ShowTallies();
listener2.ShowTallies();
resolver2.ShowTallies();
// We don't assert for partition resolver because client metadata service may
// not have fetched PR single hop info to trigger the resolver.
Assert.AreEqual(1, loader1.ExpectLoads(1));
//Assert.AreEqual(1, resolver1.ExpectLoads(1));
Assert.AreEqual(1, writer1.ExpectCreates(1));
Assert.AreEqual(0, writer1.ExpectUpdates(0));
Assert.AreEqual(2, listener1.ExpectCreates(2));
Assert.AreEqual(1, listener1.ExpectUpdates(1));
Assert.AreEqual(1, loader2.ExpectLoads(1));
//Assert.AreEqual(1, resolver2.ExpectLoads(1));
Assert.AreEqual(1, writer2.ExpectCreates(1));
Assert.AreEqual(0, writer2.ExpectUpdates(0));
Assert.AreEqual(2, listener2.ExpectCreates(2));
Assert.AreEqual(1, listener2.ExpectUpdates(1));
}
public void UpdateVals()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[0], m_keys[1], m_vals[1], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_vals[3], true);
}
public void Update2NVals(bool even, bool checkVal)
{
if (even)
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], checkVal);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], checkVal);
}
else
{
UpdateEntry(m_regionNames[0], m_keys[1], m_nvals[1], checkVal);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], checkVal);
}
}
public void UpdateNVals(bool checkVal)
{
Update2NVals(true, checkVal);
Update2NVals(false, checkVal);
}
public void Verify2Vals(bool even)
{
if (even)
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
else
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
}
public void VerifyVals()
{
Verify2Vals(true);
Verify2Vals(false);
}
public void Verify2NVals(bool even)
{
if (even)
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
else
{
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_nvals[3]);
}
}
public void DoNetsearch2Vals(bool even)
{
if (even)
{
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[1], m_keys[2], m_vals[2], true);
}
else
{
DoNetsearch(m_regionNames[0], m_keys[1], m_vals[1], true);
DoNetsearch(m_regionNames[1], m_keys[3], m_vals[3], true);
}
}
public void DoCacheLoad2Vals(bool even)
{
if (even)
{
DoCacheLoad(m_regionNames[0], m_keys[0], m_vals[0], true);
DoCacheLoad(m_regionNames[1], m_keys[2], m_vals[2], true);
}
else
{
DoCacheLoad(m_regionNames[0], m_keys[1], m_vals[1], true);
DoCacheLoad(m_regionNames[1], m_keys[3], m_vals[3], true);
}
}
public void DoNetsearchVals()
{
DoNetsearch2Vals(true);
DoNetsearch2Vals(false);
}
public void VerifyNVals()
{
Verify2NVals(true);
Verify2NVals(false);
}
public void VerifyNValsVals()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], true);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2], true);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], true);
}
public void VerifyNValVals()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], true);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], true);
}
public void VerifyValsNVals()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1], true);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
}
public void VerifyMixedNVals()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], true);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
}
public void RegisterKeysException(string key0, string key1)
{
Region region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
Region region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
if (key0 != null)
{
region0.GetSubscriptionService().RegisterKeys(new string[] {key0 });
}
if (key1 != null)
{
region1.GetSubscriptionService().RegisterKeys(new string[] {key1 });
}
}
public void RegisterRegexesException(string regex0, string regex1)
{
if (regex0 != null)
{
Region region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region0.GetSubscriptionService().RegisterRegex(regex0);
}
if (regex1 != null)
{
Region region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region1.GetSubscriptionService().RegisterRegex(regex1);
}
}
public void DistOpsCommonSteps(bool clientNotification)
{
DistOpsCommonSteps(clientNotification, true);
}
public void DistOpsCommonSteps(bool clientNotification, bool createRegions)
{
m_client1.Call(CreateHATCRegions, RegionNames, false,
(string)null, clientNotification, createRegions);
m_client1.Call(Create2Vals, true);
Util.Log("StepOne complete.");
m_client2.Call(CreateHATCRegions, RegionNames, false,
CacheHelper.Locators, !clientNotification, createRegions);
m_client2.Call(Create2Vals, false);
Util.Log("StepTwo complete.");
m_client1.Call(DoNetsearch2Vals, false);
m_client1.Call(RegisterKeys, m_keys[1], m_keys[3]);
Util.Log("StepThree complete.");
m_client2.Call(CheckServerKeys);
m_client2.Call(DoNetsearch2Vals, true);
m_client2.Call(RegisterKeys, m_keys[0], m_keys[2]);
Util.Log("StepFour complete.");
m_client1.Call(Update2NVals, true, true);
Util.Log("StepFive complete.");
m_client2.Call(Verify2NVals, true);
m_client2.Call(Update2NVals, false, true);
Util.Log("StepSix complete.");
m_client1.Call(Verify2NVals, false);
Util.Log("StepSeven complete.");
}
public void FailoverCommonSteps(int redundancyLevel, bool useRegexes)
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml",
"cacheserver_notify_subscription3.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(InitClient_Pool, CacheHelper.Locators, redundancyLevel);
m_client1.Call(CreateHATCRegions, RegionNames, false,
(string)null, useRegexes, true);
Util.Log("StepOne complete.");
m_client2.Call(InitClient_Pool, CacheHelper.Locators, redundancyLevel);
m_client2.Call(CreateHATCRegions, RegionNames, false,
(string)null, !useRegexes, true);
Util.Log("StepTwo complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
if (redundancyLevel > 1)
{
if (useRegexes)
{
m_client2.Call(RegisterRegexesException, m_regexes[0], m_regexes[2]);
}
else
{
m_client2.Call(RegisterKeysException, m_keys[0], m_keys[2]);
}
}
else
{
if (useRegexes)
{
m_client2.Call(RegisterRegexes, m_regexes[0], m_regexes[2]);
}
else
{
m_client2.Call(RegisterKeys, m_keys[0], m_keys[2]);
}
}
Util.Log("RegisterKeys done.");
m_client1.Call(CreateVals);
Util.Log("StepThree complete.");
m_client2.Call(VerifyValCreations, true);
m_client2.Call(Verify2Vals, true);
m_client2.Call(DoNetsearch2Vals, false);
Util.Log("StepFour complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
//For Failover to complete.
Thread.Sleep(5000);
m_client1.Call(CheckServerKeys);
m_client1.Call(UpdateNVals, true);
Thread.Sleep(1000);
Util.Log("StepFive complete.");
m_client2.Call(VerifyNValsVals);
Util.Log("StepSix complete.");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
//For Failover to complete.
Thread.Sleep(5000);
CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1);
Util.Log("Cacheserver 3 started.");
m_client1.Call(UpdateVals);
Thread.Sleep(1000);
Util.Log("StepSeven complete.");
m_client2.Call(VerifyVals);
if (useRegexes)
{
m_client2.Call(UnregisterRegexes, (string)null, m_regexes[2]);
}
else
{
m_client2.Call(UnregisterKeys, (string)null, m_keys[2]);
}
Util.Log("StepEight complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(3);
Util.Log("Cacheserver 3 stopped.");
m_client1.Call(UpdateNVals, true);
Thread.Sleep(1000);
Util.Log("StepNine complete.");
m_client2.Call(VerifyNValVals);
Util.Log("StepTen complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
//For Failover to complete.
Thread.Sleep(5000);
m_client1.Call(UpdateVals);
Thread.Sleep(1000);
Util.Log("StepEleven complete.");
m_client2.Call(VerifyVals);
Util.Log("StepTwelve complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
public void KillServer()
{
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
public delegate void KillServerDelegate();
public void StepOneFailover()
{
// This is here so that Client1 registers information of the cacheserver
// that has been already started
CacheHelper.SetupJavaServers(true,
"cacheserver_remoteoqlN.xml",
"cacheserver_remoteoql2N.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
//CacheHelper.StartJavaServer(1, "GFECS1");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
try
{
CacheHelper.DCache.TypeRegistry.RegisterType(Portfolio.CreateDeserializable, 8);
CacheHelper.DCache.TypeRegistry.RegisterType(Position.CreateDeserializable, 7);
}
catch (IllegalStateException)
{
// ignored since we run multiple iterations for pool and non pool configs
}
InitClient_Pool(CacheHelper.Locators, 1);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionName, true, true,
null, null, "__TESTPOOL1_", true);
Region region = CacheHelper.GetVerifyRegion<object, object>(QueryRegionName);
Portfolio port1 = new Portfolio(1, 100);
Portfolio port2 = new Portfolio(2, 200);
Portfolio port3 = new Portfolio(3, 300);
Portfolio port4 = new Portfolio(4, 400);
region["1"] = port1;
region["2"] = port2;
region["3"] = port3;
region["4"] = port4;
}
public void StepTwoFailover()
{
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
IAsyncResult killRes = null;
KillServerDelegate ksd = new KillServerDelegate(KillServer);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
for (int i = 0; i < 10000; i++)
{
Query<object> qry = qs.NewQuery<object>("select distinct * from /" + QueryRegionName);
ISelectResults<object> results = qry.Execute();
if (i == 10)
{
Util.Log("Starting the kill server thread.");
killRes = ksd.BeginInvoke(null, null);
}
var resultSize = results.Size;
if (i % 100 == 0)
{
Util.Log("Iteration upto {0} done, result size is {1}", i, resultSize);
}
Assert.AreEqual(4, resultSize, "Result size is not 4!");
}
killRes.AsyncWaitHandle.WaitOne();
ksd.EndInvoke(killRes);
}
#endregion
void runDistOps()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(InitClient_Pool, CacheHelper.Locators, 1);
m_client2.Call(InitClient_Pool, CacheHelper.Locators, 1);
m_client1.Call(CreateNonExistentRegion, CacheHelper.Locators);
DistOpsCommonSteps(true);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator 1 stopped.");
}
void runDistOpsXml()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(InitClientXml, "client_pool.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2);
m_client2.Call(InitClientXml, "client_pool.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2);
DistOpsCommonSteps(false);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
}
void runGenericsXmlPlugins()
{
Util.Log("runGenericsXmlPlugins: pool with endpoints in client XML.");
CacheHelper.SetupJavaServers(false, "cacheserver1_partitioned.xml",
"cacheserver2_partitioned.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServer(2, "GFECS2");
Util.Log("Cacheserver 2 started.");
m_client1.Call(InitClientXml, "client_pool.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2);
m_client2.Call(InitClientXml, "client_generics_plugins.xml", CacheHelper.HOST_PORT_1, CacheHelper.HOST_PORT_2);
m_client1.Call(CreateHATCRegions, RegionNames, false,
(string)null, false, false);
m_client2.Call(CreateHATCRegions, RegionNames, false,
(string)null, false, false);
Util.Log("StepOne complete.");
m_client2.Call(RegisterKeys, m_keys[0], m_keys[2]);
m_client1.Call(Create2Vals, true);
m_client2.Call(DoCacheLoad2Vals, false);
m_client1.Call(Update2NVals, true, true);
m_client2.Call(Create2Vals, false);
m_client2.Call(VerifyTallies);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
}
void runQueryFailover()
{
try
{
m_client1.Call(StepOneFailover);
Util.Log("StepOneFailover complete.");
m_client1.Call(StepTwoFailover);
Util.Log("StepTwoFailover complete.");
m_client1.Call(Close);
Util.Log("Client closed");
}
finally
{
m_client1.Call(CacheHelper.StopJavaServers);
m_client1.Call(CacheHelper.StopJavaLocator, 1);
Util.Log("Locator stopped");
}
}
void runPeriodicAck()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(InitClientForEventId_Pool, CacheHelper.Locators, false, 1, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));
m_client1.Call(CreateHATCRegions, RegionNames, false,
(string)null, false, true);
Util.Log("StepOne complete.");
m_client2.Call(InitClientForEventId_Pool, CacheHelper.Locators, true, 1, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30));
m_client2.Call(CreateHATCRegions, RegionNames, false,
(string)null, true, true);
m_client2.Call(InitDupListeners);
Util.Log("StepTwo complete.");
m_client1.Call(CreateEntriesForEventId, 50);
Util.Log("CreateEntries complete.");
Thread.Sleep(30000);
m_client2.Call(CheckClientForEventId);
Util.Log("CheckClient complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runEventIDMap()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(InitClientForEventId_Pool, CacheHelper.Locators, false, 1, TimeSpan.FromSeconds(3600), TimeSpan.FromSeconds(3600));
m_client1.Call(CreateHATCRegions, RegionNames, false,
(string)null, false, true);
Util.Log("StepOne complete.");
m_client2.Call(InitClientForEventId_Pool, CacheHelper.Locators, true, 1, TimeSpan.FromSeconds(3600), TimeSpan.FromSeconds(3600));
m_client2.Call(CreateHATCRegions, RegionNames, false,
(string)null, true, true);
m_client2.Call(InitDupListeners);
Util.Log("StepTwo complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
m_client1.Call(CreateEntriesForEventId, 10);
Util.Log("CreateEntries complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
Thread.Sleep(30000);
m_client2.Call(CheckClientForEventId);
Util.Log("CheckClient complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
[Test]
public void DistOps()
{
runDistOps();
}
[Test]
public void DistOpsXml()
{
runDistOpsXml();
}
[Test]
public void GenericsXmlPlugins()
{
runGenericsXmlPlugins();
}
[Test]
public void FailoverR1()
{
FailoverCommonSteps(1, false);
}
[Test]
public void FailoverR3()
{
FailoverCommonSteps(3, false);
}
[Test]
public void FailoverRegexR1()
{
FailoverCommonSteps(1, true);
}
[Test]
public void FailoverRegexR3()
{
FailoverCommonSteps(3, true);
}
[Test]
public void QueryFailover()
{
runQueryFailover();
}
[Test]
public void PeriodicAck()
{
runPeriodicAck();
}
[Test]
public void EventIDMap()
{
runEventIDMap();
}
}
}
| |
//
// AlbumArtLoaderFixture.cs
//
// Author:
// John Moore <jcwmoore@gmail.com>
//
// Copyright (c) 2012 John Moore
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using NUnit.Framework;
using System;
using System.Linq;
using System.Collections.Generic;
using JohnMoore.AmpacheNet.Logic;
using JohnMoore.AmpacheNet.Entities;
using JohnMoore.AmpacheNet.DataAccess;
using System.IO;
using NSubstitute;
namespace JohnMoore.AmpacheNet.Logic.Tests
{
[TestFixture()]
public class AlbumArtLoaderFixture
{
[Test()]
public void AlbumArtLoaderUsesDefaultWhenInitializedTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
Assert.That(model.AlbumArtStream, Is.Not.SameAs(defaultStream));
var target = new AlbumArtLoader(container, defaultStream);
Assert.That(model.AlbumArtStream, Is.SameAs(defaultStream));
}
[Test()]
public void AlbumArtLoaderUsesDefaultArtWhenNoArtAvailableTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = string.Empty;
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(model.AlbumArtStream, Is.SameAs(defaultStream));
}
[Test()]
public void AlbumArtLoaderUsesDefaultArtWhenLoadingArtTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(false);
int timesCalled = 0;
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(x => { ++timesCalled; Assert.That(model.AlbumArtStream, Is.SameAs(defaultStream)); return Enumerable.Empty<AlbumArt>();});
container.Register<IPersister<AlbumArt>>().To(persistor);
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(timesCalled, Is.EqualTo(1));
}
[Test()]
public void AlbumArtLoaderUsesDefaultArtWhenErrorLoadingArtTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(false);
int timesCalled = 0;
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(x => { ++timesCalled; return Enumerable.Empty<AlbumArt>();});
container.Register<IPersister<AlbumArt>>().To(persistor);
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(timesCalled, Is.EqualTo(1));
Assert.That(model.AlbumArtStream, Is.SameAs(defaultStream));
}
[Test()]
public void AlbumArtLoaderUsesLoadedArtAfterLoadingTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
container.Register<IPersister<AlbumArt>>().To(persistor);
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(false);
var art = new AlbumArt();
art.ArtStream = new MemoryStream();
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(new [] {art});
var prefs = new UserConfiguration();
prefs.CacheArt = false;
model.Configuration = prefs;
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(model.AlbumArtStream, Is.SameAs(art.ArtStream));
}
[Test()]
public void AlbumArtLoaderRespectsCachingPerferencesTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
container.Register<IPersister<AlbumArt>>().To(persistor);
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(false);
int timesCalled = 0;
persistor.When(x => x.Persist(Arg.Any<AlbumArt>())).Do( x => { ++timesCalled; });
var art = new AlbumArt();
art.ArtStream = new MemoryStream();
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(new [] {art});
var prefs = new UserConfiguration();
prefs.CacheArt = false;
model.Configuration = prefs;
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(model.AlbumArtStream, Is.SameAs(art.ArtStream));
Assert.That(timesCalled, Is.EqualTo(0));
}
[Test()]
public void AlbumArtLoaderIgnoresCachingPersistedItemTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
container.Register<IPersister<AlbumArt>>().To(persistor);
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(true);
var art = new AlbumArt();
persistor.IsPersisted(Arg.Is(art)).Returns(true);
int timesCalled = 0;
persistor.When(x => x.Persist(Arg.Any<AlbumArt>())).Do( x => { ++timesCalled; });
art.ArtStream = new MemoryStream();
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(new [] {art});
var prefs = new UserConfiguration();
prefs.CacheArt = true;
model.Configuration = prefs;
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(model.AlbumArtStream, Is.SameAs(art.ArtStream));
Assert.That(timesCalled, Is.EqualTo(0));
}
[Test()]
public void AlbumArtLoaderCachesNewArtTest ()
{
var container = new Athena.IoC.Container();
var model = new AmpacheModel();
container.Register<AmpacheModel>().To(model);
var defaultStream = new MemoryStream();
var persistor = Substitute.For<IPersister<AlbumArt>>();
container.Register<IPersister<AlbumArt>>().To(persistor);
persistor.IsPersisted(Arg.Any<IEntity>()).Returns(false);
var art = new AlbumArt();
persistor.IsPersisted(Arg.Is(art)).Returns(false);
int timesCalled = 0;
persistor.When(x => x.Persist(Arg.Any<AlbumArt>())).Do( x => { ++timesCalled; });
art.ArtStream = new MemoryStream(new byte[8]);
persistor.SelectBy<AmpacheSong>(Arg.Any<AmpacheSong>()).Returns(new [] {art});
var prefs = new UserConfiguration();
prefs.CacheArt = true;
model.Configuration = prefs;
var target = new AlbumArtLoader(container, defaultStream);
var sng = new AmpacheSong();
sng.ArtUrl = "test";
model.PlayingSong = sng;
System.Threading.Thread.Sleep(100);
Assert.That(model.AlbumArtStream, Is.SameAs(art.ArtStream));
Assert.That(timesCalled, Is.EqualTo(1));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
namespace OpenSim.Data.SQLite
{
public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
protected static SqliteConnection m_Connection;
private static bool m_initialized = false;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
if (!m_initialized)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
Migration m = new Migration(m_Connection, Assembly, "AuthStore");
m.Update();
m_initialized = true;
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
IDataReader result;
using (SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"))
{
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
result = ExecuteReader(cmd, m_Connection);
}
try
{
if (result.Read())
{
ret.PrincipalID = principalID;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
catch
{
}
return null;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
string[] values = new string[data.Data.Count];
int i = 0;
foreach (object o in data.Data.Values)
values[i++] = o.ToString();
using (SqliteCommand cmd = new SqliteCommand())
{
if (Get(data.PrincipalID) != null)
{
string update = "update `" + m_Realm + "` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = :" + field;
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
first = false;
}
update += " where UUID = :UUID";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
cmd.CommandText = update;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
//CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
m_log.Error("[SQLITE]: Exception storing authentication data", e);
//CloseCommand(cmd);
return false;
}
}
else
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (:UUID, :" + String.Join(", :", fields) + ")";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
foreach (string field in fields)
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
cmd.CommandText = insert;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
return false;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
}
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
using (SqliteCommand cmd = new SqliteCommand("update `" + m_Realm +
"` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
"', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
using (SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
" minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"))
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
}
return false;
}
private void DoExpire()
{
using (SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"))
ExecuteNonQuery(cmd, m_Connection);
m_LastExpire = System.Environment.TickCount;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.UI;
namespace Revit.SDK.Samples.AutoUpdate.CS
{
/// <summary>
/// This class implements IExternalApplication and demonstrate how to subscribe event
/// and modify model in event handler. We just demonstrate changing
/// the ProjectInformation.Address property, but user can do other modification for
/// current project, like delete element, create new element, etc.
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class ExternalApplication : IExternalApplication
{
#region Class Member Variables
/// <summary>
/// This listener is used to monitor the events arguments and the result of the sample.
/// It will be bound to log file AutoUpdate.log, it will be added to Trace.Listeners.
/// </summary>
private TextWriterTraceListener m_txtListener;
/// <summary>
/// get assembly path.
/// </summary>
private static String m_directory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
/// <summary>
/// create the temp file name.
/// </summary>
private String m_tempFile = Path.Combine(m_directory, "temp.log");
#endregion
#region IExternalApplication Members
/// <summary>
/// Implement this method to subscribe event.
/// </summary>
/// <param name="application">the controlled application.</param>
/// <returns>Return the status of the external application.
/// A result of Succeeded means that the external application successfully started.
/// Cancelled can be used to signify that the user cancelled the external operation at
/// some point.
/// If false is returned then Revit should inform the user that the external application
/// failed to load and the release the internal reference.</returns>
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application)
{
try
{
// Create a temp file to dump the log, and copy this file to log file
// at the end of the sample.
CreateTempFile();
// Register event. In this sample, we trigger this event from UI, so it must
// be registered on ControlledApplication.
application.ControlledApplication.DocumentOpened += new EventHandler
<Autodesk.Revit.DB.Events.DocumentOpenedEventArgs>(application_DocumentOpened);
}
catch (Exception)
{
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
/// <summary>
/// Implement this method to implement the external application which should be called when
/// Revit is about to exit,Any documents must have been closed before this method is called.
/// </summary>
/// <param name="application">An object that is passed to the external application
/// which contains the controlled application.</param>
/// <returns>Return the status of the external application.
/// A result of Succeeded means that the external application successfully shutdown.
/// Cancelled can be used to signify that the user cancelled the external operation at
/// some point.
/// If false is returned then the Revit user should be warned of the failure of the external
/// application to shut down correctly.</returns>
public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application)
{
// remove the event.
application.ControlledApplication.DocumentOpened -= application_DocumentOpened;
CloseLogFile();
return Autodesk.Revit.UI.Result.Succeeded;
}
#endregion
#region Event Handler
/// <summary>
/// This is the event handler. We modify the model and dump log in this method.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void application_DocumentOpened(object sender, DocumentOpenedEventArgs args)
{
// dump the args to log file.
DumpEventArgs(args);
// get document from event args.
Document doc = args.Document;
if (doc.IsFamilyDocument)
{
return;
}
try
{
//now event framework will not provide transaction,user need start by self(2009/11/18)
Transaction eventTransaction = new Transaction(doc, "Event handler modify project information");
eventTransaction.Start();
// assign specified value to ProjectInformation.Address property.
// User can change another properties of document or create(delete) something as he likes.
// Please pay attention that ProjectInformation property is empty for family document.
// But it isn't the correct usage. So please don't run this sample on family document.
doc.ProjectInformation.Address =
"United States - Massachusetts - Waltham - 610 Lincoln St";
eventTransaction.Commit();
}
catch (Exception ee)
{
Trace.WriteLine("Failed to modify project information!-"+ee.Message);
}
// write the value to log file to check whether the operation is successful.
Trace.WriteLine("The value after running the sample ------>");
Trace.WriteLine(" [Address] :" + doc.ProjectInformation.Address);
}
#endregion
#region Class Methods
/// <summary>
/// Dump the events arguments to log file: AutoUpdat.log.
/// </summary>
/// <param name="args"></param>
private void DumpEventArgs(DocumentOpenedEventArgs args)
{
Trace.WriteLine("DocumentOpenedEventArgs Parameters ------>");
Trace.WriteLine(" Event Cancel : " + args.IsCancelled()); // is it be cancelled?
Trace.WriteLine(" Event Cancellable : " + args.Cancellable); // Cancellable
Trace.WriteLine(" Status : " + args.Status); // Status
}
/// <summary>
/// Create a log file to track the subscribed events' work process.
/// </summary>
private void CreateTempFile()
{
if (File.Exists(m_tempFile)) File.Delete(m_tempFile);
m_txtListener = new TextWriterTraceListener(m_tempFile);
Trace.AutoFlush = true;
Trace.Listeners.Add(m_txtListener);
}
/// <summary>
/// Close the log file and remove the corresponding listener.
/// </summary>
private void CloseLogFile()
{
// close listeners now.
Trace.Flush();
Trace.Listeners.Remove(m_txtListener);
Trace.Close();
m_txtListener.Close();
// copy temp file to log file and delete the temp file.
String logFile = Path.Combine(m_directory, "AutoUpdate.log");
if (File.Exists(logFile)) File.Delete(logFile);
File.Copy(m_tempFile, logFile);
File.Delete(m_tempFile);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Numerics;
using Internal.Runtime.CompilerServices;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nint = System.Int64;
using nuint = System.UInt64;
#else // BIT64
using nint = System.Int32;
using nuint = System.UInt32;
#endif // BIT64
namespace System.Text.Unicode
{
internal static unsafe partial class Utf16Utility
{
#if DEBUG
static Utf16Utility()
{
Debug.Assert(sizeof(nint) == IntPtr.Size && nint.MinValue < 0, "nint is defined incorrectly.");
Debug.Assert(sizeof(nuint) == IntPtr.Size && nuint.MinValue == 0, "nuint is defined incorrectly.");
}
#endif // DEBUG
// Returns &inputBuffer[inputLength] if the input buffer is valid.
/// <summary>
/// Given an input buffer <paramref name="pInputBuffer"/> of char length <paramref name="inputLength"/>,
/// returns a pointer to where the first invalid data appears in <paramref name="pInputBuffer"/>.
/// </summary>
/// <remarks>
/// Returns a pointer to the end of <paramref name="pInputBuffer"/> if the buffer is well-formed.
/// </remarks>
public static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment)
{
Debug.Assert(inputLength >= 0, "Input length must not be negative.");
Debug.Assert(pInputBuffer != null || inputLength == 0, "Input length must be zero if input buffer pointer is null.");
// First, we'll handle the common case of all-ASCII. If this is able to
// consume the entire buffer, we'll skip the remainder of this method's logic.
int numAsciiCharsConsumedJustNow = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pInputBuffer, (uint)inputLength);
Debug.Assert(0 <= numAsciiCharsConsumedJustNow && numAsciiCharsConsumedJustNow <= inputLength);
pInputBuffer += (uint)numAsciiCharsConsumedJustNow;
inputLength -= numAsciiCharsConsumedJustNow;
if (inputLength == 0)
{
utf8CodeUnitCountAdjustment = 0;
scalarCountAdjustment = 0;
return pInputBuffer;
}
// If we got here, it means we saw some non-ASCII data, so within our
// vectorized code paths below we'll handle all non-surrogate UTF-16
// code points branchlessly. We'll only branch if we see surrogates.
//
// We still optimistically assume the data is mostly ASCII. This means that the
// number of UTF-8 code units and the number of scalars almost matches the number
// of UTF-16 code units. As we go through the input and find non-ASCII
// characters, we'll keep track of these "adjustment" fixups. To get the
// total number of UTF-8 code units required to encode the input data, add
// the UTF-8 code unit count adjustment to the number of UTF-16 code units
// seen. To get the total number of scalars present in the input data,
// add the scalar count adjustment to the number of UTF-16 code units seen.
long tempUtf8CodeUnitCountAdjustment = 0;
int tempScalarCountAdjustment = 0;
if (Sse2.IsSupported)
{
if (inputLength >= Vector128<ushort>.Count)
{
Vector128<ushort> vector0080 = Vector128.Create((ushort)0x80);
Vector128<ushort> vectorA800 = Vector128.Create((ushort)0xA800);
Vector128<short> vector8800 = Vector128.Create(unchecked((short)0x8800));
Vector128<ushort> vectorZero = Vector128<ushort>.Zero;
do
{
Vector128<ushort> utf16Data = Sse2.LoadVector128((ushort*)pInputBuffer); // unaligned
uint mask;
// The 'charIsNonAscii' vector we're about to build will have the 0x8000 or the 0x0080
// bit set (but not both!) only if the corresponding input char is non-ASCII. Which of
// the two bits is set doesn't matter, as will be explained in the diagram a few lines
// below.
Vector128<ushort> charIsNonAscii;
if (Sse41.IsSupported)
{
// sets 0x0080 bit if corresponding char element is >= 0x0080
charIsNonAscii = Sse41.Min(utf16Data, vector0080);
}
else
{
// sets 0x8000 bit if corresponding char element is >= 0x0080
charIsNonAscii = Sse2.AndNot(vector0080, Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 7)));
}
#if DEBUG
// Quick check to ensure we didn't accidentally set both 0x8080 bits in any element.
uint debugMask = (uint)Sse2.MoveMask(charIsNonAscii.AsByte());
Debug.Assert((debugMask & (debugMask << 1)) == 0, "Two set bits shouldn't occur adjacent to each other in this mask.");
#endif // DEBUG
// sets 0x8080 bits if corresponding char element is >= 0x0800
Vector128<ushort> charIsThreeByteUtf8Encoded = Sse2.Subtract(vectorZero, Sse2.ShiftRightLogical(utf16Data, 11));
mask = (uint)Sse2.MoveMask(Sse2.Or(charIsNonAscii, charIsThreeByteUtf8Encoded).AsByte());
// Each odd bit of mask will be 1 only if the char was >= 0x0080,
// and each even bit of mask will be 1 only if the char was >= 0x0800.
//
// Example for UTF-16 input "[ 0123 ] [ 1234 ] ...":
//
// ,-- set if char[1] is non-ASCII
// | ,-- set if char[0] is non-ASCII
// v v
// mask = ... 1 1 1 0
// ^ ^-- set if char[0] is >= 0x0800
// `-- set if char[1] is >= 0x0800
//
// (If the SSE4.1 code path is taken above, the meaning of the odd and even
// bits are swapped, but the logic below otherwise holds.)
//
// This means we can popcnt the number of set bits, and the result is the
// number of *additional* UTF-8 bytes that each UTF-16 code unit requires as
// it expands. This results in the wrong count for UTF-16 surrogate code
// units (we just counted that each individual code unit expands to 3 bytes,
// but in reality a well-formed UTF-16 surrogate pair expands to 4 bytes).
// We'll handle this in just a moment.
//
// For now, compute the popcnt but squirrel it away. We'll fold it in to the
// cumulative UTF-8 adjustment factor once we determine that there are no
// unpaired surrogates in our data. (Unpaired surrogates would invalidate
// our computed result and we'd have to throw it away.)
uint popcnt = (uint)BitOperations.PopCount(mask);
// Surrogates need to be special-cased for two reasons: (a) we need
// to account for the fact that we over-counted in the addition above;
// and (b) they require separate validation.
utf16Data = Sse2.Add(utf16Data, vectorA800);
mask = (uint)Sse2.MoveMask(Sse2.CompareLessThan(utf16Data.AsInt16(), vector8800).AsByte());
if (mask != 0)
{
// There's at least one UTF-16 surrogate code unit present.
// Since we performed a pmovmskb operation on the result of a 16-bit pcmpgtw,
// the resulting bits of 'mask' will occur in pairs:
// - 00 if the corresponding UTF-16 char was not a surrogate code unit;
// - 11 if the corresponding UTF-16 char was a surrogate code unit.
//
// A UTF-16 high/low surrogate code unit has the bit pattern [ 11011q## ######## ],
// where # is any bit; q = 0 represents a high surrogate, and q = 1 represents
// a low surrogate. Since we added 0xA800 in the vectorized operation above,
// our surrogate pairs will now have the bit pattern [ 10000q## ######## ].
// If we logical right-shift each word by 3, we'll end up with the bit pattern
// [ 00010000 q####### ], which means that we can immediately use pmovmskb to
// determine whether a given char was a high or a low surrogate.
//
// Therefore the resulting bits of 'mask2' will occur in pairs:
// - 00 if the corresponding UTF-16 char was a high surrogate code unit;
// - 01 if the corresponding UTF-16 char was a low surrogate code unit;
// - ## (garbage) if the corresponding UTF-16 char was not a surrogate code unit.
// Since 'mask' already has 00 in these positions (since the corresponding char
// wasn't a surrogate), "mask AND mask2 == 00" holds for these positions.
uint mask2 = (uint)Sse2.MoveMask(Sse2.ShiftRightLogical(utf16Data, 3).AsByte());
// 'lowSurrogatesMask' has its bits occur in pairs:
// - 01 if the corresponding char was a low surrogate char,
// - 00 if the corresponding char was a high surrogate char or not a surrogate at all.
uint lowSurrogatesMask = mask2 & mask;
// 'highSurrogatesMask' has its bits occur in pairs:
// - 01 if the corresponding char was a high surrogate char,
// - 00 if the corresponding char was a low surrogate char or not a surrogate at all.
uint highSurrogatesMask = (mask2 ^ 0b_0101_0101_0101_0101u /* flip all even-numbered bits 00 <-> 01 */) & mask;
Debug.Assert((highSurrogatesMask & lowSurrogatesMask) == 0,
"A char cannot simultaneously be both a high and a low surrogate char.");
Debug.Assert(((highSurrogatesMask | lowSurrogatesMask) & 0b_1010_1010_1010_1010u) == 0,
"Only even bits (no odd bits) of the masks should be set.");
// Now check that each high surrogate is followed by a low surrogate and that each
// low surrogate follows a high surrogate. We make an exception for the case where
// the final char of the vector is a high surrogate, since we can't perform validation
// on it until the next iteration of the loop when we hope to consume the matching
// low surrogate.
highSurrogatesMask <<= 2;
if ((ushort)highSurrogatesMask != lowSurrogatesMask)
{
goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic
}
if (highSurrogatesMask > ushort.MaxValue)
{
// There was a standalone high surrogate at the end of the vector.
// We'll adjust our counters so that we don't consider this char consumed.
highSurrogatesMask = (ushort)highSurrogatesMask; // don't allow stray high surrogate to be consumed by popcnt
popcnt -= 2; // the '0xC000_0000' bits in the original mask are shifted out and discarded, so account for that here
pInputBuffer--;
inputLength++;
}
// If we're 64-bit, we can perform the zero-extension of the surrogate pairs count for
// free right now, saving the extension step a few lines below. If we're 32-bit, the
// convertion to nuint immediately below is a no-op, and we'll pay the cost of the real
// 64 -bit extension a few lines below.
nuint surrogatePairsCountNuint = (uint)BitOperations.PopCount(highSurrogatesMask);
// 2 UTF-16 chars become 1 Unicode scalar
tempScalarCountAdjustment -= (int)surrogatePairsCountNuint;
// Since each surrogate code unit was >= 0x0800, we eagerly assumed
// it'd be encoded as 3 UTF-8 code units, so our earlier popcnt computation
// assumes that the pair is encoded as 6 UTF-8 code units. Since each
// pair is in reality only encoded as 4 UTF-8 code units, we need to
// perform this adjustment now.
if (IntPtr.Size == 8)
{
// Since we've already zero-extended surrogatePairsCountNuint, we can directly
// sub + sub. It's more efficient than shl + sub.
tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;
tempUtf8CodeUnitCountAdjustment -= (long)surrogatePairsCountNuint;
}
else
{
// Take the hit of the 64-bit extension now.
tempUtf8CodeUnitCountAdjustment -= 2 * (uint)surrogatePairsCountNuint;
}
}
tempUtf8CodeUnitCountAdjustment += popcnt;
pInputBuffer += Vector128<ushort>.Count;
inputLength -= Vector128<ushort>.Count;
} while (inputLength >= Vector128<ushort>.Count);
}
}
else if (Vector.IsHardwareAccelerated)
{
if (inputLength >= Vector<ushort>.Count)
{
Vector<ushort> vector0080 = new Vector<ushort>(0x0080);
Vector<ushort> vector0400 = new Vector<ushort>(0x0400);
Vector<ushort> vector0800 = new Vector<ushort>(0x0800);
Vector<ushort> vectorD800 = new Vector<ushort>(0xD800);
do
{
// The 'twoOrMoreUtf8Bytes' and 'threeOrMoreUtf8Bytes' vectors will contain
// elements whose values are 0xFFFF (-1 as signed word) iff the corresponding
// UTF-16 code unit was >= 0x0080 and >= 0x0800, respectively. By summing these
// vectors, each element of the sum will contain one of three values:
//
// 0x0000 ( 0) = original char was 0000..007F
// 0xFFFF (-1) = original char was 0080..07FF
// 0xFFFE (-2) = original char was 0800..FFFF
//
// We'll negate them to produce a value 0..2 for each element, then sum all the
// elements together to produce the number of *additional* UTF-8 code units
// required to represent this UTF-16 data. This is similar to the popcnt step
// performed by the SSE2 code path. This will overcount surrogates, but we'll
// handle that shortly.
Vector<ushort> utf16Data = Unsafe.ReadUnaligned<Vector<ushort>>(pInputBuffer);
Vector<ushort> twoOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0080);
Vector<ushort> threeOrMoreUtf8Bytes = Vector.GreaterThanOrEqual(utf16Data, vector0800);
Vector<nuint> sumVector = (Vector<nuint>)(Vector<ushort>.Zero - twoOrMoreUtf8Bytes - threeOrMoreUtf8Bytes);
// We'll try summing by a natural word (rather than a 16-bit word) at a time,
// which should halve the number of operations we must perform.
nuint popcnt = 0;
for (int i = 0; i < Vector<nuint>.Count; i++)
{
popcnt += sumVector[i];
}
uint popcnt32 = (uint)popcnt;
if (IntPtr.Size == 8)
{
popcnt32 += (uint)(popcnt >> 32);
}
// As in the SSE4.1 paths, compute popcnt but don't fold it in until we
// know there aren't any unpaired surrogates in the input data.
popcnt32 = (ushort)popcnt32 + (popcnt32 >> 16);
// Now check for surrogates.
utf16Data -= vectorD800;
Vector<ushort> surrogateChars = Vector.LessThan(utf16Data, vector0800);
if (surrogateChars != Vector<ushort>.Zero)
{
// There's at least one surrogate (high or low) UTF-16 code unit in
// the vector. We'll build up additional vectors: 'highSurrogateChars'
// and 'lowSurrogateChars', where the elements are 0xFFFF iff the original
// UTF-16 code unit was a high or low surrogate, respectively.
Vector<ushort> highSurrogateChars = Vector.LessThan(utf16Data, vector0400);
Vector<ushort> lowSurrogateChars = Vector.AndNot(surrogateChars, highSurrogateChars);
// We want to make sure that each high surrogate code unit is followed by
// a low surrogate code unit and each low surrogate code unit follows a
// high surrogate code unit. Since we don't have an equivalent of pmovmskb
// or palignr available to us, we'll do this as a loop. We won't look at
// the very last high surrogate char element since we don't yet know if
// the next vector read will have a low surrogate char element.
if (lowSurrogateChars[0] != 0)
{
goto Error; // error: start of buffer contains standalone low surrogate char
}
ushort surrogatePairsCount = 0;
for (int i = 0; i < Vector<ushort>.Count - 1; i++)
{
surrogatePairsCount -= highSurrogateChars[i]; // turns into +1 or +0
if (highSurrogateChars[i] != lowSurrogateChars[i + 1])
{
goto NonVectorizedLoop; // error: mismatched surrogate pair; break out of vectorized logic
}
}
if (highSurrogateChars[Vector<ushort>.Count - 1] != 0)
{
// There was a standalone high surrogate at the end of the vector.
// We'll adjust our counters so that we don't consider this char consumed.
pInputBuffer--;
inputLength++;
popcnt32 -= 2;
}
nint surrogatePairsCountNint = (nint)surrogatePairsCount; // zero-extend to native int size
// 2 UTF-16 chars become 1 Unicode scalar
tempScalarCountAdjustment -= (int)surrogatePairsCountNint;
// Since each surrogate code unit was >= 0x0800, we eagerly assumed
// it'd be encoded as 3 UTF-8 code units. Each surrogate half is only
// encoded as 2 UTF-8 code units (for 4 UTF-8 code units total),
// so we'll adjust this now.
tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint;
tempUtf8CodeUnitCountAdjustment -= surrogatePairsCountNint;
}
tempUtf8CodeUnitCountAdjustment += popcnt32;
pInputBuffer += Vector<ushort>.Count;
inputLength -= Vector<ushort>.Count;
} while (inputLength >= Vector<ushort>.Count);
}
}
NonVectorizedLoop:
// Vectorization isn't supported on our current platform, or the input was too small to benefit
// from vectorization, or we saw invalid UTF-16 data in the vectorized code paths and need to
// drain remaining valid chars before we report failure.
for (; inputLength > 0; pInputBuffer++, inputLength--)
{
uint thisChar = pInputBuffer[0];
if (thisChar <= 0x7F)
{
continue;
}
// Bump adjustment by +1 for U+0080..U+07FF; by +2 for U+0800..U+FFFF.
// This optimistically assumes no surrogates, which we'll handle shortly.
tempUtf8CodeUnitCountAdjustment += (thisChar + 0x0001_F800u) >> 16;
if (!UnicodeUtility.IsSurrogateCodePoint(thisChar))
{
continue;
}
// Found a surrogate char. Back out the adjustment we made above, then
// try to consume the entire surrogate pair all at once. We won't bother
// trying to interpret the surrogate pair as a scalar value; we'll only
// validate that its bit pattern matches what's expected for a surrogate pair.
tempUtf8CodeUnitCountAdjustment -= 2;
if (inputLength == 1)
{
goto Error; // input buffer too small to read a surrogate pair
}
thisChar = Unsafe.ReadUnaligned<uint>(pInputBuffer);
if (((thisChar - (BitConverter.IsLittleEndian ? 0xDC00_D800u : 0xD800_DC00u)) & 0xFC00_FC00u) != 0)
{
goto Error; // not a well-formed surrogate pair
}
tempScalarCountAdjustment--; // 2 UTF-16 code units -> 1 scalar
tempUtf8CodeUnitCountAdjustment += 2; // 2 UTF-16 code units -> 4 UTF-8 code units
pInputBuffer++; // consumed one extra char
inputLength--;
}
Error:
// Also used for normal return.
utf8CodeUnitCountAdjustment = tempUtf8CodeUnitCountAdjustment;
scalarCountAdjustment = tempScalarCountAdjustment;
return pInputBuffer;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.Text;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Class BaseCommandHelpInfo provides common functionality for
/// extracting information from FullHelp property.
/// </summary>
internal abstract class BaseCommandHelpInfo : HelpInfo
{
internal BaseCommandHelpInfo(HelpCategory helpCategory)
: base()
{
HelpCategory = helpCategory;
}
#region Basic Help Properties
internal PSObject Details
{
get
{
if (this.FullHelp == null)
return null;
if (this.FullHelp.Properties["Details"] == null ||
this.FullHelp.Properties["Details"].Value == null)
{
return null;
}
return PSObject.AsPSObject(this.FullHelp.Properties["Details"].Value);
}
}
/// <summary>
/// Name of command.
/// </summary>
/// <value>Name of command</value>
internal override string Name
{
get
{
PSObject commandDetails = this.Details;
if (commandDetails == null)
{
return string.Empty;
}
if (commandDetails.Properties["Name"] == null ||
commandDetails.Properties["Name"].Value == null)
{
return string.Empty;
}
string name = commandDetails.Properties["Name"].Value.ToString();
if (name == null)
return string.Empty;
return name.Trim();
}
}
/// <summary>
/// Synopsis for this command help.
/// </summary>
/// <value>Synopsis for this command help</value>
internal override string Synopsis
{
get
{
PSObject commandDetails = this.Details;
if (commandDetails == null)
{
return string.Empty;
}
if (commandDetails.Properties["Description"] == null ||
commandDetails.Properties["Description"].Value == null)
{
return string.Empty;
}
object[] synopsisItems = (object[])LanguagePrimitives.ConvertTo(
commandDetails.Properties["Description"].Value,
typeof(object[]),
CultureInfo.InvariantCulture);
if (synopsisItems == null || synopsisItems.Length == 0)
{
return string.Empty;
}
PSObject firstSynopsisItem = synopsisItems[0] == null ? null : PSObject.AsPSObject(synopsisItems[0]);
if (firstSynopsisItem == null ||
firstSynopsisItem.Properties["Text"] == null ||
firstSynopsisItem.Properties["Text"].Value == null)
{
return string.Empty;
}
string synopsis = firstSynopsisItem.Properties["Text"].Value.ToString();
if (synopsis == null)
{
return string.Empty;
}
return synopsis.Trim();
}
}
/// <summary>
/// Help category for this command help, which is constantly HelpCategory.Command.
/// </summary>
/// <value>Help category for this command help</value>
internal override HelpCategory HelpCategory { get; }
/// <summary>
/// Returns the Uri used by get-help cmdlet to show help
/// online. Returns only the first uri found under
/// RelatedLinks.
/// </summary>
/// <returns>
/// Null if no Uri is specified by the helpinfo or a
/// valid Uri.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Specified Uri is not valid.
/// </exception>
internal override Uri GetUriForOnlineHelp()
{
Uri result = null;
UriFormatException uriFormatException = null;
try
{
result = GetUriFromCommandPSObject(this.FullHelp);
if (result != null)
{
return result;
}
}
catch (UriFormatException urie)
{
uriFormatException = urie;
}
// else get uri from CommandInfo HelpUri attribute
result = this.LookupUriFromCommandInfo();
if (result != null)
{
return result;
}
else if (uriFormatException != null)
{
throw uriFormatException;
}
return base.GetUriForOnlineHelp();
}
internal Uri LookupUriFromCommandInfo()
{
CommandTypes cmdTypesToLookFor = CommandTypes.Cmdlet;
switch (this.HelpCategory)
{
case Automation.HelpCategory.Cmdlet:
cmdTypesToLookFor = CommandTypes.Cmdlet;
break;
case Automation.HelpCategory.Function:
cmdTypesToLookFor = CommandTypes.Function;
break;
case Automation.HelpCategory.ScriptCommand:
cmdTypesToLookFor = CommandTypes.Script;
break;
case Automation.HelpCategory.ExternalScript:
cmdTypesToLookFor = CommandTypes.ExternalScript;
break;
case Automation.HelpCategory.Filter:
cmdTypesToLookFor = CommandTypes.Filter;
break;
case Automation.HelpCategory.Configuration:
cmdTypesToLookFor = CommandTypes.Configuration;
break;
default:
return null;
}
string commandName = this.Name;
string moduleName = string.Empty;
if (this.FullHelp.Properties["ModuleName"] != null)
{
PSNoteProperty moduleNameNP = this.FullHelp.Properties["ModuleName"] as PSNoteProperty;
if (moduleNameNP != null)
{
LanguagePrimitives.TryConvertTo<string>(moduleNameNP.Value, CultureInfo.InvariantCulture,
out moduleName);
}
}
string commandToSearch = commandName;
if (!string.IsNullOrEmpty(moduleName))
{
commandToSearch = string.Format(CultureInfo.InvariantCulture,
"{0}\\{1}", moduleName, commandName);
}
ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS();
if (context == null)
{
return null;
}
try
{
CommandInfo cmdInfo = null;
if (cmdTypesToLookFor == CommandTypes.Cmdlet)
{
cmdInfo = context.SessionState.InvokeCommand.GetCmdlet(commandToSearch);
}
else
{
cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault();
}
if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null))
{
return null;
}
string uriString = cmdInfo.CommandMetadata.HelpUri;
if (!string.IsNullOrEmpty(uriString))
{
if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
{
// WinBlue: 545315 Online help links are broken with localized help
// Example: https://go.microsoft.com/fwlink/?LinkID=113324 (moglicherwei se auf Englisch)
// Split the string based on <s> (space). We decided to go with this approach as
// UX localization authors use spaces. Correctly extracting only the wellformed URI
// is out-of-scope for this fix.
string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space);
uriString = tempUriSplitArray[0];
}
try
{
return new System.Uri(uriString);
// return only the first Uri (ignore other uris)
}
catch (UriFormatException)
{
throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI,
cmdInfo.CommandMetadata.HelpUri);
}
}
}
catch (CommandNotFoundException)
{
}
return null;
}
internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp)
{
// this object knows Maml format...
// So retrieve Uri information as per the format..
if ((commandFullHelp == null) ||
(commandFullHelp.Properties["relatedLinks"] == null) ||
(commandFullHelp.Properties["relatedLinks"].Value == null))
{
// return the default..
return null;
}
PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value);
if (relatedLinks.Properties["navigationLink"] == null)
{
return null;
}
object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo(
relatedLinks.Properties["navigationLink"].Value,
typeof(object[]),
CultureInfo.InvariantCulture);
foreach (object navigationLinkAsObject in navigationLinks)
{
if (navigationLinkAsObject == null)
{
continue;
}
PSObject navigationLink = PSObject.AsPSObject(navigationLinkAsObject);
PSNoteProperty uriNP = navigationLink.Properties["uri"] as PSNoteProperty;
if (uriNP != null)
{
string uriString = string.Empty;
LanguagePrimitives.TryConvertTo<string>(uriNP.Value, CultureInfo.InvariantCulture, out uriString);
if (!string.IsNullOrEmpty(uriString))
{
if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
{
// WinBlue: 545315 Online help links are broken with localized help
// Example: https://go.microsoft.com/fwlink/?LinkID=113324 (moglicherwei se auf Englisch)
// Split the string based on <s> (space). We decided to go with this approach as
// UX localization authors use spaces. Correctly extracting only the wellformed URI
// is out-of-scope for this fix.
string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space);
uriString = tempUriSplitArray[0];
}
try
{
return new System.Uri(uriString);
// return only the first Uri (ignore other uris)
}
catch (UriFormatException)
{
throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, uriString);
}
}
}
}
return null;
}
/// <summary>
/// Returns true if help content in help info matches the
/// pattern contained in <paramref name="pattern"/>.
/// The underlying code will usually run pattern.IsMatch() on
/// content it wants to search.
/// Cmdlet help info looks for pattern in Synopsis and
/// DetailedDescription.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
internal override bool MatchPatternInContent(WildcardPattern pattern)
{
Dbg.Assert(pattern != null, "pattern cannot be null");
string synopsis = Synopsis;
string detailedDescription = DetailedDescription;
if (synopsis == null)
{
synopsis = string.Empty;
}
if (detailedDescription == null)
{
detailedDescription = string.Empty;
}
return pattern.IsMatch(synopsis) || pattern.IsMatch(detailedDescription);
}
/// <summary>
/// Returns help information for a parameter(s) identified by pattern.
/// </summary>
/// <param name="pattern">Pattern to search for parameters.</param>
/// <returns>A collection of parameters that match pattern.</returns>
internal override PSObject[] GetParameter(string pattern)
{
// this object knows Maml format...
// So retrieve parameter information as per the format..
if ((this.FullHelp == null) ||
(this.FullHelp.Properties["parameters"] == null) ||
(this.FullHelp.Properties["parameters"].Value == null))
{
// return the default..
return base.GetParameter(pattern);
}
PSObject prmts = PSObject.AsPSObject(this.FullHelp.Properties["parameters"].Value);
if (prmts.Properties["parameter"] == null)
{
return base.GetParameter(pattern);
}
// The Maml format simplifies array fields containing only one object
// by transforming them into the objects themselves. To ensure the consistency
// of the help command result we change it back into an array.
var param = prmts.Properties["parameter"].Value;
PSObject[] paramAsPSObjArray = new PSObject[1];
if (param is PSObject paramPSObj)
{
paramAsPSObjArray[0] = paramPSObj;
}
PSObject[] prmtArray = (PSObject[])LanguagePrimitives.ConvertTo(
paramAsPSObjArray[0] != null ? paramAsPSObjArray : param,
typeof(PSObject[]),
CultureInfo.InvariantCulture);
if (string.IsNullOrEmpty(pattern))
{
return prmtArray;
}
List<PSObject> returnList = new List<PSObject>();
WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (PSObject prmtr in prmtArray)
{
if ((prmtr.Properties["name"] == null) || (prmtr.Properties["name"].Value == null))
{
continue;
}
string prmName = prmtr.Properties["name"].Value.ToString();
if (matcher.IsMatch(prmName))
{
returnList.Add(prmtr);
}
}
return returnList.ToArray();
}
#endregion
#region Cmdlet Help specific Properties
/// <summary>
/// Detailed Description string of this cmdlet help info.
/// </summary>
internal string DetailedDescription
{
get
{
if (this.FullHelp == null)
return string.Empty;
if (this.FullHelp.Properties["Description"] == null ||
this.FullHelp.Properties["Description"].Value == null)
{
return string.Empty;
}
object[] descriptionItems = (object[])LanguagePrimitives.ConvertTo(
this.FullHelp.Properties["Description"].Value,
typeof(object[]),
CultureInfo.InvariantCulture);
if (descriptionItems == null || descriptionItems.Length == 0)
{
return string.Empty;
}
// I think every cmdlet description should atleast have 400 characters...
// so starting with this assumption..I did an average of all the cmdlet
// help content available at the time of writing this code and came up
// with this number.
StringBuilder result = new StringBuilder(400);
foreach (object descriptionItem in descriptionItems)
{
if (descriptionItem == null)
{
continue;
}
PSObject descriptionObject = PSObject.AsPSObject(descriptionItem);
if ((descriptionObject == null) ||
(descriptionObject.Properties["Text"] == null) ||
(descriptionObject.Properties["Text"].Value == null))
{
continue;
}
string text = descriptionObject.Properties["Text"].Value.ToString();
result.Append(text);
result.Append(Environment.NewLine);
}
return result.ToString().Trim();
}
}
#endregion
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using SharpNeat.Core;
using SharpNeat.Phenomes;
using SharpNeat.DomainsExtra.SinglePoleBalancingBox2d;
namespace SharpNeat.DomainsExtra.SinglePoleBalancingSwingUp
{
/// <summary>
/// Evaluator for the single pole balancing task.
/// </summary>
public class SinglePoleBalancingSwingUpEvaluator : IPhenomeEvaluator<IBlackBox>
{
#region Constants
const float __TrackLength = 4.8f;
const float __TrackLengthHalf = __TrackLength * 0.5f;
const float __MaxForceNewtons = 100f;
const float __MaxForceNewtonsX2 = __MaxForceNewtons * 2f;
// Some precalced angle constants.
const float __SixDegrees = (float)(Math.PI / 30.0); //= 0.1047192;
const float __TwelveDegrees = (float)(Math.PI / 15.0); //= 0.2094384;
const float __180Degrees = (float)(Math.PI / 2.0);
#endregion
#region Instance Fields
int _maxTimestepsPhase1;
int _maxTimestepsPhase2;
float _poleAngleInitial;
// Evaluator state.
ulong _evalCount;
#endregion
#region Constructors
/// <summary>
/// Construct evaluator with default task arguments/variables.
/// </summary>
public SinglePoleBalancingSwingUpEvaluator() : this(450, 10800, (float)Math.PI)
{}
/// <summary>
/// Construct evaluator with the provided task arguments/variables.
/// </summary>
public SinglePoleBalancingSwingUpEvaluator(int maxTimestepsPhase1, int maxTimestepsPhase2, float poleAngleInitial)
{
_maxTimestepsPhase1 = maxTimestepsPhase1;
_maxTimestepsPhase2 = maxTimestepsPhase2;
_poleAngleInitial = poleAngleInitial;
}
#endregion
#region IPhenomeEvaluator<IBlackBox> Members
/// <summary>
/// Gets the total number of evaluations that have been performed.
/// </summary>
public ulong EvaluationCount
{
get { return _evalCount; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that
/// the the evolutionary algorithm/search should stop. This property's value can remain false
/// to allow the algorithm to run indefinitely.
/// </summary>
public bool StopConditionSatisfied
{
get { return false; }
}
/// <summary>
/// Evaluate the provided IBlackBox.
/// </summary>
public FitnessInfo Evaluate(IBlackBox box)
{
_evalCount++;
double fitness1 = Evaluate_Phase1_SwingUp(box);
//double fitness2 = Evaluate_Phase2_Balancing(box);
//double fitness = fitness1 * fitness2;
return new FitnessInfo(fitness1, fitness1);
}
/// <summary>
/// Reset the internal state of the evaluation scheme if any exists.
/// </summary>
public void Reset()
{
}
#endregion
#region Private Methods
private double Evaluate_Phase1_SwingUp(IBlackBox box)
{
// Init sim world. We add extra length to the track to allow cart to overshoot, we then detect overshooting by monitoring the cart's X position
// (this is just simpler and more robust than detecting if the cart has hit the ends of the track exactly).
SinglePoleBalancingWorld simWorld = new SinglePoleBalancingWorld(__TrackLength + 0.5f, __180Degrees);
simWorld.InitSimulationWorld();
// Record closest approach to target state and the timestep that it occured on.
double lowestError = double.MaxValue;
int timestepLowest = 0;
// Run the pole-balancing simulation.
int timestep = 0;
for(; timestep < _maxTimestepsPhase1; timestep++)
{
SimulateOneStep(simWorld, box);
// Calc state distance from target state.
double cartPosError = Math.Abs(simWorld.CartPosX);
double cartVelocityError = Math.Abs(simWorld.CartVelocityX);
double poleAngleError = Math.Abs(simWorld.PoleAngle);
double poleAnglularVelocityError = Math.Abs(simWorld.PoleAngularVelocity);
double error = (poleAngleError) + (poleAnglularVelocityError) + (cartPosError);
// Check for failure state. Has the cart run off the ends of the track.
if((simWorld.CartPosX < -__TrackLengthHalf) || (simWorld.CartPosX > __TrackLengthHalf)) {
return 0.0;
}
// Track best state achieved.
if(error < lowestError)
{
lowestError = error;
timestepLowest = timestep;
}
}
if(0.0 == lowestError) {
return 10e9;
}
// Alternative form of 1/x that avoids rapid rise to infinity as lowestError tends towards zero.
return Math.Log10(1.0 + (1/(lowestError + 0.1)));
}
private double Evaluate_Phase2_Balancing(IBlackBox box)
{
// Init sim world. We add extra length to the track to allow cart to overshoot, we then detect overshooting by monitoring the cart's X position
// (this is just simpler and more robust than detecting if the cart has hit the ends of the track exactly).
SinglePoleBalancingWorld simWorld = new SinglePoleBalancingWorld(__TrackLength + 0.5f, __SixDegrees);
simWorld.InitSimulationWorld();
// Run the pole-balancing simulation.
int timestep = 0;
for(; timestep < _maxTimestepsPhase2; timestep++)
{
SimulateOneStep(simWorld, box);
// Check for failure state. Has the cart run off the ends of the track or has the pole
// angle gone beyond the threshold.
if( (simWorld.CartPosX < -__TrackLengthHalf) || (simWorld.CartPosX > __TrackLengthHalf)
|| (simWorld.PoleAngle > __TwelveDegrees) || (simWorld.PoleAngle < -__TwelveDegrees))
{
break;
}
}
return timestep;
}
private void SimulateOneStep(SinglePoleBalancingWorld simWorld, IBlackBox box)
{
// Provide state info to the black box inputs.
box.InputSignalArray[0] = simWorld.CartPosX / __TrackLengthHalf; // CartPosX range is +-trackLengthHalf. Here we normalize it to [-1,1].
box.InputSignalArray[1] = simWorld.CartVelocityX; // Cart track velocity x is typically +-0.75.
box.InputSignalArray[2] = simWorld.PoleAngle / __TwelveDegrees; // Rescale angle to match range of values during balancing.
box.InputSignalArray[3] = simWorld.PoleAngularVelocity; // Pole angular velocity is typically +-1.0 radians. No scaling required.
// Activate the network.
box.Activate();
// Read the network's force signal output.
float force = (float)(box.OutputSignalArray[0] - 0.5f) * __MaxForceNewtonsX2;
// Simulate one timestep.
simWorld.SetCartForce(force);
simWorld.Step();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
using System.Globalization;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ParseRecord
{
// Enums
internal InternalParseTypeE _parseTypeEnum = InternalParseTypeE.Empty;
internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
internal InternalArrayTypeE _arrayTypeEnum = InternalArrayTypeE.Empty;
internal InternalMemberTypeE _memberTypeEnum = InternalMemberTypeE.Empty;
internal InternalMemberValueE _memberValueEnum = InternalMemberValueE.Empty;
internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty;
// Object
internal string _name;
// Value
internal string _value;
internal object _varValue;
// dt attribute
internal string _keyDt;
internal Type _dtType;
internal InternalPrimitiveTypeE _dtTypeCode;
// Object ID
internal long _objectId;
// Reference ID
internal long _idRef;
// Array
// Array Element Type
internal string _arrayElementTypeString;
internal Type _arrayElementType;
internal bool _isArrayVariant = false;
internal InternalPrimitiveTypeE _arrayElementTypeCode;
// Parsed array information
internal int _rank;
internal int[] _lengthA;
internal int[] _lowerBoundA;
// Array map for placing array elements in array
internal int[] _indexMap;
internal int _memberIndex;
internal int _linearlength;
internal int[] _rectangularMap;
internal bool _isLowerBound;
// MemberInfo accumulated during parsing of members
internal ReadObjectInfo _objectInfo;
// ValueType Fixup needed
internal bool _isValueTypeFixup = false;
// Created object
internal object _newObj;
internal object[] _objectA; //optimization, will contain object[]
internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization
internal bool _isRegistered; // Used when registering nested classes
internal object[] _memberData; // member data is collected here before populating
internal SerializationInfo _si;
internal int _consecutiveNullArrayEntryCount;
internal ParseRecord() { }
// Initialize ParseRecord. Called when reusing.
internal void Init()
{
// Enums
_parseTypeEnum = InternalParseTypeE.Empty;
_objectTypeEnum = InternalObjectTypeE.Empty;
_arrayTypeEnum = InternalArrayTypeE.Empty;
_memberTypeEnum = InternalMemberTypeE.Empty;
_memberValueEnum = InternalMemberValueE.Empty;
_objectPositionEnum = InternalObjectPositionE.Empty;
// Object
_name = null;
// Value
_value = null;
// dt attribute
_keyDt = null;
_dtType = null;
_dtTypeCode = InternalPrimitiveTypeE.Invalid;
// Object ID
_objectId = 0;
// Reference ID
_idRef = 0;
// Array
// Array Element Type
_arrayElementTypeString = null;
_arrayElementType = null;
_isArrayVariant = false;
_arrayElementTypeCode = InternalPrimitiveTypeE.Invalid;
// Parsed array information
_rank = 0;
_lengthA = null;
_lowerBoundA = null;
// Array map for placing array elements in array
_indexMap = null;
_memberIndex = 0;
_linearlength = 0;
_rectangularMap = null;
_isLowerBound = false;
// ValueType Fixup needed
_isValueTypeFixup = false;
_newObj = null;
_objectA = null;
_primitiveArray = null;
_objectInfo = null;
_isRegistered = false;
_memberData = null;
_si = null;
_consecutiveNullArrayEntryCount = 0;
}
}
// Implements a stack used for parsing
internal sealed class SerStack
{
internal object[] _objects = new object[5];
internal string _stackId;
internal int _top = -1;
internal SerStack(string stackId)
{
_stackId = stackId;
}
// Push the object onto the stack
internal void Push(object obj)
{
if (_top == (_objects.Length - 1))
{
IncreaseCapacity();
}
_objects[++_top] = obj;
}
// Pop the object from the stack
internal object Pop()
{
if (_top < 0)
{
return null;
}
object obj = _objects[_top];
_objects[_top--] = null;
return obj;
}
internal void IncreaseCapacity()
{
int size = _objects.Length * 2;
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
// Gets the object on the top of the stack
internal object Peek() => _top < 0 ? null : _objects[_top];
// Gets the second entry in the stack.
internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1];
// The number of entries in the stack
internal bool IsEmpty() => _top <= 0;
}
// Implements a Growable array
[Serializable]
internal sealed class SizedArray : ICloneable
{
internal object[] _objects = null;
internal object[] _negObjects = null;
internal SizedArray()
{
_objects = new object[16];
_negObjects = new object[4];
}
internal SizedArray(int length)
{
_objects = new object[length];
_negObjects = new object[length];
}
private SizedArray(SizedArray sizedArray)
{
_objects = new object[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new object[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new SizedArray(this);
internal object this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? null : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? null : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
object[] newItems = new object[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
object[] newItems = new object[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
[Serializable]
internal sealed class IntSizedArray : ICloneable
{
internal int[] _objects = new int[16];
internal int[] _negObjects = new int[4];
public IntSizedArray() { }
private IntSizedArray(IntSizedArray sizedArray)
{
_objects = new int[sizedArray._objects.Length];
sizedArray._objects.CopyTo(_objects, 0);
_negObjects = new int[sizedArray._negObjects.Length];
sizedArray._negObjects.CopyTo(_negObjects, 0);
}
public object Clone() => new IntSizedArray(this);
internal int this[int index]
{
get
{
if (index < 0)
{
return -index > _negObjects.Length - 1 ? 0 : _negObjects[-index];
}
else
{
return index > _objects.Length - 1 ? 0 : _objects[index];
}
}
set
{
if (index < 0)
{
if (-index > _negObjects.Length - 1)
{
IncreaseCapacity(index);
}
_negObjects[-index] = value;
}
else
{
if (index > _objects.Length - 1)
{
IncreaseCapacity(index);
}
_objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(_negObjects.Length * 2, (-index) + 1);
int[] newItems = new int[size];
Array.Copy(_negObjects, 0, newItems, 0, _negObjects.Length);
_negObjects = newItems;
}
else
{
int size = Math.Max(_objects.Length * 2, index + 1);
int[] newItems = new int[size];
Array.Copy(_objects, 0, newItems, 0, _objects.Length);
_objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(SR.Serialization_CorruptedStream);
}
}
}
internal sealed class NameCache
{
private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>();
private string _name = null;
internal object GetCachedValue(string name)
{
_name = name;
object value;
return s_ht.TryGetValue(name, out value) ? value : null;
}
internal void SetCachedValue(object value) => s_ht[_name] = value;
}
// Used to fixup value types. Only currently used for valuetypes which are array items.
internal sealed class ValueFixup
{
internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty;
internal Array _arrayObj;
internal int[] _indexMap;
internal object _header = null;
internal object _memberObject;
internal static volatile MemberInfo _valueInfo;
internal ReadObjectInfo _objectInfo;
internal string _memberName;
internal ValueFixup(Array arrayObj, int[] indexMap)
{
_valueFixupEnum = ValueFixupEnum.Array;
_arrayObj = arrayObj;
_indexMap = indexMap;
}
internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo)
{
_valueFixupEnum = ValueFixupEnum.Member;
_memberObject = memberObject;
_memberName = memberName;
_objectInfo = objectInfo;
}
internal void Fixup(ParseRecord record, ParseRecord parent)
{
object obj = record._newObj;
switch (_valueFixupEnum)
{
case ValueFixupEnum.Array:
_arrayObj.SetValue(obj, _indexMap);
break;
case ValueFixupEnum.Header:
Type type = typeof(Header);
if (_valueInfo == null)
{
MemberInfo[] valueInfos = type.GetMember("Value");
if (valueInfos.Length != 1)
{
throw new SerializationException(SR.Format(SR.Serialization_HeaderReflection, valueInfos.Length));
}
_valueInfo = valueInfos[0];
}
FormatterServices.SerializationSetValue(_valueInfo, _header, obj);
break;
case ValueFixupEnum.Member:
if (_objectInfo._isSi)
{
_objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId);
}
else
{
MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName);
if (memberInfo != null)
{
_objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId);
}
}
break;
}
}
}
// Class used to transmit Enums from the XML and Binary Formatter class to the ObjectWriter and ObjectReader class
internal sealed class InternalFE
{
internal FormatterTypeStyle _typeFormat;
internal FormatterAssemblyStyle _assemblyFormat;
internal TypeFilterLevel _securityLevel;
internal InternalSerializerTypeE _serializerTypeEnum;
}
internal sealed class NameInfo
{
internal string _fullName; // Name from SerObjectInfo.GetType
internal long _objectId;
internal long _assemId;
internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
internal Type _type;
internal bool _isSealed;
internal bool _isArray;
internal bool _isArrayItem;
internal bool _transmitTypeOnObject;
internal bool _transmitTypeOnMember;
internal bool _isParentTypeOnObject;
internal InternalArrayTypeE _arrayEnum;
private bool _sealedStatusChecked = false;
internal NameInfo() { }
internal void Init()
{
_fullName = null;
_objectId = 0;
_assemId = 0;
_primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
_type = null;
_isSealed = false;
_transmitTypeOnObject = false;
_transmitTypeOnMember = false;
_isParentTypeOnObject = false;
_isArray = false;
_isArrayItem = false;
_arrayEnum = InternalArrayTypeE.Empty;
_sealedStatusChecked = false;
}
public bool IsSealed
{
get
{
if (!_sealedStatusChecked)
{
_isSealed = _type.GetTypeInfo().IsSealed;
_sealedStatusChecked = true;
}
return _isSealed;
}
}
public string NIname
{
get { return _fullName ?? (_fullName = _type.FullName); }
set { _fullName = value; }
}
}
internal sealed class PrimitiveArray
{
private InternalPrimitiveTypeE _code;
private bool[] _booleanA = null;
private char[] _charA = null;
private double[] _doubleA = null;
private short[] _int16A = null;
private int[] _int32A = null;
private long[] _int64A = null;
private sbyte[] _sbyteA = null;
private float[] _singleA = null;
private ushort[] _uint16A = null;
private uint[] _uint32A = null;
private ulong[] _uint64A = null;
internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
{
_code = code;
switch (code)
{
case InternalPrimitiveTypeE.Boolean: _booleanA = (bool[])array; break;
case InternalPrimitiveTypeE.Char: _charA = (char[])array; break;
case InternalPrimitiveTypeE.Double: _doubleA = (double[])array; break;
case InternalPrimitiveTypeE.Int16: _int16A = (short[])array; break;
case InternalPrimitiveTypeE.Int32: _int32A = (int[])array; break;
case InternalPrimitiveTypeE.Int64: _int64A = (long[])array; break;
case InternalPrimitiveTypeE.SByte: _sbyteA = (sbyte[])array; break;
case InternalPrimitiveTypeE.Single: _singleA = (float[])array; break;
case InternalPrimitiveTypeE.UInt16: _uint16A = (ushort[])array; break;
case InternalPrimitiveTypeE.UInt32: _uint32A = (uint[])array; break;
case InternalPrimitiveTypeE.UInt64: _uint64A = (ulong[])array; break;
}
}
internal void SetValue(string value, int index)
{
switch (_code)
{
case InternalPrimitiveTypeE.Boolean:
_booleanA[index] = bool.Parse(value);
break;
case InternalPrimitiveTypeE.Char:
if ((value[0] == '_') && (value.Equals("_0x00_")))
{
_charA[index] = char.MinValue;
}
else
{
_charA[index] = char.Parse(value);
}
break;
case InternalPrimitiveTypeE.Double:
_doubleA[index] = double.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int16:
_int16A[index] = short.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int32:
_int32A[index] = int.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int64:
_int64A[index] = long.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.SByte:
_sbyteA[index] = sbyte.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Single:
_singleA[index] = float.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt16:
_uint16A[index] = ushort.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt32:
_uint32A[index] = uint.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt64:
_uint64A[index] = ulong.Parse(value, CultureInfo.InvariantCulture);
break;
}
}
}
}
| |
//
// MRClearing.cs
//
// Author:
// Steve Jakab <>
//
// Copyright (c) 2014 Steve Jakab
//
// 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 UnityEngine;
using System.Collections;
using System.Collections.Generic;
using AssemblyCSharp;
namespace PortableRealm
{
public class MRClearing : MonoBehaviour, MRILocation, MRITouchable
{
#region Constants
public enum eType
{
Woods,
Cave,
Mountain,
}
#endregion
#region Properties
public int clearingNumber;
public eType type;
// MRILocation properties
public GameObject Owner
{
get{
return gameObject;
}
}
public uint Id
{
get{
return MRUtility.IdForName(Name);
}
}
public string Name
{
get {
return MyTileSide.ShortName + (clearingNumber + 1);
}
}
public ICollection<MRRoad> Roads
{
get {
return mRoads;
}
}
public MRTileSide MyTileSide
{
get {
return mMyTileSide;
}
set {
mMyTileSide = value;
}
}
public MRGamePieceStack Pieces
{
get {
return mPieces;
}
}
public MRGamePieceStack AbandonedItems
{
get {
return mAbandonedItems;
}
}
public virtual IList<MRGame.eMagicColor> MagicSupplied
{
get{
HashSet<MRGame.eMagicColor> magicSupplied = new HashSet<MRGame.eMagicColor>();
foreach (var color in MRGame.TheGame.WorldMagic)
{
magicSupplied.Add(color);
}
foreach (var color in MyTileSide.MagicSupplied)
{
magicSupplied.Add(color);
}
// borderlands supplies magic on a per-clearing basis
// @todo make this data driven
if (MyTileSide.Tile.Id == MRMap.eTileNames.borderland && MyTileSide.type == MRTileSide.eType.Enchanted)
{
switch (clearingNumber)
{
case 1:
magicSupplied.Add(MRGame.eMagicColor.Grey);
break;
case 2:
case 3:
magicSupplied.Add(MRGame.eMagicColor.Gold);
break;
case 4:
case 5:
magicSupplied.Add(MRGame.eMagicColor.Purple);
break;
case 6:
magicSupplied.Add(MRGame.eMagicColor.Grey);
magicSupplied.Add(MRGame.eMagicColor.Gold);
magicSupplied.Add(MRGame.eMagicColor.Purple);
break;
default:
Debug.LogError("MagicSupplied invalid Borderlands clearing");
break;
}
}
foreach (var item in mPieces.Pieces)
{
if (item is MRIColorSource)
{
foreach (var color in ((MRIColorSource)item).MagicSupplied)
{
magicSupplied.Add(color);
}
}
}
return new List<MRGame.eMagicColor>(magicSupplied);
}
}
#endregion
#region Methods
// Called when the script instance is being loaded
void Awake()
{
mPieces = gameObject.AddComponent<MRGamePieceStack>();
mAbandonedItems = gameObject.AddComponent<MRGamePieceStack>();
MRGame.TheGame.AddClearing(this);
}
// Use this for initialization
void Start ()
{
GetComponent<Renderer>().enabled = false;
mPieces.Layer = LayerMask.NameToLayer("Map");
mPieces.transform.parent = transform;
mPieces.transform.position = transform.position;
mPieces.StackScale = 1.0f / transform.localScale.x;
mPieces.Name = Name.Substring(1);
mAbandonedItems.Layer = LayerMask.NameToLayer("Map");
mAbandonedItems.transform.parent = transform;
mAbandonedItems.transform.position = transform.position;
mPieces.Name = Name.Substring(1);
mMapCamera = MRGame.TheGame.TheMap.MapCamera;
}
void OnDestroy()
{
//Debug.LogWarning("Destroy clearing " + Name);
MRGame.TheGame.RemoveClearing(this);
}
// Update is called once per frame
void Update ()
{
}
public bool OnTouched(GameObject touchedObject)
{
return true;
}
public bool OnReleased(GameObject touchedObject)
{
return true;
}
public bool OnSingleTapped(GameObject touchedObject)
{
return true;
}
public bool OnDoubleTapped(GameObject touchedObject)
{
if (touchedObject == gameObject)
{
Debug.Log("Clearing selected: " + Name);
SendMessageUpwards("OnClearingSelectedGame", this, SendMessageOptions.DontRequireReceiver);
}
return true;
}
public bool OnTouchHeld(GameObject touchedObject)
{
if (mMyTileSide.Tile.Front == mMyTileSide.type && mPieces.Count > 0)
{
if (!mPieces.Inspecting)
MRGame.TheGame.InspectStack(mPieces);
else
MRGame.TheGame.InspectStack(null);
}
return true;
}
public bool OnTouchMove(GameObject touchedObject, float delta_x, float delta_y)
{
return true;
}
public bool OnButtonActivate(GameObject touchedObject)
{
return true;
}
public bool OnPinchZoom(float pinchDelta)
{
MRGame.TheGame.TheMap.OnPinchZoom(pinchDelta);
return true;
}
/// <summary>
/// Returns the road connecting this location to another location, or null if the locations aren't connected.
/// </summary>
/// <returns>The road.</returns>
/// <param name="clearing">Clearing.</param>
public MRRoad RoadTo(MRILocation target)
{
foreach (MRRoad road in mRoads)
{
if ((road.clearingConnection0 == this && road.clearingConnection1 != null && road.clearingConnection1.Id == target.Id) ||
(road.clearingConnection1 == this && road.clearingConnection0 != null && road.clearingConnection0.Id == target.Id))
{
return road;
}
}
return null;
}
/// <summary>
/// Adds a piece to the top of the location.
/// </summary>
/// <param name="piece">the piece</param>
public void AddPieceToTop(MRIGamePiece piece)
{
Pieces.AddPieceToTop(piece);
}
/// <summary>
/// Adds a piece to the bottom of the location.
/// </summary>
/// <param name="piece">the piece</param>
public void AddPieceToBottom(MRIGamePiece piece)
{
Pieces.AddPieceToBottom(piece);
}
/// <summary>
/// Removes a piece from the location.
/// </summary>
/// <param name="piece">the piece to remove</param>
public void RemovePiece(MRIGamePiece piece)
{
Pieces.RemovePiece(piece);
}
public void AddRoad(MRRoad road)
{
mRoads.Add(road);
}
public bool Load(JSONObject root)
{
if (root["id"] != null)
{
if (Id != ((JSONNumber)root["id"]).UintValue)
return false;
}
else
{
// todo: check for tile and clearing number
}
if (root["pieces"] != null)
{
if (!mPieces.Load((JSONObject)root["pieces"]))
return false;
}
if (root["items"] != null)
{
if (!mAbandonedItems.Load((JSONObject)root["items"]))
return false;
}
// make sure controllable locations are set
List<MRControllable> controllables = new List<MRControllable>();
foreach (MRIGamePiece piece in mPieces.Pieces)
{
if (piece is MRControllable)
controllables.Add((MRControllable)piece);
}
foreach (MRControllable controllable in controllables)
{
if (controllable.Location == null || controllable.Location.Id != Id)
controllable.Location = this;
}
return true;
}
public void Save(JSONObject root)
{
root["id"] = new JSONNumber(Id);
root["set"] = new JSONNumber(1); // this is in anticipation of multi-set boards
JSONObject pieces = new JSONObject();
mPieces.Save(pieces);
root["pieces"] = pieces;
JSONObject items = new JSONObject();
mAbandonedItems.Save(items);
root["items"] = items;
}
#endregion
#region Members
private ICollection<MRRoad> mRoads = new List<MRRoad>();
private MRTileSide mMyTileSide;
private Camera mMapCamera;
private MRGamePieceStack mPieces;
private MRGamePieceStack mAbandonedItems;
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
[ParallelFixture]
public class LongKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStackAlloc()
{
VerifyKeyword(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOuterConst()
{
VerifyKeyword(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInnerConst()
{
VerifyKeyword(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFixedStatement()
{
VerifyKeyword(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDelegateReturnType()
{
VerifyKeyword(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType2()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void EnumBaseTypes()
{
VerifyKeyword(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType1()
{
VerifyKeyword(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType2()
{
VerifyKeyword(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType3()
{
VerifyKeyword(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType4()
{
VerifyKeyword(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInBaseList()
{
VerifyAbsence(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType_InBaseList()
{
VerifyKeyword(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideInterface()
{
VerifyKeyword(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPartial()
{
VerifyAbsence(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAbstract()
{
VerifyKeyword(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStaticPublic()
{
VerifyKeyword(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublicStatic()
{
VerifyKeyword(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterVirtualPublic()
{
VerifyKeyword(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublic()
{
VerifyKeyword(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPrivate()
{
VerifyKeyword(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedProtected()
{
VerifyKeyword(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedSealed()
{
VerifyKeyword(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStatic()
{
VerifyKeyword(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InLocalVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForeachVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InUsingVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFromVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InJoinVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodOpenParen()
{
VerifyKeyword(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodComma()
{
VerifyKeyword(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodAttribute()
{
VerifyKeyword(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorOpenParen()
{
VerifyKeyword(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorComma()
{
VerifyKeyword(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorAttribute()
{
VerifyKeyword(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateOpenParen()
{
VerifyKeyword(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateComma()
{
VerifyKeyword(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateAttribute()
{
VerifyKeyword(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterThis()
{
VerifyKeyword(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRef()
{
VerifyKeyword(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut()
{
VerifyKeyword(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaRef()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaOut()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterParams()
{
VerifyKeyword(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InImplicitOperator()
{
VerifyKeyword(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExplicitOperator()
{
VerifyKeyword(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracket()
{
VerifyKeyword(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracketComma()
{
VerifyKeyword(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNewInExpression()
{
VerifyKeyword(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InTypeOf()
{
VerifyKeyword(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDefault()
{
VerifyKeyword(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InSizeOf()
{
VerifyKeyword(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContext()
{
VerifyKeyword(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContextNotAfterDot()
{
VerifyAbsence(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAsync()
{
VerifyKeyword(@"class c { async $$ }");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAsyncAsType()
{
VerifyAbsence(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCrefTypeParameter()
{
VerifyAbsence(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Lens.Compiler;
using Lens.Translations;
using Lens.Utils;
namespace Lens.Resolver
{
/// <summary>
/// A collection of helpful methods for types.
/// </summary>
internal static class TypeExtensions
{
#region Static constructor
static TypeExtensions()
{
SignedIntegerTypes = new[]
{
typeof(sbyte),
typeof(short),
typeof(int),
typeof(long)
};
UnsignedIntegerTypes = new[]
{
typeof(byte),
typeof(ushort),
typeof(uint),
typeof(ulong),
};
FloatTypes = new[]
{
typeof(float),
typeof(double),
typeof(decimal)
};
DistanceCache = new Dictionary<Tuple<Type, Type, bool>, int>();
}
#endregion
#region Fields
public static readonly Type[] SignedIntegerTypes;
public static readonly Type[] UnsignedIntegerTypes;
public static readonly Type[] FloatTypes;
private static readonly Dictionary<Tuple<Type, Type, bool>, int> DistanceCache;
#endregion
#region Type class checking
/// <summary>
/// Checks if a type is a <see cref="Nullable{T}"/>.
/// </summary>
/// <param name="type">Checked type.</param>
/// <returns><c>true</c> if type is a <see cref="Nullable{T}"/>.</returns>
public static bool IsNullableType(this Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
/// <summary>
/// Checks if a type is a signed integer type.
/// </summary>
public static bool IsSignedIntegerType(this Type type)
{
return SignedIntegerTypes.Contains(type);
}
/// <summary>
/// Checks if a type is an unsigned integer type.
/// </summary>
public static bool IsUnsignedIntegerType(this Type type)
{
return UnsignedIntegerTypes.Contains(type);
}
/// <summary>
/// Checks if a type is a floating point type.
/// </summary>
public static bool IsFloatType(this Type type)
{
return FloatTypes.Contains(type);
}
/// <summary>
/// Checks if a type is any of integer types, signed or unsigned.
/// </summary>
public static bool IsIntegerType(this Type type)
{
return type.IsSignedIntegerType() || type.IsUnsignedIntegerType();
}
/// <summary>
/// Checks if a type is any of the numeric types.
/// </summary>
public static bool IsNumericType(this Type type, bool allowNonPrimitives = false)
{
if (!allowNonPrimitives && type == typeof(decimal))
return false;
return type.IsSignedIntegerType() || type.IsUnsignedIntegerType() || type.IsFloatType();
}
/// <summary>
/// Checks if the type is void.
/// </summary>
public static bool IsVoid(this Type type)
{
return type == typeof(void) || type == typeof(UnitType);
}
/// <summary>
/// Checks if the type is a struct.
/// </summary>
public static bool IsStruct(this Type type)
{
return type.IsValueType && !type.IsNumericType();
}
/// <summary>
/// Checks if type is actually boolean or can be implicitly casted to boolean.
/// </summary>
public static bool IsImplicitlyBoolean(this Type type)
{
return type == typeof(bool) || type.GetMethods().Any(m => m.Name == "op_Implicit" && m.ReturnType == typeof(bool));
}
/// <summary>
/// Returns T for Nullable<T>, or null if the type is not Nullable.
/// </summary>
public static Type GetNullableUnderlyingType(this Type type)
{
return type.IsNullableType() ? type.GetGenericArguments()[0] : null;
}
#endregion
#region Type distance
/// <summary>
/// Checks if a variable of given type can be assigned from other type (including type extension).
/// </summary>
/// <param name="varType">Type of assignment target (ex. variable)</param>
/// <param name="exprType">Type of assignment source (ex. expression)</param>
/// <param name="exactly">Checks whether types must be compatible as-is, or additional code may be implicitly issued by the compiler.</param>
/// <returns></returns>
public static bool IsExtendablyAssignableFrom(this Type varType, Type exprType, bool exactly = false)
{
return varType.DistanceFrom(exprType, exactly) < int.MaxValue;
}
/// <summary>
/// Gets distance between two types.
/// This method is memoized.
/// </summary>
public static int DistanceFrom(this Type varType, Type exprType, bool exactly = false)
{
var key = new Tuple<Type, Type, bool>(varType, exprType, exactly);
if (!DistanceCache.ContainsKey(key))
DistanceCache.Add(key, distanceFrom(varType, exprType, exactly));
return DistanceCache[key];
}
/// <summary>
/// Calculates the distance between two types.
/// </summary>
private static int distanceFrom(Type varType, Type exprType, bool exactly = false)
{
if (varType == exprType)
return 0;
// partial application
if (exprType == typeof(UnspecifiedType))
return 0;
if (varType.IsByRef)
return varType.GetElementType() == exprType ? 0 : int.MaxValue;
if (!exactly)
{
if (varType.IsNullableType() && exprType == Nullable.GetUnderlyingType(varType))
return 1;
if ((varType.IsClass || varType.IsNullableType()) && exprType == typeof(NullType))
return 1;
if (varType.IsNumericType(true) && exprType.IsNumericType(true))
return NumericTypeConversion(varType, exprType);
}
if (varType == typeof(object))
{
if (exprType.IsValueType)
return exactly ? int.MaxValue : 1;
if (exprType.IsInterface)
return 1;
}
if (varType.IsInterface)
{
var idist = InterfaceDistance(varType, exprType.ResolveInterfaces());
if (idist != int.MaxValue)
return idist;
}
if (varType.IsGenericParameter || exprType.IsGenericParameter)
return GenericParameterDistance(varType, exprType);
if (exprType.IsLambdaType())
return LambdaDistance(varType, exprType);
if (varType.IsGenericType && exprType.IsGenericType)
return GenericDistance(varType, exprType);
if (IsDerivedFrom(exprType, varType, out int result))
return result;
if (varType.IsArray && exprType.IsArray)
{
var varElType = varType.GetElementType();
var exprElType = exprType.GetElementType();
var areRefs = !varElType.IsValueType && !exprElType.IsValueType;
var generic = varElType.IsGenericParameter || exprElType.IsGenericParameter;
if (areRefs || generic)
return varElType.DistanceFrom(exprElType, exactly);
}
return int.MaxValue;
}
/// <summary>
/// Calculates the distance to any of given interfaces.
/// </summary>
private static int InterfaceDistance(Type interfaceType, IEnumerable<Type> ifaces, bool exactly = false)
{
var min = int.MaxValue;
foreach (var iface in ifaces)
{
if (iface == interfaceType)
return 1;
if (interfaceType.IsGenericType && iface.IsGenericType)
{
var dist = GenericDistance(interfaceType, iface, exactly);
if (dist < min)
min = dist;
}
}
return min;
}
/// <summary>
/// Checks if a type is a child for some other type.
/// </summary>
private static bool IsDerivedFrom(Type derivedType, Type baseType, out int distance)
{
distance = 0;
var current = derivedType;
while (current != null && current != baseType)
{
current = current.BaseType;
++distance;
}
return current == baseType;
}
/// <summary>
/// Calculates compound distance of two generic types' arguments if applicable.
/// </summary>
private static int GenericDistance(Type varType, Type exprType, bool exactly = false)
{
var definition = varType.GetGenericTypeDefinition();
if (definition != exprType.GetGenericTypeDefinition())
return int.MaxValue;
var arguments = definition.GetGenericArguments();
var arguments1 = varType.GetGenericArguments();
var arguments2 = exprType.GetGenericArguments();
var result = 0;
for (var i = 0; i < arguments1.Length; ++i)
{
var argument1 = arguments1[i];
var argument2 = arguments2[i];
if (argument1 == argument2)
continue;
var argument = arguments[i];
var attributes = argument.GenericParameterAttributes;
int conversionResult;
if (argument1.IsGenericParameter)
{
// generic parameter may be substituted with anything
// including value types
conversionResult = GenericParameterDistance(argument1, argument2, exactly);
}
else if (argument2.IsGenericParameter)
{
conversionResult = GenericParameterDistance(argument2, argument1, exactly);
}
else if (attributes.HasFlag(GenericParameterAttributes.Contravariant))
{
// generic variance applies to ref-types only
if (argument1.IsValueType)
return int.MaxValue;
// dist(X<in T1>, X<in T2>) = dist(T2, T1)
conversionResult = argument2.DistanceFrom(argument1, exactly);
}
else if (attributes.HasFlag(GenericParameterAttributes.Covariant))
{
if (argument2.IsValueType)
return int.MaxValue;
// dist(X<out T1>, X<out T2>) = dist(T1, T2)
conversionResult = argument1.DistanceFrom(argument2, exactly);
}
else if (argument1.IsGenericType && argument2.IsGenericType)
{
// nested generic types
conversionResult = GenericDistance(argument1, argument2, exactly);
}
else
{
// No possible conversion found.
return int.MaxValue;
}
if (conversionResult == int.MaxValue)
return int.MaxValue;
checked
{
result += conversionResult;
}
}
return result;
}
/// <summary>
/// Checks if a type can be used as a substitute for a generic parameter.
/// </summary>
private static int GenericParameterDistance(Type varType, Type exprType, bool exactly = false)
{
// generic parameter is on the same level of inheritance as the expression
// therefore getting its parent type does not take a step
var dist = varType.IsGenericParameter
? DistanceFrom(varType.BaseType, exprType, exactly)
: DistanceFrom(exprType.BaseType, varType, exactly);
return dist == int.MaxValue ? dist : dist + 1;
}
/// <summary>
/// Checks if a lambda signature matches a delegate.
/// </summary>
private static int LambdaDistance(Type varType, Type exprType)
{
if (!varType.IsCallableType())
return int.MaxValue;
var varWrapper = ReflectionHelper.WrapDelegate(varType);
var exprWrapper = ReflectionHelper.WrapDelegate(exprType);
if (varWrapper.ArgumentTypes.Length != exprWrapper.ArgumentTypes.Length)
return int.MaxValue;
// return type is not checked until lambda argument types are substituted
var sum = 0;
for (var idx = 0; idx < varWrapper.ArgumentTypes.Length; idx++)
{
var currVar = varWrapper.ArgumentTypes[idx];
var currExpr = exprWrapper.ArgumentTypes[idx];
var dist = currVar.DistanceFrom(currExpr);
if (dist == int.MaxValue)
return int.MaxValue;
sum += dist;
}
return sum;
}
#endregion
#region Most common type
/// <summary>
/// Gets the most common type that all the given types would fit into.
/// </summary>
public static Type GetMostCommonType(this Type[] types)
{
if (types.Length == 0)
return null;
if (types.Length == 1)
return types[0];
// try to get the most wide type
Type curr = null;
foreach (var type in types)
{
if (type.IsVoid())
throw new LensCompilerException(CompilerMessages.NoCommonType);
curr = GetMostCommonType(curr, type);
if (curr == typeof(object))
break;
}
// check for cases that are not transitively castable
// for example: new [1; 1.2; null]
// int -> double is fine, double -> Nullable<double> is fine as well
// but int -> Nullable<double> is currently forbidden
foreach (var type in types)
{
if (!curr.IsExtendablyAssignableFrom(type))
{
curr = typeof(object);
break;
}
}
if (!curr.IsAnyOf(typeof(object), typeof(ValueType), typeof(Delegate), typeof(Enum)))
return curr;
// try to get common interfaces
var ifaces = types[0].GetInterfaces().AsEnumerable().ToList();
for (var idx = 1; idx < types.Length; idx++)
{
var newIfaces = types[idx].IsInterface ? new[] {types[idx]} : types[idx].GetInterfaces();
ifaces = ifaces.Intersect(newIfaces).ToList();
if (!ifaces.Any())
break;
}
var iface = GetMostSpecificInterface(ifaces);
return iface ?? typeof(object);
}
/// <summary>
/// Gets the most common type between two.
/// </summary>
private static Type GetMostCommonType(Type left, Type right)
{
// corner case
if (left == null || left == right)
return right;
if (right.IsInterface)
return typeof(object);
// valuetype & null
if (left == typeof(NullType) && right.IsValueType)
return typeof(Nullable<>).MakeGenericType(right);
if (right == typeof(NullType) && left.IsValueType)
return typeof(Nullable<>).MakeGenericType(left);
// valuetype & Nullable<valuetype>
if (left.IsNullableType() && left.GetGenericArguments()[0] == right)
return left;
if (right.IsNullableType() && right.GetGenericArguments()[0] == left)
return right;
// numeric extensions
if (left.IsNumericType() && right.IsNumericType())
return GetNumericOperationType(left, right) ?? typeof(object);
// arrays
if (left.IsArray && right.IsArray)
{
var leftElem = left.GetElementType();
var rightElem = right.GetElementType();
return leftElem.IsValueType || rightElem.IsValueType
? typeof(object)
: GetMostCommonType(leftElem, rightElem).MakeArrayType();
}
// inheritance
var currLeft = left;
while (currLeft != null)
{
var currRight = right;
while (currRight != null)
{
if (currLeft == currRight)
return currLeft;
currRight = currRight.BaseType;
}
currLeft = currLeft.BaseType;
}
return typeof(object);
}
/// <summary>
/// Finds the most specific interface from that contains all others.
/// </summary>
private static Type GetMostSpecificInterface(IEnumerable<Type> ifaces)
{
var remaining = ifaces.ToDictionary(i => i, i => true);
foreach (var iface in ifaces)
{
foreach (var curr in iface.GetInterfaces())
remaining.Remove(curr);
}
if (remaining.Count == 1)
return remaining.First().Key;
var preferred = new[] {typeof(IList<>), typeof(IEnumerable<>), typeof(IList)};
foreach (var pref in preferred)
{
foreach (var curr in remaining.Keys)
if (curr == pref || (curr.IsGenericType && curr.GetGenericTypeDefinition() == pref))
return curr;
}
return null;
}
#endregion
#region Numeric type conversions
/// <summary>
/// Get the best numeric operation type for two operands.
/// </summary>
/// <param name="type1">First operand type.</param>
/// <param name="type2">Second operand type.</param>
/// <returns>Operation type. <c>null</c> if operation not permitted.</returns>
public static Type GetNumericOperationType(Type type1, Type type2)
{
if (type1.IsFloatType() || type2.IsFloatType())
{
if (type1 == typeof(long) || type2 == typeof(long))
return typeof(double);
return WidestNumericType(FloatTypes, type1, type2);
}
if (type1.IsSignedIntegerType() && type2.IsSignedIntegerType())
{
var types = SignedIntegerTypes.SkipWhile(type => type != typeof(int)).ToArray();
return WidestNumericType(types, type1, type2);
}
if (type1.IsUnsignedIntegerType() && type2.IsUnsignedIntegerType())
{
var index1 = Array.IndexOf(UnsignedIntegerTypes, type1);
var index2 = Array.IndexOf(UnsignedIntegerTypes, type2);
var uintIndex = Array.IndexOf(UnsignedIntegerTypes, typeof(uint));
if (index1 < uintIndex && index2 < uintIndex)
return typeof(int);
return WidestNumericType(UnsignedIntegerTypes, type1, type2);
}
// type1.IsSignedIntegerType() && type2.IsUnsignedIntegerType() or vice versa:
return null;
}
private static Type WidestNumericType(Type[] types, Type type1, Type type2)
{
var index1 = Array.IndexOf(types, type1);
var index2 = Array.IndexOf(types, type2);
var index = Math.Max(index1, index2);
return types[index < 0 ? 0 : index];
}
private static int NumericTypeConversion(Type varType, Type exprType)
{
if (varType.IsSignedIntegerType() && exprType.IsSignedIntegerType())
return SimpleNumericConversion(varType, exprType, SignedIntegerTypes);
if (varType.IsUnsignedIntegerType() && exprType.IsUnsignedIntegerType())
return SimpleNumericConversion(varType, exprType, UnsignedIntegerTypes);
if (varType.IsFloatType() && exprType.IsFloatType())
return SimpleNumericConversion(varType, exprType, FloatTypes);
if (varType.IsSignedIntegerType() && exprType.IsUnsignedIntegerType())
return UnsignedToSignedConversion(varType, exprType);
if (varType.IsFloatType() && exprType.IsSignedIntegerType())
return SignedToFloatConversion(varType, exprType);
if (varType.IsFloatType() && exprType.IsUnsignedIntegerType())
return UnsignedToFloatConversion(varType, exprType);
return int.MaxValue;
}
private static int SimpleNumericConversion(Type varType, Type exprType, Type[] conversionChain)
{
var varTypeIndex = Array.IndexOf(conversionChain, varType);
var exprTypeIndex = Array.IndexOf(conversionChain, exprType);
if (varTypeIndex < exprTypeIndex)
return int.MaxValue;
return varTypeIndex - exprTypeIndex;
}
private static int UnsignedToSignedConversion(Type varType, Type exprType)
{
// no unsigned type can be converted to the signed byte.
if (varType == typeof(sbyte))
return int.MaxValue;
var index = Array.IndexOf(SignedIntegerTypes, varType);
var correspondingUnsignedType = UnsignedIntegerTypes[index - 1]; // only expanding conversions allowed
var result = SimpleNumericConversion(correspondingUnsignedType, exprType, UnsignedIntegerTypes);
return result == int.MaxValue
? int.MaxValue
: result + 1;
}
private static int SignedToFloatConversion(Type varType, Type exprType)
{
var targetType = GetCorrespondingSignedType(varType);
var result = SimpleNumericConversion(targetType, exprType, SignedIntegerTypes);
return result == int.MaxValue
? int.MaxValue
: result + 1;
}
private static int UnsignedToFloatConversion(Type varType, Type exprType)
{
if (exprType == typeof(ulong) && varType == typeof(decimal))
{
// ulong can be implicitly converted only to decimal.
return 1;
}
else
{
// If type is not ulong we need to convert it to the corresponding signed type.
var correspondingSignedType = GetCorrespondingSignedType(varType);
var result = UnsignedToSignedConversion(correspondingSignedType, exprType);
return result == int.MaxValue
? int.MaxValue
: result + 1;
}
}
private static Type GetCorrespondingSignedType(Type floatType)
{
if (floatType == typeof(float))
return typeof(int);
if (floatType == typeof(double) || floatType == typeof(decimal))
return typeof(long);
return null;
}
#endregion
#region Type list distance
/// <summary>
/// Gets total distance between two sets of argument types.
/// </summary>
public static MethodLookupResult<T> ArgumentDistance<T>(IEnumerable<Type> passedTypes, Type[] actualTypes, T method, bool isVariadic)
{
if (!isVariadic)
return new MethodLookupResult<T>(method, TypeListDistance(passedTypes, actualTypes), actualTypes);
var simpleCount = actualTypes.Length - 1;
var simpleDistance = TypeListDistance(passedTypes.Take(simpleCount), actualTypes.Take(simpleCount));
var variadicDistance = VariadicArgumentDistance(passedTypes.Skip(simpleCount), actualTypes[simpleCount]);
var distance = simpleDistance == int.MaxValue || variadicDistance == int.MaxValue ? int.MaxValue : simpleDistance + variadicDistance;
return new MethodLookupResult<T>(method, distance, actualTypes);
}
/// <summary>
/// Gets total distance between two sequence of types.
/// </summary>
public static int TypeListDistance(IEnumerable<Type> passedArgs, IEnumerable<Type> calleeArgs)
{
var passedIter = passedArgs.GetEnumerator();
var calleeIter = calleeArgs.GetEnumerator();
var totalDist = 0;
while (true)
{
var passedOk = passedIter.MoveNext();
var calleeOk = calleeIter.MoveNext();
// argument count differs: method cannot be applied
if (passedOk != calleeOk)
return int.MaxValue;
// both sequences have finished
if (!calleeOk)
return totalDist;
var dist = calleeIter.Current.DistanceFrom(passedIter.Current);
if (dist == int.MaxValue)
return int.MaxValue;
totalDist += dist;
}
}
/// <summary>
/// Calculates the compound distance of a list of arguments packed into a param array.
/// </summary>
private static int VariadicArgumentDistance(IEnumerable<Type> passedArgs, Type variadicArg)
{
var args = passedArgs.ToArray();
// variadic function invoked with an array: no conversion
if (args.Length == 1 && args[0] == variadicArg)
return 0;
var sum = 0;
var elemType = variadicArg.GetElementType();
foreach (var curr in args)
{
var currDist = elemType.DistanceFrom(curr);
if (currDist == int.MaxValue)
return int.MaxValue;
sum += currDist;
}
// 1 extra distance point for packing arguments into the array:
// otherwise fun(int) and fun(int, object[]) will have equal distance for `fun 1` and cause an ambiguity error
return sum + 1;
}
#endregion
#region Interface implementations and generic type applications
/// <summary>
/// Checks if a type implements an interface.
/// </summary>
/// <param name="type">Type to check.</param>
/// <param name="iface">Desired interface.</param>
/// <param name="unwindGenerics">A flag indicating that generic arguments should be discarded from both the type and the interface.</param>
public static bool Implements(this Type type, Type iface, bool unwindGenerics)
{
var ifaces = type.ResolveInterfaces();
if (type.IsInterface)
ifaces = ifaces.Union(new[] {type}).ToArray();
if (unwindGenerics)
{
for (var idx = 0; idx < ifaces.Length; idx++)
{
var curr = ifaces[idx];
if (curr.IsGenericType)
ifaces[idx] = curr.GetGenericTypeDefinition();
}
if (iface.IsGenericType)
iface = iface.GetGenericTypeDefinition();
}
return ifaces.Contains(iface);
}
/// <summary>
/// Finds an implementation of a generic interface.
/// </summary>
/// <param name="type">Type to find the implementation in.</param>
/// <param name="iface">Desirrable interface.</param>
/// <returns>Implementation of the generic interface or null if none.</returns>
public static Type ResolveImplementationOf(this Type type, Type iface)
{
if (iface.IsGenericType && !iface.IsGenericTypeDefinition)
iface = iface.GetGenericTypeDefinition();
var ifaces = type.ResolveInterfaces();
if (type.IsInterface)
ifaces = ifaces.Union(new[] {type}).ToArray();
return ifaces.FirstOrDefault(
x => x == iface || (x.IsGenericType && x.GetGenericTypeDefinition() == iface)
);
}
/// <summary>
/// Resolves the common implementation of the given interface for two types.
/// </summary>
/// <param name="iface">Interface to find an implementation for in given types.</param>
/// <param name="type1">First type to examine.</param>
/// <param name="type2">First type to examine.</param>
/// <returns>Common implementation of an interface, or null if none.</returns>
public static Type ResolveCommonImplementationFor(this Type iface, Type type1, Type type2)
{
var impl1 = type1.ResolveImplementationOf(iface);
var impl2 = type2.ResolveImplementationOf(iface);
return impl1 == impl2 ? impl1 : null;
}
/// <summary>
/// Checks if a type is (or implements) a specified type with any generic argument values given.
/// Example: Dictionary<A, B> is Dictionary`2
/// </summary>
/// <param name="type">Closed type to test.</param>
/// <param name="genericType">Generic type.</param>
public static bool IsAppliedVersionOf(this Type type, Type genericType)
{
if (type.IsInterface && !genericType.IsInterface)
throw new ArgumentException(string.Format("Interface {0} cannot implement a type! ({1} given).", type.FullName, genericType.FullName));
if (!type.IsGenericType || !genericType.IsGenericType)
return false;
return genericType.IsInterface
? type.Implements(genericType, true)
: type.GetGenericTypeDefinition() == genericType.GetGenericTypeDefinition();
}
#endregion
}
}
| |
using ReactNative.Bridge;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Sqlite;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text.RegularExpressions;
namespace RNSqlite2
{
class RNSqlite2Module : ReactContextNativeModuleBase
{
public RNSqlite2Module(ReactContext reactContext)
: base(reactContext)
{
this.reactContext = reactContext;
}
public override string Name
{
get
{
return "RNSqlite2";
}
}
private readonly ReactContext reactContext;
private static readonly bool DEBUG_MODE = false;
private static readonly string TAG = typeof(RNSqlite2Module).Name;
private static readonly List<object> EMPTY_ROWS = new List<object>();
private static readonly List<string> EMPTY_COLUMNS = new List<string>();
//protected Context context = null;
private static readonly SQLitePLuginResult EMPTY_RESULT = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null);
private static readonly Dictionary<string, SqliteConnection> DATABASES = new Dictionary<string, SqliteConnection>();
private static readonly Dictionary<string, SqliteTransaction> TRANSACTIONS = new Dictionary<string, SqliteTransaction>();
[ReactMethod]
public void test(string message, IPromise promise)
{
debug("example", "test called: " + message);
promise.Resolve(message + "\u0000" + "hoge");
}
private SqliteConnection getDatabase(string name)
{
if (!DATABASES.ContainsKey(name))
{
#if WINDOWS_UWP
string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, name);
#else
string path = Path.Combine(PCLStorage.FileSystem.Current.LocalStorage.Path, name);
#endif
SqliteConnection conn = new SqliteConnection("Filename=" + path);
DATABASES[name] = conn;
TRANSACTIONS[name] = null;
}
return DATABASES[name];
}
// TODO: Need improve . This function : command.Parameters.AddWithValue(item.Key, item.Value); don't support bind string by index or i missing something
private static void parseJsonArrayToParams(ref string sql, List<JToken> jsonArray, ref SqliteCommand statement)
{
MatchCollection matches = Regex.Matches(sql, @"\?");
Dictionary<string, string> array = new Dictionary<string, string>();
int len = matches.Count;
if (len > 0)
{
if (matches.Count > jsonArray.Count)
{
throw new Exception("parameter not correct");
}
var lastLen = 0;
for (int i = 0; i < len; i++)
{
var stringBuilder = new StringBuilder(sql);
stringBuilder.Remove(lastLen + matches[i].Index, 1);
stringBuilder.Insert(lastLen + matches[i].Index, "@" + i);
statement.Parameters.AddWithValue("@" + i, jsonArray[i].ToString());
lastLen += i.ToString().Length;
sql = stringBuilder.ToString();
}
}
else
{
// This is old code handle txn.executeSql('INSERT INTO Users (name) VALUES (:name)', ['narumiya'])
matches = Regex.Matches(sql, @"\:([A-Za-z0-9]*)");
len = matches.Count;
if (matches.Count > jsonArray.Count)
{
throw new Exception("parameter not correct");
}
for (int i = 0; i < len; i++)
{
statement.Parameters.AddWithValue(matches[i].Value, jsonArray[i].ToString());
}
}
}
private static bool isSelect(String str)
{
return str.TrimStart().StartsWith("select", StringComparison.OrdinalIgnoreCase);
}
private static bool isInsert(String str)
{
return str.TrimStart().StartsWith("insert", StringComparison.OrdinalIgnoreCase);
}
private static bool isDelete(String str)
{
return str.TrimStart().StartsWith("delete", StringComparison.OrdinalIgnoreCase);
}
private static bool isUpdate(String str)
{
return str.TrimStart().StartsWith("update", StringComparison.OrdinalIgnoreCase);
}
private static bool isBegin(String str)
{
return str.TrimStart().StartsWith("begin", StringComparison.OrdinalIgnoreCase);
}
private static bool isEnd(String str)
{
return str.TrimStart().StartsWith("end", StringComparison.OrdinalIgnoreCase);
}
private static bool isCommit(String str)
{
return str.TrimStart().StartsWith("commit", StringComparison.OrdinalIgnoreCase);
}
private static bool isRollback(String str)
{
return str.TrimStart().StartsWith("rollback", StringComparison.OrdinalIgnoreCase);
}
[ReactMethod]
public void exec(string dbName, JArray queries, bool readOnly, IPromise promise)
{
debug("test called: " + dbName);
SqliteConnection db = getDatabase(dbName);
try
{
int numQueries = queries.Count;
SQLitePLuginResult[] results = new SQLitePLuginResult[numQueries];
if (TRANSACTIONS[dbName] == null)
{
db.Open();
}
for (int i = 0; i < numQueries; i++)
{
var sqlQuery = queries[i];
string sql = sqlQuery[0].ToString();
try
{
if (isSelect(sql))
{
results[i] = doSelectInBackgroundAndPossiblyThrow(sql, sqlQuery[1].ToList(), db, TRANSACTIONS[dbName]);
}
else if (isBegin(sql))
{
//Handle begin without end
if (TRANSACTIONS[dbName] != null)
{
TRANSACTIONS[dbName].Rollback();
TRANSACTIONS[dbName].Dispose();
TRANSACTIONS[dbName] = null;
}
TRANSACTIONS[dbName] = db.BeginTransaction();
results[i] = EMPTY_RESULT;
}
else if (isEnd(sql) || isCommit(sql))
{
if (TRANSACTIONS[dbName] != null)
{
TRANSACTIONS[dbName].Commit();
TRANSACTIONS[dbName].Dispose();
TRANSACTIONS[dbName] = null;
}
results[i] = EMPTY_RESULT;
}
else if (isRollback(sql))
{
if (TRANSACTIONS[dbName] != null)
{
TRANSACTIONS[dbName].Rollback();
TRANSACTIONS[dbName].Dispose();
TRANSACTIONS[dbName] = null;
}
results[i] = EMPTY_RESULT;
}
else
{ // update/insert/delete
if (readOnly)
{
results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, new ReadOnlyException());
}
else
{
results[i] = doUpdateInBackgroundAndPossiblyThrow(sql, sqlQuery[1].ToList(), db, TRANSACTIONS[dbName]);
}
}
}
catch (Exception e)
{
if (RNSqlite2Module.DEBUG_MODE)
{
Console.WriteLine(e.ToString());
}
if (TRANSACTIONS[dbName] != null)
{
TRANSACTIONS[dbName].Rollback();
TRANSACTIONS[dbName].Dispose();
TRANSACTIONS[dbName] = null;
}
results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e);
}
}
List<Object> data = pluginResultsToPrimitiveData(results);
promise.Resolve(data);
}
catch (Exception e)
{
promise.Reject("SQLiteError", e);
if (TRANSACTIONS[dbName] != null)
{
TRANSACTIONS[dbName].Rollback();
TRANSACTIONS[dbName].Dispose();
TRANSACTIONS[dbName] = null;
}
}
finally
{
if (TRANSACTIONS[dbName] == null)
{
db.Close();
}
}
}
private Object getValueFromCursor(SqliteDataReader reader, int index, Type dataType)
{
if (dataType == typeof(Int16))
{
return reader.GetInt16(index);
}
else if (dataType == typeof(Int32))
{
return reader.GetInt32(index);
}
else if (dataType == typeof(Int64))
{
return reader.GetInt64(index);
}
else if (dataType == typeof(double))
{
return reader.GetDouble(index);
}
else if (dataType == typeof(decimal))
{
return reader.GetDecimal(index);
}
else if (dataType == typeof(string))
{
return reader.GetString(index);
}
else
{
return "";
}
}
private static void debug(String line, object format = null)
{
if (DEBUG_MODE)
{
Console.WriteLine(TAG, string.Format(line, format));
}
}
// do a select operation
private SQLitePLuginResult doSelectInBackgroundAndPossiblyThrow(string sql, List<JToken> queryParams,
SqliteConnection db, SqliteTransaction transaction = null)
{
debug("\"all\" query: %s", sql);
SqliteDataReader query = null;
try
{
SqliteCommand command = new SqliteCommand();
command.Connection = db;
command.Transaction = transaction;
if (queryParams != null && queryParams.Count > 0)
{
parseJsonArrayToParams(ref sql, queryParams, ref command);
}
command.CommandText = sql;
query = command.ExecuteReader();
if (!query.HasRows)
{
return EMPTY_RESULT;
}
List<Object> entries = new List<Object>();
while (query.Read())
{
List<Object> row = new List<Object>();
for (int i = 0; i < query.FieldCount; i++)
{
var type = query.GetValue(i).GetType();
row.Add(getValueFromCursor(query, i, type));
}
entries.Add(row);
}
List<string> columns = Enumerable.Range(0, query.FieldCount).Select(query.GetName).ToList();
debug("returning %d rows", entries.Count());
return new SQLitePLuginResult(entries, columns, 0, 0, null);
}
catch (Exception e)
{
debug("Query error", e.Message);
return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null);
}
finally
{
if (query != null)
{
query.Dispose();
}
}
}
private static List<Object> pluginResultsToPrimitiveData(SQLitePLuginResult[] results)
{
List<Object> list = new List<Object>();
for (int i = 0; i < results.Count(); i++)
{
SQLitePLuginResult result = results[i];
List<Object> arr = convertPluginResultToArray(result);
list.Add(arr);
}
return list;
}
private static List<Object> convertPluginResultToArray(SQLitePLuginResult result)
{
List<Object> data = new List<Object>();
if (result.error != null)
{
data.Add(result.error.Message);
}
else
{
data.Add(null);
}
data.Add((long)result.insertId);
data.Add((int)result.rowsAffected);
// column names
data.Add(result.columns);
data.Add(result.rows);
return data;
}
// do a update/delete/insert operation
private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(string sql, List<JToken> queryParams,
SqliteConnection db, SqliteTransaction transaction = null)
{
debug("\"run\" query: %s", sql);
SqliteCommand statement = null;
try
{
statement = new SqliteCommand();
statement.Connection = db;
statement.Transaction = transaction;
statement.CommandType = CommandType.Text;
debug("compiled statement");
if (queryParams != null && queryParams.Count > 0)
{
parseJsonArrayToParams(ref sql, queryParams, ref statement);
}
statement.CommandText = sql;
debug("bound args");
if (isInsert(sql))
{
debug("type: insert");
int rowsAffected = statement.ExecuteNonQuery();
long insertId = 0;
if (rowsAffected > 0)
{
statement.CommandText = "SELECT last_insert_rowid()";
insertId = (long)statement.ExecuteScalar();
}
return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null);
}
else if (isDelete(sql) || isUpdate(sql))
{
debug("type: update/delete");
int rowsAffected = statement.ExecuteNonQuery();
return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null);
}
else
{
// in this case, we don't need rowsAffected or insertId, so we can have a slight
// perf boost by just executing the query
debug("type: drop/create/etc.");
statement.ExecuteScalar();
return EMPTY_RESULT;
}
}
catch (Exception e)
{
debug("insert or update or delete error", e.Message);
throw new Exception(e.Message);
}
finally
{
if (statement != null)
{
statement.Dispose();
}
}
}
private class SQLitePLuginResult
{
public readonly List<Object> rows;
public readonly List<string> columns;
public readonly int rowsAffected;
public readonly long insertId;
public readonly Exception error;
public SQLitePLuginResult(List<Object> rows, List<string> columns,
int rowsAffected, long insertId, Exception error)
{
this.rows = rows;
this.columns = columns;
this.rowsAffected = rowsAffected;
this.insertId = insertId;
this.error = error;
}
}
private class ReadOnlyException : Exception
{
public ReadOnlyException() : base("could not prepare statement (23 not authorized)")
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
/// <summary>
/// Associates a model object with it's corresponding <see cref="ModelMetadata"/>.
/// </summary>
[DebuggerDisplay("DeclaredType={Metadata.ModelType.Name} PropertyName={Metadata.PropertyName}")]
public class ModelExplorer
{
private readonly IModelMetadataProvider _metadataProvider;
private object _model;
private Func<object, object> _modelAccessor;
private ModelExplorer[] _properties;
/// <summary>
/// Creates a new <see cref="ModelExplorer"/>.
/// </summary>
/// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
/// <param name="metadata">The <see cref="ModelMetadata"/>.</param>
/// <param name="model">The model object. May be <c>null</c>.</param>
public ModelExplorer(
IModelMetadataProvider metadataProvider,
ModelMetadata metadata,
object model)
{
if (metadataProvider == null)
{
throw new ArgumentNullException(nameof(metadataProvider));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
_metadataProvider = metadataProvider;
Metadata = metadata;
_model = model;
}
/// <summary>
/// Creates a new <see cref="ModelExplorer"/>.
/// </summary>
/// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
/// <param name="container">The container <see cref="ModelExplorer"/>.</param>
/// <param name="metadata">The <see cref="ModelMetadata"/>.</param>
/// <param name="modelAccessor">A model accessor function..</param>
public ModelExplorer(
IModelMetadataProvider metadataProvider,
ModelExplorer container,
ModelMetadata metadata,
Func<object, object> modelAccessor)
{
if (metadataProvider == null)
{
throw new ArgumentNullException(nameof(metadataProvider));
}
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
_metadataProvider = metadataProvider;
Container = container;
Metadata = metadata;
_modelAccessor = modelAccessor;
}
/// <summary>
/// Creates a new <see cref="ModelExplorer"/>.
/// </summary>
/// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
/// <param name="container">The container <see cref="ModelExplorer"/>.</param>
/// <param name="metadata">The <see cref="ModelMetadata"/>.</param>
/// <param name="model">The model object. May be <c>null</c>.</param>
public ModelExplorer(
IModelMetadataProvider metadataProvider,
ModelExplorer container,
ModelMetadata metadata,
object model)
{
if (metadataProvider == null)
{
throw new ArgumentNullException(nameof(metadataProvider));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
_metadataProvider = metadataProvider;
Container = container;
Metadata = metadata;
_model = model;
}
/// <summary>
/// Gets the container <see cref="ModelExplorer"/>.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="Container"/> will most commonly be set as a result of calling
/// <see cref="GetExplorerForProperty(string)"/>. In this case, the returned <see cref="ModelExplorer"/> will
/// have it's <see cref="Container"/> set to the instance upon which <see cref="GetExplorerForProperty(string)"/>
/// was called.
/// </para>
/// <para>
/// This however is not a requirement. The <see cref="Container"/> is informational, and may not
/// represent a type that defines the property represented by <see cref="Metadata"/>. This can
/// occur when constructing a <see cref="ModelExplorer"/> based on evaluation of a complex
/// expression.
/// </para>
/// <para>
/// If calling code relies on a parent-child relationship between <see cref="ModelExplorer"/>
/// instances, then use <see cref="ModelMetadata.ContainerType"/> to validate this assumption.
/// </para>
/// </remarks>
public ModelExplorer Container { get; }
/// <summary>
/// Gets the <see cref="ModelMetadata"/>.
/// </summary>
public ModelMetadata Metadata { get; }
/// <summary>
/// Gets the model object.
/// </summary>
/// <remarks>
/// Retrieving the <see cref="Model"/> object will execute the model accessor function if this
/// <see cref="ModelExplorer"/> was provided with one.
/// </remarks>
public object Model
{
get
{
if (_model == null && _modelAccessor != null)
{
Debug.Assert(Container != null);
_model = _modelAccessor(Container.Model);
// Null-out the accessor so we don't invoke it repeatedly if it returns null.
_modelAccessor = null;
}
return _model;
}
}
/// <remarks>
/// Retrieving the <see cref="ModelType"/> will execute the model accessor function if this
/// <see cref="ModelExplorer"/> was provided with one.
/// </remarks>
public Type ModelType
{
get
{
if (Metadata.IsNullableValueType)
{
// We have a model, but if it's a nullable value type, then Model.GetType() will return
// the non-nullable type (int? -> int). Since it's a value type, there's no subclassing,
// just go with the declared type.
return Metadata.ModelType;
}
if (Model == null)
{
// If the model is null, then use the declared model type;
return Metadata.ModelType;
}
// We have a model, and it's not a nullable, so use the runtime type to handle
// cases where the model is a subclass of the declared type and has extra data.
return Model.GetType();
}
}
/// <summary>
/// Gets the properties.
/// </summary>
/// <remarks>
/// Includes a <see cref="ModelExplorer"/> for each property of the <see cref="ModelMetadata"/>
/// for <see cref="ModelType"/>.
/// </remarks>
public IEnumerable<ModelExplorer> Properties => PropertiesInternal;
internal ModelExplorer[] PropertiesInternal
{
get
{
if (_properties == null)
{
var metadata = GetMetadataForRuntimeType();
var properties = metadata.Properties;
var propertyHelpers = PropertyHelper.GetProperties(ModelType);
_properties = new ModelExplorer[properties.Count];
for (var i = 0; i < properties.Count; i++)
{
var propertyMetadata = properties[i];
PropertyHelper propertyHelper = null;
for (var j = 0; j < propertyHelpers.Length; j++)
{
if (string.Equals(
propertyMetadata.PropertyName,
propertyHelpers[j].Property.Name,
StringComparison.Ordinal))
{
propertyHelper = propertyHelpers[j];
break;
}
}
Debug.Assert(propertyHelper != null);
_properties[i] = CreateExplorerForProperty(propertyMetadata, propertyHelper);
}
}
return _properties;
}
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the given <paramref name="model"/> value.
/// </summary>
/// <param name="model">The model value.</param>
/// <returns>A <see cref="ModelExplorer"/>.</returns>
public ModelExplorer GetExplorerForModel(object model)
{
if (Container == null)
{
return new ModelExplorer(_metadataProvider, Metadata, model);
}
else
{
return new ModelExplorer(_metadataProvider, Container, Metadata, model);
}
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the property with given <paramref name="name"/>, or <c>null</c> if
/// the property cannot be found.
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A <see cref="ModelExplorer"/>, or <c>null</c>.</returns>
public ModelExplorer GetExplorerForProperty(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
for (var i = 0; i < PropertiesInternal.Length; i++)
{
var property = PropertiesInternal[i];
if (string.Equals(name, property.Metadata.PropertyName, StringComparison.Ordinal))
{
return property;
}
}
return null;
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the property with given <paramref name="name"/>, or <c>null</c> if
/// the property cannot be found.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="modelAccessor">An accessor for the model value.</param>
/// <returns>A <see cref="ModelExplorer"/>, or <c>null</c>.</returns>
/// <remarks>
/// As this creates a model explorer with a specific model accessor function, the result is not cached.
/// </remarks>
public ModelExplorer GetExplorerForProperty(string name, Func<object, object> modelAccessor)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var metadata = GetMetadataForRuntimeType();
var propertyMetadata = metadata.Properties[name];
if (propertyMetadata == null)
{
return null;
}
return new ModelExplorer(_metadataProvider, this, propertyMetadata, modelAccessor);
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the property with given <paramref name="name"/>, or <c>null</c> if
/// the property cannot be found.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="model">The model value.</param>
/// <returns>A <see cref="ModelExplorer"/>, or <c>null</c>.</returns>
/// <remarks>
/// As this creates a model explorer with a specific model value, the result is not cached.
/// </remarks>
public ModelExplorer GetExplorerForProperty(string name, object model)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var metadata = GetMetadataForRuntimeType();
var propertyMetadata = metadata.Properties[name];
if (propertyMetadata == null)
{
return null;
}
return new ModelExplorer(_metadataProvider, this, propertyMetadata, model);
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the provided model value and model <see cref="Type"/>.
/// </summary>
/// <param name="modelType">The model <see cref="Type"/>.</param>
/// <param name="model">The model value.</param>
/// <returns>A <see cref="ModelExplorer"/>.</returns>
/// <remarks>
/// <para>
/// A <see cref="ModelExplorer"/> created by <see cref="GetExplorerForExpression(Type, object)"/>
/// represents the result of executing an arbitrary expression against the model contained
/// in the current <see cref="ModelExplorer"/> instance.
/// </para>
/// <para>
/// The returned <see cref="ModelExplorer"/> will have the current instance set as its <see cref="Container"/>.
/// </para>
/// </remarks>
public ModelExplorer GetExplorerForExpression(Type modelType, object model)
{
if (modelType == null)
{
throw new ArgumentNullException(nameof(modelType));
}
var metadata = _metadataProvider.GetMetadataForType(modelType);
return GetExplorerForExpression(metadata, model);
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the provided model value and model <see cref="Type"/>.
/// </summary>
/// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param>
/// <param name="model">The model value.</param>
/// <returns>A <see cref="ModelExplorer"/>.</returns>
/// <remarks>
/// <para>
/// A <see cref="ModelExplorer"/> created by
/// <see cref="GetExplorerForExpression(ModelMetadata, object)"/>
/// represents the result of executing an arbitrary expression against the model contained
/// in the current <see cref="ModelExplorer"/> instance.
/// </para>
/// <para>
/// The returned <see cref="ModelExplorer"/> will have the current instance set as its <see cref="Container"/>.
/// </para>
/// </remarks>
public ModelExplorer GetExplorerForExpression(ModelMetadata metadata, object model)
{
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
return new ModelExplorer(_metadataProvider, this, metadata, model);
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the provided model value and model <see cref="Type"/>.
/// </summary>
/// <param name="modelType">The model <see cref="Type"/>.</param>
/// <param name="modelAccessor">A model accessor function.</param>
/// <returns>A <see cref="ModelExplorer"/>.</returns>
/// <remarks>
/// <para>
/// A <see cref="ModelExplorer"/> created by
/// <see cref="GetExplorerForExpression(Type, Func{object, object})"/>
/// represents the result of executing an arbitrary expression against the model contained
/// in the current <see cref="ModelExplorer"/> instance.
/// </para>
/// <para>
/// The returned <see cref="ModelExplorer"/> will have the current instance set as its <see cref="Container"/>.
/// </para>
/// </remarks>
public ModelExplorer GetExplorerForExpression(Type modelType, Func<object, object> modelAccessor)
{
if (modelType == null)
{
throw new ArgumentNullException(nameof(modelType));
}
var metadata = _metadataProvider.GetMetadataForType(modelType);
return GetExplorerForExpression(metadata, modelAccessor);
}
/// <summary>
/// Gets a <see cref="ModelExplorer"/> for the provided model value and model <see cref="Type"/>.
/// </summary>
/// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param>
/// <param name="modelAccessor">A model accessor function.</param>
/// <returns>A <see cref="ModelExplorer"/>.</returns>
/// <remarks>
/// <para>
/// A <see cref="ModelExplorer"/> created by
/// <see cref="GetExplorerForExpression(ModelMetadata, Func{object, object})"/>
/// represents the result of executing an arbitrary expression against the model contained
/// in the current <see cref="ModelExplorer"/> instance.
/// </para>
/// <para>
/// The returned <see cref="ModelExplorer"/> will have the current instance set as its <see cref="Container"/>.
/// </para>
/// </remarks>
public ModelExplorer GetExplorerForExpression(ModelMetadata metadata, Func<object, object> modelAccessor)
{
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
return new ModelExplorer(_metadataProvider, this, metadata, modelAccessor);
}
private ModelMetadata GetMetadataForRuntimeType()
{
// We want to make sure we're looking at the runtime properties of the model, and for
// that we need the model metadata of the runtime type.
var metadata = Metadata;
if (Metadata.ModelType != ModelType)
{
metadata = _metadataProvider.GetMetadataForType(ModelType);
}
return metadata;
}
private ModelExplorer CreateExplorerForProperty(
ModelMetadata propertyMetadata,
PropertyHelper propertyHelper)
{
if (propertyHelper == null)
{
return new ModelExplorer(_metadataProvider, this, propertyMetadata, modelAccessor: null);
}
var modelAccessor = new Func<object, object>((c) =>
{
return c == null ? null : propertyHelper.GetValue(c);
});
return new ModelExplorer(_metadataProvider, this, propertyMetadata, modelAccessor);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Media3D.Matrix3D.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Media3D
{
public partial struct Matrix3D : IFormattable
{
#region Methods and constructors
public static bool operator != (System.Windows.Media.Media3D.Matrix3D matrix1, System.Windows.Media.Media3D.Matrix3D matrix2)
{
return default(bool);
}
public static System.Windows.Media.Media3D.Matrix3D operator * (System.Windows.Media.Media3D.Matrix3D matrix1, System.Windows.Media.Media3D.Matrix3D matrix2)
{
return default(System.Windows.Media.Media3D.Matrix3D);
}
public static bool operator == (System.Windows.Media.Media3D.Matrix3D matrix1, System.Windows.Media.Media3D.Matrix3D matrix2)
{
return default(bool);
}
public void Append(System.Windows.Media.Media3D.Matrix3D matrix)
{
}
public static bool Equals(System.Windows.Media.Media3D.Matrix3D matrix1, System.Windows.Media.Media3D.Matrix3D matrix2)
{
return default(bool);
}
public bool Equals(System.Windows.Media.Media3D.Matrix3D value)
{
return default(bool);
}
public override bool Equals(Object o)
{
return default(bool);
}
public override int GetHashCode()
{
return default(int);
}
public void Invert()
{
}
public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44)
{
}
public static System.Windows.Media.Media3D.Matrix3D Multiply(System.Windows.Media.Media3D.Matrix3D matrix1, System.Windows.Media.Media3D.Matrix3D matrix2)
{
return default(System.Windows.Media.Media3D.Matrix3D);
}
public static System.Windows.Media.Media3D.Matrix3D Parse(string source)
{
return default(System.Windows.Media.Media3D.Matrix3D);
}
public void Prepend(System.Windows.Media.Media3D.Matrix3D matrix)
{
}
public void Rotate(Quaternion quaternion)
{
}
public void RotateAt(Quaternion quaternion, Point3D center)
{
}
public void RotateAtPrepend(Quaternion quaternion, Point3D center)
{
}
public void RotatePrepend(Quaternion quaternion)
{
}
public void Scale(Vector3D scale)
{
}
public void ScaleAt(Vector3D scale, Point3D center)
{
}
public void ScaleAtPrepend(Vector3D scale, Point3D center)
{
}
public void ScalePrepend(Vector3D scale)
{
}
public void SetIdentity()
{
}
string System.IFormattable.ToString(string format, IFormatProvider provider)
{
return default(string);
}
public string ToString(IFormatProvider provider)
{
return default(string);
}
public Vector3D Transform(Vector3D vector)
{
return default(Vector3D);
}
public void Transform(Vector3D[] vectors)
{
}
public Point3D Transform(Point3D point)
{
return default(Point3D);
}
public void Transform(Point4D[] points)
{
}
public Point4D Transform(Point4D point)
{
return default(Point4D);
}
public void Transform(Point3D[] points)
{
}
public void Translate(Vector3D offset)
{
}
public void TranslatePrepend(Vector3D offset)
{
}
#endregion
#region Properties and indexers
public double Determinant
{
get
{
return default(double);
}
}
public bool HasInverse
{
get
{
return default(bool);
}
}
public static System.Windows.Media.Media3D.Matrix3D Identity
{
get
{
return default(System.Windows.Media.Media3D.Matrix3D);
}
}
public bool IsAffine
{
get
{
return default(bool);
}
}
public bool IsIdentity
{
get
{
return default(bool);
}
}
public double M11
{
get
{
return default(double);
}
set
{
}
}
public double M12
{
get
{
return default(double);
}
set
{
}
}
public double M13
{
get
{
return default(double);
}
set
{
}
}
public double M14
{
get
{
return default(double);
}
set
{
}
}
public double M21
{
get
{
return default(double);
}
set
{
}
}
public double M22
{
get
{
return default(double);
}
set
{
}
}
public double M23
{
get
{
return default(double);
}
set
{
}
}
public double M24
{
get
{
return default(double);
}
set
{
}
}
public double M31
{
get
{
return default(double);
}
set
{
}
}
public double M32
{
get
{
return default(double);
}
set
{
}
}
public double M33
{
get
{
return default(double);
}
set
{
}
}
public double M34
{
get
{
return default(double);
}
set
{
}
}
public double M44
{
get
{
return default(double);
}
set
{
}
}
public double OffsetX
{
get
{
return default(double);
}
set
{
}
}
public double OffsetY
{
get
{
return default(double);
}
set
{
}
}
public double OffsetZ
{
get
{
return default(double);
}
set
{
}
}
#endregion
}
}
| |
namespace Palaso.UI.WindowsForms.SuperToolTip
{
partial class dlgSuperToolTipEditor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
SuperToolTipInfoWrapper superToolTipInfoWrapper1 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper2 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper3 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper4 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper5 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper6 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper14 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper8 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper7 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper12 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper9 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper10 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper11 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper13 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper18 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper15 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper17 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper16 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper32 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper19 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper20 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper22 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper21 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper24 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper23 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper31 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper25 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper26 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper27 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper28 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper29 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper30 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper33 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper34 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper41 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper36 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper35 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper40 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper37 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper38 = new SuperToolTipInfoWrapper();
SuperToolTipInfoWrapper superToolTipInfoWrapper39 = new SuperToolTipInfoWrapper();
this.dlgColorPicker = new System.Windows.Forms.ColorDialog();
this.tltpHelper = new System.Windows.Forms.ToolTip(this.components);
this.btnFooterFont = new System.Windows.Forms.Button();
this.btnHeaderFont = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnBodyFont = new System.Windows.Forms.Button();
this.dlgFontPicker = new System.Windows.Forms.FontDialog();
this.dlgImagePicker = new System.Windows.Forms.OpenFileDialog();
this.chkFooter = new System.Windows.Forms.CheckBox();
this.chkHeader = new System.Windows.Forms.CheckBox();
this.grpFooter = new System.Windows.Forms.GroupBox();
this.grpFooterText = new System.Windows.Forms.GroupBox();
this.txtFooter = new System.Windows.Forms.RichTextBox();
this.grpFooterImage = new System.Windows.Forms.GroupBox();
this.btnBrowseFooterImage = new System.Windows.Forms.Button();
this.picFooterImage = new System.Windows.Forms.PictureBox();
this.btnClearFooterImage = new System.Windows.Forms.Button();
this.chkShowFooterSeparator = new System.Windows.Forms.CheckBox();
this.grpHeader = new System.Windows.Forms.GroupBox();
this.chkShowHeaderSeparator = new System.Windows.Forms.CheckBox();
this.grpHeaderText = new System.Windows.Forms.GroupBox();
this.txtHeader = new System.Windows.Forms.RichTextBox();
this.grpBackgroundColor = new System.Windows.Forms.GroupBox();
this.rdbtnCustom = new System.Windows.Forms.RadioButton();
this.rdbtnPredefined = new System.Windows.Forms.RadioButton();
this.grpPredefined = new System.Windows.Forms.GroupBox();
this.cmbPredefined = new System.Windows.Forms.ComboBox();
this.grpPreview = new System.Windows.Forms.GroupBox();
this.pnlBackColorPreview = new System.Windows.Forms.Panel();
this.grpCustom = new System.Windows.Forms.GroupBox();
this.lblMiddle = new System.Windows.Forms.Label();
this.btnBegin = new System.Windows.Forms.Button();
this.lblBegin = new System.Windows.Forms.Label();
this.lblEnd = new System.Windows.Forms.Label();
this.btnEnd = new System.Windows.Forms.Button();
this.btnMiddle = new System.Windows.Forms.Button();
this.btnPreview = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.grpBody = new System.Windows.Forms.GroupBox();
this.grpBodyText = new System.Windows.Forms.GroupBox();
this.txtBody = new System.Windows.Forms.RichTextBox();
this.grpBodyImage = new System.Windows.Forms.GroupBox();
this.btnBrowseBodyImage = new System.Windows.Forms.Button();
this.picBodyImage = new System.Windows.Forms.PictureBox();
this.btnClearBodyImage = new System.Windows.Forms.Button();
this.superToolTip1 = new SuperToolTip(this.components);
this.grpFooter.SuspendLayout();
this.grpFooterText.SuspendLayout();
this.grpFooterImage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picFooterImage)).BeginInit();
this.grpHeader.SuspendLayout();
this.grpHeaderText.SuspendLayout();
this.grpBackgroundColor.SuspendLayout();
this.grpPredefined.SuspendLayout();
this.grpPreview.SuspendLayout();
this.grpCustom.SuspendLayout();
this.grpBody.SuspendLayout();
this.grpBodyText.SuspendLayout();
this.grpBodyImage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picBodyImage)).BeginInit();
this.SuspendLayout();
//
// dlgColorPicker
//
this.dlgColorPicker.AnyColor = true;
this.dlgColorPicker.FullOpen = true;
//
// tltpHelper
//
this.tltpHelper.UseAnimation = false;
//
// btnFooterFont
//
this.btnFooterFont.Location = new System.Drawing.Point(211, 16);
this.btnFooterFont.Name = "btnFooterFont";
this.btnFooterFont.Size = new System.Drawing.Size(27, 25);
superToolTipInfoWrapper1.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnFooterFont, superToolTipInfoWrapper1);
this.btnFooterFont.TabIndex = 38;
this.btnFooterFont.Text = "...";
this.tltpHelper.SetToolTip(this.btnFooterFont, "Footer Font and Color Picker");
this.btnFooterFont.UseVisualStyleBackColor = true;
this.btnFooterFont.Click += new System.EventHandler(this.GetFont);
//
// btnHeaderFont
//
this.btnHeaderFont.Location = new System.Drawing.Point(211, 14);
this.btnHeaderFont.Name = "btnHeaderFont";
this.btnHeaderFont.Size = new System.Drawing.Size(27, 27);
superToolTipInfoWrapper2.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnHeaderFont, superToolTipInfoWrapper2);
this.btnHeaderFont.TabIndex = 37;
this.btnHeaderFont.Text = "...";
this.tltpHelper.SetToolTip(this.btnHeaderFont, "Header Font and Color Picker");
this.btnHeaderFont.UseVisualStyleBackColor = true;
this.btnHeaderFont.Click += new System.EventHandler(this.GetFont);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(353, 471);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 28);
superToolTipInfoWrapper3.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnCancel, superToolTipInfoWrapper3);
this.btnCancel.TabIndex = 27;
this.btnCancel.Text = "Cancel";
this.tltpHelper.SetToolTip(this.btnCancel, "123456");
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnBodyFont
//
this.btnBodyFont.Location = new System.Drawing.Point(211, 12);
this.btnBodyFont.Name = "btnBodyFont";
this.btnBodyFont.Size = new System.Drawing.Size(27, 26);
superToolTipInfoWrapper4.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnBodyFont, superToolTipInfoWrapper4);
this.btnBodyFont.TabIndex = 36;
this.btnBodyFont.Text = "...";
this.tltpHelper.SetToolTip(this.btnBodyFont, "Body Font and Color Picker");
this.btnBodyFont.UseVisualStyleBackColor = true;
this.btnBodyFont.Click += new System.EventHandler(this.GetFont);
//
// dlgFontPicker
//
this.dlgFontPicker.FontMustExist = true;
this.dlgFontPicker.ShowColor = true;
//
// chkFooter
//
this.chkFooter.AutoSize = true;
this.chkFooter.Location = new System.Drawing.Point(20, 262);
this.chkFooter.Name = "chkFooter";
this.chkFooter.Size = new System.Drawing.Size(56, 17);
superToolTipInfoWrapper5.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.chkFooter, superToolTipInfoWrapper5);
this.chkFooter.TabIndex = 54;
this.chkFooter.Text = "Footer";
this.chkFooter.UseVisualStyleBackColor = true;
this.chkFooter.CheckedChanged += new System.EventHandler(this.chkFooter_CheckedChanged);
//
// chkHeader
//
this.chkHeader.AutoSize = true;
this.chkHeader.Location = new System.Drawing.Point(19, 384);
this.chkHeader.Name = "chkHeader";
this.chkHeader.Size = new System.Drawing.Size(61, 17);
superToolTipInfoWrapper6.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.chkHeader, superToolTipInfoWrapper6);
this.chkHeader.TabIndex = 53;
this.chkHeader.Text = "Header";
this.chkHeader.UseVisualStyleBackColor = true;
this.chkHeader.CheckedChanged += new System.EventHandler(this.chkHeader_CheckedChanged);
//
// grpFooter
//
this.grpFooter.Controls.Add(this.grpFooterText);
this.grpFooter.Controls.Add(this.grpFooterImage);
this.grpFooter.Controls.Add(this.chkShowFooterSeparator);
this.grpFooter.Location = new System.Drawing.Point(12, 263);
this.grpFooter.Name = "grpFooter";
this.grpFooter.Size = new System.Drawing.Size(482, 116);
superToolTipInfoWrapper14.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpFooter, superToolTipInfoWrapper14);
this.grpFooter.TabIndex = 52;
this.grpFooter.TabStop = false;
//
// grpFooterText
//
this.grpFooterText.Controls.Add(this.txtFooter);
this.grpFooterText.Controls.Add(this.btnFooterFont);
this.grpFooterText.Location = new System.Drawing.Point(33, 9);
this.grpFooterText.Name = "grpFooterText";
this.grpFooterText.Size = new System.Drawing.Size(244, 85);
superToolTipInfoWrapper8.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpFooterText, superToolTipInfoWrapper8);
this.grpFooterText.TabIndex = 50;
this.grpFooterText.TabStop = false;
//
// txtFooter
//
this.txtFooter.Location = new System.Drawing.Point(6, 16);
this.txtFooter.Name = "txtFooter";
this.txtFooter.Size = new System.Drawing.Size(199, 64);
superToolTipInfoWrapper7.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.txtFooter, superToolTipInfoWrapper7);
this.txtFooter.TabIndex = 44;
this.txtFooter.Text = "";
this.txtFooter.TextChanged += new System.EventHandler(this.OnTextSettingsChanged);
//
// grpFooterImage
//
this.grpFooterImage.Controls.Add(this.btnBrowseFooterImage);
this.grpFooterImage.Controls.Add(this.picFooterImage);
this.grpFooterImage.Controls.Add(this.btnClearFooterImage);
this.grpFooterImage.Location = new System.Drawing.Point(283, 9);
this.grpFooterImage.Name = "grpFooterImage";
this.grpFooterImage.Size = new System.Drawing.Size(193, 101);
superToolTipInfoWrapper12.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpFooterImage, superToolTipInfoWrapper12);
this.grpFooterImage.TabIndex = 49;
this.grpFooterImage.TabStop = false;
this.grpFooterImage.Text = "Image";
//
// btnBrowseFooterImage
//
this.btnBrowseFooterImage.Location = new System.Drawing.Point(6, 24);
this.btnBrowseFooterImage.Name = "btnBrowseFooterImage";
this.btnBrowseFooterImage.Size = new System.Drawing.Size(63, 23);
superToolTipInfoWrapper9.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnBrowseFooterImage, superToolTipInfoWrapper9);
this.btnBrowseFooterImage.TabIndex = 49;
this.btnBrowseFooterImage.Text = "Browse";
this.btnBrowseFooterImage.UseVisualStyleBackColor = true;
this.btnBrowseFooterImage.Click += new System.EventHandler(this.btnBrowseFooterImage_Click);
//
// picFooterImage
//
this.picFooterImage.Location = new System.Drawing.Point(94, 10);
this.picFooterImage.Name = "picFooterImage";
this.picFooterImage.Size = new System.Drawing.Size(96, 88);
this.picFooterImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
superToolTipInfoWrapper10.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.picFooterImage, superToolTipInfoWrapper10);
this.picFooterImage.TabIndex = 47;
this.picFooterImage.TabStop = false;
//
// btnClearFooterImage
//
this.btnClearFooterImage.Location = new System.Drawing.Point(6, 53);
this.btnClearFooterImage.Name = "btnClearFooterImage";
this.btnClearFooterImage.Size = new System.Drawing.Size(63, 23);
superToolTipInfoWrapper11.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnClearFooterImage, superToolTipInfoWrapper11);
this.btnClearFooterImage.TabIndex = 48;
this.btnClearFooterImage.Text = "Clear";
this.btnClearFooterImage.UseVisualStyleBackColor = true;
this.btnClearFooterImage.Click += new System.EventHandler(this.btnClearFooterImage_Click);
//
// chkShowFooterSeparator
//
this.chkShowFooterSeparator.Anchor = System.Windows.Forms.AnchorStyles.None;
this.chkShowFooterSeparator.AutoSize = true;
this.chkShowFooterSeparator.Location = new System.Drawing.Point(33, 96);
this.chkShowFooterSeparator.Name = "chkShowFooterSeparator";
this.chkShowFooterSeparator.Size = new System.Drawing.Size(135, 17);
superToolTipInfoWrapper13.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.chkShowFooterSeparator, superToolTipInfoWrapper13);
this.chkShowFooterSeparator.TabIndex = 48;
this.chkShowFooterSeparator.Text = "Show Footer Separator";
this.chkShowFooterSeparator.UseVisualStyleBackColor = true;
this.chkShowFooterSeparator.CheckedChanged += new System.EventHandler(this.chkShowFooterSeparator_CheckedChanged);
//
// grpHeader
//
this.grpHeader.Controls.Add(this.chkShowHeaderSeparator);
this.grpHeader.Controls.Add(this.grpHeaderText);
this.grpHeader.Location = new System.Drawing.Point(12, 385);
this.grpHeader.Name = "grpHeader";
this.grpHeader.Size = new System.Drawing.Size(286, 114);
superToolTipInfoWrapper18.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpHeader, superToolTipInfoWrapper18);
this.grpHeader.TabIndex = 51;
this.grpHeader.TabStop = false;
//
// chkShowHeaderSeparator
//
this.chkShowHeaderSeparator.Anchor = System.Windows.Forms.AnchorStyles.None;
this.chkShowHeaderSeparator.AutoSize = true;
this.chkShowHeaderSeparator.Location = new System.Drawing.Point(33, 93);
this.chkShowHeaderSeparator.Name = "chkShowHeaderSeparator";
this.chkShowHeaderSeparator.Size = new System.Drawing.Size(140, 17);
superToolTipInfoWrapper15.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.chkShowHeaderSeparator, superToolTipInfoWrapper15);
this.chkShowHeaderSeparator.TabIndex = 47;
this.chkShowHeaderSeparator.Text = "Show Header Separator";
this.chkShowHeaderSeparator.UseVisualStyleBackColor = true;
this.chkShowHeaderSeparator.CheckedChanged += new System.EventHandler(this.chkShowHeaderSeparator_CheckedChanged);
//
// grpHeaderText
//
this.grpHeaderText.Controls.Add(this.txtHeader);
this.grpHeaderText.Controls.Add(this.btnHeaderFont);
this.grpHeaderText.Location = new System.Drawing.Point(33, 14);
this.grpHeaderText.Name = "grpHeaderText";
this.grpHeaderText.Size = new System.Drawing.Size(244, 77);
superToolTipInfoWrapper17.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpHeaderText, superToolTipInfoWrapper17);
this.grpHeaderText.TabIndex = 48;
this.grpHeaderText.TabStop = false;
//
// txtHeader
//
this.txtHeader.Location = new System.Drawing.Point(6, 14);
this.txtHeader.Name = "txtHeader";
this.txtHeader.Size = new System.Drawing.Size(199, 57);
superToolTipInfoWrapper16.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.txtHeader, superToolTipInfoWrapper16);
this.txtHeader.TabIndex = 42;
this.txtHeader.Text = "";
this.txtHeader.TextChanged += new System.EventHandler(this.OnTextSettingsChanged);
//
// grpBackgroundColor
//
this.grpBackgroundColor.Controls.Add(this.rdbtnCustom);
this.grpBackgroundColor.Controls.Add(this.rdbtnPredefined);
this.grpBackgroundColor.Controls.Add(this.grpPredefined);
this.grpBackgroundColor.Controls.Add(this.grpPreview);
this.grpBackgroundColor.Controls.Add(this.grpCustom);
this.grpBackgroundColor.Location = new System.Drawing.Point(12, 12);
this.grpBackgroundColor.Name = "grpBackgroundColor";
this.grpBackgroundColor.Size = new System.Drawing.Size(482, 123);
superToolTipInfoWrapper32.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpBackgroundColor, superToolTipInfoWrapper32);
this.grpBackgroundColor.TabIndex = 49;
this.grpBackgroundColor.TabStop = false;
this.grpBackgroundColor.Text = "BackgroundColor";
//
// rdbtnCustom
//
this.rdbtnCustom.AutoSize = true;
this.rdbtnCustom.Checked = true;
this.rdbtnCustom.Location = new System.Drawing.Point(13, 63);
this.rdbtnCustom.Name = "rdbtnCustom";
this.rdbtnCustom.Size = new System.Drawing.Size(60, 17);
superToolTipInfoWrapper19.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.rdbtnCustom, superToolTipInfoWrapper19);
this.rdbtnCustom.TabIndex = 50;
this.rdbtnCustom.TabStop = true;
this.rdbtnCustom.Text = "Custom";
this.rdbtnCustom.UseVisualStyleBackColor = true;
this.rdbtnCustom.CheckedChanged += new System.EventHandler(this.OnBackgroundColorSettingChanged);
//
// rdbtnPredefined
//
this.rdbtnPredefined.AutoSize = true;
this.rdbtnPredefined.Location = new System.Drawing.Point(12, 15);
this.rdbtnPredefined.Name = "rdbtnPredefined";
this.rdbtnPredefined.Size = new System.Drawing.Size(76, 17);
superToolTipInfoWrapper20.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.rdbtnPredefined, superToolTipInfoWrapper20);
this.rdbtnPredefined.TabIndex = 49;
this.rdbtnPredefined.Text = "Predefined";
this.rdbtnPredefined.UseVisualStyleBackColor = true;
this.rdbtnPredefined.CheckedChanged += new System.EventHandler(this.OnBackgroundColorSettingChanged);
//
// grpPredefined
//
this.grpPredefined.Controls.Add(this.cmbPredefined);
this.grpPredefined.Enabled = false;
this.grpPredefined.Location = new System.Drawing.Point(6, 15);
this.grpPredefined.Name = "grpPredefined";
this.grpPredefined.Size = new System.Drawing.Size(362, 46);
superToolTipInfoWrapper22.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpPredefined, superToolTipInfoWrapper22);
this.grpPredefined.TabIndex = 47;
this.grpPredefined.TabStop = false;
this.grpPredefined.Text = "Predefined";
//
// cmbPredefined
//
this.cmbPredefined.FormattingEnabled = true;
this.cmbPredefined.Location = new System.Drawing.Point(66, 20);
this.cmbPredefined.Name = "cmbPredefined";
this.cmbPredefined.Size = new System.Drawing.Size(214, 21);
superToolTipInfoWrapper21.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.cmbPredefined, superToolTipInfoWrapper21);
this.cmbPredefined.TabIndex = 0;
this.cmbPredefined.SelectedIndexChanged += new System.EventHandler(this.cmbPredefined_SelectedIndexChanged);
//
// grpPreview
//
this.grpPreview.Controls.Add(this.pnlBackColorPreview);
this.grpPreview.Location = new System.Drawing.Point(374, 15);
this.grpPreview.Name = "grpPreview";
this.grpPreview.Size = new System.Drawing.Size(102, 102);
superToolTipInfoWrapper24.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpPreview, superToolTipInfoWrapper24);
this.grpPreview.TabIndex = 46;
this.grpPreview.TabStop = false;
this.grpPreview.Text = "Preview";
//
// pnlBackColorPreview
//
this.pnlBackColorPreview.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlBackColorPreview.Location = new System.Drawing.Point(3, 16);
this.pnlBackColorPreview.Name = "pnlBackColorPreview";
this.pnlBackColorPreview.Size = new System.Drawing.Size(96, 83);
superToolTipInfoWrapper23.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.pnlBackColorPreview, superToolTipInfoWrapper23);
this.pnlBackColorPreview.TabIndex = 45;
this.pnlBackColorPreview.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlBackColorPreview_Paint);
//
// grpCustom
//
this.grpCustom.Controls.Add(this.lblMiddle);
this.grpCustom.Controls.Add(this.btnBegin);
this.grpCustom.Controls.Add(this.lblBegin);
this.grpCustom.Controls.Add(this.lblEnd);
this.grpCustom.Controls.Add(this.btnEnd);
this.grpCustom.Controls.Add(this.btnMiddle);
this.grpCustom.Location = new System.Drawing.Point(6, 65);
this.grpCustom.Name = "grpCustom";
this.grpCustom.Size = new System.Drawing.Size(362, 49);
superToolTipInfoWrapper31.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpCustom, superToolTipInfoWrapper31);
this.grpCustom.TabIndex = 48;
this.grpCustom.TabStop = false;
this.grpCustom.Text = "Custom";
//
// lblMiddle
//
this.lblMiddle.AutoSize = true;
this.lblMiddle.Location = new System.Drawing.Point(131, 18);
this.lblMiddle.Name = "lblMiddle";
this.lblMiddle.Size = new System.Drawing.Size(44, 13);
superToolTipInfoWrapper25.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.lblMiddle, superToolTipInfoWrapper25);
this.lblMiddle.TabIndex = 34;
this.lblMiddle.Text = "Middle :";
//
// btnBegin
//
this.btnBegin.Location = new System.Drawing.Point(91, 15);
this.btnBegin.Name = "btnBegin";
this.btnBegin.Size = new System.Drawing.Size(24, 20);
superToolTipInfoWrapper26.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnBegin, superToolTipInfoWrapper26);
this.btnBegin.TabIndex = 29;
this.btnBegin.Text = "...";
this.btnBegin.UseVisualStyleBackColor = true;
this.btnBegin.Click += new System.EventHandler(this.GetColor);
//
// lblBegin
//
this.lblBegin.AutoSize = true;
this.lblBegin.Location = new System.Drawing.Point(42, 18);
this.lblBegin.Name = "lblBegin";
this.lblBegin.Size = new System.Drawing.Size(40, 13);
superToolTipInfoWrapper27.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.lblBegin, superToolTipInfoWrapper27);
this.lblBegin.TabIndex = 33;
this.lblBegin.Text = "Begin :";
//
// lblEnd
//
this.lblEnd.AutoSize = true;
this.lblEnd.Location = new System.Drawing.Point(224, 18);
this.lblEnd.Name = "lblEnd";
this.lblEnd.Size = new System.Drawing.Size(32, 13);
superToolTipInfoWrapper28.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.lblEnd, superToolTipInfoWrapper28);
this.lblEnd.TabIndex = 35;
this.lblEnd.Text = "End :";
//
// btnEnd
//
this.btnEnd.Location = new System.Drawing.Point(263, 14);
this.btnEnd.Name = "btnEnd";
this.btnEnd.Size = new System.Drawing.Size(24, 20);
superToolTipInfoWrapper29.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnEnd, superToolTipInfoWrapper29);
this.btnEnd.TabIndex = 31;
this.btnEnd.Text = "...";
this.btnEnd.UseVisualStyleBackColor = true;
this.btnEnd.Click += new System.EventHandler(this.GetColor);
//
// btnMiddle
//
this.btnMiddle.Location = new System.Drawing.Point(177, 15);
this.btnMiddle.Name = "btnMiddle";
this.btnMiddle.Size = new System.Drawing.Size(24, 20);
superToolTipInfoWrapper30.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnMiddle, superToolTipInfoWrapper30);
this.btnMiddle.TabIndex = 30;
this.btnMiddle.Text = "...";
this.btnMiddle.UseVisualStyleBackColor = true;
this.btnMiddle.Click += new System.EventHandler(this.GetColor);
//
// btnPreview
//
this.btnPreview.Anchor = System.Windows.Forms.AnchorStyles.None;
this.btnPreview.Location = new System.Drawing.Point(353, 399);
this.btnPreview.Name = "btnPreview";
this.btnPreview.Size = new System.Drawing.Size(157, 66);
superToolTipInfoWrapper33.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnPreview, superToolTipInfoWrapper33);
this.btnPreview.TabIndex = 28;
this.btnPreview.Text = "Hover Here to preview";
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(435, 471);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 28);
superToolTipInfoWrapper34.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnOK, superToolTipInfoWrapper34);
this.btnOK.TabIndex = 26;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
//
// grpBody
//
this.grpBody.Controls.Add(this.grpBodyText);
this.grpBody.Controls.Add(this.grpBodyImage);
this.grpBody.Location = new System.Drawing.Point(12, 142);
this.grpBody.Name = "grpBody";
this.grpBody.Size = new System.Drawing.Size(482, 115);
superToolTipInfoWrapper41.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpBody, superToolTipInfoWrapper41);
this.grpBody.TabIndex = 50;
this.grpBody.TabStop = false;
this.grpBody.Text = "Body";
//
// grpBodyText
//
this.grpBodyText.Controls.Add(this.txtBody);
this.grpBodyText.Controls.Add(this.btnBodyFont);
this.grpBodyText.Location = new System.Drawing.Point(33, 9);
this.grpBodyText.Name = "grpBodyText";
this.grpBodyText.Size = new System.Drawing.Size(244, 100);
superToolTipInfoWrapper36.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpBodyText, superToolTipInfoWrapper36);
this.grpBodyText.TabIndex = 47;
this.grpBodyText.TabStop = false;
//
// txtBody
//
this.txtBody.Location = new System.Drawing.Point(6, 12);
this.txtBody.Name = "txtBody";
this.txtBody.Size = new System.Drawing.Size(199, 82);
superToolTipInfoWrapper35.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.txtBody, superToolTipInfoWrapper35);
this.txtBody.TabIndex = 43;
this.txtBody.Text = "";
this.txtBody.TextChanged += new System.EventHandler(this.OnTextSettingsChanged);
//
// grpBodyImage
//
this.grpBodyImage.Controls.Add(this.btnBrowseBodyImage);
this.grpBodyImage.Controls.Add(this.picBodyImage);
this.grpBodyImage.Controls.Add(this.btnClearBodyImage);
this.grpBodyImage.Location = new System.Drawing.Point(283, 9);
this.grpBodyImage.Name = "grpBodyImage";
this.grpBodyImage.Size = new System.Drawing.Size(193, 100);
superToolTipInfoWrapper40.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.grpBodyImage, superToolTipInfoWrapper40);
this.grpBodyImage.TabIndex = 46;
this.grpBodyImage.TabStop = false;
this.grpBodyImage.Text = "Image";
//
// btnBrowseBodyImage
//
this.btnBrowseBodyImage.Location = new System.Drawing.Point(6, 24);
this.btnBrowseBodyImage.Name = "btnBrowseBodyImage";
this.btnBrowseBodyImage.Size = new System.Drawing.Size(63, 23);
superToolTipInfoWrapper37.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnBrowseBodyImage, superToolTipInfoWrapper37);
this.btnBrowseBodyImage.TabIndex = 46;
this.btnBrowseBodyImage.Text = "Browse";
this.btnBrowseBodyImage.UseVisualStyleBackColor = true;
this.btnBrowseBodyImage.Click += new System.EventHandler(this.btnBrowseBodyImage_Click);
//
// picBodyImage
//
this.picBodyImage.Location = new System.Drawing.Point(94, 12);
this.picBodyImage.Name = "picBodyImage";
this.picBodyImage.Size = new System.Drawing.Size(96, 82);
this.picBodyImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
superToolTipInfoWrapper38.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.picBodyImage, superToolTipInfoWrapper38);
this.picBodyImage.TabIndex = 44;
this.picBodyImage.TabStop = false;
//
// btnClearBodyImage
//
this.btnClearBodyImage.Location = new System.Drawing.Point(6, 53);
this.btnClearBodyImage.Name = "btnClearBodyImage";
this.btnClearBodyImage.Size = new System.Drawing.Size(63, 23);
superToolTipInfoWrapper39.SuperToolTipInfo = null;
this.superToolTip1.SetSuperStuff(this.btnClearBodyImage, superToolTipInfoWrapper39);
this.btnClearBodyImage.TabIndex = 45;
this.btnClearBodyImage.Text = "Clear";
this.btnClearBodyImage.UseVisualStyleBackColor = true;
this.btnClearBodyImage.Click += new System.EventHandler(this.btnClearBodyImage_Click);
//
// dlgSuperToolTipEditor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(511, 501);
this.Controls.Add(this.chkFooter);
this.Controls.Add(this.chkHeader);
this.Controls.Add(this.grpFooter);
this.Controls.Add(this.grpHeader);
this.Controls.Add(this.grpBackgroundColor);
this.Controls.Add(this.btnPreview);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.grpBody);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "dlgSuperToolTipEditor";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "SuperToolTip Editor";
this.grpFooter.ResumeLayout(false);
this.grpFooter.PerformLayout();
this.grpFooterText.ResumeLayout(false);
this.grpFooterImage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.picFooterImage)).EndInit();
this.grpHeader.ResumeLayout(false);
this.grpHeader.PerformLayout();
this.grpHeaderText.ResumeLayout(false);
this.grpBackgroundColor.ResumeLayout(false);
this.grpBackgroundColor.PerformLayout();
this.grpPredefined.ResumeLayout(false);
this.grpPreview.ResumeLayout(false);
this.grpCustom.ResumeLayout(false);
this.grpCustom.PerformLayout();
this.grpBody.ResumeLayout(false);
this.grpBodyText.ResumeLayout(false);
this.grpBodyImage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.picBodyImage)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ColorDialog dlgColorPicker;
private System.Windows.Forms.ToolTip tltpHelper;
private System.Windows.Forms.FontDialog dlgFontPicker;
private System.Windows.Forms.Panel pnlBackColorPreview;
private System.Windows.Forms.Button btnFooterFont;
private System.Windows.Forms.RichTextBox txtFooter;
private System.Windows.Forms.Button btnHeaderFont;
private System.Windows.Forms.Button btnBodyFont;
private System.Windows.Forms.RichTextBox txtBody;
private System.Windows.Forms.RichTextBox txtHeader;
private System.Windows.Forms.Label lblBegin;
private System.Windows.Forms.Button btnBegin;
private System.Windows.Forms.Label lblMiddle;
private System.Windows.Forms.Label lblEnd;
private System.Windows.Forms.Button btnMiddle;
private System.Windows.Forms.Button btnEnd;
private System.Windows.Forms.CheckBox chkShowHeaderSeparator;
private System.Windows.Forms.CheckBox chkShowFooterSeparator;
private System.Windows.Forms.Button btnPreview;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.GroupBox grpBackgroundColor;
private System.Windows.Forms.GroupBox grpPredefined;
private System.Windows.Forms.GroupBox grpPreview;
private System.Windows.Forms.ComboBox cmbPredefined;
private System.Windows.Forms.GroupBox grpCustom;
private System.Windows.Forms.RadioButton rdbtnCustom;
private System.Windows.Forms.RadioButton rdbtnPredefined;
private System.Windows.Forms.GroupBox grpBody;
private System.Windows.Forms.PictureBox picBodyImage;
private System.Windows.Forms.GroupBox grpHeader;
private System.Windows.Forms.GroupBox grpFooter;
private System.Windows.Forms.GroupBox grpBodyText;
private System.Windows.Forms.GroupBox grpBodyImage;
private System.Windows.Forms.Button btnClearBodyImage;
private System.Windows.Forms.Button btnBrowseBodyImage;
private System.Windows.Forms.OpenFileDialog dlgImagePicker;
private System.Windows.Forms.GroupBox grpFooterImage;
private System.Windows.Forms.Button btnBrowseFooterImage;
private System.Windows.Forms.PictureBox picFooterImage;
private System.Windows.Forms.Button btnClearFooterImage;
private System.Windows.Forms.GroupBox grpFooterText;
private System.Windows.Forms.GroupBox grpHeaderText;
private System.Windows.Forms.CheckBox chkHeader;
private System.Windows.Forms.CheckBox chkFooter;
private SuperToolTip superToolTip1;
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InstructionScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using GameStateManagement;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.GamerServices;
using System.Text.RegularExpressions;
using YachtServices;
#endregion
namespace Yacht
{
/// <summary>
/// A screen which displays the game instructions.
/// </summary>
class InstructionScreen : GameScreen
{
#region Fields
Texture2D background;
SpriteFont font;
bool isExit = false;
bool screenExited = false;
string name;
bool askName;
bool isInvalidName;
string invalidName;
#endregion
#region Initialization
/// <summary>
/// Creates a new screen instance.
/// </summary>
/// <param name="askName">Whether or not to ask the player for his name.</param>
public InstructionScreen(bool askName)
{
TransitionOnTime = TimeSpan.FromSeconds(0.0);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
EnabledGestures = GestureType.Tap;
this.askName = askName;
}
#endregion
#region Loading
/// <summary>
/// Load screen resources.
/// </summary>
public override void LoadContent()
{
background = Load<Texture2D>(@"Images\instruction");
font = Load<SpriteFont>(@"Fonts\MenuFont");
}
#endregion
#region Update and Render
/// <summary>
/// Advance to the gameplay screen on a tap.
/// </summary>
/// <param name="input">Player input information.</param>
public override void HandleInput(InputState input)
{
if (input.IsPauseGame(null))
{
ExitScreen();
ScreenManager.AddScreen(new MainMenuScreen(), null);
}
if (!isExit)
{
if (input.Gestures.Count > 0 &&
input.Gestures[0].GestureType == GestureType.Tap)
{
if (askName)
{
Guide.BeginShowKeyboardInput(PlayerIndex.One, "Enter your name", String.Empty, "Player1",
EnterNameDialogEnded, null);
}
else
{
isExit = true;
}
}
}
}
/// <summary>
/// Called once the player has selected a name for himself.
/// </summary>
/// <param name="result">Dialog result containing the text entered by the user.</param>
private void EnterNameDialogEnded(IAsyncResult result)
{
name = Guide.EndShowKeyboardInput(result);
if (name == null)
{
ExitScreen();
ScreenManager.AddScreen(new MainMenuScreen(), null);
}
else if (StringUtility.IsNameValid(name))
{
isExit = true;
}
else
{
isInvalidName = true;
invalidName = name;
}
}
/// <summary>
/// Updates the screen.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="otherScreenHasFocus">Whether another screen has the focus currently.</param>
/// <param name="coveredByOtherScreen">Whether this screen is covered by another screen.</param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
if (isInvalidName)
{
isInvalidName = false;
Guide.BeginShowKeyboardInput(PlayerIndex.One, "Enter your name", "The name is not valid.", invalidName,
EnterNameDialogEnded, null);
return;
}
if (isExit && !screenExited)
{
// Move on to the gameplay screen
foreach (GameScreen screen in ScreenManager.GetScreens())
{
screen.ExitScreen();
}
ScreenManager.AddScreen(new GameplayScreen(name, GameTypes.Offline), null);
screenExited = true;
}
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
/// <summary>
/// Render the screen.
/// </summary>
/// <param name="gameTime">Game time information.</param>
public override void Draw(GameTime gameTime)
{
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
// Draw the background
spriteBatch.Draw(background, ScreenManager.GraphicsDevice.Viewport.Bounds,
Color.White * TransitionAlpha);
if (isExit)
{
Rectangle safeArea = ScreenManager.SafeArea;
string text = "Loading...";
Vector2 measure = font.MeasureString(text);
Vector2 textPosition = new Vector2(safeArea.Center.X - measure.X / 2,
safeArea.Center.Y - measure.Y / 2);
spriteBatch.DrawString(font, text, textPosition, Color.Black);
}
spriteBatch.End();
base.Draw(gameTime);
}
#endregion
}
}
| |
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Tao.FFmpeg;
using Tao.OpenAl;
namespace FFmpegExamples
{
public delegate void LiveUpdateCallback(object update);
public class Decoder
{
// public static string text;
private IntPtr pFormatContext;
private FFmpeg.AVFormatContext formatContext;
private FFmpeg.AVCodecContext audioCodecContext;
private IntPtr pAudioCodecContext;
private FFmpeg.AVRational timebase;
private IntPtr pAudioStream;
private IntPtr pAudioCodec;
//private FFmpeg.AVCodecStruct audioCodec;
//private readonly String path;
private int audioStartIndex = -1;
private int audioSampleRate;
private int format;
private const int AUDIO_FRAME_SIZE = 5000;
private byte[] samples = new byte[AUDIO_FRAME_SIZE];
private int sampleSize = -1;
private bool isAudioStream = false;
private const int TIMESTAMP_BASE = 1000000;
public event LiveUpdateCallback LivtUpdateEvent;
public Decoder()
{
FFmpeg.av_register_all();
}
~Decoder()
{
if (pFormatContext != IntPtr.Zero)
FFmpeg.av_close_input_file(pFormatContext);
FFmpeg.av_free_static();
}
public void Reset()
{
if (pFormatContext != IntPtr.Zero)
FFmpeg.av_close_input_file(pFormatContext);
sampleSize = -1;
audioStartIndex = -1;
}
public bool Open(string path)
{
Reset();
int ret;
ret = FFmpeg.av_open_input_file(out pFormatContext, path, IntPtr.Zero, 0, IntPtr.Zero);
if (ret < 0)
{
Console.WriteLine("couldn't opne input file");
return false;
}
ret = FFmpeg.av_find_stream_info(pFormatContext);
if (ret < 0)
{
Console.WriteLine("couldnt find stream informaion");
return false;
}
formatContext = (FFmpeg.AVFormatContext)
Marshal.PtrToStructure(pFormatContext, typeof(FFmpeg.AVFormatContext));
for (int i = 0; i < formatContext.nb_streams; ++i)
{
FFmpeg.AVStream stream = (FFmpeg.AVStream)
Marshal.PtrToStructure(formatContext.streams[i], typeof(FFmpeg.AVStream));
FFmpeg.AVCodecContext codec = (FFmpeg.AVCodecContext)
Marshal.PtrToStructure(stream.codec, typeof(FFmpeg.AVCodecContext));
if (codec.codec_type == FFmpeg.CodecType.CODEC_TYPE_AUDIO &&
audioStartIndex == -1)
{
this.pAudioCodecContext = stream.codec;
this.pAudioStream = formatContext.streams[i];
this.audioCodecContext = codec;
this.audioStartIndex = i;
this.timebase = stream.time_base;
pAudioCodec = FFmpeg.avcodec_find_decoder(this.audioCodecContext.codec_id);
if (pAudioCodec == IntPtr.Zero)
{
Console.WriteLine("couldn't find codec");
return false;
}
FFmpeg.avcodec_open(stream.codec, pAudioCodec);
}
}
if (audioStartIndex == -1)
{
Console.WriteLine("Couldn't find audio streamn");
return false;
}
audioSampleRate = audioCodecContext.sample_rate;
if (audioCodecContext.channels == 1)
{
format = Al.AL_FORMAT_MONO16;
}
else
{
format = Al.AL_FORMAT_STEREO16;
}
return true;
}
static int count = 0;
public bool Stream()
{
int result;
// FFmpeg.AVPacket packet = new FFmpeg.AVPacket();
IntPtr pPacket = Marshal.AllocHGlobal(56);
//Marshal.StructureToPtr(packet, pPacket, false);
// Marshal.PtrToStructure(
result = FFmpeg.av_read_frame(pFormatContext, pPacket);
if (result < 0)
return false;
count++;
int frameSize = 0;
IntPtr pSamples = IntPtr.Zero;
FFmpeg.AVPacket packet = (FFmpeg.AVPacket)
Marshal.PtrToStructure(pPacket, typeof(FFmpeg.AVPacket));
Marshal.FreeHGlobal(pPacket);
if (LivtUpdateEvent != null)
{
int cur = (int)(packet.dts * timebase.num / timebase.den);
int total = (int)(formatContext.duration / TIMESTAMP_BASE);
string time = String.Format("{0} out of {1} seconds", cur, total);
LivtUpdateEvent(time);
}
if (packet.stream_index != this.audioStartIndex)
{
this.isAudioStream = false;
return true;
}
this.isAudioStream = true;
try
{
pSamples = Marshal.AllocHGlobal(AUDIO_FRAME_SIZE);
int size = FFmpeg.avcodec_decode_audio(pAudioCodecContext, pSamples,
ref frameSize, packet.data, packet.size);
//FFmpeg.av_free_packet(pPacket);
this.sampleSize = frameSize;
Marshal.Copy(pSamples, samples, 0, AUDIO_FRAME_SIZE);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
Marshal.FreeHGlobal(pSamples);
}
return true;
}
public byte[] Samples
{
get { return samples; }
}
public int SampleSize
{
get { return sampleSize; }
}
public int Format
{
get { return format; }
}
public int Frequency
{
get { return audioSampleRate; }
}
public bool IsAudioStream
{
get { return isAudioStream; }
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// <para>The InstanceProfile data type contains information about an instance profile.</para> <para> This data type is used as a response
/// element in the following actions:</para>
/// <ul>
/// <li> <para> CreateInstanceProfile </para> </li>
/// <li> <para> GetInstanceProfile </para> </li>
/// <li> <para> ListsInstanceProfile </para> </li>
/// <li> <para> ListsInstanceProfilesForRole </para> </li>
///
/// </ul>
/// </summary>
public class InstanceProfile
{
private string path;
private string instanceProfileName;
private string instanceProfileId;
private string arn;
private DateTime? createDate;
private List<Role> roles = new List<Role>();
/// <summary>
/// Path to the instance profile. For more information about paths, see <a
/// href="http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html" target="_blank">Identifiers for IAM
/// Entities</a> in <i>Using AWS Identity and Access Management</i>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 512</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>(\u002F)|(\u002F[\u0021-\u007F]+\u002F)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Path
{
get { return this.path; }
set { this.path = value; }
}
/// <summary>
/// Sets the Path property
/// </summary>
/// <param name="path">The value to set for the Path property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithPath(string path)
{
this.path = path;
return this;
}
// Check to see if Path property is set
internal bool IsSetPath()
{
return this.path != null;
}
/// <summary>
/// The name identifying the instance profile.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 128</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\w+=,.@-]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceProfileName
{
get { return this.instanceProfileName; }
set { this.instanceProfileName = value; }
}
/// <summary>
/// Sets the InstanceProfileName property
/// </summary>
/// <param name="instanceProfileName">The value to set for the InstanceProfileName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithInstanceProfileName(string instanceProfileName)
{
this.instanceProfileName = instanceProfileName;
return this;
}
// Check to see if InstanceProfileName property is set
internal bool IsSetInstanceProfileName()
{
return this.instanceProfileName != null;
}
/// <summary>
/// The stable and unique string identifying the instance profile. For more information about IDs, see <a
/// href="http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html" target="_blank">Identifiers for IAM
/// Entities</a> in <i>Using AWS Identity and Access Management</i>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>16 - 32</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\w]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceProfileId
{
get { return this.instanceProfileId; }
set { this.instanceProfileId = value; }
}
/// <summary>
/// Sets the InstanceProfileId property
/// </summary>
/// <param name="instanceProfileId">The value to set for the InstanceProfileId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithInstanceProfileId(string instanceProfileId)
{
this.instanceProfileId = instanceProfileId;
return this;
}
// Check to see if InstanceProfileId property is set
internal bool IsSetInstanceProfileId()
{
return this.instanceProfileId != null;
}
/// <summary>
/// The Amazon Resource Name (ARN) specifying the instance profile. For more information about ARNs and how to use them in policies, see <a
/// href="http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html" target="_blank">Identifiers for IAM
/// Entities</a> in <i>Using AWS Identity and Access Management</i>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>20 - 2048</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Arn
{
get { return this.arn; }
set { this.arn = value; }
}
/// <summary>
/// Sets the Arn property
/// </summary>
/// <param name="arn">The value to set for the Arn property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithArn(string arn)
{
this.arn = arn;
return this;
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this.arn != null;
}
/// <summary>
/// The date when the instance profile was created.
///
/// </summary>
public DateTime CreateDate
{
get { return this.createDate ?? default(DateTime); }
set { this.createDate = value; }
}
/// <summary>
/// Sets the CreateDate property
/// </summary>
/// <param name="createDate">The value to set for the CreateDate property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithCreateDate(DateTime createDate)
{
this.createDate = createDate;
return this;
}
// Check to see if CreateDate property is set
internal bool IsSetCreateDate()
{
return this.createDate.HasValue;
}
/// <summary>
/// The role associated with the instance profile.
///
/// </summary>
public List<Role> Roles
{
get { return this.roles; }
set { this.roles = value; }
}
/// <summary>
/// Adds elements to the Roles collection
/// </summary>
/// <param name="roles">The values to add to the Roles collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithRoles(params Role[] roles)
{
foreach (Role element in roles)
{
this.roles.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Roles collection
/// </summary>
/// <param name="roles">The values to add to the Roles collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public InstanceProfile WithRoles(IEnumerable<Role> roles)
{
foreach (Role element in roles)
{
this.roles.Add(element);
}
return this;
}
// Check to see if Roles property is set
internal bool IsSetRoles()
{
return this.roles.Count > 0;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataConnectionError.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Web.UI;
[assembly:WebResource("add_permissions_for_users.gif", "image/gif")]
[assembly:WebResource("properties_security_tab_w_user.gif", "image/gif")]
[assembly:WebResource("properties_security_tab.gif", "image/gif")]
namespace System.Web.DataAccess
{
using System;
using System.Web;
using System.Globalization;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Threading;
using System.Configuration;
using System.Web.Util;
using System.Security.Permissions;
using System.Web.Hosting;
using System.Security.Principal;
using System.Web.UI;
using System.Web.Handlers;
using System.Web.Configuration;
using System.Diagnostics;
using System.Text;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
internal enum DataConnectionErrorEnum
{
CanNotCreateDataDir,
CanNotWriteToDataDir,
CanNotWriteToDBFile
}
internal static class DataConnectionHelper
{
internal static string GetCurrentName()
{
string userName = "NETWORK SERVICE";
string domainName = "NT AUTHORITY";
IntPtr pSid = IntPtr.Zero;
try
{
if( UnsafeNativeMethods.ConvertStringSidToSid( "S-1-5-20", out pSid ) != 0 &&
pSid != IntPtr.Zero )
{
int userNameLen = 256;
int domainNameLen = 256;
int sidNameUse = 0;
StringBuilder bufUserName = new StringBuilder( userNameLen );
StringBuilder bufDomainName = new StringBuilder( domainNameLen );
if( 0 != UnsafeNativeMethods.LookupAccountSid( null,
pSid,
bufUserName,
ref userNameLen,
bufDomainName,
ref domainNameLen,
ref sidNameUse ) )
{
userName = bufUserName.ToString();
domainName = bufDomainName.ToString();
}
}
WindowsIdentity id = WindowsIdentity.GetCurrent();
if( id != null && id.Name != null )
{
if ( string.Compare( id.Name,
domainName + @"\" + userName,
StringComparison.OrdinalIgnoreCase ) == 0 )
{
return userName;
}
return id.Name;
}
}
catch {}
finally
{
if( pSid != IntPtr.Zero )
{
UnsafeNativeMethods.LocalFree( pSid );
}
}
return String.Empty;
}
}
internal class DataConnectionErrorFormatter : ErrorFormatter
{
protected static NameValueCollection s_errMessages = new NameValueCollection();
protected static object s_Lock = new object ();
protected string _UserName;
protected DataConnectionErrorEnum _Error;
protected override string ErrorTitle
{
get { return null; }
}
protected override string Description
{
get { return null; }
}
protected override string MiscSectionTitle
{
get
{
return SR.GetString(SR.DataAccessError_MiscSectionTitle) ;
}
}
protected override string MiscSectionContent
{
get
{
string url;
int currentNumber = 1;
string resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_1);
string miscContent = "<ol>\n<li>" + resourceString + "</li>\n";
switch (_Error)
{
case DataConnectionErrorEnum.CanNotCreateDataDir:
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_2_CanNotCreateDataDir);
miscContent += "<li>" + resourceString + "</li>\n";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_2);
miscContent += "<li>" + resourceString + "</li>\n";
break;
case DataConnectionErrorEnum.CanNotWriteToDataDir:
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_2);
miscContent += "<li>" + resourceString + "</li>\n";
break;
case DataConnectionErrorEnum.CanNotWriteToDBFile:
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_2_CanNotWriteToDBFile_a);
miscContent += "<li>" + resourceString + "</li>\n";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_2_CanNotWriteToDBFile_b);
miscContent += "<li>" + resourceString + "</li>\n";
break;
}
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_3);
miscContent += "<li>" + resourceString + "<br></li>\n";
url = AssemblyResourceLoader.GetWebResourceUrl(typeof(Page), "properties_security_tab.gif", true);
miscContent += "<br><br><IMG SRC=\"" + url + "\"><br><br><br>";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_ClickAdd);
miscContent += "<li>" + resourceString + "</li>\n";
url = AssemblyResourceLoader.GetWebResourceUrl(typeof(Page), "add_permissions_for_users.gif", true);
miscContent += "<br><br><IMG SRC=\"" + url + "\"><br><br>";
string four;
if (!String.IsNullOrEmpty(_UserName))
four = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_4, _UserName);
else
four = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_4_2);
miscContent += "<li>" + four + "</li>\n";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_ClickOK);
miscContent += "<li>" + resourceString + "</li>\n";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_5);
miscContent += "<li>" + resourceString + "</li>\n";
url = AssemblyResourceLoader.GetWebResourceUrl(typeof(Page), "properties_security_tab_w_user.gif", true);
miscContent += "<br><br><IMG SRC=\"" + url + "\"><br><br>";
resourceString = GetResourceStringAndSetAdaptiveNumberedText(ref currentNumber, SR.DataAccessError_MiscSection_ClickOK);
miscContent += "<li>" + resourceString + "</li>\n";
return miscContent;
}
}
protected override string ColoredSquareTitle
{
get { return null; }
}
protected override string ColoredSquareContent
{
get { return null; }
}
protected override bool ShowSourceFileInfo
{
get { return false; }
}
private string GetResourceStringAndSetAdaptiveNumberedText(ref int currentNumber, string resourceId) {
string resourceString = SR.GetString(resourceId);
SetAdaptiveNumberedText(ref currentNumber, resourceString);
return resourceString;
}
private string GetResourceStringAndSetAdaptiveNumberedText(ref int currentNumber, string resourceId, string parameter1) {
string resourceString = SR.GetString(resourceId, parameter1);
SetAdaptiveNumberedText(ref currentNumber, resourceString);
return resourceString;
}
private void SetAdaptiveNumberedText(ref int currentNumber, string resourceString) {
string adaptiveText = currentNumber.ToString(CultureInfo.InvariantCulture) + " " + resourceString;
AdaptiveMiscContent.Add(adaptiveText);
currentNumber += 1;
}
}
internal sealed class SqlExpressConnectionErrorFormatter : DataConnectionErrorFormatter
{
internal SqlExpressConnectionErrorFormatter(DataConnectionErrorEnum error)
{
_UserName = (HttpRuntime.HasUnmanagedPermission() ? DataConnectionHelper.GetCurrentName() : String.Empty);
_Error = error;
}
internal SqlExpressConnectionErrorFormatter(string userName, DataConnectionErrorEnum error)
{
_UserName = userName;
_Error = error;
}
protected override string ErrorTitle
{
get
{
string resourceKey = null;
switch ( _Error )
{
case DataConnectionErrorEnum.CanNotCreateDataDir:
resourceKey = SR.DataAccessError_CanNotCreateDataDir_Title;
break;
case DataConnectionErrorEnum.CanNotWriteToDataDir:
resourceKey = SR.SqlExpressError_CanNotWriteToDataDir_Title;
break;
case DataConnectionErrorEnum.CanNotWriteToDBFile:
resourceKey = SR.SqlExpressError_CanNotWriteToDbfFile_Title;
break;
}
return SR.GetString (resourceKey);
}
}
protected override string Description
{
get
{
string resourceKey1 = null;
string resourceKey2 = null;
switch (_Error)
{
case DataConnectionErrorEnum.CanNotCreateDataDir:
resourceKey1 = SR.DataAccessError_CanNotCreateDataDir_Description;
resourceKey2 = SR.DataAccessError_CanNotCreateDataDir_Description_2;
break;
case DataConnectionErrorEnum.CanNotWriteToDataDir:
resourceKey1 = SR.SqlExpressError_CanNotWriteToDataDir_Description;
resourceKey2 = SR.SqlExpressError_CanNotWriteToDataDir_Description_2;
break;
case DataConnectionErrorEnum.CanNotWriteToDBFile:
resourceKey1 = SR.SqlExpressError_CanNotWriteToDbfFile_Description;
resourceKey2 = SR.SqlExpressError_CanNotWriteToDbfFile_Description_2;
break;
}
string desc;
if (!String.IsNullOrEmpty(_UserName))
desc = SR.GetString (resourceKey1, _UserName);
else
desc = SR.GetString (resourceKey2);
desc += " " + SR.GetString(SR.SqlExpressError_Description_1);
return desc;
}
}
}
internal sealed class SqlExpressDBFileAutoCreationErrorFormatter : UnhandledErrorFormatter
{
static string s_errMessage = null;
static object s_Lock = new object();
internal SqlExpressDBFileAutoCreationErrorFormatter( Exception exception ) : base( exception )
{
}
protected override string MiscSectionTitle
{
get
{
return SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation_MiscSectionTitle) ;
}
}
protected override string MiscSectionContent
{
get
{
return CustomErrorMessage;
}
}
internal static string CustomErrorMessage
{
get
{
if( s_errMessage == null )
{
lock( s_Lock )
{
if( s_errMessage == null )
{
string resourceString;
resourceString = SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation) ;
s_errMessage += "<br><br><p>" + resourceString + "<br></p>\n";
s_errMessage += "<ol>\n";
resourceString = SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation_1) ;
s_errMessage += "<li>" + resourceString + "</li>\n";
resourceString = SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation_2) ;
s_errMessage += "<li>" + resourceString + "</li>\n";
resourceString = SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation_3) ;
s_errMessage += "<li>" + resourceString + "</li>\n";
resourceString = SR.GetString(SR.SqlExpress_MDF_File_Auto_Creation_4) ;
s_errMessage += "<li>" + resourceString + "</li>\n";
s_errMessage += "</ol>\n";
}
}
}
return s_errMessage;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Sketching.Tool;
using Xamarin.Forms;
namespace Sketching.Views
{
public partial class ToolSettingsView : ContentPage
{
private StackOrientation _orientation;
private List<KeyValuePair<string, Color>> _colorPalette;
private List<KeyValuePair<string, Color>> _customColorPalette;
private const double ColumnsInVertical = 3.0;
private const double ColumnsInHorisontal = 5.0;
public ICommand ColorSelectedCommand { get; set; }
public ITool Tool { get; set; }
public ToolSettingsView(ITool tool, StackOrientation orientation)
{
Tool = tool;
ColorSelectedCommand = new Command<ToolSettings>(paletteItem =>
{
Tool.Geometry.ToolSettings = paletteItem;
Navigation.PopAsync();
});
_orientation = orientation;
InitializeComponent();
BindingContext = this;
thinLineImage.Source = ImageSource.FromResource("Sketching.Resources.ThinLine.png");
thickLineImage.Source = ImageSource.FromResource("Sketching.Resources.ThickLine.png");
customColorsLayout.IsVisible = false;
CreateColorPalette(tool);
SetupAndFillColorGrids();
// Xamarin.Forms bug still not fixed https://bugzilla.xamarin.com/show_bug.cgi?id=31970
// Andreas 2016-12-21
if (Device.OS == TargetPlatform.Windows)
{
var toolInitSize = tool.Geometry.Size;
Device.StartTimer(TimeSpan.FromMilliseconds(10), () =>
{
sizeSlider.Value = toolInitSize;
return false;
});
}
}
private void CreateColorPalette(ITool tool)
{
if (tool?.CustomToolbarColors != null && tool.CustomToolbarColors.Any())
{
customColorsLayout.IsVisible = true;
customColorsTitle.Text = tool.CustomToolbarName;
_customColorPalette = tool.CustomToolbarColors.ToList();
}
if (tool != null && tool.ShowDefaultToolbar)
{
_colorPalette = new List<KeyValuePair<string, Color>>
{
new KeyValuePair<string, Color>(string.Empty, Color.White),
new KeyValuePair<string, Color>(string.Empty, Color.Silver),
new KeyValuePair<string, Color>(string.Empty, Color.Gray),
new KeyValuePair<string, Color>(string.Empty, Color.Black),
new KeyValuePair<string, Color>(string.Empty, Color.Orange),
new KeyValuePair<string, Color>(string.Empty, Color.Yellow),
new KeyValuePair<string, Color>(string.Empty, Color.Aqua),
new KeyValuePair<string, Color>(string.Empty, Color.Blue),
new KeyValuePair<string, Color>(string.Empty, Color.Navy),
new KeyValuePair<string, Color>(string.Empty, Color.Lime),
new KeyValuePair<string, Color>(string.Empty, Color.Green),
new KeyValuePair<string, Color>(string.Empty, Color.Teal),
new KeyValuePair<string, Color>(string.Empty, Color.Fuchsia),
new KeyValuePair<string, Color>(string.Empty, Color.Red),
new KeyValuePair<string, Color>(string.Empty, Color.Purple)
};
}
}
private void OnSizeChanged(object sender, EventArgs e)
{
_orientation = Width > Height ? StackOrientation.Horizontal : StackOrientation.Vertical;
if (Device.Idiom == TargetIdiom.Desktop) return;
SetupAndFillColorGrids();
}
protected override void OnAppearing()
{
base.OnAppearing();
SizeChanged += OnSizeChanged;
}
private void SetupAndFillColorGrids()
{
// Custom colors
var numberOfRowsInCustomColorGrid = 0;
if (_customColorPalette != null && _customColorPalette.Any() && _customColorPalette.Count == 1)
{
singleObjectLabel.GestureRecognizers.Clear();
customColorsGrid.IsVisible = false;
singleObjectLabel.IsVisible = true;
var item = _customColorPalette.First();
CreatePaletteItem(item, singleObjectLabel);
singleObjectLabel.WidthRequest = 360;
singleObjectLabel.HeightRequest = 200;
singleObjectLabel.VerticalOptions = LayoutOptions.StartAndExpand;
singleObjectLabel.HorizontalOptions = LayoutOptions.StartAndExpand;
if (_colorPalette != null && _colorPalette.Any()) numberOfRowsInCustomColorGrid = 1;
}
else
{
numberOfRowsInCustomColorGrid = CreateColorGridAndReturnNumberOfRows(_customColorPalette, customColorsGrid);
}
// Default colors
var numberOfRowsInDefaultColorGrid = CreateColorGridAndReturnNumberOfRows(_colorPalette, colorGrid);
// Height ratio of the two color grids
if (_customColorPalette != null && _customColorPalette.Any() && numberOfRowsInCustomColorGrid > 0)
{
CalculatePaletteGridHeights(numberOfRowsInDefaultColorGrid, numberOfRowsInCustomColorGrid);
}
}
private int CreateColorGridAndReturnNumberOfRows(List<KeyValuePair<string, Color>> palette, Grid grid)
{
// Clear previous definitions
if (palette == null || !palette.Any()) return 0;
if (grid.ColumnDefinitions.Any()) grid.ColumnDefinitions.Clear();
if (grid.RowDefinitions.Any()) grid.RowDefinitions.Clear();
if (grid.Children.Any()) grid.Children.Clear();
return _orientation == StackOrientation.Vertical ? CreateVerticalPalette(palette, grid) : CreateHorisontalPalette(palette, grid);
}
private int CreateVerticalPalette(List<KeyValuePair<string, Color>> palette, Grid grid)
{
// Create the definitions
var numberOfColors = palette.Count;
var numberOfRows = (int)Math.Ceiling(numberOfColors / ColumnsInVertical);
for (var i = 0; i < numberOfRows; i++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
}
for (var i = 0; i < ColumnsInVertical; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
// Populate the grid
var j = 1;
var left = -1;
var top = 0;
var timeForNewRowInVertical = (int)ColumnsInVertical + 1;
foreach (var item in palette)
{
var paletteItem = new Label();
CreatePaletteItem(item, paletteItem);
left++;
if (j == timeForNewRowInVertical) // New line
{
left = 0;
top++;
timeForNewRowInVertical += (int)ColumnsInVertical;
}
grid.Children.Add(paletteItem, left, top);
j++;
}
return numberOfRows;
}
private int CreateHorisontalPalette(List<KeyValuePair<string, Color>> palette, Grid grid)
{
// Create the definitions
var numberOfColors = palette.Count;
var numberOfRows = (int)Math.Ceiling(numberOfColors / ColumnsInHorisontal);
for (var i = 0; i < numberOfRows; i++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
}
for (var i = 0; i < ColumnsInHorisontal; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
// Populate the grid
var j = 1;
var left = -1;
var top = 0;
var timeForNewRowInHorisontal = (int)ColumnsInHorisontal + 1;
foreach (var item in palette)
{
var paletteItem = new Label();
CreatePaletteItem(item, paletteItem);
left++;
if (j == timeForNewRowInHorisontal) // New line
{
left = 0;
top++;
timeForNewRowInHorisontal += (int)ColumnsInHorisontal;
}
grid.Children.Add(paletteItem, left, top);
j++;
}
return numberOfRows;
}
private void CreatePaletteItem(KeyValuePair<string, Color> item, Label paletteItem)
{
var toolSettings = new ToolSettings
{
SelectedColor = item.Value,
SelectedText = item.Key
};
paletteItem.HorizontalTextAlignment = TextAlignment.Center;
paletteItem.VerticalTextAlignment = TextAlignment.Center;
paletteItem.FontSize = 12.0;
paletteItem.LineBreakMode = LineBreakMode.TailTruncation;
paletteItem.TextColor = GetTextColor(item.Value);
paletteItem.BindingContext = toolSettings;
paletteItem.SetBinding(Label.TextProperty, "SelectedText");
paletteItem.SetBinding(Label.BackgroundColorProperty, "SelectedColor");
var tapGestureRecognizer = new TapGestureRecognizer
{
Command = ColorSelectedCommand,
CommandParameter = paletteItem.BindingContext
};
paletteItem.GestureRecognizers.Add(tapGestureRecognizer);
}
private void CalculatePaletteGridHeights(int numberOfRowsInDefaultColorGrid, int numberOfRowsInCustomColorGrid)
{
if (paletteGrid.ColumnDefinitions.Any()) paletteGrid.ColumnDefinitions.Clear();
if (paletteGrid.RowDefinitions.Any()) paletteGrid.RowDefinitions.Clear();
if (paletteGrid.Children.Any()) paletteGrid.Children.Clear();
// Calculate the height of each palette
var customColorGridHeight = 1.0;
var defaultColorGridHeight = 1.0;
if (numberOfRowsInDefaultColorGrid > numberOfRowsInCustomColorGrid)
{
var ratio = (double)numberOfRowsInCustomColorGrid / numberOfRowsInDefaultColorGrid;
customColorGridHeight = 1 - ratio;
}
if (numberOfRowsInDefaultColorGrid < numberOfRowsInCustomColorGrid)
{
if (numberOfRowsInDefaultColorGrid == 0 && numberOfRowsInCustomColorGrid == 1)
{
customColorGridHeight = 0.4;
}
else
{
var ratio = (double)numberOfRowsInDefaultColorGrid / numberOfRowsInCustomColorGrid;
defaultColorGridHeight = 1 - ratio;
}
}
paletteGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(customColorGridHeight, GridUnitType.Star) });
paletteGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(defaultColorGridHeight, GridUnitType.Star) });
paletteGrid.Children.Add(customColorsLayout, 0, 0);
paletteGrid.Children.Add(colorGrid, 0, 1);
}
private static Color GetTextColor(Color backgroundColor)
{
var backgroundColorDelta = ((backgroundColor.R * 0.3) + (backgroundColor.G * 0.6) + (backgroundColor.B * 0.1));
return (backgroundColorDelta > 0.4f) ? Color.Black : Color.White; // Returns black or white text depending on the delta channel
}
}
}
| |
//WordSlide
//Copyright (C) 2008-2012 Jonathan Ray <asky314159@gmail.com>
//WordSlide is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//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.
//A copy of the GNU General Public License should be in the
//Installer directory of this source tree. If not, see
//<http://www.gnu.org/licenses/>.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WordSlideEngine;
namespace WordSlide
{
public partial class SetupForm : Form
{
private List<string> slidePool;
private List<string> limitedPool;
private List<string> slideOrder;
public DisplaySlideSet[] selectedslideslist
{
get
{
DisplaySlideSet[] ret = new DisplaySlideSet[slideOrder.Count];
for (int x = 0; x < ret.Length; x++)
{
if (((string)slideOrder[x]) == "<Blank Slide>")
{
ret[x] = new DisplaySlideSet();
}
else
{
ret[x] = new DisplaySlideSet(EditableSlideSet.getNewPath((string)slideOrder[x]));
}
}
return ret;
}
}
public SetupForm()
{
InitializeComponent();
slidePool = new List<string>();
limitedPool = new List<string>();
slideOrder = new List<string>();
allSlides.DataSource = limitedPool;
selectedSlides.DataSource = slideOrder;
acceptButton.Enabled = false;
}
private void SetupForm_Load(object sender, EventArgs e)
{
/*if (Program.isRunningOnMono())
{
this.Height += 30;
this.Width += 3;
}*/
string[] slides = Library.getCurrentLibraryList();
Array.Sort(slides);
slidePool.AddRange(slides);
loadLastTime();
/*for (int x = 0; x < Screen.AllScreens.Length; x++)
screenSelect.Items.Add("Screen " + (x + 1));
screenSelect.SelectedIndex = 0;
if (Screen.AllScreens.Length == 1)
screenSelect.Visible = false;*/
fillLimitedPool();
refreshLists();
checkButtons();
}
private void allSlides_DoubleClick(object sender, MouseEventArgs e)
{
addSlides_Click(sender, e);
}
private void addSlides_Click(object sender, EventArgs e)
{
for (int x = 0; x < allSlides.SelectedIndices.Count; x++)
{
slideOrder.Add(limitedPool[allSlides.SelectedIndices[x]]);
}
refreshLists();
checkButtons();
}
private void removeSlides_Click(object sender, EventArgs e)
{
//Have to move backwards through the list because the indices change when removeAt is called,
//and the selectedIndices array does not update accordingly.
for (int x = selectedSlides.SelectedIndices.Count - 1; x >= 0; x--)
{
slideOrder.RemoveAt(selectedSlides.SelectedIndices[x]);
}
refreshLists();
checkButtons();
}
private void reorderUp_Click(object sender, EventArgs e)
{
bool[] toSelect = new bool[slideOrder.Count];
for (int x = 0; x < slideOrder.Count; x++)
{
toSelect[x] = false;
if (selectedSlides.GetSelected(x))
{
int index = x;
if (index > 0)
{
string selected = slideOrder[index];
slideOrder.RemoveAt(index);
slideOrder.Insert(index - 1, selected);
toSelect[index - 1] = true;
}
else
{
toSelect[index] = true;
}
}
}
refreshLists();
updateSelection(toSelect);
}
private void reorderDown_Click(object sender, EventArgs e)
{
bool[] toSelect = new bool[slideOrder.Count];
for (int x = slideOrder.Count - 1; x >= 0; x--)
{
toSelect[x] = false;
if (selectedSlides.GetSelected(x))
{
int index = x;
if (index < selectedSlides.Items.Count - 1)
{
string selected = slideOrder[index];
slideOrder.RemoveAt(index);
slideOrder.Insert(index + 1, selected);
toSelect[index + 1] = true;
}
else
{
toSelect[index] = true;
}
}
}
refreshLists();
updateSelection(toSelect);
}
private void addblankButton_Click(object sender, EventArgs e)
{
slideOrder.Insert(selectedSlides.SelectedIndex + 1, "<Blank Slide>");
refreshLists();
checkButtons();
}
private void loadLastTime()
{
if (File.Exists(Path.Combine(Engine.DataDirectory, "lastshow.o")))
{
BinaryReader reader = new BinaryReader(new FileStream(Path.Combine(Engine.DataDirectory, "lastshow.o"), FileMode.Open));
byte count = reader.ReadByte();
for (int x = 0; x < count; x++)
{
string temp = reader.ReadString();
if (temp.Equals("<Blank Slide>"))
{
slideOrder.Add(temp);
}
else
{
for (int y = 0; y < slidePool.Count; y++)
{
if (temp.Equals(slidePool[y].ToString()))
{
slideOrder.Add(temp);
break;
}
}
}
}
reader.Close();
}
}
private void saveLastTime()
{
BinaryWriter writer = new BinaryWriter(new FileStream(Path.Combine(Engine.DataDirectory, "lastshow.o"), FileMode.Create));
writer.Write((byte)slideOrder.Count);
for (int x = 0; x < slideOrder.Count; x++)
{
writer.Write(slideOrder[x]);
}
writer.Close();
}
private void acceptButton_Click(object sender, EventArgs e)
{
saveLastTime();
this.Close();
}
private void clearButton_Click(object sender, EventArgs e)
{
slideOrder.Clear();
refreshLists();
checkButtons();
}
private void searchBox_TextChanged(object sender, EventArgs e)
{
fillLimitedPool();
refreshLists();
checkButtons();
}
private void fillLimitedPool()
{
limitedPool.Clear();
if (searchBox.Text == "")
{
for (int x = 0; x < slidePool.Count; x++)
{
limitedPool.Add(slidePool[x]);
}
}
else
{
string searchstring = searchBox.Text.ToLower();
for (int x = 0; x < slidePool.Count; x++)
{
string title = slidePool[x];
StringBuilder newtitle = new StringBuilder();
for (int y = 0; y < title.Length; y++)
{
if (Char.IsPunctuation(title[y]))
{
}
else if (Char.IsUpper(title[y]))
{
newtitle.Append(Char.ToLower(title[y]));
}
else
{
newtitle.Append(title[y]);
}
}
if (newtitle.ToString().Contains(searchstring))
{
limitedPool.Add(slidePool[x]);
}
}
}
}
private void refreshLists()
{
CurrencyManager cm = (CurrencyManager)BindingContext[limitedPool];
cm.Refresh();
cm = (CurrencyManager)BindingContext[slideOrder];
cm.Refresh();
}
private void checkButtons()
{
acceptButton.Enabled = (slideOrder.Count > 0);
addSlides.Enabled = (limitedPool.Count > 0);
removeSlides.Enabled = (slideOrder.Count > 0);
reorderUp.Enabled = (slideOrder.Count > 0);
reorderDown.Enabled = (slideOrder.Count > 0);
}
private void updateSelection(bool[] toSelect)
{
for (int x = 0; x < toSelect.Length; x++)
{
selectedSlides.SetSelected(x, toSelect[x]);
}
}
private void searchBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addSlides_Click(sender, e);
}
if (e.KeyCode == Keys.Up)
{
if (allSlides.SelectedIndex > 0)
{
int index = allSlides.SelectedIndices[0] - 1;
allSlides.SelectedIndices.Clear();
allSlides.SelectedIndices.Add(index);
}
}
if (e.KeyCode == Keys.Down)
{
if (allSlides.SelectedIndex < slidePool.Count - 1)
{
int index = allSlides.SelectedIndices[0] + 1;
allSlides.SelectedIndices.Clear();
allSlides.SelectedIndices.Add(index);
}
}
}
private void selectedSlides_MouseDown(object sender, MouseEventArgs e)
{
}
private void selectedSlides_DragEnter(object sender, DragEventArgs e)
{
}
private void selectedSlides_DragDrop(object sender, DragEventArgs e)
{
}
private void allSlides_MouseDown(object sender, MouseEventArgs e)
{
}
private void allSlides_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addSlides_Click(sender, e);
}
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. 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.
// */
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Alachisoft.NosDB.Common.Protobuf {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class DisposeReaderCommand {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand, global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static DisposeReaderCommand() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChpEaXNwb3NlUmVhZGVyQ29tbWFuZC5wcm90bxIgQWxhY2hpc29mdC5Ob3NE",
"Qi5Db21tb24uUHJvdG9idWYiKQoURGlzcG9zZVJlYWRlckNvbW1hbmQSEQoJ",
"cmVhZGVyVUlEGAEgASgJQkQKJGNvbS5hbGFjaGlzb2Z0Lm5vc2RiLmNvbW1v",
"bi5wcm90b2J1ZkIcRGlzcG9zZVJlYWRlckNvbW1hbmRQcm90b2NvbA=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand, global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__Descriptor,
new string[] { "ReaderUID", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DisposeReaderCommand : pb::GeneratedMessage<DisposeReaderCommand, DisposeReaderCommand.Builder> {
private DisposeReaderCommand() { }
private static readonly DisposeReaderCommand defaultInstance = new DisposeReaderCommand().MakeReadOnly();
private static readonly string[] _disposeReaderCommandFieldNames = new string[] { "readerUID" };
private static readonly uint[] _disposeReaderCommandFieldTags = new uint[] { 10 };
public static DisposeReaderCommand DefaultInstance {
get { return defaultInstance; }
}
public override DisposeReaderCommand DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override DisposeReaderCommand ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.DisposeReaderCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<DisposeReaderCommand, DisposeReaderCommand.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.DisposeReaderCommand.internal__static_Alachisoft_NosDB_Common_Protobuf_DisposeReaderCommand__FieldAccessorTable; }
}
public const int ReaderUIDFieldNumber = 1;
private bool hasReaderUID;
private string readerUID_ = "";
public bool HasReaderUID {
get { return hasReaderUID; }
}
public string ReaderUID {
get { return readerUID_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _disposeReaderCommandFieldNames;
if (hasReaderUID) {
output.WriteString(1, field_names[0], ReaderUID);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasReaderUID) {
size += pb::CodedOutputStream.ComputeStringSize(1, ReaderUID);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static DisposeReaderCommand ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static DisposeReaderCommand ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static DisposeReaderCommand ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DisposeReaderCommand ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private DisposeReaderCommand MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(DisposeReaderCommand prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<DisposeReaderCommand, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(DisposeReaderCommand cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private DisposeReaderCommand result;
private DisposeReaderCommand PrepareBuilder() {
if (resultIsReadOnly) {
DisposeReaderCommand original = result;
result = new DisposeReaderCommand();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override DisposeReaderCommand MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand.Descriptor; }
}
public override DisposeReaderCommand DefaultInstanceForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand.DefaultInstance; }
}
public override DisposeReaderCommand BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is DisposeReaderCommand) {
return MergeFrom((DisposeReaderCommand) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(DisposeReaderCommand other) {
if (other == global::Alachisoft.NosDB.Common.Protobuf.DisposeReaderCommand.DefaultInstance) return this;
PrepareBuilder();
if (other.HasReaderUID) {
ReaderUID = other.ReaderUID;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_disposeReaderCommandFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _disposeReaderCommandFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasReaderUID = input.ReadString(ref result.readerUID_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasReaderUID {
get { return result.hasReaderUID; }
}
public string ReaderUID {
get { return result.ReaderUID; }
set { SetReaderUID(value); }
}
public Builder SetReaderUID(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasReaderUID = true;
result.readerUID_ = value;
return this;
}
public Builder ClearReaderUID() {
PrepareBuilder();
result.hasReaderUID = false;
result.readerUID_ = "";
return this;
}
}
static DisposeReaderCommand() {
object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.DisposeReaderCommand.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
//---------------------------------------------------------------------------
//
// <copyright file="D3DImage.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: D3DImage class
// An ImageSource that displays a user created D3D surface
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.PresentationCore;
using MS.Win32.PresentationCore;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Security.Permissions;
using System.Security;
using System.Threading;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace System.Windows.Interop
{
/// <summary>
/// Specifies the acceptible resources for SetBackBuffer.
/// </summary>
public enum D3DResourceType
{
IDirect3DSurface9
}
/// <SecurityNote>
/// It's possible for a D3DImage to be created where unmanaged code permission is
/// granted and then handed off to a partial trust add-in. We must protect the
/// necessary virtual overrides so base class calls don't bypass the link demand.
/// </SecurityNote>
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
public class D3DImage : ImageSource, IAppDomainShutdownListener
{
static D3DImage()
{
IsFrontBufferAvailablePropertyKey =
DependencyProperty.RegisterReadOnly(
"IsFrontBufferAvailable",
typeof(bool),
typeof(D3DImage),
new UIPropertyMetadata(
BooleanBoxes.TrueBox,
new PropertyChangedCallback(IsFrontBufferAvailablePropertyChanged)
)
);
IsFrontBufferAvailableProperty = IsFrontBufferAvailablePropertyKey.DependencyProperty;
}
/// <summary>
/// Default constructor, sets DPI to 96.0
/// </summary>
/// <SecurityNote>
/// The non-default ctor demands so if we stop calling it we need to demand here
/// </SecurityNote>
public D3DImage() : this(96.0, 96.0)
{
}
/// <summary>
/// DPI constructor
/// </summary>
/// <SecurityNote>
/// Critical - access critical types (FrontBufferAvailableCallback)
/// PublicOK - class demands unmanaged code permission
/// </SecurityNote>
[SecurityCritical]
public D3DImage(double dpiX, double dpiY)
{
SecurityHelper.DemandUnmanagedCode();
if (dpiX < 0)
{
throw new ArgumentOutOfRangeException("dpiX", SR.Get(SRID.ParameterMustBeGreaterThanZero));
}
if (dpiY < 0)
{
throw new ArgumentOutOfRangeException("dpiY", SR.Get(SRID.ParameterMustBeGreaterThanZero));
}
_canWriteEvent = new ManualResetEvent(true);
_availableCallback = Callback;
_sendPresentDelegate = SendPresent;
_dpiX = dpiX;
_dpiY = dpiY;
_listener = new WeakReference(this);
AppDomainShutdownMonitor.Add(_listener);
}
[SecurityCritical, SecurityTreatAsSafe]
~D3DImage()
{
if (_pInteropDeviceBitmap != null)
{
// Stop unmanaged code from sending us messages because we're being collected
UnsafeNativeMethods.InteropDeviceBitmap.Detach(_pInteropDeviceBitmap);
}
AppDomainShutdownMonitor.Remove(_listener);
}
/// <summary>
/// Sets a back buffer source for this D3DImage. See the 2nd overload for details.
/// </summary>
public void SetBackBuffer(D3DResourceType backBufferType, IntPtr backBuffer)
{
SetBackBuffer(backBufferType, backBuffer, false);
}
/// <summary>
/// Sets a back buffer source for this D3DImage.
///
/// If enableSoftwareFallback is true, D3DImage will enable rendering of your surface
/// in software (TS, etc.).
///
/// You can only call this while locked. You only need to call this once, unless
/// IsFrontBufferAvailable goes from false -> true and then you MUST call this
/// again. When IsFrontBufferAvailable goes to false, we release our reference
/// to your back buffer, except when enableSoftwareFallBack is true, in which case
/// you are responsible for calling SetBackBuffer again with a null value to get us
/// to release the reference. In this case, you are responsible for checking your
/// device for device loss when rendering.
///
/// Requirements on backBuffer by type:
/// IDirect3DSurface9
/// D3DFMT_A8R8G8B8 or D3DFMT_X8R8G8B8
/// D3DUSAGE_RENDERTARGET
/// D3DPOOL_DEFAULT
/// Multisampling is allowed on 9Ex only
/// Lockability is optional but has performance impact (see below)
///
/// For best performance by type:
/// IDirect3DSurface9
/// Vista WDDM: non-lockable, created on IDirect3DDevice9Ex with
/// D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES and
/// D3DCAPS2_CANSHARERESOURCE support.
/// Vista XDDM: Doesn't matter. Software copying is fastest.
/// non-Vista: Lockable with GetDC support for the pixel format and
/// D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES support.
///
/// </summary>
/// <SecurityNote>
/// Critical - access critical code, accepts pointer arguments
/// PublicOK - demands unmanaged code permission
/// </SecurityNote>
[SecurityCritical]
public void SetBackBuffer(D3DResourceType backBufferType, IntPtr backBuffer, bool enableSoftwareFallback)
{
SecurityHelper.DemandUnmanagedCode();
WritePreamble();
if (_lockCount == 0)
{
throw new InvalidOperationException(SR.Get(SRID.Image_MustBeLocked));
}
// In case the user passed in something like "(D3DResourceType)-1"
if (backBufferType != D3DResourceType.IDirect3DSurface9)
{
throw new ArgumentOutOfRangeException("backBufferType");
}
// Early-out if the current back buffer equals the new one. If the front buffer
// is not available and software fallback is not enabled, _pUserSurfaceUnsafe
// will be null and this check will fail. We don't want a null backBuffer to
// early-out when the front buffer isn't available.
if (backBuffer != IntPtr.Zero && backBuffer == _pUserSurfaceUnsafe)
{
return;
}
SafeMILHandle newBitmap = null;
uint newPixelWidth = 0;
uint newPixelHeight = 0;
// Create a new CInteropDeviceBitmap. Note that a null backBuffer will result
// in a null _pInteropDeviceBitmap at the end
if (backBuffer != IntPtr.Zero)
{
HRESULT.Check(UnsafeNativeMethods.InteropDeviceBitmap.Create(
backBuffer,
_dpiX,
_dpiY,
++_version,
_availableCallback,
enableSoftwareFallback,
out newBitmap,
out newPixelWidth,
out newPixelHeight
));
}
//
// We need to completely disassociate with the old interop bitmap if it
// exists because it won't be deleted until the composition thread is done
// with it or until the garbage collector runs.
//
if (_pInteropDeviceBitmap != null)
{
// 1. Tell the old bitmap to stop sending front buffer messages because
// our new back buffer may be on a different adapter. Plus, tell the
// bitmap to release the back buffer in case the user wants to delete
// it immediately.
UnsafeNativeMethods.InteropDeviceBitmap.Detach(_pInteropDeviceBitmap);
// 2. If we were waiting for a present, unhook from commit
UnsubscribeFromCommittingBatch();
// 3. We are no longer dirty
_isDirty = false;
// Note: We don't need to do anything to the event because we're under
// the protection of Lock
}
// If anything about the new surface were unacceptible, we would have recieved
// a bad HRESULT from Create() so everything must be good
_pInteropDeviceBitmap = newBitmap;
_pUserSurfaceUnsafe = backBuffer;
_pixelWidth = newPixelWidth;
_pixelHeight = newPixelHeight;
_isSoftwareFallbackEnabled = enableSoftwareFallback;
// AddDirtyRect is usually what triggers Changed, but AddDirtyRect isn't allowed with
// no back buffer so we mark for Changed here
if (_pInteropDeviceBitmap == null)
{
_isChangePending = true;
}
RegisterForAsyncUpdateResource();
_waitingForUpdateResourceBecauseBitmapChanged = true;
// WritePostscript will happen at Unlock
}
/// <summary>
/// Locks the D3DImage
///
/// While locked you can call AddDirtyRect, SetBackBuffer, and Unlock. You can
/// also write to your back buffer. You should not write to the back buffer without
/// being locked.
/// </summary>
public void Lock()
{
WritePreamble();
LockImpl(Duration.Forever);
}
/// <summary>
/// Trys to lock the D3DImage but gives up once duration expires. Returns true
/// if the lock was obtained. See Lock for more details.
/// </summary>
public bool TryLock(Duration timeout)
{
WritePreamble();
if (timeout == Duration.Automatic)
{
throw new ArgumentOutOfRangeException("timeout");
}
return LockImpl(timeout);
}
/// <summary>
/// Unlocks the D3DImage
///
/// Can only be called while locked.
///
/// If you have dirtied the image with AddDirtyRect, Unlocking will trigger us to
/// copy the dirty regions from the back buffer to the front buffer. While this is
/// taking place, Lock will block. To avoid locking indefinitely, use TryLock.
/// </summary>
public void Unlock()
{
WritePreamble();
if (_lockCount == 0)
{
throw new InvalidOperationException(SR.Get(SRID.Image_MustBeLocked));
}
--_lockCount;
if (_isDirty && _lockCount == 0)
{
SubscribeToCommittingBatch();
}
if (_isChangePending)
{
_isChangePending = false;
WritePostscript();
}
}
/// <Summary>
/// Adds a dirty rect to the D3DImage
///
/// When you update a part of your back buffer you must dirty the same area on
/// the D3DImage. After you unlock, we will copy the dirty areas to the front buffer.
///
/// Can only be called while locked.
///
/// IMPORTANT: After five dirty rects, we will union them all together. This
/// means you must have valid data outside of the dirty regions.
/// </Summary>
/// <SecurityNote>
/// Critical - access critical code
/// PublicOK - only deals with managed types, unmanaged call is considered safe
/// </SecurityNote>
[SecurityCritical]
public void AddDirtyRect(Int32Rect dirtyRect)
{
WritePreamble();
if (_lockCount == 0)
{
throw new InvalidOperationException(SR.Get(SRID.Image_MustBeLocked));
}
if (_pInteropDeviceBitmap == null)
{
throw new InvalidOperationException(SR.Get(SRID.D3DImage_MustHaveBackBuffer));
}
dirtyRect.ValidateForDirtyRect("dirtyRect", PixelWidth, PixelHeight);
if (dirtyRect.HasArea)
{
// Unmanaged code will make sure that the rect is well-formed
HRESULT.Check(UnsafeNativeMethods.InteropDeviceBitmap.AddDirtyRect(
dirtyRect.X,
dirtyRect.Y,
dirtyRect.Width,
dirtyRect.Height,
_pInteropDeviceBitmap
));
// We're now dirty, but we won't consider it a change until Unlock
_isDirty = true;
_isChangePending = true;
}
}
/// <Summary>
/// When true, a front buffer exists and back buffer updates will be copied forward.
/// When false, a front buffer does not exist. Your changes will not be seen.
/// </Summary>
public bool IsFrontBufferAvailable
{
get
{
return (bool)GetValue(IsFrontBufferAvailableProperty);
}
}
public static readonly DependencyProperty IsFrontBufferAvailableProperty;
/// <Summary>
/// Event that fires when IsFrontBufferAvailable changes
///
/// After a true -> false transition, you should stop updating your surface as
/// we have stopped processing updates.
///
/// After a false -> true transition, you MUST set a valid back buffer
/// </Summary>
public event DependencyPropertyChangedEventHandler IsFrontBufferAvailableChanged
{
add
{
WritePreamble();
if (value != null)
{
_isFrontBufferAvailableChangedHandlers += value;
}
}
remove
{
WritePreamble();
if (value != null)
{
_isFrontBufferAvailableChangedHandlers -= value;
}
}
}
/// <Summary>
/// Width in pixels
/// </Summary>
public int PixelWidth
{
get
{
ReadPreamble();
return (int)_pixelWidth;
}
}
/// <Summary>
/// Height in pixels
/// </Summary>
public int PixelHeight
{
get
{
ReadPreamble();
return (int)_pixelHeight;
}
}
/// <summary>
/// Get the width of the image in measure units (96ths of an inch).
///
/// Sealed to prevent subclasses from modifying the correct behavior.
/// </summary>
public sealed override double Width
{
get
{
ReadPreamble();
return ImageSource.PixelsToDIPs(_dpiX, (int)_pixelWidth);
}
}
/// <summary>
/// Get the height of the image in measure units (96ths of an inch).
///
/// Sealed to prevent subclasses from modifying the correct behavior.
/// </summary>
public sealed override double Height
{
get
{
ReadPreamble();
return ImageSource.PixelsToDIPs(_dpiY, (int)_pixelHeight);
}
}
/// <summary>
/// Get the metadata associated with this image source
///
/// Sealed to prevent subclasses from modifying the correct behavior.
/// </summary>
public sealed override ImageMetadata Metadata
{
get
{
ReadPreamble();
return null;
}
}
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new D3DImage Clone()
{
return (D3DImage)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new D3DImage CloneCurrentValue()
{
return (D3DImage)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
/// <SecurityNote>
/// Calls the ctor which demands unmanaged code
/// </SecurityNote>
protected override Freezable CreateInstanceCore()
{
return new D3DImage();
}
/// <summary>
/// Freezing is not allowed because the user will always have to make
/// changes to the object based upon IsFrontBufferAvailable. We could consider
/// SetBackBuffer to not count as a "change" but any thread could call it
/// and that would violate our synchronization assumptions.
///
/// Sealed to prevent subclasses from modifying the correct behavior.
/// </summary>
protected sealed override bool FreezeCore(bool isChecking)
{
return false;
}
/// <summary>
/// Clone overrides
///
/// Not sealed to allow subclasses to clone their private data
/// </summary>
/// <SecurityNote>
/// The clone overrides call CloneCommon which calls SetBackBuffer
/// which demands unmanaged code
/// </SecurityNote>
protected override void CloneCore(Freezable sourceFreezable)
{
base.CloneCore(sourceFreezable);
CloneCommon(sourceFreezable);
}
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
base.CloneCurrentValueCore(sourceFreezable);
CloneCommon(sourceFreezable);
}
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
base.GetAsFrozenCore(sourceFreezable);
CloneCommon(sourceFreezable);
}
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
base.GetCurrentValueAsFrozenCore(sourceFreezable);
CloneCommon(sourceFreezable);
}
/// <Summary>
/// Gets a software copy of D3DImage. Called by printing, RTB, and BMEs. The
/// user can override this to return something else in the case of the
/// device lost, for example.
/// </Summary>
/// <SecurityNote>
/// Critical: accesses critical code (GetAsSoftwareBitmap)
/// TreatAsSafe: exposes nothing sensitive, demands unmanaged code
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
protected internal virtual BitmapSource CopyBackBuffer()
{
SecurityHelper.DemandUnmanagedCode();
BitmapSource copy = null;
if (_pInteropDeviceBitmap != null)
{
BitmapSourceSafeMILHandle pIWICBitmapSource;
if (HRESULT.Succeeded(UnsafeNativeMethods.InteropDeviceBitmap.GetAsSoftwareBitmap(
_pInteropDeviceBitmap,
out pIWICBitmapSource
)))
{
// CachedBitmap will AddRef the bitmap
copy = new CachedBitmap(pIWICBitmapSource);
}
}
return copy;
}
/// <SecurityNote>
/// Critical: Calls SetBackBuffer which demands unmanaged code
/// TreatAsSafe: This code copies the critical pointer which we must
/// already trust, since SetBackBuffer is critical. It is okay to expose.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void CloneCommon(Freezable sourceFreezable)
{
D3DImage source = (D3DImage)sourceFreezable;
_dpiX = source._dpiX;
_dpiY = source._dpiY;
Lock();
// If we've lost the front buffer, _pUserSurface unsafe will be null
SetBackBuffer(D3DResourceType.IDirect3DSurface9, source._pUserSurfaceUnsafe);
Unlock();
}
private void SubscribeToCommittingBatch()
{
if (!_isWaitingForPresent)
{
// Suppose this D3DImage is not on the main UI thread. This thread will
// never commit a batch so we don't want to add an event handler to it
// since it will never get removed
MediaContext mediaContext = MediaContext.From(Dispatcher);
if (_duceResource.IsOnChannel(mediaContext.Channel))
{
mediaContext.CommittingBatch += _sendPresentDelegate;
_isWaitingForPresent = true;
}
}
}
private void UnsubscribeFromCommittingBatch()
{
if (_isWaitingForPresent)
{
MediaContext mediaContext = MediaContext.From(Dispatcher);
mediaContext.CommittingBatch -= _sendPresentDelegate;
_isWaitingForPresent = false;
}
}
/// <summary>
/// Lock implementation shared by Lock and TryLock
/// </summary>
private bool LockImpl(Duration timeout)
{
Debug.Assert(timeout != Duration.Automatic);
bool lockObtained = false;
if (_lockCount == UInt32.MaxValue)
{
throw new InvalidOperationException(SR.Get(SRID.Image_LockCountLimit));
}
if (_lockCount == 0)
{
if (timeout == Duration.Forever)
{
lockObtained = _canWriteEvent.WaitOne();
}
else
{
lockObtained = _canWriteEvent.WaitOne(timeout.TimeSpan, false);
}
// Consider the situation: Lock(); AddDirtyRect(); Unlock(); Lock(); return;
// The Unlock will have set us up to send a present packet but since
// the user re-locked the buffer we shouldn't copy forward
UnsubscribeFromCommittingBatch();
}
++_lockCount;
// no WritePostscript because this isn't a "change" yet
return lockObtained;
}
private static readonly DependencyPropertyKey IsFrontBufferAvailablePropertyKey;
/// <summary>
/// Propery changed handler for our read only IsFrontBufferAvailable DP. Calls any
/// user added handlers.
/// </summary>
/// <SecurityNote>
/// Critical: This code overwrites critical _pUserSurfaceUnsafe
/// TreatAsSafe: This code only overwrites the critical pointer, it does not
/// access it. It is okay to expose.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void IsFrontBufferAvailablePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.Assert(e.OldValue != e.NewValue);
bool isFrontBufferAvailable = (bool)e.NewValue;
D3DImage img = (D3DImage)d;
if (!isFrontBufferAvailable)
{
//
// This isn't a true "ref" to their surface, so we don't need to do this,
// but if the user clones this D3DImage afterwards we don't want to
// have a pontentially garbage pointer being copied
//
// We are not Detach()-ing from or releasing _pInteropDeviceBitmap because
// if we did, we would never get a notification when the front buffer became
// available again.
//
if (!img._isSoftwareFallbackEnabled)
{
// If software fallback is enabled, we keep this pointer around to make sure SetBackBuffer with
// the same surface pointer is still a no-op. The user is responsible for calling SetBackBuffer
// again (possibly with a null value) to force the release of this pointer.
img._pUserSurfaceUnsafe = IntPtr.Zero;
}
}
if (img._isFrontBufferAvailableChangedHandlers != null)
{
img._isFrontBufferAvailableChangedHandlers(img, e);
}
}
/// <Summary>
/// Sends Present packet to MIL. When MIL receives the packet, it will copy the
/// dirty regions to the front buffer and set the event.
/// </Summary>
/// <SecurityNote>
/// Critical: This code calls critical SendCommandD3DImagePresent
/// TreatAsSafe: This code does not return any critical data. It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void SendPresent(object sender, EventArgs args)
{
Debug.Assert(_isDirty);
Debug.Assert(_isWaitingForPresent);
Debug.Assert(_lockCount == 0);
//
// If we were waiting for present when the bitmap changed, SetBackBuffer removed
// us from waiting for present. So if this is true then the NEW bitmap has been
// dirtied before it has been sent to the render thread. We need to delay the
// present until after the update resource because the D3DImage resource is still
// referencing the old bitmap.
//
if (_waitingForUpdateResourceBecauseBitmapChanged)
{
return;
}
UnsubscribeFromCommittingBatch();
unsafe
{
DUCE.MILCMD_D3DIMAGE_PRESENT data;
DUCE.Channel channel = sender as DUCE.Channel;
Debug.Assert(_duceResource.IsOnChannel(channel));
data.Type = MILCMD.MilCmdD3DImagePresent;
data.Handle = _duceResource.GetHandle(channel);
// We need to make sure the event stays alive in case we get collected before
// the composition thread processes the packet
IntPtr hDuplicate;
IntPtr hCurrentProc = MS.Win32.UnsafeNativeMethods.GetCurrentProcess();
if (!MS.Win32.UnsafeNativeMethods.DuplicateHandle(
hCurrentProc,
_canWriteEvent.SafeWaitHandle,
hCurrentProc,
out hDuplicate,
0,
false,
MS.Win32.UnsafeNativeMethods.DUPLICATE_SAME_ACCESS
))
{
throw new Win32Exception();
}
data.hEvent = (ulong)hDuplicate.ToPointer();
// Send packed command structure
// Note that the command is sent in its own batch (sendInSeparateBatch == true) because this method is called under the
// context of the MediaContext.CommitChannel and the command needs to make it into the current set of changes which are
// being commited to the compositor. If the command would not be added to a separate batch, it would go into the
// "future" batch which would not get submitted this time around. This leads to a dead-lock situation which occurs when
// the app calls Lock on the D3DImage because Lock waits on _canWriteEvent which the compositor sets when it sees the
// Present command. However, since the compositor does not get the Present command, it will not set the event and the
// UI thread will wait forever on the compositor which will hang the application.
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_D3DIMAGE_PRESENT),
true /* sendInSeparateBatch */
);
}
_isDirty = false;
// Block on next Lock
_canWriteEvent.Reset();
}
/// <summary>
/// The DispatcherOperation corresponding to the composition thread callback.
///
/// If the back buffer version matches the current version, update the front
/// buffer status.
/// </summary>
private object SetIsFrontBufferAvailable(object isAvailableVersionPair)
{
Pair pair = (Pair)isAvailableVersionPair;
uint version = (uint)pair.Second;
if (version == _version)
{
bool isFrontBufferAvailable = (bool)pair.First;
SetValue(IsFrontBufferAvailablePropertyKey, isFrontBufferAvailable);
}
// ...just because DispatcherOperationCallback requires returning an object
return null;
}
/// <summary>
/// *** WARNING ***: This runs on the composition thread!
///
/// What the composition thread calls when it wants to update D3DImage about
/// front buffer state. It may be called multiple times with the same value.
/// Since we're on a different thread we can't touch this, so queue a dispatcher
/// operation.
/// </summary>
// NOTE: Called from the render thread!We must execute the reaction on the UI thread.
private void Callback(bool isFrontBufferAvailable, uint version)
{
Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
new DispatcherOperationCallback(SetIsFrontBufferAvailable),
new Pair(BooleanBoxes.Box(isFrontBufferAvailable), version)
);
}
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data. It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
bool isSynchronous = channel.IsSynchronous;
DUCE.MILCMD_D3DIMAGE data;
unsafe
{
data.Type = MILCMD.MilCmdD3DImage;
data.Handle = _duceResource.GetHandle(channel);
if (_pInteropDeviceBitmap != null)
{
UnsafeNativeMethods.MILUnknown.AddRef(_pInteropDeviceBitmap);
data.pInteropDeviceBitmap = (ulong)_pInteropDeviceBitmap.DangerousGetHandle().ToPointer();
}
else
{
data.pInteropDeviceBitmap = 0;
}
data.pSoftwareBitmap = 0;
if (isSynchronous)
{
_softwareCopy = CopyBackBuffer();
if (_softwareCopy != null)
{
UnsafeNativeMethods.MILUnknown.AddRef(_softwareCopy.WicSourceHandle);
data.pSoftwareBitmap = (ulong)_softwareCopy.WicSourceHandle.DangerousGetHandle().ToPointer();
}
}
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_D3DIMAGE),
false /* sendInSeparateBatch */
);
}
// Presents only happen on the async channel so don't let RTB flip this bit
if (!isSynchronous)
{
_waitingForUpdateResourceBecauseBitmapChanged = false;
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_D3DIMAGE))
{
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
// If we are being put onto the asynchronous compositor channel in
// a dirty state, we need to subscribe to the commit batch event.
if (!channel.IsSynchronous && _isDirty)
{
SubscribeToCommittingBatch();
}
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
ReleaseOnChannelAnimations(channel);
// If we are being pulled off the asynchronous compositor channel
// while we still have a handler hooked to the commit batch event,
// remove the handler to avoid situations where would leak the D3DImage
if (!channel.IsSynchronous)
{
UnsubscribeFromCommittingBatch();
}
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
// IAppDomainShutdownListener
/// <SecurityNote>
/// Critical: This code calls a critical native method.
/// TreatAsSafe: This code does not return any critical data or access the critical pointer
/// directly, it just passes the trusted pointer to a critical method. It is okay to expose.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
void IAppDomainShutdownListener.NotifyShutdown()
{
if (_pInteropDeviceBitmap != null)
{
// Stop unmanaged code from sending us messages because the AppDomain is going down
UnsafeNativeMethods.InteropDeviceBitmap.Detach(_pInteropDeviceBitmap);
}
// The finalizer does the same thing, so it's no longer necessary
GC.SuppressFinalize(this);
}
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
// User-specified DPI of their surface
private double _dpiX;
private double _dpiY;
// Handle to our unmanaged interop bitmap that is the front buffer. This can be null!
private SafeMILHandle _pInteropDeviceBitmap;
// This will be null until the user prints, uses an RTB, or uses a BME. It's the result
// of calling CopyBackBuffer() which could be something created by the user. We must
// hold onto it indefinitely because we're never sure when the render thread is done
// with it (not even ReleaseOnChannel because it queues a command)
private BitmapSource _softwareCopy;
// Pointer to the user's surface that IS NOT ADDREF'D (hence the unsafe). Used
// only for cloning purposes. This can be IntPtr.Zero!
/// <SecurityNote>
/// Critical - pointer to IDirect3DSurface9 unmanaged object that methods are called on.
/// </SecurityNote>
[SecurityCritical]
private IntPtr _pUserSurfaceUnsafe;
// Whether or not the user wanted software fallback for the last back buffer.
private bool _isSoftwareFallbackEnabled;
// Event used to synchronize between the UI and composition thread. This prevents the user
// from writing to the back buffer while MIL is copying to the front buffer.
private ManualResetEvent _canWriteEvent;
// Per-instance callback from composition thread plus handlers to notify
/// <SecurityNote>
/// Critical - Field for critical type
/// </SecurityNote>
[SecurityCritical]
private UnsafeNativeMethods.InteropDeviceBitmap.FrontBufferAvailableCallback _availableCallback;
private DependencyPropertyChangedEventHandler _isFrontBufferAvailableChangedHandlers;
// We'll be adding and removing a lot from CommittingBatch, so create the delegate up front
// to avoid creating many during runtime.
private EventHandler _sendPresentDelegate;
// WeakReference to this used to listen to AddDomain shutdown
private WeakReference _listener;
// Keeps track of how many times the user has nested Lock
private uint _lockCount;
// Size of the user's surface in pixels
private uint _pixelWidth;
private uint _pixelHeight;
//
// This is incremented every time a new back buffer is set and it's passed to the bitmap.
// When we recieve a front buffer notification, we ignore it if it doesn't match the current
// version.
//
// Of course SetBackBuffer calls detach to tell the old bitmap to stop sending messages, but
// it is possible the old buffer queued a message right before detach happened. If the old
// back buffer and new back buffer are on the same adapter, it's not really an issue. If they
// are on different ones, it's a big problem because we don't want to give incorrect front
// buffer updates. Since we have to at least send the adapter back, let's instead use a
// version counter that will guarantee we receive no updates from the old bitmap.
//
// Now if the user happens to call SetBackBuffer 2^32 times exactly we'll end up back
// and the same version and could get a bad message, but that won't break anything.
//
private uint _version;
// True if we're dirty and need to send a present
private bool _isDirty;
// Used to prevent Unlock from registering for commit notification more than once
private bool _isWaitingForPresent;
// Set to true when we want to fire Changed in Unlock
private bool _isChangePending;
// Depending upon timing, we could commit a batch and send a present before the UpdateResource
// for a new bitmap happens. This is used to delay the present. See SendPresent().
private bool _waitingForUpdateResourceBecauseBitmapChanged;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NuGet.Test;
using NuGet.Test.Mocks;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Test;
namespace NuGet.PowerShell.Commands.Test {
using PackageUtility = NuGet.Test.PackageUtility;
[TestClass]
public class GetPackageCommandTest {
[TestMethod]
public void GetPackageReturnsAllInstalledPackagesWhenNoParametersAreSpecified() {
// Arrange
var cmdlet = BuildCmdlet();
// Act
var result = cmdlet.GetResults().Cast<dynamic>();
// Assert
Assert.AreEqual(2, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P1", Version = new Version("0.9") });
AssertPackageResultsEqual(result.Last(), new { Id = "P2", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsCorrectInstalledPackagesWhenNoParametersAreSpecifiedAndSkipAndTakeAreSpecified() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.First = 1;
cmdlet.Skip = 1;
// Act
var result = cmdlet.GetResults().Cast<dynamic>();
// Assert
Assert.AreEqual(1, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P2", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsFilteredPackagesFromInstalledRepo() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Filter = "P2";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(1, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P2", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsAllPackagesFromActiveRepositoryWhenRemoteIsPresent() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(4, result.Count());
AssertPackageResultsEqual(result.ElementAt(0), new { Id = "P0", Version = new Version("1.1") });
AssertPackageResultsEqual(result.ElementAt(1), new { Id = "P1", Version = new Version("1.1") });
AssertPackageResultsEqual(result.ElementAt(2), new { Id = "P2", Version = new Version("1.2") });
AssertPackageResultsEqual(result.ElementAt(3), new { Id = "P3", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsCorrectPackagesFromActiveRepositoryWhenRemoteAndSkipAndFirstIsPresent() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
cmdlet.First = 2;
cmdlet.Skip = 1;
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(2, result.Count());
AssertPackageResultsEqual(result.ElementAt(0), new { Id = "P1", Version = new Version("1.1") });
AssertPackageResultsEqual(result.ElementAt(1), new { Id = "P2", Version = new Version("1.2") });
}
[TestMethod]
public void GetPackageReturnsFilteredPackagesFromActiveRepositoryWhenRemoteIsPresent() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
cmdlet.Filter = "P1";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(1, result.Count());
AssertPackageResultsEqual(result.ElementAt(0), new { Id = "P1", Version = new Version("1.1") });
}
[TestMethod]
public void GetPackageReturnsAllPackagesFromSpecifiedSourceWhenNoFilterIsSpecified() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
cmdlet.Source = "foo";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(2, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P1", Version = new Version("1.4") });
AssertPackageResultsEqual(result.Last(), new { Id = "P6", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsAllPackagesFromSpecifiedSourceWhenNoFilterIsSpecifiedAndRemoteIsNotSpecified() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Source = "foo";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(2, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P1", Version = new Version("1.4") });
AssertPackageResultsEqual(result.Last(), new { Id = "P6", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsFilteredPackagesFromSpecifiedSourceWhenNoFilterIsSpecified() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
cmdlet.Filter = "P6";
cmdlet.Source = "foo";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(1, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P6", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageThrowsWhenSolutionIsClosedAndRemoteIsNotPresent() {
// Arrange
var cmdlet = BuildCmdlet(isSolutionOpen: false);
// Act
ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(),
"The current environment doesn't have a solution open.");
}
[TestMethod]
public void GetPackageReturnsPackagesFromRemoteWhenSolutionIsClosedAndRemoteIsPresent() {
// Arrange
var cmdlet = BuildCmdlet(isSolutionOpen: false);
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(4, result.Count());
AssertPackageResultsEqual(result.ElementAt(0), new { Id = "P0", Version = new Version("1.1") });
AssertPackageResultsEqual(result.ElementAt(1), new { Id = "P1", Version = new Version("1.1") });
AssertPackageResultsEqual(result.ElementAt(2), new { Id = "P2", Version = new Version("1.2") });
AssertPackageResultsEqual(result.ElementAt(3), new { Id = "P3", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageReturnsPackagesFromRemoteWhenSolutionIsClosedAndSourceIsPresent() {
// Arrange
var cmdlet = BuildCmdlet(isSolutionOpen: false);
cmdlet.Source = "foo";
// Act
var result = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(2, result.Count());
AssertPackageResultsEqual(result.First(), new { Id = "P1", Version = new Version("1.4") });
AssertPackageResultsEqual(result.Last(), new { Id = "P6", Version = new Version("1.0") });
}
[TestMethod]
public void GetPackageThrowsWhenSolutionIsClosedAndUpdatesIsPresent() {
// Arrange
var cmdlet = BuildCmdlet(isSolutionOpen: false);
cmdlet.Updates = new SwitchParameter(isPresent: true);
// Act and Assert
ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(),
"The current environment doesn't have a solution open.");
}
[TestMethod]
public void GetPackageThrowsWhenSolutionIsClosedUpdatesAndSourceArePresent() {
// Arrange
var cmdlet = BuildCmdlet(isSolutionOpen: false);
cmdlet.Updates = new SwitchParameter(isPresent: true);
cmdlet.Source = "foo";
// Act and Assert
ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(),
"The current environment doesn't have a solution open.");
}
[TestMethod]
public void GetPackageReturnsListOfPackagesWithUpdates() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Updates = new SwitchParameter(isPresent: true);
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 2);
AssertPackageResultsEqual(packages.First(), new { Id = "P1", Version = new Version("1.1") });
AssertPackageResultsEqual(packages.Last(), new { Id = "P2", Version = new Version("1.2") });
}
[TestMethod]
public void GetPackageReturnsFilteredListOfPackagesWithUpdates() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Updates = new SwitchParameter(isPresent: true);
cmdlet.Filter = "P1";
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 1);
AssertPackageResultsEqual(packages.First(), new { Id = "P1", Version = new Version("1.1") });
}
[TestMethod]
public void GetPackageReturnsAllPackagesFromSourceWithUpdates() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Updates = new SwitchParameter(isPresent: true);
cmdlet.Source = "foo";
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 1);
AssertPackageResultsEqual(packages.First(), new { Id = "P1", Version = new Version("1.4") });
}
[TestMethod]
public void GetPackageReturnsFilteredPackagesFromSourceWithUpdates() {
// Arrange
var cmdlet = BuildCmdlet();
cmdlet.Updates = new SwitchParameter(isPresent: true);
cmdlet.Source = "foo";
cmdlet.Filter = "P1";
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 1);
AssertPackageResultsEqual(packages.First(), new { Id = "P1", Version = new Version("1.4") });
}
[TestMethod]
public void GetPackagesThrowsWhenNoSourceIsProvidedAndRemoteIsPresent() {
// Arrange
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(GetPackageManager);
var repositorySettings = new Mock<IRepositorySettings>();
repositorySettings.Setup(m => m.RepositoryPath).Returns("foo");
var cmdlet = new Mock<GetPackageCommand>(GetDefaultRepositoryFactory(), new Mock<IPackageSourceProvider>().Object, TestUtils.GetSolutionManager(isSolutionOpen: false), packageManagerFactory.Object, new Mock<IPackageRepository>().Object, null, null) { CallBase = true }.Object;
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
// Act and Assert
ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(), "Unable to retrieve package list because no source was specified.");
}
[TestMethod]
public void GetPackagesReturnsLatestPackageVersionByDefault() {
// Arrange
var source = "http://multi-source";
var cmdlet = BuildCmdlet(repositoryFactory: GetRepositoryFactoryWithMultiplePackageVersions(source), activeSourceName: source);
cmdlet.Source = source;
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 3);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "NHibernate", Version = new Version("1.13") });
AssertPackageResultsEqual(packages.ElementAt(2), new { Id = "TestPack", Version = new Version("0.7") });
}
[TestMethod]
public void GetPackagesDoesNotCollapseVersionIfAllVersionsIsPresent() {
// Arrange
var source = "http://multi-source";
var cmdlet = BuildCmdlet(repositoryFactory: GetRepositoryFactoryWithMultiplePackageVersions(source), packageManagerFactory: GetPackageManagerForMultipleVersions(),
activeSourceName: source);
cmdlet.Source = source;
cmdlet.ListAvailable = new SwitchParameter(isPresent: true);
cmdlet.AllVersions = true;
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 6);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.44") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "jQuery", Version = new Version("1.51") });
AssertPackageResultsEqual(packages.ElementAt(2), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(3), new { Id = "NHibernate", Version = new Version("1.1") });
AssertPackageResultsEqual(packages.ElementAt(4), new { Id = "NHibernate", Version = new Version("1.13") });
AssertPackageResultsEqual(packages.ElementAt(5), new { Id = "TestPack", Version = new Version("0.7") });
}
[TestMethod]
public void GetPackagesReturnsLatestUpdateVersions() {
// Arrange
var source = "http://multi-source";
var cmdlet = BuildCmdlet(repositoryFactory: GetRepositoryFactoryWithMultiplePackageVersions(source), packageManagerFactory: GetPackageManagerForMultipleVersions(),
activeSourceName: source);
cmdlet.Source = source;
cmdlet.Updates = new SwitchParameter(isPresent: true);
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 2);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "TestPack", Version = new Version("0.7") });
}
[TestMethod]
public void RecentPackagesCollapsesVersion() {
// Arrange
var cmdlet = BuildCmdlet(repositoryFactory: GetDefaultRepositoryFactory(), recentPackageRepository: GetRepositoryWithMultiplePackageVersions());
cmdlet.Recent = new SwitchParameter(isPresent: true);
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 3);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "NHibernate", Version = new Version("1.13") });
AssertPackageResultsEqual(packages.ElementAt(2), new { Id = "TestPack", Version = new Version("0.7") });
}
[TestMethod]
public void RecentPackagesFiltersAndCollapsesVersion() {
// Arrange
var cmdlet = BuildCmdlet(repositoryFactory: GetDefaultRepositoryFactory(), recentPackageRepository: GetRepositoryWithMultiplePackageVersions());
cmdlet.Recent = true;
cmdlet.Filter = "NHibernate jQuery";
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 2);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "NHibernate", Version = new Version("1.13") });
}
[TestMethod]
public void RecentPackagesShowsAllPackageVersionsIfSwitchIsPresent() {
// Arrange
var cmdlet = BuildCmdlet(repositoryFactory: GetDefaultRepositoryFactory(), recentPackageRepository: GetRepositoryWithMultiplePackageVersions());
cmdlet.Recent = true;
cmdlet.AllVersions = true;
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 6);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.44") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "jQuery", Version = new Version("1.51") });
AssertPackageResultsEqual(packages.ElementAt(2), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(3), new { Id = "NHibernate", Version = new Version("1.1") });
AssertPackageResultsEqual(packages.ElementAt(4), new { Id = "NHibernate", Version = new Version("1.13") });
AssertPackageResultsEqual(packages.ElementAt(5), new { Id = "TestPack", Version = new Version("0.7") });
}
[TestMethod]
public void RecentPackagesWithShowAllVersionsAppliesFirstAndSkipFilters() {
// Arrange
var cmdlet = BuildCmdlet(repositoryFactory: GetDefaultRepositoryFactory(), recentPackageRepository: GetRepositoryWithMultiplePackageVersions());
cmdlet.Recent = true;
cmdlet.AllVersions = true;
cmdlet.Skip = 2;
cmdlet.First = 2;
// Act
var packages = cmdlet.GetResults<dynamic>();
// Assert
Assert.AreEqual(packages.Count(), 2);
AssertPackageResultsEqual(packages.ElementAt(0), new { Id = "jQuery", Version = new Version("1.52") });
AssertPackageResultsEqual(packages.ElementAt(1), new { Id = "NHibernate", Version = new Version("1.1") });
}
[TestMethod]
public void TestRecentSwitchWorkCorrectly() {
// Arrange
var packageA = PackageUtility.CreatePackage("A", "1.0");
var packageB = PackageUtility.CreatePackage("B", "2.0");
var packageC = PackageUtility.CreatePackage("C", "3.0");
var repository = new MockPackageRepository();
repository.Add(packageA);
repository.Add(packageB);
repository.Add(packageC);
var cmdlet = BuildCmdlet(false, repository);
cmdlet.Recent = true;
// Act
var packages = cmdlet.GetResults().OfType<IPackage>().ToList();
// Assert
Assert.AreEqual(3, packages.Count);
Assert.AreSame(packageA, packages[0]);
Assert.AreSame(packageB, packages[1]);
Assert.AreSame(packageC, packages[2]);
}
[TestMethod]
public void GetPackageInvokeProductUpdateCheckWhenSourceIsHttp() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(productUpdateService: productUpdateService.Object);
cmdlet.Source = "http://bing.com";
cmdlet.ListAvailable = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once());
}
[TestMethod]
public void GetPackageInvokeProductUpdateCheckWhenActiveSourceIsHttp() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(isSolutionOpen: false, productUpdateService: productUpdateService.Object, activeSourceName: "http://msn.com");
cmdlet.ListAvailable = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once());
}
[TestMethod]
public void GetPackageDoNotInvokeProductUpdateCheckWhenActiveSourceIsNotHttp() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(isSolutionOpen: false, productUpdateService: productUpdateService.Object);
cmdlet.ListAvailable = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
[TestMethod]
public void GetPackageInvokeProductUpdateCheckWhenSourceIsNotHttp() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(productUpdateService: productUpdateService.Object);
cmdlet.Source = "foo";
cmdlet.ListAvailable = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
[TestMethod]
public void GetPackageDoNotInvokeProductUpdateCheckWhenGetLocalPackages() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(productUpdateService: productUpdateService.Object);
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
[TestMethod]
public void GetPackageDoNotInvokeProductUpdateCheckWhenGetUpdatesPackages() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(productUpdateService: productUpdateService.Object);
cmdlet.Updates = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
[TestMethod]
public void GetPackageDoNotInvokeProductUpdateCheckWhenGetRecentPackages() {
// Arrange
var productUpdateService = new Mock<IProductUpdateService>();
var cmdlet = BuildCmdlet(productUpdateService: productUpdateService.Object);
cmdlet.Recent = true;
// Act
var packages = cmdlet.GetResults();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
private static void AssertPackageResultsEqual(dynamic a, dynamic b) {
Assert.AreEqual(a.Id, b.Id);
Assert.AreEqual(a.Version, b.Version);
}
private static GetPackageCommand BuildCmdlet(
bool isSolutionOpen = true,
IPackageRepository recentPackageRepository = null,
IProductUpdateService productUpdateService = null,
IPackageRepositoryFactory repositoryFactory = null,
IVsPackageManagerFactory packageManagerFactory = null,
string activeSourceName = "ActiveRepo") {
if (packageManagerFactory == null) {
var mockFactory = new Mock<IVsPackageManagerFactory>();
mockFactory.Setup(m => m.CreatePackageManager()).Returns(GetPackageManager);
packageManagerFactory = mockFactory.Object;
}
if (recentPackageRepository == null) {
recentPackageRepository = new Mock<IPackageRepository>().Object;
}
return new GetPackageCommand(
repositoryFactory ?? GetDefaultRepositoryFactory(activeSourceName),
GetSourceProvider(activeSourceName),
TestUtils.GetSolutionManager(isSolutionOpen: isSolutionOpen),
packageManagerFactory,
recentPackageRepository,
null,
productUpdateService);
}
private static IPackageRepositoryFactory GetDefaultRepositoryFactory(string activeSourceName = "ActiveRepo") {
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
var repository = new Mock<IPackageRepository>();
var packages = new[] { PackageUtility.CreatePackage("P1", "1.4"), PackageUtility.CreatePackage("P6") };
repository.Setup(c => c.GetPackages()).Returns(packages.AsQueryable());
repositoryFactory.Setup(c => c.CreateRepository(new PackageSource("http://bing.com", "http://bing.com"))).Returns(repository.Object);
repositoryFactory.Setup(c => c.CreateRepository(new PackageSource("foo", "foo"))).Returns(repository.Object);
repositoryFactory.Setup(c => c.CreateRepository(new PackageSource(activeSourceName, activeSourceName))).Returns(GetActiveRepository());
return repositoryFactory.Object;
}
private static IPackageRepositoryFactory GetRepositoryFactoryWithMultiplePackageVersions(string sourceName = "MultiSource") {
var factory = new Mock<IPackageRepositoryFactory>();
factory.Setup(c => c.CreateRepository(new PackageSource(sourceName, sourceName))).Returns(GetRepositoryWithMultiplePackageVersions());
return factory.Object;
}
private static IPackageRepository GetRepositoryWithMultiplePackageVersions(string sourceName = "MultiSource") {
var repositoryWithMultiplePackageVersions = new Mock<IPackageRepository>();
var packages = new[] {
PackageUtility.CreatePackage("jQuery", "1.44"),
PackageUtility.CreatePackage("jQuery", "1.51"),
PackageUtility.CreatePackage("jQuery", "1.52"),
PackageUtility.CreatePackage("NHibernate", "1.1"),
PackageUtility.CreatePackage("NHibernate", "1.13"),
PackageUtility.CreatePackage("TestPack", "0.7")
};
repositoryWithMultiplePackageVersions.Setup(c => c.GetPackages()).Returns(packages.AsQueryable());
return repositoryWithMultiplePackageVersions.Object;
}
private static IPackageRepositoryFactory GetRepositoryFactory(IDictionary<string, IPackageRepository> repository) {
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.IsAny<PackageSource>())).Returns<PackageSource>(p => repository[p.Name]);
return repositoryFactory.Object;
}
private static IVsPackageManager GetPackageManager() {
var fileSystem = new Mock<IFileSystem>();
var localRepo = new Mock<ISharedPackageRepository>();
var localPackages = new[] { PackageUtility.CreatePackage("P1", "0.9"), PackageUtility.CreatePackage("P2") };
localRepo.Setup(c => c.GetPackages()).Returns(localPackages.AsQueryable());
return new VsPackageManager(TestUtils.GetSolutionManager(), GetActiveRepository(), fileSystem.Object, localRepo.Object, new Mock<IRecentPackageRepository>().Object);
}
private static IVsPackageManagerFactory GetPackageManagerForMultipleVersions() {
var fileSystem = new Mock<IFileSystem>();
var localRepo = new Mock<ISharedPackageRepository>();
var localPackages = new[] { PackageUtility.CreatePackage("jQuery", "1.2"), PackageUtility.CreatePackage("TestPack", "0.1") };
localRepo.Setup(c => c.GetPackages()).Returns(localPackages.AsQueryable());
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), GetActiveRepository(), fileSystem.Object, localRepo.Object, new Mock<IRecentPackageRepository>().Object);
var factory = new Mock<IVsPackageManagerFactory>();
factory.Setup(c => c.CreatePackageManager()).Returns(packageManager);
return factory.Object;
}
private static IPackageRepository GetActiveRepository() {
var remotePackages = new[] { PackageUtility.CreatePackage("P0", "1.1"), PackageUtility.CreatePackage("P1", "1.1"),
PackageUtility.CreatePackage("P2", "1.2"), PackageUtility.CreatePackage("P3") };
var remoteRepo = new Mock<IPackageRepository>();
remoteRepo.Setup(c => c.GetPackages()).Returns(remotePackages.AsQueryable());
return remoteRepo.Object;
}
private static IPackageSourceProvider GetSourceProvider(string activeSourceName) {
Mock<IPackageSourceProvider> sourceProvider = new Mock<IPackageSourceProvider>();
sourceProvider.Setup(c => c.ActivePackageSource).Returns(new PackageSource(activeSourceName, activeSourceName));
return sourceProvider.Object;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Imaging
{
[StructLayout(LayoutKind.Sequential)]
public sealed class EncoderParameter : IDisposable
{
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
[MarshalAs(UnmanagedType.Struct)]
#pragma warning restore CS0618
private Guid _parameterGuid; // GUID of the parameter
private int _numberOfValues; // Number of the parameter values
private EncoderParameterValueType _parameterValueType; // Value type, like ValueTypeLONG etc.
private IntPtr _parameterValue; // A pointer to the parameter values
~EncoderParameter()
{
Dispose(false);
}
/// <summary>
/// Gets/Sets the Encoder for the EncoderPameter.
/// </summary>
public Encoder Encoder
{
get
{
return new Encoder(_parameterGuid);
}
set
{
_parameterGuid = value.Guid;
}
}
/// <summary>
/// Gets the EncoderParameterValueType object from the EncoderParameter.
/// </summary>
public EncoderParameterValueType Type
{
get
{
return _parameterValueType;
}
}
/// <summary>
/// Gets the EncoderParameterValueType object from the EncoderParameter.
/// </summary>
public EncoderParameterValueType ValueType
{
get
{
return _parameterValueType;
}
}
/// <summary>
/// Gets the NumberOfValues from the EncoderParameter.
/// </summary>
public int NumberOfValues
{
get
{
return _numberOfValues;
}
}
public void Dispose()
{
Dispose(true);
GC.KeepAlive(this);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_parameterValue != IntPtr.Zero)
Marshal.FreeHGlobal(_parameterValue);
_parameterValue = IntPtr.Zero;
}
public EncoderParameter(Encoder encoder, byte value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteByte(_parameterValue, value);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, byte value, bool undefined)
{
_parameterGuid = encoder.Guid;
if (undefined == true)
_parameterValueType = EncoderParameterValueType.ValueTypeUndefined;
else
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteByte(_parameterValue, value);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, short value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeShort;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(short)));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteInt16(_parameterValue, value);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, long value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLong;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, unchecked((int)value));
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, int numerator, int denominator)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeRational;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(2 * size);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, numerator);
Marshal.WriteInt32(Add(_parameterValue, size), denominator);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, long rangebegin, long rangeend)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLongRange;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(2 * size);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, unchecked((int)rangebegin));
Marshal.WriteInt32(Add(_parameterValue, size), unchecked((int)rangeend));
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder,
int numerator1, int demoninator1,
int numerator2, int demoninator2)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeRationalRange;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(4 * size);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, numerator1);
Marshal.WriteInt32(Add(_parameterValue, size), demoninator1);
Marshal.WriteInt32(Add(_parameterValue, 2 * size), numerator2);
Marshal.WriteInt32(Add(_parameterValue, 3 * size), demoninator2);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, string value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeAscii;
_numberOfValues = value.Length;
_parameterValue = Marshal.StringToHGlobalAnsi(value);
GC.KeepAlive(this);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
}
public EncoderParameter(Encoder encoder, byte[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = value.Length;
_parameterValue = Marshal.AllocHGlobal(_numberOfValues);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, byte[] value, bool undefined)
{
_parameterGuid = encoder.Guid;
if (undefined == true)
_parameterValueType = EncoderParameterValueType.ValueTypeUndefined;
else
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = value.Length;
_parameterValue = Marshal.AllocHGlobal(_numberOfValues);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, short[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeShort;
_numberOfValues = value.Length;
int size = Marshal.SizeOf(typeof(short));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * size));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
public unsafe EncoderParameter(Encoder encoder, long[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLong;
_numberOfValues = value.Length;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * size));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
int* dest = (int*)_parameterValue;
fixed (long* source = value)
{
for (int i = 0; i < value.Length; i++)
{
dest[i] = unchecked((int)source[i]);
}
}
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, int[] numerator, int[] denominator)
{
_parameterGuid = encoder.Guid;
if (numerator.Length != denominator.Length)
throw Gdip.StatusException(Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeRational;
_numberOfValues = numerator.Length;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 2 * size));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(i * 2 * size, _parameterValue), (int)numerator[i]);
Marshal.WriteInt32(Add((i * 2 + 1) * size, _parameterValue), (int)denominator[i]);
}
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder, long[] rangebegin, long[] rangeend)
{
_parameterGuid = encoder.Guid;
if (rangebegin.Length != rangeend.Length)
throw Gdip.StatusException(Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeLongRange;
_numberOfValues = rangebegin.Length;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 2 * size));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(i * 2 * size, _parameterValue), unchecked((int)rangebegin[i]));
Marshal.WriteInt32(Add((i * 2 + 1) * size, _parameterValue), unchecked((int)rangeend[i]));
}
GC.KeepAlive(this);
}
public EncoderParameter(Encoder encoder,
int[] numerator1, int[] denominator1,
int[] numerator2, int[] denominator2)
{
_parameterGuid = encoder.Guid;
if (numerator1.Length != denominator1.Length ||
numerator1.Length != denominator2.Length ||
denominator1.Length != denominator2.Length)
throw Gdip.StatusException(Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeRationalRange;
_numberOfValues = numerator1.Length;
int size = Marshal.SizeOf(typeof(int));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 4 * size));
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(_parameterValue, 4 * i * size), numerator1[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 1) * size), denominator1[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 2) * size), numerator2[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 3) * size), denominator2[i]);
}
GC.KeepAlive(this);
}
[Obsolete("This constructor has been deprecated. Use EncoderParameter(Encoder encoder, int numberValues, EncoderParameterValueType type, IntPtr value) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public EncoderParameter(Encoder encoder, int NumberOfValues, int Type, int Value)
{
int size;
switch ((EncoderParameterValueType)Type)
{
case EncoderParameterValueType.ValueTypeByte:
case EncoderParameterValueType.ValueTypeAscii:
size = 1;
break;
case EncoderParameterValueType.ValueTypeShort:
size = 2;
break;
case EncoderParameterValueType.ValueTypeLong:
size = 4;
break;
case EncoderParameterValueType.ValueTypeRational:
case EncoderParameterValueType.ValueTypeLongRange:
size = 2 * 4;
break;
case EncoderParameterValueType.ValueTypeUndefined:
size = 1;
break;
case EncoderParameterValueType.ValueTypeRationalRange:
size = 2 * 2 * 4;
break;
default:
throw Gdip.StatusException(Gdip.WrongState);
}
int bytes = checked(size * NumberOfValues);
_parameterValue = Marshal.AllocHGlobal(bytes);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
for (int i = 0; i < bytes; i++)
{
Marshal.WriteByte(Add(_parameterValue, i), Marshal.ReadByte((IntPtr)(Value + i)));
}
_parameterValueType = (EncoderParameterValueType)Type;
_numberOfValues = NumberOfValues;
_parameterGuid = encoder.Guid;
GC.KeepAlive(this);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
public EncoderParameter(Encoder encoder, int numberValues, EncoderParameterValueType type, IntPtr value)
{
int size;
switch (type)
{
case EncoderParameterValueType.ValueTypeByte:
case EncoderParameterValueType.ValueTypeAscii:
size = 1;
break;
case EncoderParameterValueType.ValueTypeShort:
size = 2;
break;
case EncoderParameterValueType.ValueTypeLong:
size = 4;
break;
case EncoderParameterValueType.ValueTypeRational:
case EncoderParameterValueType.ValueTypeLongRange:
size = 2 * 4;
break;
case EncoderParameterValueType.ValueTypeUndefined:
size = 1;
break;
case EncoderParameterValueType.ValueTypeRationalRange:
size = 2 * 2 * 4;
break;
default:
throw Gdip.StatusException(Gdip.WrongState);
}
int bytes = checked(size * numberValues);
_parameterValue = Marshal.AllocHGlobal(bytes);
if (_parameterValue == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
for (int i = 0; i < bytes; i++)
{
Marshal.WriteByte(Add(_parameterValue, i), Marshal.ReadByte((IntPtr)(value + i)));
}
_parameterValueType = type;
_numberOfValues = numberValues;
_parameterGuid = encoder.Guid;
GC.KeepAlive(this);
}
private static IntPtr Add(IntPtr a, int b)
{
return (IntPtr)((long)a + (long)b);
}
private static IntPtr Add(int a, IntPtr b)
{
return (IntPtr)((long)a + (long)b);
}
}
}
| |
//
// ActionManager.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Gtk;
using System.Collections.Generic;
using ClipperLibrary;
namespace Pinta.Core
{
public class ActionManager
{
public AccelGroup AccelGroup { get; private set; }
public FileActions File { get; private set; }
public EditActions Edit { get; private set; }
public ViewActions View { get; private set; }
public ImageActions Image { get; private set; }
public LayerActions Layers { get; private set; }
public AdjustmentsActions Adjustments { get; private set; }
public EffectsActions Effects { get; private set; }
public AddinActions Addins { get; private set; }
public WindowActions Window { get; private set; }
public HelpActions Help { get; private set; }
public ActionManager ()
{
AccelGroup = new AccelGroup ();
File = new FileActions ();
Edit = new EditActions ();
View = new ViewActions ();
Image = new ImageActions ();
Layers = new LayerActions ();
Adjustments = new AdjustmentsActions ();
Effects = new EffectsActions ();
Addins = new AddinActions ();
Window = new WindowActions ();
Help = new HelpActions ();
}
public void CreateMainMenu (Gtk.MenuBar menu)
{
// File menu
ImageMenuItem file = (ImageMenuItem)menu.Children[0];
file.Submenu = new Menu ();
File.CreateMainMenu ((Menu)file.Submenu);
//Edit menu
ImageMenuItem edit = (ImageMenuItem)menu.Children[1];
edit.Submenu = new Menu ();
Edit.CreateMainMenu ((Menu)edit.Submenu);
// View menu
ImageMenuItem view = (ImageMenuItem)menu.Children[2];
View.CreateMainMenu ((Menu)view.Submenu);
// Image menu
ImageMenuItem image = (ImageMenuItem)menu.Children[3];
image.Submenu = new Menu ();
Image.CreateMainMenu ((Menu)image.Submenu);
//Layers menu
ImageMenuItem layer = (ImageMenuItem)menu.Children[4];
layer.Submenu = new Menu ();
Layers.CreateMainMenu ((Menu)layer.Submenu);
//Adjustments menu
ImageMenuItem adj = (ImageMenuItem)menu.Children[5];
adj.Submenu = new Menu ();
Adjustments.CreateMainMenu ((Menu)adj.Submenu);
// Effects menu
ImageMenuItem eff = (ImageMenuItem)menu.Children[6];
eff.Submenu = new Menu ();
Effects.CreateMainMenu ((Menu)eff.Submenu);
// Add-ins menu
ImageMenuItem addins = (ImageMenuItem)menu.Children[7];
addins.Submenu = new Menu ();
Addins.CreateMainMenu ((Menu)addins.Submenu);
// Window menu
ImageMenuItem window = (ImageMenuItem)menu.Children[8];
window.Submenu = new Menu ();
Window.CreateMainMenu ((Menu)window.Submenu);
//Help menu
ImageMenuItem help = (ImageMenuItem)menu.Children[9];
help.Submenu = new Menu ();
Help.CreateMainMenu ((Menu)help.Submenu);
}
public void CreateToolBar (Gtk.Toolbar toolbar)
{
toolbar.AppendItem (File.New.CreateToolBarItem ());
toolbar.AppendItem (File.Open.CreateToolBarItem ());
toolbar.AppendItem (File.Save.CreateToolBarItem ());
toolbar.AppendItem (File.Print.CreateToolBarItem ());
toolbar.AppendItem (new SeparatorToolItem ());
// Cut/Copy/Paste comes before Undo/Redo on Windows
if (PintaCore.System.OperatingSystem == OS.Windows) {
toolbar.AppendItem (Edit.Cut.CreateToolBarItem ());
toolbar.AppendItem (Edit.Copy.CreateToolBarItem ());
toolbar.AppendItem (Edit.Paste.CreateToolBarItem ());
toolbar.AppendItem (new SeparatorToolItem ());
toolbar.AppendItem (Edit.Undo.CreateToolBarItem ());
toolbar.AppendItem (Edit.Redo.CreateToolBarItem ());
} else {
toolbar.AppendItem (Edit.Undo.CreateToolBarItem ());
toolbar.AppendItem (Edit.Redo.CreateToolBarItem ());
toolbar.AppendItem (new SeparatorToolItem ());
toolbar.AppendItem (Edit.Cut.CreateToolBarItem ());
toolbar.AppendItem (Edit.Copy.CreateToolBarItem ());
toolbar.AppendItem (Edit.Paste.CreateToolBarItem ());
}
toolbar.AppendItem (new SeparatorToolItem ());
toolbar.AppendItem (Image.CropToSelection.CreateToolBarItem ());
toolbar.AppendItem (Edit.Deselect.CreateToolBarItem ());
View.CreateToolBar (toolbar);
toolbar.AppendItem (new SeparatorToolItem ());
toolbar.AppendItem (new ToolBarImage ("StatusBar.CursorXY.png"));
ToolBarLabel cursor = new ToolBarLabel (" 0, 0");
toolbar.AppendItem (cursor);
PintaCore.Chrome.LastCanvasCursorPointChanged += delegate {
Gdk.Point pt = PintaCore.Chrome.LastCanvasCursorPoint;
cursor.Text = string.Format (" {0}, {1}", pt.X, pt.Y);
};
toolbar.AppendItem(new SeparatorToolItem());
toolbar.AppendItem(new ToolBarImage("Tools.RectangleSelect.png"));
ToolBarLabel SelectionSize = new ToolBarLabel(" 0, 0");
toolbar.AppendItem(SelectionSize);
PintaCore.Workspace.SelectionChanged += delegate
{
double minX = double.MaxValue;
double minY = double.MaxValue;
double maxX = double.MinValue;
double maxY = double.MinValue;
//Calculate the minimum rectangular bounds that surround the current selection.
foreach (List<IntPoint> li in PintaCore.Workspace.ActiveDocument.Selection.SelectionPolygons)
{
foreach (IntPoint ip in li)
{
if (minX > ip.X)
{
minX = ip.X;
}
if (minY > ip.Y)
{
minY = ip.Y;
}
if (maxX < ip.X)
{
maxX = ip.X;
}
if (maxY < ip.Y)
{
maxY = ip.Y;
}
}
}
double xDiff = maxX - minX;
double yDiff = maxY - minY;
if (double.IsNegativeInfinity(xDiff))
{
xDiff = 0d;
}
if (double.IsNegativeInfinity(yDiff))
{
yDiff = 0d;
}
SelectionSize.Text = string.Format(" {0}, {1}", xDiff, yDiff);
};
}
public void RegisterHandlers ()
{
File.RegisterHandlers ();
Edit.RegisterHandlers ();
Image.RegisterHandlers ();
Layers.RegisterHandlers ();
View.RegisterHandlers ();
Help.RegisterHandlers ();
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using CoreTweet.Core;
using Newtonsoft.Json;
namespace CoreTweet
{
/// <summary>
/// Represents a user.
/// </summary>
public class User : CoreBase
{
/// <summary>
/// Gets or sets a value that determines if the user has an account with "contributor mode" enabled, allowing for Tweets issued by the user to be co-authored by another account. Rarely true.
/// </summary>
[JsonProperty("contributors_enabled")]
public bool IsContributorsEnabled { get; set; }
/// <summary>
/// Gets or sets the UTC datetime that the user account was created on Twitter.
/// </summary>
[JsonProperty("created_at")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has not altered the theme or background of its user profile.
/// </summary>
[JsonProperty("default_profile")]
public bool IsDefaultProfile { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has not uploaded their own avatar and a default egg avatar is used instead.
/// </summary>
[JsonProperty("default_profile_image")]
public bool IsDefaultProfileImage { get; set; }
/// <summary>
/// <para>Gets or sets the user-defined string describing their account.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets the email address.
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Gets or sets the entities which have been parsed out of the URL or description fields defined by the user.
/// </summary>
[JsonProperty("entities")]
public UserEntities Entities { get; set; }
/// <summary>
/// <para>Gets or sets the number of tweets this user has favorited in the account's lifetime.</para>
/// <para>British spelling used in the field name for historical reasons.</para>
/// </summary>
[JsonProperty("favourites_count")]
public int FavouritesCount { get; set; }
/// <summary>
/// <para>Gets or sets a value that determines if the authenticating user has issued a follow request to this protected user account.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("follow_request_sent")]
public bool? IsFollowRequestSent { get; set; }
/// <summary>
/// <para>Gets or sets the number of followers this account currently has.</para>
/// <para>Under certain conditions of duress, the field will temporarily indicates 0.</para>
/// </summary>
[JsonProperty("followers_count")]
public int FollowersCount { get; set; }
/// <summary>
/// <para>Gets or sets the number of the account is following (AKA its followings).</para>
/// <para>Under certain conditions of duress, the field will temporarily indicates 0.</para>
/// </summary>
[JsonProperty("friends_count")]
public int FriendsCount { get; set; }
/// <summary>
/// <para>Gets or sets a value that determines if the user has enabled the possibility of geotagging their Tweets.</para>
/// <para>This field must be true for the current user to attach geographic data when using statuses/update.</para>
/// </summary>
[JsonProperty("geo_enabled")]
public bool IsGeoEnabled { get; set; }
/// <summary>
/// Gets or sets the integer representation of the unique identifier for this User.
/// </summary>
[JsonProperty("id")]
public long? Id { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is a participant in Twitter's translator community.
/// </summary>
[JsonProperty("is_translator")]
public bool IsTranslator { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is a participant in Twitter's translator community.
/// </summary>
[JsonProperty("is_translation_enabled")]
public bool IsTranslationEnabled { get; set; }
/// <summary>
/// <para>Gets or sets the BCP 47 code for the user's self-declared user interface language.</para>
/// <para>May or may not have anything to do with the content of their Tweets.</para>
/// </summary>
[JsonProperty("lang")]
public string Language { get; set; }
/// <summary>
/// Gets or sets the number of public lists that the user is a member of.
/// </summary>
[JsonProperty("listed_count")]
public int? ListedCount { get; set; }
/// <summary>
/// <para>Gets or sets the user-defined location for this account's profile.</para>
/// <para>Not necessarily a location nor parsable.</para>
/// <para>This field will occasionally be fuzzily interpreted by the Search service.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is muted by authenticating user.
/// </summary>
[JsonProperty("muting")]
public bool? IsMuting { get; set; }
/// <summary>
/// <para>Gets or sets the name of the user, as they've defined it.</para>
/// <para>Not necessarily a person's name.</para>
/// <para>Typically capped at 20 characters, but subject to be changed.</para>
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("needs_phone_verification")]
public bool? NeedsPhoneVerification { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color chosen by the user for their background.
/// </summary>
[JsonProperty("profile_background_color")]
public string ProfileBackgroundColor { get; set; }
/// <summary>
/// Gets or sets a HTTP-based URL pointing to the background image the user has uploaded for their profile.
/// </summary>
[JsonProperty("profile_background_image_url")]
public string ProfileBackgroundImageUrl { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the background image the user has uploaded for their profile.
/// </summary>
[JsonProperty("profile_background_image_url_https")]
public string ProfileBackgroundImageUrlHttps { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user's <see cref="CoreTweet.User.ProfileBackgroundImageUrl"/> should be tiled when displayed.
/// </summary>
[JsonProperty("profile_background_tile")]
public bool IsProfileBackgroundTile { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the standard web representation of the user's uploaded profile banner. By adding a final path element of the URL, you can obtain different image sizes optimized for specific displays. In the future, an API method will be provided to serve these URLs so that you need not modify the original URL. For size variations, please see User Profile Images and Banners.
/// </summary>
[JsonProperty("profile_banner_url")]
public string ProfileBannerUrl { get; set; }
/// <summary>
/// Gets or sets a HTTP-based URL pointing to the user's avatar image. See User Profile Images and Banners.
/// </summary>
[JsonProperty("profile_image_url")]
public string ProfileImageUrl { get; set; }
/// <summary>
/// Gets or sets a HTTPS-based URL pointing to the user's avatar image.
/// </summary>
[JsonProperty("profile_image_url_https")]
public string ProfileImageUrlHttps { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display links with in their Twitter UI.
/// </summary>
[JsonProperty("profile_link_color")]
public string ProfileLinkColor { get; set; }
/// <summary>
/// Gets or sets the user-defined location for this account's profile.
/// </summary>
[JsonProperty("profile_location")]
public Place ProfileLocation { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display sidebar borders with in their Twitter UI.
/// </summary>
[JsonProperty("profile_sidebar_border_color")]
public string ProfileSidebarBorderColor { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display sidebar backgrounds with in their Twitter UI.
/// </summary>
[JsonProperty("profile_sidebar_fill_color")]
public string ProfileSidebarFillColor { get; set; }
/// <summary>
/// Gets or sets the hexadecimal color the user has chosen to display text with in their Twitter UI.
/// </summary>
[JsonProperty("profile_text_color")]
public string ProfileTextColor { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user wants their uploaded background image to be used.
/// </summary>
[JsonProperty("profile_use_background_image")]
public bool IsProfileUseBackgroundImage { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has chosen to protect their Tweets.
/// </summary>
[JsonProperty("protected")]
public bool IsProtected { get; set; }
/// <summary>
/// <para>Gets or sets the screen name, handle, or alias that this user identifies themselves with.</para>
/// <para><see cref="ScreenName"/> are unique but subject to be changed.</para>
/// <para>Use <see cref="Id"/> as a user identifier whenever possible.</para>
/// <para>Typically a maximum of 15 characters long, but some historical accounts may exist with longer names.</para>
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user would like to see media inline. Somewhat disused.
/// </summary>
[JsonProperty("show_all_inline_media")]
public bool? IsShowAllInlineMedia { get; set; }
/// <summary>
/// <para>Gets or sets the user's most recent tweet or retweet.</para>
/// <para>In some circumstances, this data cannot be provided and this field will be omitted, null, or empty.</para>
/// <para>Perspectival attributes within tweets embedded within users cannot always be relied upon.</para>
/// </summary>
[JsonProperty("status")]
public Status Status { get; set; }
/// <summary>
/// Gets or sets the number of tweets (including retweets) issued by the user.
/// </summary>
[JsonProperty("statuses_count")]
public int StatusesCount { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has been suspended by Twitter.
/// </summary>
[JsonProperty("suspended")]
public bool? IsSuspended { get; set; }
/// <summary>
/// <para>Gets or sets the string describes the time zone the user declares themselves within.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("time_zone")]
public string TimeZone { get; set; }
/// <summary>
/// <para>Gets or sets the URL provided by the user in association with their profile.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
/// <summary>
/// <para>Gets or sets the offset from GMT/UTC in seconds.</para>
/// <para>Nullable.</para>
/// </summary>
[JsonProperty("utc_offset")]
public int? UtcOffset { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user has a verified account.
/// </summary>
[JsonProperty("verified")]
public bool IsVerified { get; set; }
/// <summary>
/// Gets or sets a textual representation of the two-letter country codes this user is withheld from.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string WithheldInCountries { get; set; }
/// <summary>
/// Gets or sets the content being withheld is the "status" or a "user."
/// </summary>
[JsonProperty("withheld_scope")]
public string WithheldScope { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id.HasValue ? this.Id.Value.ToString("D") : "";
}
}
/// <summary>
/// Represents a user response with rate limit.
/// </summary>
public class UserResponse : User, ITwitterResponse
{
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a relationship with another user.
/// </summary>
public class Relationship : CoreBase, ITwitterResponse
{
/// <summary>
/// Gets or sets the target of the relationship.
/// </summary>
[JsonProperty("target")]
public RelationshipTarget Target { get; set; }
/// <summary>
/// Gets or sets the source of the relationship.
/// </summary>
[JsonProperty("source")]
public RelationshipSource Source { get; set; }
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class RelationshipTarget : CoreBase
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the screen name of the user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are following the user.
/// </summary>
[JsonProperty("following")]
public bool IsFollowing { get; set; }
/// <summary>
/// Gets or sets a value that determines if the user is following you.
/// </summary>
[JsonProperty("followed_by")]
public bool IsFollowedBy { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user has received a follower request from the other.
/// </summary>
[JsonProperty("following_received")]
public bool? IsFollowingReceived { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user has sent a follower request to the other.
/// </summary>
[JsonProperty("following_requested")]
public bool? IsFollowingRequested { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class RelationshipSource : RelationshipTarget
{
/// <summary>
/// Gets or sets a value that determines if you can send a direct message to the user.
/// </summary>
[JsonProperty("can_dm")]
public bool CanDM { get; set; }
/// <summary>
/// Gets or sets a value that determines if you get all replies.
/// </summary>
[JsonProperty("all_replies")]
public bool? AllReplies { get; set; }
/// <summary>
/// Gets or sets a value that determines if you want retweets or not.
/// </summary>
[JsonProperty("want_retweets")]
public bool? WantsRetweets { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are blocking the user.
/// </summary>
[JsonProperty("blocking")]
public bool? IsBlocking { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are blocked by the user.
/// </summary>
[JsonProperty("blocked_by")]
public bool? IsBlockedBy { get; set; }
/// <summary>
/// Gets or sets a value that determines if you marked the user as spam.
/// </summary>
[JsonProperty("marked_spam")]
public bool? IsMarkedSpam { get; set; }
/// <summary>
/// Gets or sets a value that determines if the notifications of the user enabled or not.
/// </summary>
[JsonProperty("notifications_enabled")]
public bool? IsNotificationsEnabled { get; set; }
/// <summary>
/// Gets or sets a value that determines if you are muting the user.
/// </summary>
[JsonProperty("muting")]
public bool? IsMuting { get; set; }
}
/// <summary>
/// Represents a frienship.
/// </summary>
public class Friendship : CoreBase
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the screen name of the user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
//TODO: improve this summary
/// <summary>
/// Gets or sets the connections.
/// </summary>
[JsonProperty("connections")]
public string[] Connections { get; set; }
}
/// <summary>
/// Represents a category.
/// </summary>
public class Category : CoreBase
{
/// <summary>
/// Gets or sets the name of the category.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the slug of the category.
/// </summary>
[JsonProperty("slug")]
public string Slug { get; set; }
/// <summary>
/// Gets or sets the size of the category.
/// </summary>
[JsonProperty("size")]
public int Size { get; set; }
/// <summary>
/// Gets or sets the users in this category.
/// </summary>
[JsonProperty("users")]
public User[] Users { get; set; }
}
/// <summary>
/// Represents a category response with rate limit.
/// </summary>
public class CategoryResponse : Category, ITwitterResponse
{
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents the variations of a size of a profile banner.
/// </summary>
public class ProfileBannerSizes : CoreBase, ITwitterResponse
{
/// <summary>
/// Gets or sets the size for Web.
/// </summary>
[JsonProperty("web")]
public ProfileBannerSize Web { get; set; }
/// <summary>
/// Gets or sets the size for Web with high resolution devices.
/// </summary>
[JsonProperty("web_retina")]
public ProfileBannerSize WebRetina { get; set; }
/// <summary>
/// Gets or sets the size for Apple iPad.
/// </summary>
[JsonProperty("ipad")]
public ProfileBannerSize IPad { get; set; }
/// <summary>
/// Gets or sets the size for Apple iPad with high resolution.
/// </summary>
[JsonProperty("ipad_retina")]
public ProfileBannerSize IPadRetina { get; set; }
/// <summary>
/// Gets or sets the size for mobile devices.
/// </summary>
[JsonProperty("mobile")]
public ProfileBannerSize Mobile { get; set; }
/// <summary>
/// Gets or sets the size for mobile devices with high resolution devices.
/// </summary>
[JsonProperty("mobile_retina")]
public ProfileBannerSize MobileRetina { get; set; }
/// <summary>
/// Gets or sets the rate limit of the response.
/// </summary>
public RateLimit RateLimit { get; set; }
/// <summary>
/// Gets or sets the JSON of the response.
/// </summary>
public string Json { get; set; }
}
/// <summary>
/// Represents a size of a profile banner.
/// </summary>
public class ProfileBannerSize : CoreBase
{
/// <summary>
/// Gets or sets the width in pixels of the size.
/// </summary>
[JsonProperty("w")]
public int Width { get; set; }
/// <summary>
/// Gets or sets the height in pixels of the size.
/// </summary>
[JsonProperty("h")]
public int Height { get; set; }
/// <summary>
/// Gets or sets the URL of the size.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
/// <summary>
/// Represents an entity object for user.
/// </summary>
public class UserEntities : CoreBase
{
/// <summary>
/// Gets or sets the entities for <see cref="User.Url"/> field.
/// </summary>
[JsonProperty("url")]
public Entities Url { get; set; }
/// <summary>
/// Gets or sets the entities for <see cref="User.Description"/> field.
/// </summary>
[JsonProperty("description")]
public Entities Description { get; set; }
}
}
| |
//
// IWidgetBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Drawing;
namespace Xwt.Backends
{
/// <summary>
/// The Xwt widget backend base interface. All Xwt widget backends implement it.
/// </summary>
public interface IWidgetBackend: IBackend
{
/// <summary>
/// Initialize the backend with the specified EventSink.
/// </summary>
/// <param name="eventSink">The frontend event sink (usually the <see cref="Xwt.Backends.BackendHost"/> of the frontend).</param>
void Initialize (IWidgetEventSink eventSink);
/// <summary>
/// Releases all resources used by the widget
/// </summary>
/// <remarks>
/// This method is called to free all managed and unmanaged resources held by the backend.
/// In general, the backend should destroy the native widget at this point.
/// When a widget that has children is disposed, the Dispose method is called on all
/// backends of all widgets in the children hierarchy.
/// </remarks>
void Dispose ();
/// <summary>
/// Gets or sets a value indicating whether this widget is visible.
/// </summary>
/// <value><c>true</c> if visible; otherwise, <c>false</c>.</value>
bool Visible { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this widget is sensitive/enabled.
/// </summary>
/// <value><c>true</c> if sensitive; otherwise, <c>false</c>.</value>
bool Sensitive { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this widget can get focus.
/// </summary>
/// <value><c>true</c> if this instance can get focus; otherwise, <c>false</c>.</value>
bool CanGetFocus { get; set; }
/// <summary>
/// Gets a value indicating whether this widget has the focus.
/// </summary>
/// <value><c>true</c> if this widget has the focus; otherwise, <c>false</c>.</value>
bool HasFocus { get; }
/// <summary>
/// Gets or sets the opacity of this widget.
/// </summary>
/// <value>The opacity.</value>
double Opacity { get; set; }
/// <summary>
/// Gets the final size of this widget.
/// </summary>
/// <value>The size.</value>
Size Size { get; }
/// <summary>
/// Converts widget relative coordinates to screen coordinates.
/// </summary>
/// <returns>The screen coordinates.</returns>
/// <param name="widgetCoordinates">The relative widget coordinates.</param>
Point ConvertToScreenCoordinates (Point widgetCoordinates);
/// <summary>
/// Sets the minimum size of the widget
/// </summary>
/// <param name='width'>
/// Minimum width. If the value is -1, it means no minimum width.
/// </param>
/// <param name='height'>
/// Minimum height. If the value is -1, it means no minimum height.
/// </param>
void SetMinSize (double width, double height);
/// <summary>
/// Sets the size request / natural size of this widget.
/// </summary>
/// <param name="width">Natural width, or -1 if no custom natural width has been set.</param>
/// <param name="height">Natural height, or -1 if no custom natural height has been set.</param>
void SetSizeRequest (double width, double height);
/// <summary>
/// Sets the focus on this widget.
/// </summary>
void SetFocus ();
/// <summary>
/// Updates the layout of this widget.
/// </summary>
void UpdateLayout ();
/// <summary>
/// Gets the preferred size of this widget.
/// </summary>
/// <returns>The widgets preferred size.</returns>
/// <param name="widthConstraint">Width constraint.</param>
/// <param name="heightConstraint">Height constraint.</param>
Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint);
/// <summary>
/// Gets the native toolkit widget.
/// </summary>
/// <value>The native widget.</value>
object NativeWidget { get; }
/// <summary>
/// Starts a drag operation originated in this widget
/// </summary>
/// <param name='data'>
/// Drag operation arguments
/// </param>
void DragStart (DragStartData data);
/// <summary>
/// Sets up a widget so that XWT will start a drag operation when the user clicks and drags on the widget.
/// </summary>
/// <param name='types'>
/// Types of data that can be dragged from this widget
/// </param>
/// <param name='dragAction'>
/// Bitmask of possible actions for a drag from this widget
/// </param>
/// <remarks>
/// When a drag operation is started, the backend should fire the OnDragStarted event
/// </remarks>
void SetDragSource (TransferDataType[] types, DragDropAction dragAction);
/// <summary>
/// Sets a widget as a potential drop destination
/// </summary>
/// <param name='types'>
/// Types of data that can be dropped on this widget
/// </param>
/// <param name='dragAction'>
/// Bitmask of possible actions for a drop on this widget
/// </param>
void SetDragTarget (TransferDataType[] types, DragDropAction dragAction);
/// <summary>
/// Gets or sets the native font of this widget.
/// </summary>
/// <value>The font.</value>
object Font { get; set; }
/// <summary>
/// Gets or sets the background color of this widget.
/// </summary>
/// <value>The background color.</value>
Color BackgroundColor { get; set; }
/// <summary>
/// Gets or sets the tooltip text.
/// </summary>
/// <value>The tooltip text.</value>
string TooltipText { get; set; }
/// <summary>
/// Sets the cursor shape to be used when the mouse is over the widget
/// </summary>
/// <param name='cursorType'>
/// The cursor type.
/// </param>
void SetCursor (CursorType cursorType);
}
/// <summary>
/// The widget event sink routes backend events to the frontend
/// </summary>
public interface IWidgetEventSink
{
/// <summary>
/// Notifies the frontend that the mouse is moved over the widget in a drag operation,
/// to check whether a drop operation is allowed.
/// </summary>
/// <param name="args">The drag over check event arguments.</param>
/// <remarks>
/// This event handler provides information about the type of the data that is going
/// to be dropped, but not the actual data.
/// The frontend decides which of the proposed actions will be performed when
/// the item is dropped by setting <see cref="Xwt.DragOverCheckEventArgs.AllowedAction"/>.
/// If the value is not set or it is set to <see cref="Xwt.DragDropAction.Default"/>,
/// the action data should be provided using <see cref="OnDragOver"/>. If the proposed action
/// is not allowed, the backend should not allow the user to perform the drop action.
/// </remarks>
void OnDragOverCheck (DragOverCheckEventArgs args);
/// <summary>
/// Notifies the frontend that the mouse is moved over the widget in a drag operation,
/// to check whether a drop operation is allowed for the data being dragged.
/// </summary>
/// <param name="args">The drag over event arguments.</param>
/// <remarks>
/// This event handler provides information about the actual data that is going to be dropped.
/// The frontend decides which of the proposed actions will be performed when the
/// item is dropped by setting <see cref="Xwt.DragOverEventArgs.AllowedAction"/>. If the proposed action
/// is not allowed, the backend should not perform the drop action.
/// </remarks>
void OnDragOver (DragOverEventArgs args);
/// <summary>
/// Notifies the frontend that there is a pending drop operation, to check whether it is allowed.
/// </summary>
/// <param name="args">The drop check event arguments.</param>
/// <remarks>
/// This event handler provides information about the type of the data that is going
/// to be dropped, but not the actual data. The frontend decides whether the action
/// is allowed or not by setting <see cref="Xwt.DragCheckEventArgs.Result"/>.
/// The backend should abort the drop operation, if the result is <see cref="Xwt.DragDropResult.Canceled"/>,
/// or provide more information including actual data using <see cref="OnDragDrop"/> otherwise.
/// </remarks>
void OnDragDropCheck (DragCheckEventArgs args);
/// <summary>
/// Notifies the frontend of a drop operation to perform.
/// </summary>
/// <param name="args">The drop event arguments.</param>
/// <remarks>
/// This event handler provides information about the dropped data and the actual data.
/// The frontend will set <see cref="Xwt.DragEventArgs.Success"/> to <c>true</c> when the drop
/// was successful, <c>false</c> otherwise.
/// </remarks>
void OnDragDrop (DragEventArgs args);
/// <summary>
/// Notifies the frontend that the mouse is leaving the widget in a drag operation.
/// </summary>
void OnDragLeave (EventArgs args);
/// <summary>
/// Notifies the frontend that the drag&drop operation has finished.
/// </summary>
/// <param name="args">The event arguments.</param>
void OnDragFinished (DragFinishedEventArgs args);
/// <summary>
/// Notifies the frontend about a starting drag operation and retrieves the data for the drag&drop operation.
/// </summary>
/// <returns>
/// The information about the starting drag operation and the data to be transferred,
/// or <c>null</c> to abort dragging.
/// </returns>
DragStartData OnDragStarted ();
/// <summary>
/// Notifies the frontend that a key has been pressed.
/// </summary>
/// <param name="args">The Key arguments.</param>
void OnKeyPressed (KeyEventArgs args);
/// <summary>
/// Notifies the frontend that a key has been released.
/// </summary>
/// <param name="args">The Key arguments.</param>
void OnKeyReleased (KeyEventArgs args);
/// <summary>
/// Notifies the frontend that a text has been entered.
/// </summary>
/// <param name="args">The text input arguments.</param>
void OnTextInput (TextInputEventArgs args);
/// <summary>
/// Notifies the frontend that the widget has received the focus.
/// </summary>
void OnGotFocus ();
/// <summary>
/// Notifies the frontend that the widget has lost the focus.
/// </summary>
void OnLostFocus ();
/// <summary>
/// Notifies the frontend that the mouse has entered the widget.
/// </summary>
void OnMouseEntered ();
/// <summary>
/// Notifies the frontend that the mouse has left the widget.
/// </summary>
void OnMouseExited ();
/// <summary>
/// Notifies the frontend that a mouse button has been pressed.
/// </summary>
/// <param name="args">The button arguments.</param>
void OnButtonPressed (ButtonEventArgs args);
/// <summary>
/// Notifies the frontend that a mouse button has been released.
/// </summary>
/// <param name="args">The button arguments.</param>
void OnButtonReleased (ButtonEventArgs args);
/// <summary>
/// Notifies the frontend that the mouse has moved.
/// </summary>
/// <param name="args">The mouse movement arguments.</param>
void OnMouseMoved (MouseMovedEventArgs args);
/// <summary>
/// Notifies the frontend that the widget bounds have changed.
/// </summary>
void OnBoundsChanged ();
/// <summary>
/// Notifies the frontend about a scroll action.
/// </summary>
/// <param name="args">The mouse scrolled arguments.</param>
void OnMouseScrolled(MouseScrolledEventArgs args);
/// <summary>
/// Gets the preferred size from the frontend (it will not include the widget margin).
/// </summary>
/// <returns>The size preferred by the frontend without widget margin.</returns>
/// <param name="widthConstraint">The width constraint.</param>
/// <param name="heightConstraint">The height constraint.</param>
/// <remarks>
/// The returned size is >= 0. If a constraint is specified, the returned size will not
/// be bigger than the constraint. In most cases the frontend will retrieve the preferred size
/// from the backend using <see cref="Xwt.Backends.IWidgetBackend.GetPreferredSize"/> and adjust it
/// optionally.
/// </remarks>
Size GetPreferredSize (SizeConstraint widthConstraint = default(SizeConstraint), SizeConstraint heightConstraint = default(SizeConstraint));
/// <summary>
/// Notifies the frontend that the preferred size of this widget has changed
/// </summary>
/// <remarks>
/// This method must be called when the widget changes its preferred size.
/// This method doesn't need to be called if the resize is the result of changing
/// a widget property. For example, it is not necessary to call it when the text
/// of a label is changed (the fronted will automatically rise this event when
/// the property changes). However, it has to be called when the the shape of the
/// widget changes on its own, for example if the size of a button changes as
/// a result of clicking on it.
/// </remarks>
void OnPreferredSizeChanged ();
/// <summary>
/// Gets a value indicating whether the frontend supports custom scrolling.
/// </summary>
/// <returns><c>true</c>, if custom scrolling is supported, <c>false</c> otherwise.</returns>
/// <remarks>
/// If the frontend supports custom scrolling, the backend must set the scroll adjustments
/// using <see cref="SetScrollAdjustments"/> to allow the frontend to handle scrolling.
/// </remarks>
bool SupportsCustomScrolling ();
/// <summary>
/// Sets the scroll adjustments for custom scrolling.
/// </summary>
/// <param name="horizontal">The horizontal adjustment backend.</param>
/// <param name="vertical">The vertical adjustment backend.</param>
void SetScrollAdjustments (IScrollAdjustmentBackend horizontal, IScrollAdjustmentBackend vertical);
/// <summary>
/// Gets the default natural size of the widget
/// </summary>
/// <returns>
/// The default natural size.
/// </returns>
/// <remarks>
/// This method should only be used if there isn't a platform-specific natural
/// size for the widget. There may be widgets for which XWT can't provide
/// a default natural width or height, in which case it return 0.
/// </remarks>
Size GetDefaultNaturalSize ();
}
/// <summary>
/// Event identifiers supported by all Xwt widgets to subscribe to
/// </summary>
[Flags]
public enum WidgetEvent
{
/// <summary> The widget can/wants to validate the type of a drag over operation. </summary>
DragOverCheck = 1,
/// <summary> The widget can/wants to validate the data of a drag over operation. </summary>
DragOver = 1 << 1,
/// <summary> The widget can/wants to validate a drop operation by its type. </summary>
DragDropCheck = 1 << 2,
/// <summary> The widget can/wants to validate the data of and perform a drop operation. </summary>
DragDrop = 1 << 3,
/// <summary> The widget can/wants to be notified of leaving drag operations. </summary>
DragLeave = 1 << 4,
/// <summary> The widget can/wants to be notified of pressed keys. </summary>
KeyPressed = 1 << 5,
/// <summary> The widget can/wants to be notified of released keys. </summary>
KeyReleased = 1 << 6,
/// <summary> The widget wants to check its size when it changes. </summary>
PreferredSizeCheck = 1 << 7,
/// <summary> The widget can/wants to be notified when it receives the focus. </summary>
GotFocus = 1 << 8,
/// <summary> The widget can/wants to be notified when it looses the focus. </summary>
LostFocus = 1 << 9,
/// <summary> The widget can/wants to be notified when the mouse enters it. </summary>
MouseEntered = 1 << 10,
/// <summary> The widget can/wants to be notified when the mouse leaves it. </summary>
MouseExited = 1 << 11,
/// <summary> The widget can/wants to be notified of pressed buttons. </summary>
ButtonPressed = 1 << 12,
/// <summary> The widget can/wants to be notified of released buttons. </summary>
ButtonReleased = 1 << 13,
/// <summary> The widget can/wants to be notified of mouse movements. </summary>
MouseMoved = 1 << 14,
/// <summary> The widget can/wants to be notified when a drag operation starts. </summary>
DragStarted = 1 << 15,
/// <summary> The widget can/wants to be notified when its bounds change. </summary>
BoundsChanged = 1 << 16,
/// <summary> The widget can/wants to be notified of scroll events. </summary>
MouseScrolled = 1 << 17,
/// <summary> The widget can/wants to be notified of text input events. </summary>
TextInput = 1 << 18
}
/// <summary>
/// Arguments for a starting drag&drop operation.
/// </summary>
public class DragStartData
{
/// <summary>
/// Gets the collection of data to be transferred through the drag operation.
/// </summary>
/// <value>The data to transfer.</value>
public TransferDataSource Data { get; private set; }
/// <summary>
/// Gets the type of the drag action.
/// </summary>
/// <value>The drag action type.</value>
public DragDropAction DragAction { get; private set; }
/// <summary>
/// Gets the image backend of the drag image.
/// </summary>
/// <value>The drag icon backend.</value>
public object ImageBackend { get; private set; }
/// <summary>
/// Gets X coordinate of the drag image hotspot.
/// </summary>
/// <value>The image hotspot X coordinate.</value>
public double HotX { get; private set; }
/// <summary>
/// Gets Y coordinate of the drag image hotspot.
/// </summary>
/// <value>The image hotspot Y coordinate.</value>
public double HotY { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Xwt.Backends.DragStartData"/> class.
/// </summary>
/// <param name="data">The collection of data to be transferred through drag operation.</param>
/// <param name="action">The type of the drag action.</param>
/// <param name="imageBackend">The image backend of the drag image.</param>
/// <param name="hotX">The image hotspot X coordinate.</param>
/// <param name="hotY">The image hotspot Y coordinate.</param>
internal DragStartData (TransferDataSource data, DragDropAction action, object imageBackend, double hotX, double hotY)
{
Data = data;
DragAction = action;
ImageBackend = imageBackend;
HotX = hotX;
HotY = hotY;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.PostEditor
{
public partial class PostEditorFooter : UserControl, IStatusBar
{
private const int MIN_STATUS_MESSAGE_WIDTH = 50;
private readonly List<ViewSwitchTabControl> tabs = new List<ViewSwitchTabControl>();
private readonly Stack<string> statusStack = new Stack<string>();
private string defaultStatus;
private readonly Image imgBg;
public PostEditorFooter()
{
imgBg = ResourceHelper.LoadAssemblyResourceBitmap("Images.StatusBackground.png");
SetStyle(
ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint,
true);
SetStyle(ControlStyles.ResizeRedraw, true);
InitializeComponent();
tableLayoutPanel1.BackColor = Color.Transparent;
ManageVisibility();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (!SystemInformation.HighContrast)
{
Rectangle fadeRect = new Rectangle(0, tableLayoutPanel1.Top + 1, ClientSize.Width, imgBg.Height);
GraphicsHelper.TileFillUnscaledImageHorizontally(e.Graphics, imgBg, fadeRect);
using (Brush b = new SolidBrush(new HCColor(229, 238, 248, SystemColors.Window)))
e.Graphics.FillRectangle(b, 0, fadeRect.Bottom, ClientSize.Width, ClientSize.Height - fadeRect.Bottom);
}
else
{
e.Graphics.Clear(SystemColors.Window);
}
HCColor startColor = new HCColor(0xA5A5A5, SystemColors.WindowFrame);
HCColor endColor = new HCColor(0xC1CEDE, SystemColors.WindowFrame);
if (BidiHelper.IsRightToLeft)
Swap(ref startColor, ref endColor);
const int GRADIENT_WIDTH = 350;
int gradientStart = !BidiHelper.IsRightToLeft ? flowLayoutPanel.Right : flowLayoutPanel.Left - GRADIENT_WIDTH;
int gradientEnd = !BidiHelper.IsRightToLeft ? flowLayoutPanel.Right + GRADIENT_WIDTH : flowLayoutPanel.Left;
DrawGradientLine(e.Graphics, startColor, endColor, 0, tableLayoutPanel1.Top, ClientSize.Width, gradientStart, gradientEnd);
}
private static void DrawGradientLine(Graphics g, Color leftColor, Color rightColor, int left, int top, int right, int startGradient, int endGradient)
{
if (startGradient > left)
using (Pen p = new Pen(leftColor))
g.DrawLine(p, left, top, startGradient, top);
if (endGradient < right)
using (Pen p = new Pen(rightColor))
g.DrawLine(p, endGradient, top, right, top);
if (startGradient < right && endGradient > left)
{
using (Brush b = new LinearGradientBrush(
new Rectangle(startGradient, top, endGradient - startGradient, 1),
leftColor, rightColor, LinearGradientMode.Horizontal))
{
using (Pen p = new Pen(b))
{
g.DrawLine(p, startGradient, top, endGradient, top);
}
}
}
}
private static void Swap<T>(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
public string[] TabNames
{
set
{
flowLayoutPanel.Controls.Clear();
tabs.Clear();
int i = 0;
foreach (string name in value)
{
i++;
var tab = new ViewSwitchTabControl();
tab.AccessibleName = name;
tab.AccessibleRole = AccessibleRole.PageTab;
tab.Text = name;
tab.TabStop = true;
tab.TabIndex = i;
tab.Margin = new Padding(0);
tab.Click += tab_Click;
tab.SelectedChanged += tab_SelectedChanged;
flowLayoutPanel.Controls.Add(tab);
tabs.Add(tab);
}
}
}
public string[] Shortcuts
{
set
{
for (int i = 0; i < value.Length; i++)
tabs[i].Shortcut = value[i];
}
}
void tab_SelectedChanged(object sender, EventArgs e)
{
if (!((ViewSwitchTabControl)sender).Selected)
return;
int selectedIndex = tabs.IndexOf((ViewSwitchTabControl)sender);
for (int i = 0; i < tabs.Count; i++)
{
ViewSwitchTabControl tab = tabs[i];
if (i != selectedIndex)
tab.Selected = false;
}
foreach (ViewSwitchTabControl tab in tabs)
tab.Refresh();
}
void tab_Click(object sender, EventArgs e)
{
int index = tabs.IndexOf((ViewSwitchTabControl)sender);
SelectTab(index);
}
public int SelectedTabIndex
{
get
{
for (int i = 0; i < tabs.Count; i++)
if (tabs[i].Selected)
return i;
return -1;
}
}
public void SelectTab(int index)
{
if (index < 0 || index >= tabs.Count)
throw new IndexOutOfRangeException();
for (int i = 0; i < tabs.Count; i++)
tabs[i].Selected = (index == i);
if (SelectedTabChanged != null)
SelectedTabChanged(this, EventArgs.Empty);
}
public event EventHandler SelectedTabChanged;
public void SetWordCountMessage(string msg)
{
labelWordCount.Text = msg ?? "";
ManageVisibility();
}
public void PushStatusMessage(string msg)
{
statusStack.Push(msg);
UpdateStatusMessage();
}
public void PopStatusMessage()
{
Debug.Assert(statusStack.Count > 0);
if (statusStack.Count > 0)
statusStack.Pop();
UpdateStatusMessage();
}
public void SetStatusMessage(string msg)
{
defaultStatus = msg;
UpdateStatusMessage();
}
private void UpdateStatusMessage()
{
string msg = null;
foreach (string str in statusStack)
{
if (str != null)
{
msg = str;
break;
}
}
if (msg == null)
msg = defaultStatus;
labelStatus.Text = msg ?? "";
ManageVisibility();
}
private void ManageVisibility()
{
tableLayoutPanel1.SuspendLayout();
labelWordCount.Visible = labelWordCount.Text.Length > 0;
labelStatus.Visible = labelStatus.Text.Length > 0;
labelSeparator.Visible = labelStatus.Visible && labelWordCount.Visible;
// Set a minumum width so the columns in the TableLayoutPanel don't overlap.
int tableMinimumWidth = tableLayoutPanel1.Padding.Horizontal + tableLayoutPanel1.Margin.Horizontal;
int tableMinimumHeight = tableLayoutPanel1.Height;
if (flowLayoutPanel.Visible)
tableMinimumWidth += flowLayoutPanel.Padding.Horizontal + flowLayoutPanel.Margin.Horizontal + flowLayoutPanel.Width;
if (labelWordCount.Visible)
tableMinimumWidth += labelWordCount.Padding.Horizontal + labelWordCount.Margin.Horizontal + labelWordCount.Width;
if (labelSeparator.Visible)
tableMinimumWidth += labelSeparator.Padding.Horizontal + labelSeparator.Margin.Horizontal + labelSeparator.Width;
if (labelStatus.Visible)
{
tableMinimumWidth += labelStatus.Padding.Horizontal + labelStatus.Margin.Horizontal;
int maximumWidth = Math.Max(Width - tableMinimumWidth, MIN_STATUS_MESSAGE_WIDTH);
tableMinimumWidth += FitOrAutoEllipsisLabel(labelStatus, maximumWidth);
}
tableLayoutPanel1.MinimumSize = new Size(tableMinimumWidth, tableMinimumHeight);
tableLayoutPanel1.ResumeLayout(true);
}
/// <param name="label">The label to try and fit in the remaining width.</param>
/// <param name="maximumWidth">The maximum width the label can be.</param>
/// <returns>The width of the label after fitting or auto-ellipsising it.</returns>
private int FitOrAutoEllipsisLabel(Label label, int maximumWidth)
{
if (label.PreferredWidth > maximumWidth)
{
label.AutoEllipsis = true;
label.AutoSize = false;
label.Width = maximumWidth;
label.Height = label.PreferredHeight;
return maximumWidth;
}
else
{
label.AutoEllipsis = false;
label.AutoSize = true;
return label.PreferredWidth;
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
ManageVisibility();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
internal sealed class ComplexViewGenerator : ViewGenerator
{
internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory,
PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
{
base.Initialize(errorContext, expressionFactory, so, db, parameters);
this.inputParameters = parameters;
}
internal override FormatStartData GenerateStartData(PSObject so)
{
FormatStartData startFormat = base.GenerateStartData(so);
startFormat.shapeInfo = new ComplexViewHeaderInfo();
return startFormat;
}
internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit)
{
FormatEntryData fed = new FormatEntryData();
if (this.dataBaseInfo.view != null)
fed.formatEntryInfo = GenerateComplexViewEntryFromDataBaseInfo(so, enumerationLimit);
else
fed.formatEntryInfo = GenerateComplexViewEntryFromProperties(so, enumerationLimit);
return fed;
}
private ComplexViewEntry GenerateComplexViewEntryFromProperties(PSObject so, int enumerationLimit)
{
ComplexViewObjectBrowser browser = new ComplexViewObjectBrowser(this.ErrorManager, this.expressionFactory, enumerationLimit);
return browser.GenerateView(so, this.inputParameters);
}
private ComplexViewEntry GenerateComplexViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit)
{
// execute on the format directive
ComplexViewEntry cve = new ComplexViewEntry();
// NOTE: we set a max depth to protect ourselves from infinite loops
const int maxTreeDepth = 50;
ComplexControlGenerator controlGenerator =
new ComplexControlGenerator(this.dataBaseInfo.db,
this.dataBaseInfo.view.loadingInfo,
this.expressionFactory,
this.dataBaseInfo.view.formatControlDefinitionHolder.controlDefinitionList,
this.ErrorManager,
enumerationLimit,
this.errorContext);
controlGenerator.GenerateFormatEntries(maxTreeDepth,
this.dataBaseInfo.view.mainControl, so, cve.formatValueList);
return cve;
}
}
/// <summary>
/// Class to process a complex control directive and generate
/// the corresponding formatting tokens.
/// </summary>
internal sealed class ComplexControlGenerator
{
internal ComplexControlGenerator(TypeInfoDataBase dataBase,
DatabaseLoadingInfo loadingInfo,
PSPropertyExpressionFactory expressionFactory,
List<ControlDefinition> controlDefinitionList,
FormatErrorManager resultErrorManager,
int enumerationLimit,
TerminatingErrorContext errorContext)
{
_db = dataBase;
_loadingInfo = loadingInfo;
_expressionFactory = expressionFactory;
_controlDefinitionList = controlDefinitionList;
_errorManager = resultErrorManager;
_enumerationLimit = enumerationLimit;
_errorContext = errorContext;
}
internal void GenerateFormatEntries(int maxTreeDepth, ControlBase control,
PSObject so, List<FormatValue> formatValueList)
{
if (control == null)
{
throw PSTraceSource.NewArgumentNullException("control");
}
ExecuteFormatControl(new TraversalInfo(0, maxTreeDepth), control,
so, formatValueList);
}
private bool ExecuteFormatControl(TraversalInfo level, ControlBase control,
PSObject so, List<FormatValue> formatValueList)
{
// we are looking for a complex control to execute
ComplexControlBody complexBody = null;
// we might have a reference
ControlReference controlReference = control as ControlReference;
if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody))
{
// retrieve the reference
complexBody = DisplayDataQuery.ResolveControlReference(
_db,
_controlDefinitionList,
controlReference) as ComplexControlBody;
}
else
{
// try as an in line control
complexBody = control as ComplexControlBody;
}
// finally, execute the control body
if (complexBody != null)
{
// we have an inline control, just execute it
ExecuteFormatControlBody(level, so, complexBody, formatValueList);
return true;
}
return false;
}
private void ExecuteFormatControlBody(TraversalInfo level,
PSObject so, ComplexControlBody complexBody, List<FormatValue> formatValueList)
{
ComplexControlEntryDefinition activeControlEntryDefinition =
GetActiveComplexControlEntryDefinition(complexBody, so);
ExecuteFormatTokenList(level,
so, activeControlEntryDefinition.itemDefinition.formatTokenList, formatValueList);
}
private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(ComplexControlBody complexBody, PSObject so)
{
// see if we have an override that matches
var typeNames = so.InternalTypeNames;
TypeMatch match = new TypeMatch(_expressionFactory, _db, typeNames);
foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList)
{
if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo, so)))
{
return x;
}
}
if (match.BestMatch != null)
{
return match.BestMatch as ComplexControlEntryDefinition;
}
else
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
match = new TypeMatch(_expressionFactory, _db, typesWithoutPrefix);
foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList)
{
if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo)))
{
return x;
}
}
if (match.BestMatch != null)
{
return match.BestMatch as ComplexControlEntryDefinition;
}
}
// we do not have any override, use default
return complexBody.defaultEntry;
}
}
private void ExecuteFormatTokenList(TraversalInfo level,
PSObject so, List<FormatToken> formatTokenList, List<FormatValue> formatValueList)
{
if (so == null)
{
throw PSTraceSource.NewArgumentNullException("so");
}
// guard against infinite loop
if (level.Level == level.MaxDepth)
{
return;
}
FormatEntry fe = new FormatEntry();
formatValueList.Add(fe);
#region foreach loop
foreach (FormatToken t in formatTokenList)
{
TextToken tt = t as TextToken;
if (tt != null)
{
FormatTextField ftf = new FormatTextField();
ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt);
fe.formatValueList.Add(ftf);
continue;
}
var newline = t as NewLineToken;
if (newline != null)
{
for (int i = 0; i < newline.count; i++)
{
fe.formatValueList.Add(new FormatNewLine());
}
continue;
}
FrameToken ft = t as FrameToken;
if (ft != null)
{
// instantiate a new entry and attach a frame info object
FormatEntry feFrame = new FormatEntry();
feFrame.frameInfo = new FrameInfo();
// add the frame info
feFrame.frameInfo.firstLine = ft.frameInfoDefinition.firstLine;
feFrame.frameInfo.leftIndentation = ft.frameInfoDefinition.leftIndentation;
feFrame.frameInfo.rightIndentation = ft.frameInfoDefinition.rightIndentation;
// execute the list inside the frame
ExecuteFormatTokenList(level, so, ft.itemDefinition.formatTokenList, feFrame.formatValueList);
// add the frame computation results to the current format entry
fe.formatValueList.Add(feFrame);
continue;
}
#region CompoundPropertyToken
CompoundPropertyToken cpt = t as CompoundPropertyToken;
if (cpt != null)
{
if (!EvaluateDisplayCondition(so, cpt.conditionToken))
{
// token not active, skip it
continue;
}
// get the property from the object
object val = null;
// if no expression was specified, just use the
// object itself
if (cpt.expression == null || string.IsNullOrEmpty(cpt.expression.expressionValue))
{
val = so;
}
else
{
PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(cpt.expression, _loadingInfo);
List<PSPropertyExpressionResult> resultList = ex.GetValues(so);
if (resultList.Count > 0)
{
val = resultList[0].Result;
if (resultList[0].Exception != null)
{
_errorManager.LogPSPropertyExpressionFailedResult(resultList[0], so);
}
}
}
// if the token is has a formatting string, it's a leaf node,
// do the formatting and we will be done
if (cpt.control == null || cpt.control is FieldControlBody)
{
// Since it is a leaf node we just consider it an empty string and go
// on with formatting
if (val == null)
{
val = string.Empty;
}
FieldFormattingDirective fieldFormattingDirective = null;
StringFormatError formatErrorObject = null;
if (cpt.control != null)
{
fieldFormattingDirective = ((FieldControlBody)cpt.control).fieldFormattingDirective;
if (fieldFormattingDirective != null && _errorManager.DisplayFormatErrorString)
{
formatErrorObject = new StringFormatError();
}
}
IEnumerable e = PSObjectHelper.GetEnumerable(val);
FormatPropertyField fpf = new FormatPropertyField();
if (cpt.enumerateCollection && e != null)
{
foreach (object x in e)
{
if (x == null)
{
// nothing to process
continue;
}
fpf = new FormatPropertyField();
fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, _enumerationLimit, formatErrorObject, _expressionFactory);
fe.formatValueList.Add(fpf);
}
}
else
{
fpf = new FormatPropertyField();
fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, _enumerationLimit, formatErrorObject, _expressionFactory);
fe.formatValueList.Add(fpf);
}
if (formatErrorObject != null && formatErrorObject.exception != null)
{
_errorManager.LogStringFormatError(formatErrorObject);
fpf.propertyValue = _errorManager.FormatErrorString;
}
}
else
{
// An empty result that is not a leaf node should not be expanded
if (val == null)
{
continue;
}
IEnumerable e = PSObjectHelper.GetEnumerable(val);
if (cpt.enumerateCollection && e != null)
{
foreach (object x in e)
{
if (x == null)
{
// nothing to process
continue;
}
// proceed with the recursion
ExecuteFormatControl(level.NextLevel, cpt.control, PSObject.AsPSObject(x), fe.formatValueList);
}
}
else
{
// proceed with the recursion
ExecuteFormatControl(level.NextLevel, cpt.control, PSObjectHelper.AsPSObject(val), fe.formatValueList);
}
}
}
#endregion CompoundPropertyToken
}
#endregion foreach loop
}
private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken)
{
if (conditionToken == null)
return true;
PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(conditionToken, _loadingInfo);
PSPropertyExpressionResult expressionResult;
bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult);
if (expressionResult != null && expressionResult.Exception != null)
{
_errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so);
}
return retVal;
}
private TypeInfoDataBase _db;
private DatabaseLoadingInfo _loadingInfo;
private PSPropertyExpressionFactory _expressionFactory;
private List<ControlDefinition> _controlDefinitionList;
private FormatErrorManager _errorManager;
private TerminatingErrorContext _errorContext;
private int _enumerationLimit;
}
internal class TraversalInfo
{
internal TraversalInfo(int level, int maxDepth)
{
_level = level;
_maxDepth = maxDepth;
}
internal int Level { get { return _level; } }
internal int MaxDepth { get { return _maxDepth; } }
internal TraversalInfo NextLevel
{
get
{
return new TraversalInfo(_level + 1, _maxDepth);
}
}
private int _level;
private int _maxDepth;
}
/// <summary>
/// Class to generate a complex view from properties.
/// </summary>
internal sealed class ComplexViewObjectBrowser
{
internal ComplexViewObjectBrowser(FormatErrorManager resultErrorManager, PSPropertyExpressionFactory mshExpressionFactory, int enumerationLimit)
{
_errorManager = resultErrorManager;
_expressionFactory = mshExpressionFactory;
_enumerationLimit = enumerationLimit;
}
/// <summary>
/// Given an object, generate a tree-like view
/// of the object.
/// </summary>
/// <param name="so">Object to process.</param>
/// <param name="inputParameters">Parameters from the command line.</param>
/// <returns>Complex view entry to send to the output command.</returns>
internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParameters inputParameters)
{
_complexSpecificParameters = (ComplexSpecificParameters)inputParameters.shapeParameters;
int maxDepth = _complexSpecificParameters.maxDepth;
TraversalInfo level = new TraversalInfo(0, maxDepth);
List<MshParameter> mshParameterList = null;
mshParameterList = inputParameters.mshParameterList;
// create a top level entry as root of the tree
ComplexViewEntry cve = new ComplexViewEntry();
var typeNames = so.InternalTypeNames;
if (TreatAsScalarType(typeNames))
{
FormatEntry fe = new FormatEntry();
cve.formatValueList.Add(fe);
DisplayRawObject(so, fe.formatValueList);
}
else
{
// check if the top level object is an enumeration
IEnumerable e = PSObjectHelper.GetEnumerable(so);
if (e != null)
{
// let's start the traversal with an enumeration
FormatEntry fe = new FormatEntry();
cve.formatValueList.Add(fe);
DisplayEnumeration(e, level, fe.formatValueList);
}
else
{
// let's start the traversal with a traversal on properties
DisplayObject(so, level, mshParameterList, cve.formatValueList);
}
}
return cve;
}
private void DisplayRawObject(PSObject so, List<FormatValue> formatValueList)
{
FormatPropertyField fpf = new FormatPropertyField();
StringFormatError formatErrorObject = null;
if (_errorManager.DisplayFormatErrorString)
{
// we send a format error object down to the formatting calls
// only if we want to show the formatting error strings
formatErrorObject = new StringFormatError();
}
fpf.propertyValue = PSObjectHelper.SmartToString(so, _expressionFactory, _enumerationLimit, formatErrorObject);
if (formatErrorObject != null && formatErrorObject.exception != null)
{
// if we did no thave any errors in the expression evaluation
// we might have errors in the formatting, if present
_errorManager.LogStringFormatError(formatErrorObject);
if (_errorManager.DisplayFormatErrorString)
{
fpf.propertyValue = _errorManager.FormatErrorString;
}
}
formatValueList.Add(fpf);
formatValueList.Add(new FormatNewLine());
}
/// <summary>
/// Recursive call to display an object.
/// </summary>
/// <param name="so">Object to display.</param>
/// <param name="currentLevel">Current level in the traversal.</param>
/// <param name="parameterList">List of parameters from the command line.</param>
/// <param name="formatValueList">List of format tokens to add to.</param>
private void DisplayObject(PSObject so, TraversalInfo currentLevel, List<MshParameter> parameterList,
List<FormatValue> formatValueList)
{
// resolve the names of the properties
List<MshResolvedExpressionParameterAssociation> activeAssociationList =
AssociationManager.SetupActiveProperties(parameterList, so, _expressionFactory);
// create a format entry
FormatEntry fe = new FormatEntry();
formatValueList.Add(fe);
// add the display name of the object
string objectDisplayName = GetObjectDisplayName(so);
if (objectDisplayName != null)
objectDisplayName = "class " + objectDisplayName;
AddPrologue(fe.formatValueList, "{", objectDisplayName);
ProcessActiveAssociationList(so, currentLevel, activeAssociationList, AddIndentationLevel(fe.formatValueList));
AddEpilogue(fe.formatValueList, "}");
}
private void ProcessActiveAssociationList(PSObject so,
TraversalInfo currentLevel,
List<MshResolvedExpressionParameterAssociation> activeAssociationList,
List<FormatValue> formatValueList)
{
foreach (MshResolvedExpressionParameterAssociation a in activeAssociationList)
{
FormatTextField ftf = new FormatTextField();
ftf.text = a.ResolvedExpression.ToString() + " = ";
formatValueList.Add(ftf);
// compute the value of the entry
List<PSPropertyExpressionResult> resList = a.ResolvedExpression.GetValues(so);
object val = null;
if (resList.Count >= 1)
{
PSPropertyExpressionResult result = resList[0];
if (result.Exception != null)
{
_errorManager.LogPSPropertyExpressionFailedResult(result, so);
if (_errorManager.DisplayErrorStrings)
{
val = _errorManager.ErrorString;
}
else
{
val = string.Empty;
}
}
else
{
val = result.Result;
}
}
// extract the optional max depth
TraversalInfo level = currentLevel;
if (a.OriginatingParameter != null)
{
object maxDepthKey = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.DepthEntryKey);
if (maxDepthKey != AutomationNull.Value)
{
int parameterMaxDept = (int)maxDepthKey;
level = new TraversalInfo(currentLevel.Level, parameterMaxDept);
}
}
IEnumerable e = null;
if (val != null || (level.Level >= level.MaxDepth))
e = PSObjectHelper.GetEnumerable(val);
if (e != null)
{
formatValueList.Add(new FormatNewLine());
DisplayEnumeration(e, level.NextLevel, AddIndentationLevel(formatValueList));
}
else if (val == null || TreatAsLeafNode(val, level))
{
DisplayLeaf(val, formatValueList);
}
else
{
formatValueList.Add(new FormatNewLine());
// we need to go one more level down
DisplayObject(PSObject.AsPSObject(val), level.NextLevel, null,
AddIndentationLevel(formatValueList));
}
}
}
/// <summary>
/// Recursive call to display an object.
/// </summary>
/// <param name="e">Enumeration to display.</param>
/// <param name="level">Current level in the traversal.</param>
/// <param name="formatValueList">List of format tokens to add to.</param>
private void DisplayEnumeration(IEnumerable e, TraversalInfo level, List<FormatValue> formatValueList)
{
AddPrologue(formatValueList, "[", null);
DisplayEnumerationInner(e, level, AddIndentationLevel(formatValueList));
AddEpilogue(formatValueList, "]");
formatValueList.Add(new FormatNewLine());
}
private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List<FormatValue> formatValueList)
{
int enumCount = 0;
foreach (object x in e)
{
if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping)
{
throw new PipelineStoppedException();
}
if (_enumerationLimit >= 0)
{
if (_enumerationLimit == enumCount)
{
DisplayLeaf(PSObjectHelper.Ellipsis, formatValueList);
break;
}
enumCount++;
}
if (TreatAsLeafNode(x, level))
{
DisplayLeaf(x, formatValueList);
}
else
{
// check if the top level object is an enumeration
IEnumerable e1 = PSObjectHelper.GetEnumerable(x);
if (e1 != null)
{
formatValueList.Add(new FormatNewLine());
DisplayEnumeration(e1, level.NextLevel, AddIndentationLevel(formatValueList));
}
else
{
DisplayObject(PSObjectHelper.AsPSObject(x), level.NextLevel, null, formatValueList);
}
}
}
}
/// <summary>
/// Display a leaf value.
/// </summary>
/// <param name="val">Object to display.</param>
/// <param name="formatValueList">List of format tokens to add to.</param>
private void DisplayLeaf(object val, List<FormatValue> formatValueList)
{
FormatPropertyField fpf = new FormatPropertyField();
fpf.propertyValue = PSObjectHelper.FormatField(null, PSObjectHelper.AsPSObject(val), _enumerationLimit, null, _expressionFactory);
formatValueList.Add(fpf);
formatValueList.Add(new FormatNewLine());
}
/// <summary>
/// Determine if we have to stop the expansion.
/// </summary>
/// <param name="val">Object to verify.</param>
/// <param name="level">Current level of recursion.</param>
/// <returns></returns>
private static bool TreatAsLeafNode(object val, TraversalInfo level)
{
if (level.Level >= level.MaxDepth || val == null)
return true;
return TreatAsScalarType(PSObject.GetTypeNames(val));
}
/// <summary>
/// Treat as scalar check.
/// </summary>
/// <param name="typeNames">Name of the type to check.</param>
/// <returns>True if it has to be treated as a scalar.</returns>
private static bool TreatAsScalarType(Collection<string> typeNames)
{
return DefaultScalarTypes.IsTypeInList(typeNames);
}
private string GetObjectDisplayName(PSObject so)
{
if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.none)
return null;
var typeNames = so.InternalTypeNames;
if (typeNames.Count == 0)
{
return "PSObject";
}
if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName)
{
// get the last token in the full name
string[] arr = typeNames[0].Split(Utils.Separators.Dot);
if (arr.Length > 0)
return arr[arr.Length - 1];
}
return typeNames[0];
}
private static void AddPrologue(List<FormatValue> formatValueList, string openTag, string label)
{
if (label != null)
{
FormatTextField ftfLabel = new FormatTextField();
ftfLabel.text = label;
formatValueList.Add(ftfLabel);
formatValueList.Add(new FormatNewLine());
}
FormatTextField ftf = new FormatTextField();
ftf.text = openTag;
formatValueList.Add(ftf);
formatValueList.Add(new FormatNewLine());
}
private static void AddEpilogue(List<FormatValue> formatValueList, string closeTag)
{
FormatTextField ftf = new FormatTextField();
ftf.text = closeTag;
formatValueList.Add(ftf);
formatValueList.Add(new FormatNewLine());
}
private List<FormatValue> AddIndentationLevel(List<FormatValue> formatValueList)
{
FormatEntry feFrame = new FormatEntry();
feFrame.frameInfo = new FrameInfo();
// add the frame info
feFrame.frameInfo.firstLine = 0;
feFrame.frameInfo.leftIndentation = _indentationStep;
feFrame.frameInfo.rightIndentation = 0;
formatValueList.Add(feFrame);
return feFrame.formatValueList;
}
private ComplexSpecificParameters _complexSpecificParameters;
/// <summary>
/// Indentation added to each level in the recursion.
/// </summary>
private int _indentationStep = 2;
private FormatErrorManager _errorManager;
private PSPropertyExpressionFactory _expressionFactory;
private int _enumerationLimit;
}
}
| |
#pragma warning disable 0168
using System;
using System.Linq;
using nHydrate.Generator.Models;
using System.Text;
using nHydrate.Generator.Common.Util;
using System.Collections.Generic;
using nHydrate.Generator.Common;
namespace nHydrate.Generator.EFCodeFirstNetCore.Generators.Contexts
{
public class ContextGeneratedTemplate : EFCodeFirstNetCoreBaseTemplate
{
private StringBuilder sb = new StringBuilder();
private ModelConfiguration _modelConfiguration = null;
public ContextGeneratedTemplate(ModelRoot model)
: base(model)
{
if (model.ModelConfigurations.ContainsKey(typeof(EFCodeFirstNetCoreProjectGenerator).Name))
_modelConfiguration = model.ModelConfigurations[typeof(EFCodeFirstNetCoreProjectGenerator).Name] as ModelConfiguration;
if (_modelConfiguration == null)
_modelConfiguration = new ModelConfiguration();
}
#region BaseClassTemplate overrides
public override string FileName => _model.ProjectName + "Entities.Generated.cs";
public string ParentItemName => _model.ProjectName + "Entities.cs";
public override string FileContent
{
get
{
GenerateContent();
return sb.ToString();
}
}
#endregion
#region GenerateContent
private void GenerateContent()
{
nHydrate.Generator.GenerationHelper.AppendFileGeneatedMessageInCode(sb);
sb.AppendLine("#pragma warning disable 612");
this.AppendUsingStatements();
sb.AppendLine("namespace " + this.GetLocalNamespace());
sb.AppendLine("{");
this.AppendTypeTableEnums();
this.AppendTableMapping();
this.AppendClass();
sb.AppendLine("}");
sb.AppendLine();
sb.AppendLine($"namespace {this.GetLocalNamespace()}.Entity");
sb.AppendLine("{");
sb.AppendLine("}");
sb.AppendLine("#pragma warning restore 612");
}
private void AppendTableMapping()
{
sb.AppendLine(" #region EntityMappingConstants Enumeration");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// A map for all entity types in this library");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public enum EntityMappingConstants");
sb.AppendLine(" {");
foreach (var table in _model.Database.Tables.Where(x => (x.TypedTable != TypedTableConstants.EnumOnly)).OrderBy(x => x.PascalName))
{
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// A mapping for the the {table.PascalName} entity");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" {table.PascalName},");
}
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
}
private void AppendUsingStatements()
{
sb.AppendLine("using System;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using Microsoft.EntityFrameworkCore;");
sb.AppendLine("using System.Configuration;");
sb.AppendLine("using Microsoft.EntityFrameworkCore.ChangeTracking;");
sb.AppendLine();
}
private void AppendClass()
{
sb.AppendLine(" #region Entity Context");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The entity context for the defined model schema");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public partial class " + _model.ProjectName + "Entities : Microsoft.EntityFrameworkCore.DbContext, IContext");
sb.AppendLine(" {");
sb.AppendLine(" /// <summary />");
sb.AppendLine(" public static Action<string> QueryLogger { get; set; }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// A unique key for this object instance");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public Guid InstanceKey { get; private set; }");
sb.AppendLine();
//Create the modifier property
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The audit modifier used to mark database edits");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" protected ContextStartup _contextStartup = new ContextStartup(null);");
sb.AppendLine();
sb.AppendLine(" private static object _seqCacheLock = new object();");
sb.AppendLine();
// Create consts for version and modelKey
sb.AppendLine(" private const string _version = \"" + _model.Version + "." + _model.GeneratedVersion + "\";");
sb.AppendLine(" private const string _modelKey = \"" + _model.Key + "\";");
sb.AppendLine(" protected string _connectionString = null;");
sb.AppendLine();
//Events
sb.AppendLine(" /// <summary />");
sb.AppendLine(" public event EventHandler<" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs> BeforeSaveModifiedEntity;");
sb.AppendLine(" /// <summary />");
sb.AppendLine(" protected virtual void OnBeforeSaveModifiedEntity(" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs e)");
sb.AppendLine(" {");
sb.AppendLine(" if (this.BeforeSaveModifiedEntity != null)");
sb.AppendLine(" this.BeforeSaveModifiedEntity(this, e);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary />");
sb.AppendLine(" public event EventHandler<" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs> BeforeSaveAddedEntity;");
sb.AppendLine(" /// <summary />");
sb.AppendLine(" protected virtual void OnBeforeSaveAddedEntity(" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs e)");
sb.AppendLine(" {");
sb.AppendLine(" if (this.BeforeSaveAddedEntity != null)");
sb.AppendLine(" this.BeforeSaveAddedEntity(this, e);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary />");
sb.AppendLine(" public event EventHandler<" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs> AfterSaveModifiedEntity;");
sb.AppendLine(" /// <summary />");
sb.AppendLine(" protected virtual void OnAfterSaveModifiedEntity(" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs e)");
sb.AppendLine(" {");
sb.AppendLine(" if (this.AfterSaveModifiedEntity != null)");
sb.AppendLine(" this.AfterSaveModifiedEntity(this, e);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary />");
sb.AppendLine(" public event EventHandler<" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs> AfterSaveAddedEntity;");
sb.AppendLine(" /// <summary />");
sb.AppendLine(" protected virtual void OnAfterSaveAddedEntity(" + this.GetLocalNamespace() + ".EventArguments.EntityListEventArgs e)");
sb.AppendLine(" {");
sb.AppendLine(" if (this.AfterSaveAddedEntity != null)");
sb.AppendLine(" this.AfterSaveAddedEntity(this, e);");
sb.AppendLine(" }");
sb.AppendLine();
#region Constructors
sb.AppendLine(" #region Constructors");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initializes a new {_model.ProjectName}Entities object using the connection string found in the '{_model.ProjectName}Entities' section of the application configuration file.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities() :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _connectionString = ConfigurationManager.ConnectionStrings[\"" + _model.ProjectName + "Entities\"]?.ConnectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = new ContextStartup(null, true);");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(ContextStartup contextStartup) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _connectionString = ConfigurationManager.ConnectionStrings[\"" + _model.ProjectName + "Entities\"]?.ConnectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = contextStartup;");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(ContextStartup contextStartup, string connectionString) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _connectionString = connectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = contextStartup;");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// Initialize a new {_model.ProjectName}Entities object with an audit modifier.");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public {_model.ProjectName}Entities(string connectionString) :");
sb.AppendLine(" base()");
sb.AppendLine(" {");
sb.AppendLine(" _connectionString = connectionString;");
sb.AppendLine(" InstanceKey = Guid.NewGuid();");
sb.AppendLine(" _contextStartup = new ContextStartup(null, true);");
sb.AppendLine(" this.CommandTimeout = _contextStartup.CommandTimeout;");
sb.AppendLine(" this.OnContextCreated();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" partial void OnContextCreated();");
sb.AppendLine(" partial void OnBeforeSaveChanges(ref bool cancel);");
sb.AppendLine(" partial void OnAfterSaveChanges();");
sb.AppendLine(" partial void OnModelCreated(ModelBuilder modelBuilder);");
sb.AppendLine();
#region OnModelCreating
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Model creation event");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" protected override void OnModelCreating(ModelBuilder modelBuilder)");
sb.AppendLine(" {");
sb.AppendLine(" base.OnModelCreating(modelBuilder);");
sb.AppendLine();
#region Map Tables
sb.AppendLine(" #region Map Tables");
//Tables
foreach (var item in _model.Database.Tables.Where(x => !x.AssociativeTable && (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
string schema = null;
if (!string.IsNullOrEmpty(item.DBSchema)) schema = item.DBSchema;
var dbTableName = item.DatabaseName;
if (item.IsTenant)
dbTableName = _model.TenantPrefix + "_" + item.DatabaseName;
if (string.IsNullOrEmpty(schema))
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + ">().ToTable(\"" + dbTableName + "\");");
else
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + ">().ToTable(\"" + dbTableName + "\", \"" + schema + "\");");
}
//Views
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.DatabaseName))
{
string schema = null;
if (!string.IsNullOrEmpty(item.DBSchema)) schema = item.DBSchema;
var dbTableName = item.DatabaseName;
if (string.IsNullOrEmpty(schema))
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + ">().ToTable(\"" + dbTableName + "\");");
else
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + ">().ToTable(\"" + dbTableName + "\", \"" + schema + "\");");
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Create annotations for properties
sb.AppendLine(" #region Setup Fields");
sb.AppendLine();
//Tables
foreach (var table in _model.Database.Tables.Where(x => (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
sb.AppendLine(" //Field setup for " + table.PascalName + " entity");
foreach (var column in table.GetColumns().OrderBy(x => x.Name))
{
#region Determine if this is a type table Value field and if so ignore
{
Table typeTable = null;
if (table.IsColumnRelatedToTypeTable(column, out string pascalRoleName) || (column.PrimaryKey && table.TypedTable != TypedTableConstants.None))
{
typeTable = table.GetRelatedTypeTableByColumn(column, out pascalRoleName);
if (typeTable == null) typeTable = table;
if (typeTable != null)
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().Ignore(d => d." + pascalRoleName + typeTable.PascalName + "Value);");
}
}
#endregion
//If the column is not a PK then process it
//if (!column.PrimaryKey)
{
sb.Append($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>()");
sb.Append($".Property(d => d.{column.PascalName})");
if (column.AllowNull)
sb.Append(".IsRequired(false)");
else
sb.Append(".IsRequired(true)");
if (column.Identity == IdentityTypeConstants.Database && column.DataType.IsIntegerType())
{
switch (_modelConfiguration.DatabaseType)
{
case DatabaseTypeConstants.SqlServer:
sb.Append(".ValueGeneratedOnAdd()");
break;
case DatabaseTypeConstants.Postgress:
sb.Append(".ValueGeneratedOnAdd()");
break;
case DatabaseTypeConstants.Sqlite:
sb.Append(".ValueGeneratedOnAdd()");
break;
}
}
if (column.DataType.IsTextType() && column.Length > 0 && column.DataType != System.Data.SqlDbType.Xml)
sb.Append($".HasMaxLength({column.GetAnnotationStringLength()})");
if (column.DatabaseName != column.PascalName)
sb.Append($".HasColumnName(\"{column.DatabaseName}\")");
sb.AppendLine(";");
}
}
if (table.AllowCreateAudit)
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().Property(d => d." + _model.Database.CreatedDateColumnName + ").IsRequired();");
if (table.AllowModifiedAudit)
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().Property(d => d." + _model.Database.ModifiedDateColumnName + ").IsRequired();");
if (table.AllowTimestamp)
{
if (!String.Equals(_model.Database.TimestampDatabaseName, _model.Database.TimestampPascalName, StringComparison.OrdinalIgnoreCase))
{
sb.Append(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">()");
sb.Append(".Property(d => d." + _model.Database.TimestampPascalName + ")");
sb.Append(".HasColumnName(\"" + _model.Database.TimestampDatabaseName + "\")");
sb.AppendLine(";");
}
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().Property(d => d." + _model.Database.TimestampPascalName + ").HasMaxLength(8).IsRowVersion();");
}
sb.AppendLine();
}
//Views
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.Name))
{
sb.AppendLine(" //Field setup for " + item.PascalName + " entity");
foreach (var column in item.GetColumns().OrderBy(x => x.Name))
{
sb.Append(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + ">()");
sb.Append(".Property(d => d." + column.PascalName + ")");
if (!column.AllowNull)
sb.Append(".IsRequired()");
if (column.DataType.IsTextType() && column.Length > 0 && column.DataType != System.Data.SqlDbType.Xml) sb.Append(".HasMaxLength(" + column.GetAnnotationStringLength() + ")");
if (column.DatabaseName != column.PascalName) sb.Append(".HasColumnName(\"" + column.DatabaseName + "\")");
sb.AppendLine(";");
}
sb.AppendLine();
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Setup ignores for Enum properties
sb.AppendLine(" #region Ignore Enum Properties");
sb.AppendLine();
foreach (var table in _model.Database.Tables.Where(x => (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
foreach (var column in table.GetColumns().OrderBy(x => x.Name))
{
if (table.IsColumnRelatedToTypeTable(column, out var pascalRoleName) || (column.PrimaryKey && table.TypedTable != TypedTableConstants.None))
{
var typeTable = table.GetRelatedTypeTableByColumn(column, out pascalRoleName);
if (typeTable == null) typeTable = table;
if (typeTable != null)
{
sb.AppendLine(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().Ignore(t => t." + pascalRoleName + typeTable.PascalName + "Value);");
}
}
}
}
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Primary Keys
sb.AppendLine(" #region Primary Keys");
sb.AppendLine();
foreach (var table in _model.Database.Tables
.Where(x => (x.TypedTable != Models.TypedTableConstants.EnumOnly))
.OrderBy(x => x.Name))
{
sb.Append(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().HasKey(x => new { ");
var columnList = table.GetColumns().Where(x => x.PrimaryKey).OrderBy(x => x.Name).ToList();
foreach (var c in columnList)
{
sb.Append("x." + c.PascalName);
if (columnList.IndexOf(c) < columnList.Count - 1)
sb.Append(", ");
}
sb.AppendLine(" });");
}
foreach (var table in _model.Database.CustomViews.OrderBy(x => x.Name))
{
sb.Append(" modelBuilder.Entity<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">().HasKey(x => new { ");
var columnList = table.GetColumns().Where(x => x.IsPrimaryKey).OrderBy(x => x.Name).ToList();
foreach (var c in columnList)
{
sb.Append("x." + c.PascalName);
if (columnList.IndexOf(c) < columnList.Count - 1)
sb.Append(", ");
}
sb.AppendLine(" });");
}
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Create annotations for relationships
sb.AppendLine(" #region Relations");
sb.AppendLine();
foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
foreach (Relation relation in table.GetRelations())
{
var childTable = relation.ChildTableRef.Object as Table;
if (!childTable.IsInheritedFrom(table) && !childTable.AssociativeTable)
{
if (relation.IsOneToOne)
{
sb.AppendLine($" //Relation [{table.PascalName}] -> [{childTable.PascalName}] (Multiplicity 1:1)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{table.PascalName}>()");
sb.AppendLine($" .HasOne(a => a.{relation.PascalRoleName}{childTable.PascalName})");
sb.AppendLine($" .WithOne(x => x.{relation.PascalRoleName}{table.PascalName})");
sb.AppendLine(" .HasForeignKey<" + this.GetLocalNamespace() + ".Entity." + childTable.PascalName + ">(q => new { " +
string.Join(",", relation.ColumnRelationships.Select(x => x.ChildColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .HasPrincipalKey<" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ">(q => new { " +
string.Join(",", relation.ColumnRelationships.Select(x => x.ParentColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
if (relation.IsRequired)
sb.AppendLine(" .IsRequired(true)");
else
sb.AppendLine(" .IsRequired(false)");
//Specify what to do on delete
if (relation.DeleteAction == Relation.DeleteActionConstants.Cascade)
sb.AppendLine(" .OnDelete(DeleteBehavior.Cascade);");
else if (relation.DeleteAction == Relation.DeleteActionConstants.SetNull)
sb.AppendLine(" .OnDelete(DeleteBehavior.SetNull);");
else if (relation.DeleteAction == Relation.DeleteActionConstants.NoAction)
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
}
else
{
sb.AppendLine($" //Relation [{table.PascalName}] -> [{childTable.PascalName}] (Multiplicity 1:N)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{childTable.PascalName}>()");
sb.AppendLine($" .HasOne(a => a.{relation.PascalRoleName}{table.PascalName})");
if (relation.IsOneToOne)
sb.AppendLine($" .WithOne(x => x.{relation.PascalRoleName}{childTable.PascalName})");
else
sb.AppendLine($" .WithMany(b => b.{relation.PascalRoleName}{childTable.PascalName}List)");
if (relation.IsRequired)
sb.AppendLine(" .IsRequired(true)");
else
sb.AppendLine(" .IsRequired(false)");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation.ColumnRelationships.Select(x => x.ParentColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.Append(" .HasForeignKey(u => new { ");
var index = 0;
foreach (var columnPacket in relation.ColumnRelationships
.Select(x => new {Child = x.ChildColumnRef.Object as Column, Parent = x.ParentColumnRef.Object as Column})
.Where(x => x.Child != null && x.Parent != null)
.OrderBy(x => x.Parent.Name)
.ToList())
{
sb.Append("u." + columnPacket.Child.PascalName);
if (index < relation.ColumnRelationships.Count - 1)
sb.Append(", ");
index++;
}
sb.AppendLine(" })");
var indexName = ("FK_" + relation.RoleName + "_" + relation.ChildTable.DatabaseName + "_" + relation.ParentTable.DatabaseName).ToUpper();
sb.AppendLine($" .HasConstraintName(\"{indexName}\")");
//Specify what to do on delete
if (relation.DeleteAction == Relation.DeleteActionConstants.Cascade)
sb.AppendLine(" .OnDelete(DeleteBehavior.Cascade);");
else if (relation.DeleteAction == Relation.DeleteActionConstants.SetNull)
sb.AppendLine(" .OnDelete(DeleteBehavior.SetNull);");
else if (relation.DeleteAction == Relation.DeleteActionConstants.NoAction)
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
}
sb.AppendLine();
}
}
}
//Associative tables
foreach (var table in _model.Database.Tables.Where(x => x.AssociativeTable && (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
var relations = table.GetRelationsWhereChild().ToList();
if (relations.Count == 2)
{
var relation1 = relations.First();
var relation2 = relations.Last();
var index1Name = ("FK_" + relation1.RoleName + "_" + relation1.ChildTable.DatabaseName + "_" + relation1.ParentTable.DatabaseName).ToUpper();
var index2Name = ("FK_" + relation2.RoleName + "_" + relation2.ChildTable.DatabaseName + "_" + relation2.ParentTable.DatabaseName).ToUpper();
sb.AppendLine($" //Relation for [{relation1.ParentTable.PascalName}] -> [{relation2.ParentTable.PascalName}] (Multiplicity N:M)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{relation1.ParentTable.PascalName}>()");
sb.AppendLine($" .HasMany(q => q.{relation1.PascalRoleName}{table.PascalName}List)");
sb.AppendLine($" .WithOne(q => q.{relation1.PascalRoleName}{relation1.ParentTable.PascalName})");
sb.AppendLine($" .HasConstraintName(\"{index1Name}\")");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation1.ColumnRelationships.Select(x => x.ParentColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .HasForeignKey(q => new { " + string.Join(", ", relation1.ColumnRelationships.Select(x => x.ChildColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
sb.AppendLine();
sb.AppendLine($" //Relation for [{relation2.ParentTable.PascalName}] -> [{relation1.ParentTable.PascalName}] (Multiplicity N:M)");
sb.AppendLine($" modelBuilder.Entity<{this.GetLocalNamespace()}.Entity.{relation2.ParentTable.PascalName}>()");
sb.AppendLine($" .HasMany(q => q.{relation2.PascalRoleName}{table.PascalName}List)");
sb.AppendLine($" .WithOne(q => q.{relation2.PascalRoleName}{relation2.ParentTable.PascalName})");
sb.AppendLine($" .HasConstraintName(\"{index2Name}\")");
sb.AppendLine(" .HasPrincipalKey(q => new { " + string.Join(", ", relation2.ColumnRelationships.Select(x => x.ParentColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .HasForeignKey(q => new { " + string.Join(", ", relation2.ColumnRelationships.Select(x => x.ChildColumn.Name).OrderBy(x => x).Select(c => "q." + c)) + " })");
sb.AppendLine(" .OnDelete(DeleteBehavior.Restrict);");
sb.AppendLine();
}
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" // Override this event in the partial class to add any custom model changes or validation");
sb.AppendLine(" this.OnModelCreated(modelBuilder);");
sb.AppendLine();
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region Auditing
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Persists all updates to the data source and resets change tracking in the object context.");
sb.AppendLine(" /// </summary>");
sb.AppendLine(
" /// <returns>The number of objects in an System.Data.Entity.EntityState.Added, System.Data.Entity.EntityState.Modified, or System.Data.Entity.EntityState.Deleted state when System.Data.Objects.ObjectContext.SaveChanges() was called.</returns>");
sb.AppendLine(" public override int SaveChanges()");
sb.AppendLine(" {");
sb.AppendLine(" var cancel = false;");
sb.AppendLine(" OnBeforeSaveChanges(ref cancel);");
sb.AppendLine(" if (cancel) return 0;");
sb.AppendLine(" var markedTime = " + (_model.UseUTCTime ? "System.DateTime.UtcNow" : "System.DateTime.Now") + ";");
sb.AppendLine();
#region Added Items
sb.AppendLine(" //Get the added list");
sb.AppendLine(" var addedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Added);");
sb.AppendLine(" //Process added list");
sb.AppendLine(" foreach (var item in addedList)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item.Entity as IAuditable;");
sb.AppendLine(" if (entity != null)");
sb.AppendLine(" {");
sb.AppendLine(" var audit = entity as IAuditableSet;");
sb.AppendLine(" if (entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifier)");
sb.AppendLine(" {");
sb.AppendLine(" if (audit != null) audit.CreatedBy = this.ContextStartup.Modifier;");
sb.AppendLine(" if (audit != null) audit.ModifiedBy = this.ContextStartup.Modifier;");
sb.AppendLine(" }");
sb.AppendLine(" audit.CreatedDate = markedTime;");
sb.AppendLine(" audit.ModifiedDate = markedTime;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" this.OnBeforeSaveAddedEntity(new EventArguments.EntityListEventArgs { List = addedList });");
sb.AppendLine();
#endregion
#region Modified Items
sb.AppendLine(" //Process modified list");
sb.AppendLine(" var modifiedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Modified);");
sb.AppendLine(" foreach (var item in modifiedList)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item.Entity as IAuditable;");
sb.AppendLine(" if (entity != null)");
sb.AppendLine(" {");
sb.AppendLine(" var audit = entity as IAuditableSet;");
sb.AppendLine(" if (entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifier)");
sb.AppendLine(" {");
sb.AppendLine(" if (audit != null) audit.ModifiedBy = this.ContextStartup.Modifier;");
sb.AppendLine(" }");
sb.AppendLine(" audit.ModifiedDate = markedTime;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" this.OnBeforeSaveModifiedEntity(new EventArguments.EntityListEventArgs { List = modifiedList });");
sb.AppendLine();
#endregion
sb.AppendLine(" var retval = 0;");
sb.AppendLine(" Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction customTrans = null;");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" if (base.Database.CurrentTransaction == null)");
sb.AppendLine(" customTrans = base.Database.BeginTransaction();");
sb.AppendLine(" retval += base.SaveChanges();");
sb.AppendLine(" if (customTrans != null)");
sb.AppendLine(" customTrans.Commit();");
sb.AppendLine(" }");
sb.AppendLine(" catch");
sb.AppendLine(" {");
sb.AppendLine(" throw;");
sb.AppendLine(" }");
sb.AppendLine(" finally");
sb.AppendLine(" {");
sb.AppendLine(" if (customTrans != null)");
sb.AppendLine(" customTrans.Dispose();");
sb.AppendLine(" }");
sb.AppendLine(" this.OnAfterSaveAddedEntity(new EventArguments.EntityListEventArgs { List = addedList });");
sb.AppendLine(" this.OnAfterSaveModifiedEntity(new EventArguments.EntityListEventArgs { List = modifiedList });");
sb.AppendLine(" OnAfterSaveChanges();");
sb.AppendLine(" return retval;");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
#region Entity Sets
sb.AppendLine(" #region Entity Sets");
sb.AppendLine();
foreach (var item in _model.Database.Tables.Where(x => (x.TypedTable != Models.TypedTableConstants.EnumOnly)).OrderBy(x => x.Name))
{
var name = item.PascalName;
var scope = "public";
if (item.AssociativeTable)
scope = "protected";
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Entity set for " + item.PascalName);
sb.AppendLine(" /// </summary>");
sb.AppendLine($" {scope} virtual DbSet<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + "> " + name + " { get; set; }");
sb.AppendLine();
}
foreach (var item in _model.Database.CustomViews.OrderBy(x => x.Name))
{
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Entity set for " + item.PascalName);
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual DbSet<" + this.GetLocalNamespace() + ".Entity." + item.PascalName + "> " + item.PascalName + " { get; set; }");
sb.AppendLine();
}
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// The global settings of this context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual ContextStartup ContextStartup => _contextStartup;");
sb.AppendLine();
#region Configuration API/Database verification
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the version of the model that created this library.");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual string Version => _version;");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the key of the model that created this library.");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public virtual string ModelKey => _modelKey;");
sb.AppendLine();
#endregion
#region Add Functionality
//Add an strongly-typed extension for "AddItem" method
sb.AppendLine(" #region AddItem Methods");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry Add( object entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the AddItem method.");
sb.AppendLine(" return base.Add(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry<TEntity> Add<TEntity>( TEntity entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the AddItem method.");
sb.AppendLine(" return base.Add(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void AddRange(IEnumerable<object> entities)");
sb.AppendLine(" {");
sb.AppendLine(" if (entities == null) return;");
sb.AppendLine(" //This will enforce model validation.");
sb.AppendLine(" foreach (var item in entities)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item as IBusinessObject;");
sb.AppendLine(" if (entity == null)");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" this.AddItem(entity);");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void AddRange(params object[] entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.AddRange(entities?.AsEnumerable());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public virtual void AddRange(IEnumerable<IBusinessObject> entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.AddRange(entities?.AsEnumerable<object>());");
sb.AppendLine(" }");
sb.AppendLine();
#region Tables
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Adds an entity of to the object context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" /// <param name=\"entity\">The entity to add</param>");
sb.AppendLine($" public virtual {this.GetLocalNamespace()}.IBusinessObject AddItem({this.GetLocalNamespace()}.IBusinessObject entity)");
sb.AppendLine(" {");
sb.AppendLine(" if (entity == null) throw new NullReferenceException();");
sb.AppendLine($" var audit = entity as {this.GetLocalNamespace()}.IAuditableSet;");
sb.AppendLine(" if (audit != null)");
sb.AppendLine(" {");
sb.AppendLine(" audit.CreatedBy = _contextStartup.Modifier;");
sb.AppendLine(" audit.ModifiedBy = _contextStartup.Modifier;");
sb.AppendLine(" }");
sb.AppendLine(" if (false) { }");
foreach (var table in _model.Database.Tables.Where(x => !x.Immutable).OrderBy(x => x.PascalName))
{
sb.AppendLine($" else if (entity is {GetLocalNamespace()}.Entity.{table.PascalName})");
sb.AppendLine(" {");
sb.AppendLine($" this.Add(entity);");
sb.AppendLine(" }");
}
//If not an entity then throw exception
sb.AppendLine($" else");
sb.AppendLine(" {");
sb.AppendLine(" //If not an entity then throw exception");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" }");
sb.AppendLine(" return entity;");
sb.AppendLine(" }");
sb.AppendLine();
#endregion
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Delete Functionality
//Add an strongly-typed extension for "RemoveItem" method
sb.AppendLine(" #region RemoveItem Methods");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry Remove( object entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the RemoveItem method.");
sb.AppendLine(" return base.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override EntityEntry<TEntity> Remove<TEntity>( TEntity entity)");
sb.AppendLine(" {");
sb.AppendLine(" //No model validation. You should use the RemoveItem method.");
sb.AppendLine(" return base.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void RemoveRange(IEnumerable<object> entities)");
sb.AppendLine(" {");
sb.AppendLine(" if (entities == null) return;");
sb.AppendLine(" foreach (var item in entities)");
sb.AppendLine(" {");
sb.AppendLine(" var entity = item as IBusinessObject;");
sb.AppendLine(" if (entity == null)");
sb.AppendLine(" throw new Exception(\"Unknown entity type\");");
sb.AppendLine(" this.RemoveItem(entity);");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public override void RemoveRange(params object[] entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.RemoveRange(entities?.AsEnumerable());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" public virtual void RemoveRange(IEnumerable<IBusinessObject> entities)");
sb.AppendLine(" {");
sb.AppendLine(" this.RemoveRange(entities?.AsEnumerable<object>());");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Deletes an entity from the context");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" /// <param name=\"entity\">The entity to delete</param>");
sb.AppendLine(" public virtual void RemoveItem(IBusinessObject entity)");
sb.AppendLine(" {");
sb.AppendLine(" if (entity == null) return;");
sb.AppendLine(" else this.Remove(entity);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Connection String
sb.AppendLine(" #region Connection String");
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Returns the connection string used for this context object");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public string ConnectionString");
sb.AppendLine(" {");
sb.AppendLine(" get");
sb.AppendLine(" {");
sb.AppendLine(" try");
sb.AppendLine(" {");
sb.AppendLine(" if (this.Database.GetDbConnection() != null && !string.IsNullOrEmpty(this.Database.GetDbConnection().ConnectionString))");
sb.AppendLine(" return this.Database.GetDbConnection().ConnectionString;");
sb.AppendLine(" else return null;");
sb.AppendLine(" }");
sb.AppendLine(" catch (Exception) { return null; }");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region IContext Interface
sb.AppendLine(" #region IContext Interface");
sb.AppendLine(" Enum IContext.GetEntityFromField(Enum field) => GetEntityFromField(field);");
sb.AppendLine(" System.Type IContext.GetFieldType(Enum field) => this.GetFieldType(field);");
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region GetEntityFromField
sb.AppendLine(" #region GetEntityFromField");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the entity from one of its fields");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public static EntityMappingConstants GetEntityFromField(Enum field)");
sb.AppendLine(" {");
foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && (x.TypedTable != TypedTableConstants.EnumOnly)).OrderBy(x => x.PascalName))
{
sb.AppendLine(" if (field is " + this.GetLocalNamespace() + ".Entity." + table.PascalName + ".FieldNameConstants) return " + this.GetLocalNamespace() + ".EntityMappingConstants." + table.PascalName + ";");
}
sb.AppendLine(" throw new Exception(\"Unknown field type!\");");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region Extra
sb.AppendLine(" #region Interface Extras");
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Reloads the context object from database");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public void ReloadItem(BaseEntity entity)");
sb.AppendLine(" {");
sb.AppendLine(" this.Entry(entity).Reload();");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
#region ObjectContext
sb.AppendLine(" #region ObjectContext");
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Determines the timeout of the database connection");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public int? CommandTimeout");
sb.AppendLine(" {");
sb.AppendLine(" get { return this.Database.GetCommandTimeout(); }");
sb.AppendLine(" set { this.Database.SetCommandTimeout(value); }");
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
#endregion
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
}
private void AppendTypeTableEnums()
{
foreach (var table in _model.Database.Tables.Where(x => x.TypedTable != TypedTableConstants.None).OrderBy(x => x.Name))
{
if (table.PrimaryKeyColumns.Count == 1)
{
var pk = table.PrimaryKeyColumns.First();
sb.AppendLine(" #region StaticDataConstants Enumeration for '" + table.PascalName + "' entity");
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Enumeration to define static data items and their ids '" + table.PascalName + "' table.");
sb.AppendLine(" /// </summary>");
sb.Append(" public enum " + table.PascalName + "Constants");
//Non-integer types must explicitly add the type
if (pk.DataType != System.Data.SqlDbType.Int)
sb.Append(" : " + pk.GetCodeType(false));
sb.AppendLine();
sb.AppendLine(" {");
foreach (RowEntry rowEntry in table.StaticData)
{
var idValue = rowEntry.GetCodeIdValue(table);
var identifier = rowEntry.GetCodeIdentifier(table);
var description = rowEntry.GetCodeDescription(table);
var raw = rowEntry.GetDataRaw(table);
var sort = rowEntry.GetDataSort(table);
if (!string.IsNullOrEmpty(description))
{
sb.AppendLine(" /// <summary>");
StringHelper.LineBreakCode(sb, description, " /// ");
sb.AppendLine(" /// </summary>");
sb.AppendLine(" [Description(\"" + description + "\")]");
}
else
{
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// Enumeration for the '" + identifier + "' item");
sb.AppendLine(" /// </summary>");
}
var key = ValidationHelper.MakeDatabaseIdentifier(identifier.Replace(" ", string.Empty));
if ((key.Length > 0) && ("0123456789".Contains(key[0])))
key = "_" + key;
//If there is a sort value then format as attribute
if (int.TryParse(sort, out var svalue))
{
sort = ", Order = " + svalue;
}
else
{
sort = string.Empty;
}
sb.AppendLine(" [System.ComponentModel.DataAnnotations.Display(Name = \"" + raw + "\"" + sort + ")]");
sb.AppendLine(" " + key + " = " + idValue + ",");
}
sb.AppendLine(" }");
sb.AppendLine(" #endregion");
sb.AppendLine();
}
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System.Collections.Generic;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Task test result.
/// </summary>
public class BinarizableTaskTest : AbstractTaskTest
{
/// <summary>
/// Constructor.
/// </summary>
public BinarizableTaskTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected BinarizableTaskTest(bool fork) : base(fork) { }
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestBinarizableObjectInTask()
{
var taskArg = new BinarizableWrapper {Item = ToBinary(Grid1, new BinarizableTaskArgument(100))};
TestTask task = new TestTask(Grid1, taskArg);
var res = Grid1.GetCompute().Execute(task, taskArg).Item;
Assert.NotNull(res);
Assert.AreEqual(400, res.GetField<int>("val"));
BinarizableTaskResult resObj = res.Deserialize<BinarizableTaskResult>();
Assert.AreEqual(400, resObj.Val);
}
private static IBinaryObject ToBinary(IIgnite grid, object obj)
{
var cache = grid.GetCache<object, object>(Cache1Name).WithKeepBinary<object, object>();
cache.Put(1, obj);
return (IBinaryObject) cache.Get(1);
}
/** <inheritDoc /> */
override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs)
{
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJobArgument)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJobResult)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableTaskArgument)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableTaskResult)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJob)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableWrapper)));
}
/// <summary>
/// Test task.
/// </summary>
class TestTask : ComputeTaskAdapter<BinarizableWrapper, BinarizableWrapper, BinarizableWrapper>
{
/** */
private readonly IIgnite _grid;
private readonly BinarizableWrapper _taskArgField;
public TestTask(IIgnite grid, BinarizableWrapper taskArgField)
{
_grid = grid;
_taskArgField = taskArgField;
}
/** <inheritDoc /> */
override public IDictionary<IComputeJob<BinarizableWrapper>, IClusterNode> Map(IList<IClusterNode> subgrid, BinarizableWrapper arg)
{
Assert.AreEqual(3, subgrid.Count);
Assert.NotNull(_grid);
var taskArg = arg;
CheckTaskArgument(taskArg);
CheckTaskArgument(_taskArgField);
var jobs = new Dictionary<IComputeJob<BinarizableWrapper>, IClusterNode>();
foreach (IClusterNode node in subgrid)
{
if (!Grid3Name.Equals(node.GetAttribute<string>("org.apache.ignite.ignite.name"))) // Grid3 does not have cache.
{
var job = new BinarizableJob
{
Arg = new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableJobArgument(200))}
};
jobs.Add(job, node);
}
}
Assert.AreEqual(2, jobs.Count);
return jobs;
}
private void CheckTaskArgument(BinarizableWrapper arg)
{
Assert.IsNotNull(arg);
var taskArg = arg.Item;
Assert.IsNotNull(taskArg);
Assert.AreEqual(100, taskArg.GetField<int>("val"));
BinarizableTaskArgument taskArgObj = taskArg.Deserialize<BinarizableTaskArgument>();
Assert.AreEqual(100, taskArgObj.Val);
}
/** <inheritDoc /> */
override public BinarizableWrapper Reduce(IList<IComputeJobResult<BinarizableWrapper>> results)
{
Assert.NotNull(_grid);
Assert.AreEqual(2, results.Count);
foreach (var res in results)
{
var jobRes = res.Data.Item;
Assert.NotNull(jobRes);
Assert.AreEqual(300, jobRes.GetField<int>("val"));
BinarizableJobResult jobResObj = jobRes.Deserialize<BinarizableJobResult>();
Assert.AreEqual(300, jobResObj.Val);
}
return new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableTaskResult(400))};
}
}
/// <summary>
///
/// </summary>
class BinarizableJobArgument
{
/** */
public readonly int Val;
public BinarizableJobArgument(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableJobResult
{
/** */
public readonly int Val;
public BinarizableJobResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableTaskArgument
{
/** */
public readonly int Val;
public BinarizableTaskArgument(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableTaskResult
{
/** */
public readonly int Val;
public BinarizableTaskResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableJob : IComputeJob<BinarizableWrapper>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** */
public BinarizableWrapper Arg;
/** <inheritDoc /> */
public BinarizableWrapper Execute()
{
Assert.IsNotNull(Arg);
var arg = Arg.Item;
Assert.IsNotNull(arg);
Assert.AreEqual(200, arg.GetField<int>("val"));
var argObj = arg.Deserialize<BinarizableJobArgument>();
Assert.AreEqual(200, argObj.Val);
return new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableJobResult(300))};
}
public void Cancel()
{
// No-op.
}
}
class BinarizableWrapper
{
public IBinaryObject Item { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Microsoft.Msagl.Core.DataStructures {
//public class TestRB :IComparer<int>{
// public static void Test() {
// var tree = new RBTree<int>(new TestRB());
// tree.insert(1);
// tree.insert(6);
// tree.insert(8);
// tree.insert(11);
// tree.insert(13);
// tree.insert(17);
// tree.insert(15);
// tree.insert(25);
// tree.insert(22);
// tree.insert(27);
// tree.insert(16);
// var t = tree.findLast(delegate(int i) { return i <= 15.5; });
// }
// #region IComparer<int> Members
// public int Compare(int x, int y) {
// return x - y;
// }
// #endregion
//}
#if TEST_MSAGL
[Serializable]
#endif
internal class RbTree<T> : IEnumerable<T> {
/// <summary>
/// find the first, minimal, node in the tree such that predicate holds
/// </summary>
/// <param name="predicate">Has to be monotone in the sense that if it holds for t then it holds for any t' greater or equal than t
/// so the predicate values have a form (false, false, ..., false, true, true, ..., true)
/// </param>
/// <returns>the first node where predicate holds or null</returns>
internal RBNode<T> FindFirst(Func<T, bool> predicate) {
return FindFirst(root, predicate);
}
internal RbTree() {
comparer = new DefaultComperer<T>();
root = nil = new RBNode<T>(RBColor.Black);
}
RBNode<T> FindFirst(RBNode<T> n, Func<T, bool> p) {
if (n == nil)
return null;
RBNode<T> good = null;
while (n != nil)
n = p(n.Item) ? (good = n).left : n.right;
return good;
}
/// <summary>
/// find the last, maximal, node in the tree such that predicate holds
/// </summary>
/// <param name="predicate">Has to be monotone in the sense that if it holds for t then it holds for any t' less or equal than t
/// so the predicate values on the tree have a form (true, true, ..., true, false, false, ..., false)
/// </param>
/// <returns>the last node where predicate holds or null</returns>
internal RBNode<T> FindLast(Func<T,bool> predicate) {
return FindLast(root, predicate);
}
RBNode<T> FindLast(RBNode<T> n, Func<T,bool> p) {
if (n == nil)
return null;
RBNode<T> good = null;
while (n != nil)
n = p(n.Item) ? (good = n).right : n.left;
return good;
}
readonly IComparer<T> comparer;
IComparer<T> Comparer {
get { return comparer; }
}
public IEnumerator<T> GetEnumerator() { return new RBTreeEnumerator<T>(this); }
RBNode<T> nil;
internal RBNode<T> Nil { get { return nil; } }
RBNode<T> root;
internal RBNode<T> Root { get { return root; } }
internal RBNode<T> Next(RBNode<T> x) {
if (x.right != nil)
return TreeMinimum(x.right);
RBNode<T> y = x.parent;
while (y != nil && x == y.right) {
x = y;
y = y.parent;
}
return ToNull(y);
}
RBNode<T> ToNull(RBNode<T> y) {
return y != nil ? y : null;
}
internal RBNode<T> Previous(RBNode<T> x) {
if (x.left != nil)
return TreeMaximum(x.left);
RBNode<T> y = x.parent;
while (y != nil && x == y.left) {
x = y;
y = y.parent;
}
return ToNull(y);
}
RBNode<T> TreeMinimum(RBNode<T> x) {
while (x.left != nil)
x = x.left;
return ToNull(x);
}
internal RBNode<T> TreeMinimum() {
return TreeMinimum(root);
}
RBNode<T> TreeMaximum(RBNode<T> x) {
while (x.right != nil)
x = x.right;
return ToNull(x);
}
internal RBNode<T> TreeMaximum() {
return TreeMaximum(root);
}
//RBTree<T> Clone() {
// RBTree<T> clone = new RBTree<T>(this.Comparer);
// foreach (T n in this) {
// clone.insert(n);
// }
// return clone;
//}
public override string ToString() {
string ret = "{";
int i = 0;
foreach (T p in this) {
ret += p.ToString();
if (i != count - 1) {
ret += ",";
}
i++;
}
return ret + "}";
}
internal RBNode<T> DeleteSubtree(RBNode<T> z) {
System.Diagnostics.Debug.Assert(z != nil);
RBNode<T> y;
if (z.left == nil || z.right == nil) {
/* y has a nil node as a child */
y = z;
} else {
/* find tree successor with a nil node as a child */
y = z.right;
while (y.left != nil) y = y.left;
}
/* x is y's only child */
RBNode<T> x = y.left != nil ? y.left : y.right;
x.parent = y.parent;
if (y.parent == nil)
root = x;
else {
if (y == y.parent.left)
y.parent.left = x;
else
y.parent.right = x;
}
if (y != z)
z.Item = y.Item;
if (y.color == RBColor.Black)
DeleteFixup(x);
// checkTheTree();
return ToNull(z);
}
int count;
public int Count { get { return count; } }
internal RBNode<T> Remove(T i) {
RBNode<T> n = Find(i);
if (n != null) {
count--;
return DeleteSubtree(n);
}
return null;
}
internal void DeleteNodeInternal(RBNode<T> x) {
count--;
DeleteSubtree(x);
}
RBNode<T> Find(RBNode<T> x, T i) {
int compareResult;
while (x != nil && (compareResult = Comparer.Compare(i, x.Item)) != 0)
x = compareResult < 0 ? x.left : x.right;
return ToNull(x);
}
internal RBNode<T> Find(T i) {
return Find(root, i);
}
internal bool Contains(T i) {
return Find(i) != null;
}
void DeleteFixup(RBNode<T> x) {
while (x != root && x.color == RBColor.Black) {
if (x == x.parent.left) {
RBNode<T> w = x.parent.right;
if (w.color == RBColor.Red) {
w.color = RBColor.Black;
x.parent.color = RBColor.Red;
LeftRotate(x.parent);
w = x.parent.right;
}
if (w.left.color == RBColor.Black && w.right.color == RBColor.Black) {
w.color = RBColor.Red;
x = x.parent;
} else {
if (w.right.color == RBColor.Black) {
w.left.color = RBColor.Black;
w.color = RBColor.Red;
RightRotate(w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = RBColor.Black;
w.right.color = RBColor.Black;
LeftRotate(x.parent);
x = root;
}
} else {
RBNode<T> w = x.parent.left;
if (w.color == RBColor.Red) {
w.color = RBColor.Black;
x.parent.color = RBColor.Red;
RightRotate(x.parent);
w = x.parent.left;
}
if (w.right.color == RBColor.Black && w.left.color == RBColor.Black) {
w.color = RBColor.Red;
x = x.parent;
} else {
if (w.left.color == RBColor.Black) {
w.right.color = RBColor.Black;
w.color = RBColor.Red;
LeftRotate(w);
w = x.parent.left;
}
w.color = x.parent.color;
x.parent.color = RBColor.Black;
w.left.color = RBColor.Black;
RightRotate(x.parent);
x = root;
}
}
}
x.color = RBColor.Black;
}
internal bool IsEmpty() { return root == nil; }
RBNode<T> TreeInsert(T z) {
var y = nil;
var x = root;
var compareRes = 0;
while (x != nil) {
y = x;
#if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=368
compareRes = Comparer.Compare(z, x.Item);
x = compareRes < 0 ? x.left : x.right;
#else
x = (compareRes = Comparer.Compare(z, x.Item)) < 0 ? x.left : x.right;
#endif
}
var nz = new RBNode<T>(RBColor.Black, z, y, nil, nil);
if (y == nil)
root = nz;
else if (compareRes < 0)
y.left = nz;
else
y.right = nz;
return ToNull(nz);
}
void InsertPrivate(RBNode<T> x) {
count++;
x.color = RBColor.Red;
while (x != root && x.parent.color == RBColor.Red) {
if (x.parent == x.parent.parent.left) {
RBNode<T> y = x.parent.parent.right;
if (y.color == RBColor.Red) {
x.parent.color = RBColor.Black;
y.color = RBColor.Black;
x.parent.parent.color = RBColor.Red;
x = x.parent.parent;
} else {
if (x == x.parent.right) {
x = x.parent;
LeftRotate(x);
}
x.parent.color = RBColor.Black;
x.parent.parent.color = RBColor.Red;
RightRotate(x.parent.parent);
}
} else {
RBNode<T> y = x.parent.parent.left;
if (y.color == RBColor.Red) {
x.parent.color = RBColor.Black;
y.color = RBColor.Black;
x.parent.parent.color = RBColor.Red;
x = x.parent.parent;
} else {
if (x == x.parent.left) {
x = x.parent;
RightRotate(x);
}
x.parent.color = RBColor.Black;
x.parent.parent.color = RBColor.Red;
LeftRotate(x.parent.parent);
}
}
}
root.color = RBColor.Black;
//checkTheTree();
}
internal RBNode<T> Insert(T v) {
RBNode<T> x = TreeInsert(v);
InsertPrivate(x);
return ToNull(x);
}
void LeftRotate(RBNode<T> x) {
RBNode<T> y = x.right;
x.right = y.left;
if (y.left != nil)
y.left.parent = x;
y.parent = x.parent;
if (x.parent == nil)
root = y;
else if (x == x.parent.left)
x.parent.left = y;
else
x.parent.right = y;
y.left = x;
x.parent = y;
}
void RightRotate(RBNode<T> x) {
RBNode<T> y = x.left;
x.left = y.right;
if (y.right != nil)
y.right.parent = x;
y.parent = x.parent;
if (x.parent == nil)
root = y;
else if (x == x.parent.right)
x.parent.right = y;
else
x.parent.left = y;
y.right = x;
x.parent = y;
}
internal RbTree(Func<T, T, int> func) : this(new ComparerOnDelegate<T>(func)) {}
internal RbTree(IComparer<T> comparer) {
Clear();
this.comparer = comparer;
}
internal void Clear() {
root = nil = new RBNode<T>(RBColor.Black);
}
//void checkTheTree() {
// int blacks = -1;
// checkBlacks(root, 0, ref blacks);
// checkColors(root);
//}
//void checkBlacks(RBNode<T> node, int nnow, ref int blacks) {
// if (node != nil) {
// RBNode<T> l = node.left, r = node.right;
// if (l != nil)
// if (Comparer.Compare(l.item,node.item) >= 0)
// throw new Exception("order");
// if (r != nil)
// if (Comparer.Compare(r.item,node.item) <= 0)
// throw new Exception("order");
// }
// if (node == nil) {
// if (blacks != nnow + 1 && blacks != -1)
// throw new Exception("blacks");
// blacks = nnow + 1;
// } else if (node.color == RBColor.Black) {
// checkBlacks(node.left, nnow + 1, ref blacks);
// checkBlacks(node.right, nnow + 1, ref blacks);
// } else {
// checkBlacks(node.left, nnow, ref blacks);
// checkBlacks(node.right, nnow, ref blacks);
// }
//}
//void checkColors(RBNode<T> x) {
// if (x == nil)
// return;
// //property 3
// if (x.color == RBColor.Red)
// if (x.left.color == RBColor.Red || x.right.color == RBColor.Red)
// throw new Exception("colors");
// checkColors(x.left);
// checkColors(x.right);
//}
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return new RBTreeEnumerator<T>(this);
}
#endregion
internal void AddCollection(IEnumerable<T> enumerable) {
foreach (var p in enumerable)
Insert(p);
}
internal RBNode<T> InsertUnique(T item) {
var node = Find(item);
if (node != null)
return node;
return Insert(item);
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// RewardInfo
/// </summary>
[DataContract]
public partial class RewardInfo : IEquatable<RewardInfo>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="RewardInfo" /> class.
/// </summary>
/// <param name="Description">Description.</param>
/// <param name="Id">Id.</param>
/// <param name="ImageUrl">ImageUrl.</param>
/// <param name="PriceInPoints">PriceInPoints.</param>
/// <param name="RedeemRequest">RedeemRequest.</param>
/// <param name="Value">Value.</param>
public RewardInfo(string Description = null, string Id = null, string ImageUrl = null, double? PriceInPoints = null, RedeemRequestInfo RedeemRequest = null, RewardValue Value = null)
{
this.Description = Description;
this.Id = Id;
this.ImageUrl = ImageUrl;
this.PriceInPoints = PriceInPoints;
this.RedeemRequest = RedeemRequest;
this.Value = Value;
}
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=true)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets ImageUrl
/// </summary>
[DataMember(Name="imageUrl", EmitDefaultValue=true)]
public string ImageUrl { get; set; }
/// <summary>
/// Gets or Sets PriceInPoints
/// </summary>
[DataMember(Name="priceInPoints", EmitDefaultValue=true)]
public double? PriceInPoints { get; set; }
/// <summary>
/// Gets or Sets RedeemRequest
/// </summary>
[DataMember(Name="redeemRequest", EmitDefaultValue=true)]
public RedeemRequestInfo RedeemRequest { get; set; }
/// <summary>
/// Gets or Sets Value
/// </summary>
[DataMember(Name="value", EmitDefaultValue=true)]
public RewardValue Value { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RewardInfo {\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n");
sb.Append(" PriceInPoints: ").Append(PriceInPoints).Append("\n");
sb.Append(" RedeemRequest: ").Append(RedeemRequest).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RewardInfo);
}
/// <summary>
/// Returns true if RewardInfo instances are equal
/// </summary>
/// <param name="other">Instance of RewardInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RewardInfo other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ImageUrl == other.ImageUrl ||
this.ImageUrl != null &&
this.ImageUrl.Equals(other.ImageUrl)
) &&
(
this.PriceInPoints == other.PriceInPoints ||
this.PriceInPoints != null &&
this.PriceInPoints.Equals(other.PriceInPoints)
) &&
(
this.RedeemRequest == other.RedeemRequest ||
this.RedeemRequest != null &&
this.RedeemRequest.Equals(other.RedeemRequest)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.ImageUrl != null)
hash = hash * 59 + this.ImageUrl.GetHashCode();
if (this.PriceInPoints != null)
hash = hash * 59 + this.PriceInPoints.GetHashCode();
if (this.RedeemRequest != null)
hash = hash * 59 + this.RedeemRequest.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Aurora.Framework
{
public class ThreadMonitor
{
#region Delegates
public delegate bool Heartbeat();
#endregion
protected List<InternalHeartbeat> m_heartbeats = new List<InternalHeartbeat>();
protected Object m_lock = new Object();
private int m_sleepTime;
protected int m_timesToIterate;
protected Thread m_thread;
private bool startedshutdown = false;
/// <summary>
/// Add this delegate to the tracker so that it can run.
/// </summary>
/// <param name = "millisecondTimeOut">The time that the thread can run before it is forcefully stopped.</param>
/// <param name = "hb">The delegate to run.</param>
public void StartTrackingThread(int millisecondTimeOut, Heartbeat hb)
{
lock (m_lock)
{
m_heartbeats.Add(new InternalHeartbeat {heartBeat = hb, millisecondTimeOut = millisecondTimeOut});
}
}
/// <summary>
/// Start the thread and run through the threads that are given.
/// </summary>
/// <param name = "timesToIterate">The number of times to run the delegate.
/// <remarks>
/// If you set this parameter to 0, it will loop infinitely.
/// </remarks>
/// </param>
/// <param name = "sleepTime">The sleep time between each iteration.
/// <remarks>
/// If you set this parameter to 0, it will loop without sleeping at all.
/// The sleeping will have to be deal with in the delegates.
/// </remarks>
/// </param>
public void StartMonitor(int timesToIterate, int sleepTime)
{
m_timesToIterate = timesToIterate;
m_sleepTime = sleepTime;
m_thread = new Thread(Run)
{IsBackground = true, Name = "ThreadMonitor", Priority = ThreadPriority.Normal};
m_thread.Start();
}
/// <summary>
/// Run the loop through the heartbeats.
/// </summary>
protected internal void Run()
{
Culture.SetCurrentCulture();
try
{
List<InternalHeartbeat> hbToRemove = null;
while ((m_timesToIterate >= 0) && (!startedshutdown))
{
lock (m_lock)
{
foreach (InternalHeartbeat intHB in m_heartbeats)
{
bool isRunning = false;
if (!CallAndWait(intHB.millisecondTimeOut, intHB.heartBeat, out isRunning))
{
MainConsole.Instance.Warn("[ThreadTracker]: Could not run Heartbeat in specified limits!");
}
else if (!isRunning)
{
if (hbToRemove == null)
hbToRemove = new List<InternalHeartbeat>();
hbToRemove.Add(intHB);
}
}
if (hbToRemove != null)
{
foreach (InternalHeartbeat intHB in hbToRemove)
{
m_heartbeats.Remove(intHB);
}
//Renull it for later
hbToRemove = null;
if (m_heartbeats.Count == 0) //None left, break
break;
}
}
//0 is infinite
if (m_timesToIterate != 0)
{
//Subtract, then see if it is 0, and if it is, it is time to stop
m_timesToIterate--;
if (m_timesToIterate == 0)
break;
}
if (m_timesToIterate == -1) //Kill signal
break;
if (m_sleepTime != 0)
Thread.Sleep(m_sleepTime);
}
}
catch
{
}
Thread.CurrentThread.Abort();
}
/// <summary>
/// Call the method and wait for it to complete or the max time.
/// </summary>
/// <param name = "timeout"></param>
/// <param name = "enumerator"></param>
/// <returns></returns>
public static bool CallAndWait(int timeout, Heartbeat enumerator, out bool isRunning)
{
isRunning = false;
bool RetVal = false;
if (timeout == 0)
{
isRunning = enumerator();
RetVal = true;
}
else
{
//The action to fire
FireEvent wrappedAction = delegate(Heartbeat en)
{
// Set this culture for the thread
// to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
en();
RetVal = true;
};
//Async the action (yeah, this is bad, but otherwise we can't abort afaik)
IAsyncResult result = wrappedAction.BeginInvoke(enumerator, null, null);
if (((timeout != 0) && !result.IsCompleted) &&
(!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
{
isRunning = false;
return false;
}
else
{
wrappedAction.EndInvoke(result);
isRunning = true;
}
}
//Return what we got
return RetVal;
}
public void Stop()
{
startedshutdown = true;
lock (m_lock)
{
//Remove all
m_heartbeats.Clear();
//Kill it
m_timesToIterate = -1;
if (m_thread != null)
m_thread.Join();
m_thread = null;
}
}
#region Nested type: FireEvent
protected internal delegate void FireEvent(Heartbeat thread);
#endregion
#region Nested type: InternalHeartbeat
protected internal class InternalHeartbeat
{
public Heartbeat heartBeat;
public int millisecondTimeOut;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
namespace Abp.Dependency
{
/// <summary>
/// This class is used to directly perform dependency injection tasks.
/// </summary>
public class IocManager : IIocManager
{
/// <summary>
/// The Singleton instance.
/// </summary>
public static IocManager Instance { get; private set; }
/// <summary>
/// Reference to the Castle Windsor Container.
/// </summary>
public IWindsorContainer IocContainer { get; private set; }
/// <summary>
/// List of all registered conventional registrars.
/// </summary>
private readonly List<IConventionalDependencyRegistrar> _conventionalRegistrars;
static IocManager()
{
Instance = new IocManager();
}
/// <summary>
/// Creates a new <see cref="IocManager"/> object.
/// Normally, you don't directly instantiate an <see cref="IocManager"/>.
/// This may be useful for test purposes.
/// </summary>
public IocManager()
{
IocContainer = new WindsorContainer();
_conventionalRegistrars = new List<IConventionalDependencyRegistrar>();
//Register self!
IocContainer.Register(
Component.For<IocManager, IIocManager, IIocRegistrar, IIocResolver>().UsingFactoryMethod(() => this)
);
}
/// <summary>
/// Adds a dependency registrar for conventional registration.
/// </summary>
/// <param name="registrar">dependency registrar</param>
public void AddConventionalRegistrar(IConventionalDependencyRegistrar registrar)
{
_conventionalRegistrars.Add(registrar);
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
public void RegisterAssemblyByConvention(Assembly assembly)
{
RegisterAssemblyByConvention(assembly, new ConventionalRegistrationConfig());
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
/// <param name="config">Additional configuration</param>
public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config)
{
var context = new ConventionalRegistrationContext(assembly, this, config);
foreach (var registerer in _conventionalRegistrars)
{
registerer.RegisterAssembly(context);
}
if (config.InstallInstallers)
{
IocContainer.Install(FromAssembly.Instance(assembly));
}
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <typeparam name="TType">Type of the class</typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class
{
IocContainer.Register(ApplyLifestyle(Component.For<TType>(), lifeStyle));
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type), lifeStyle));
}
/// <summary>
/// Registers a type with it's implementation.
/// </summary>
/// <typeparam name="TType">Registering type</typeparam>
/// <typeparam name="TImpl">The type that implements <see cref="TType"/></typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType, TImpl>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
where TType : class
where TImpl : class, TType
{
IocContainer.Register(ApplyLifestyle(Component.For<TType, TImpl>().ImplementedBy<TImpl>(), lifeStyle));
}
/// <summary>
/// Registers a class as self registration.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="impl">The type that implements <paramref name="type"/></param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, Type impl, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type, impl).ImplementedBy(impl), lifeStyle));
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <param name="type">Type to check</param>
public bool IsRegistered(Type type)
{
return IocContainer.Kernel.HasComponent(type);
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <typeparam name="TType">Type to check</typeparam>
public bool IsRegistered<TType>()
{
return IocContainer.Kernel.HasComponent(typeof(TType));
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <returns>The instance object</returns>
public T Resolve<T>()
{
return IocContainer.Resolve<T>();
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to cast</typeparam>
/// <param name="type">Type of the object to resolve</param>
/// <returns>The object instance</returns>
public T Resolve<T>(Type type)
{
return (T)IocContainer.Resolve(type);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public T Resolve<T>(object argumentsAsAnonymousType)
{
return IocContainer.Resolve<T>(argumentsAsAnonymousType);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <returns>The instance object</returns>
public object Resolve(Type type)
{
return IocContainer.Resolve(type);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public object Resolve(Type type, object argumentsAsAnonymousType)
{
return IocContainer.Resolve(type, argumentsAsAnonymousType);
}
/// <summary>
/// Releases a pre-resolved object. See Resolve methods.
/// </summary>
/// <param name="obj">Object to be released</param>
public void Release(object obj)
{
IocContainer.Release(obj);
}
/// <inheritdoc/>
public void Dispose()
{
IocContainer.Dispose();
}
private static ComponentRegistration<T> ApplyLifestyle<T>(ComponentRegistration<T> registration, DependencyLifeStyle lifeStyle)
where T : class
{
switch (lifeStyle)
{
case DependencyLifeStyle.Transient:
return registration.LifestyleTransient();
case DependencyLifeStyle.Singleton:
return registration.LifestyleSingleton();
default:
return registration;
}
}
}
}
| |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
[HideInInspector][SerializeField] protected bool mApplyGradient = false;
[HideInInspector][SerializeField] protected Color mGradientTop = Color.white;
[HideInInspector][SerializeField] protected Color mGradientBottom = new Color(0.7f, 0.7f, 0.7f);
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
protected Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.GammaToLinearSpace(colF.r);
colF.g = Mathf.GammaToLinearSpace(colF.g);
colF.b = Mathf.GammaToLinearSpace(colF.b);
colF.a = Mathf.GammaToLinearSpace(colF.a);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
if (!mApplyGradient)
{
Color32 c = drawingColor;
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
else
{
AddVertexColours(cols, 1, 1);
AddVertexColours(cols, 1, 2);
AddVertexColours(cols, 2, 2);
AddVertexColours(cols, 2, 1);
}
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
if (!mApplyGradient)
{
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
else
{
AddVertexColours(cols, x, y);
AddVertexColours(cols, x, y2);
AddVertexColours(cols, x2, y2);
AddVertexColours(cols, x2, y);
}
}
}
}
/// <summary>
/// Adds a gradient-based vertex color to the sprite.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
void AddVertexColours (BetterList<Color32> cols, int x, int y)
{
if (y == 0 || y == 1)
{
cols.Add((Color32)(drawingColor * mGradientBottom));
}
else if (y == 2 || y == 3)
{
cols.Add((Color32)(drawingColor * mGradientTop));
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible) ||
(x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| |
//
// Copyright (c) 2004-2018 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.Common
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using NLog.Internal;
/// <summary>
/// Helpers for asynchronous operations.
/// </summary>
public static class AsyncHelpers
{
internal static int GetManagedThreadId()
{
#if NETSTANDARD1_3
return System.Environment.CurrentManagedThreadId;
#else
return Thread.CurrentThread.ManagedThreadId;
#endif
}
internal static void StartAsyncTask(Action<object> action, object state)
{
#if NET4_0 || NET4_5 || NETSTANDARD
System.Threading.Tasks.Task.Factory.StartNew(action, state, CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
#else
ThreadPool.QueueUserWorkItem(new WaitCallback(action), state);
#endif
}
internal static void WaitForDelay(TimeSpan delay)
{
#if NETSTANDARD1_3
System.Threading.Tasks.Task.Delay(delay).Wait();
#else
Thread.Sleep(delay);
#endif
}
/// <summary>
/// Iterates over all items in the given collection and runs the specified action
/// in sequence (each action executes only after the preceding one has completed without an error).
/// </summary>
/// <typeparam name="T">Type of each item.</typeparam>
/// <param name="items">The items to iterate.</param>
/// <param name="asyncContinuation">The asynchronous continuation to invoke once all items
/// have been iterated.</param>
/// <param name="action">The action to invoke for each item.</param>
public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action)
{
action = ExceptionGuard(action);
AsyncContinuation invokeNext = null;
IEnumerator<T> enumerator = items.GetEnumerator();
invokeNext = ex =>
{
if (ex != null)
{
asyncContinuation(ex);
return;
}
if (!enumerator.MoveNext())
{
enumerator.Dispose();
asyncContinuation(null);
return;
}
action(enumerator.Current, PreventMultipleCalls(invokeNext));
};
invokeNext(null);
}
/// <summary>
/// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end.
/// </summary>
/// <param name="repeatCount">The repeat count.</param>
/// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param>
/// <param name="action">The action to invoke.</param>
public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action)
{
action = ExceptionGuard(action);
AsyncContinuation invokeNext = null;
int remaining = repeatCount;
invokeNext = ex =>
{
if (ex != null)
{
asyncContinuation(ex);
return;
}
if (remaining-- <= 0)
{
asyncContinuation(null);
return;
}
action(PreventMultipleCalls(invokeNext));
};
invokeNext(null);
}
/// <summary>
/// Modifies the continuation by pre-pending given action to execute just before it.
/// </summary>
/// <param name="asyncContinuation">The async continuation.</param>
/// <param name="action">The action to pre-pend.</param>
/// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns>
public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action)
{
action = ExceptionGuard(action);
AsyncContinuation continuation =
ex =>
{
if (ex != null)
{
// if got exception from from original invocation, don't execute action
asyncContinuation(ex);
return;
}
// call the action and continue
action(PreventMultipleCalls(asyncContinuation));
};
return continuation;
}
/// <summary>
/// Attaches a timeout to a continuation which will invoke the continuation when the specified
/// timeout has elapsed.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">The timeout.</param>
/// <returns>Wrapped continuation.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Continuation will be disposed of elsewhere.")]
public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
return new TimeoutContinuation(asyncContinuation, timeout).Function;
}
/// <summary>
/// Iterates over all items in the given collection and runs the specified action
/// in parallel (each action executes on a thread from thread pool).
/// </summary>
/// <typeparam name="T">Type of each item.</typeparam>
/// <param name="values">The items to iterate.</param>
/// <param name="asyncContinuation">The asynchronous continuation to invoke once all items
/// have been iterated.</param>
/// <param name="action">The action to invoke for each item.</param>
public static void ForEachItemInParallel<T>(IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action)
{
action = ExceptionGuard(action);
var items = new List<T>(values);
int remaining = items.Count;
var exceptions = new List<Exception>();
InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count);
if (remaining == 0)
{
asyncContinuation(null);
return;
}
AsyncContinuation continuation =
ex =>
{
InternalLogger.Trace("Continuation invoked: {0}", ex);
if (ex != null)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
var r = Interlocked.Decrement(ref remaining);
InternalLogger.Trace("Parallel task completed. {0} items remaining", r);
if (r == 0)
{
asyncContinuation(GetCombinedException(exceptions));
}
};
foreach (T item in items)
{
T itemCopy = item;
StartAsyncTask(s =>
{
try
{
action(itemCopy, PreventMultipleCalls(continuation));
}
catch (Exception ex)
{
InternalLogger.Error(ex, "ForEachItemInParallel - Unhandled Exception");
if (ex.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
}, null);
}
}
/// <summary>
/// Runs the specified asynchronous action synchronously (blocks until the continuation has
/// been invoked).
/// </summary>
/// <param name="action">The action.</param>
/// <remarks>
/// Using this method is not recommended because it will block the calling thread.
/// </remarks>
public static void RunSynchronously(AsynchronousAction action)
{
var ev = new ManualResetEvent(false);
Exception lastException = null;
action(PreventMultipleCalls(ex => { lastException = ex; ev.Set(); }));
ev.WaitOne();
if (lastException != null)
{
throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException);
}
}
/// <summary>
/// Wraps the continuation with a guard which will only make sure that the continuation function
/// is invoked only once.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Wrapped asynchronous continuation.</returns>
public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation)
{
if (asyncContinuation.Target is SingleCallContinuation)
{
return asyncContinuation;
}
return new SingleCallContinuation(asyncContinuation).Function;
}
/// <summary>
/// Gets the combined exception from all exceptions in the list.
/// </summary>
/// <param name="exceptions">The exceptions.</param>
/// <returns>Combined exception or null if no exception was thrown.</returns>
public static Exception GetCombinedException(IList<Exception> exceptions)
{
if (exceptions.Count == 0)
{
return null;
}
if (exceptions.Count == 1)
{
return exceptions[0];
}
var sb = new StringBuilder();
string separator = string.Empty;
string newline = EnvironmentHelper.NewLine;
foreach (var ex in exceptions)
{
sb.Append(separator);
sb.Append(ex.ToString());
sb.Append(newline);
separator = newline;
}
return new NLogRuntimeException("Got multiple exceptions:\r\n" + sb);
}
private static AsynchronousAction ExceptionGuard(AsynchronousAction action)
{
return cont =>
{
try
{
action(cont);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
cont(exception);
}
};
}
private static AsynchronousAction<T> ExceptionGuard<T>(AsynchronousAction<T> action)
{
return (T argument, AsyncContinuation cont) =>
{
try
{
action(argument, cont);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
cont(exception);
}
};
}
/// <summary>
/// Disposes the Timer, and waits for it to leave the Timer-callback-method
/// </summary>
/// <param name="timer">The Timer object to dispose</param>
/// <param name="timeout">Timeout to wait (TimeSpan.Zero means dispose without wating)</param>
/// <returns>Timer disposed within timeout (true/false)</returns>
internal static bool WaitForDispose(this Timer timer, TimeSpan timeout)
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
if (timeout != TimeSpan.Zero)
{
ManualResetEvent waitHandle = new ManualResetEvent(false);
if (timer.Dispose(waitHandle) && !waitHandle.WaitOne((int)timeout.TotalMilliseconds))
{
return false; // Return without waiting for timer, and without closing waitHandle (Avoid ObjectDisposedException)
}
waitHandle.Close();
}
else
{
timer.Dispose();
}
return true;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// SupplierInfoDetail (read only object).<br/>
/// This is a generated <see cref="SupplierInfoDetail"/> business object.
/// This class is a root object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="Products"/> of type <see cref="SupplierProductList"/> (1:M relation to <see cref="SupplierProductInfo"/>)
/// </remarks>
[Serializable]
public partial class SupplierInfoDetail : ReadOnlyBase<SupplierInfoDetail>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SupplierId"/> property.
/// </summary>
public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id");
/// <summary>
/// For simplicity sake, use the VAT number (no auto increment here).
/// </summary>
/// <value>The Supplier Id.</value>
public int SupplierId
{
get { return GetProperty(SupplierIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="AddressLine1"/> property.
/// </summary>
public static readonly PropertyInfo<string> AddressLine1Property = RegisterProperty<string>(p => p.AddressLine1, "Address Line1");
/// <summary>
/// Gets the Address Line1.
/// </summary>
/// <value>The Address Line1.</value>
public string AddressLine1
{
get { return GetProperty(AddressLine1Property); }
}
/// <summary>
/// Maintains metadata about <see cref="AddressLine2"/> property.
/// </summary>
public static readonly PropertyInfo<string> AddressLine2Property = RegisterProperty<string>(p => p.AddressLine2, "Address Line2");
/// <summary>
/// Gets the Address Line2.
/// </summary>
/// <value>The Address Line2.</value>
public string AddressLine2
{
get { return GetProperty(AddressLine2Property); }
}
/// <summary>
/// Maintains metadata about <see cref="ZipCode"/> property.
/// </summary>
public static readonly PropertyInfo<string> ZipCodeProperty = RegisterProperty<string>(p => p.ZipCode, "Zip Code");
/// <summary>
/// Gets the Zip Code.
/// </summary>
/// <value>The Zip Code.</value>
public string ZipCode
{
get { return GetProperty(ZipCodeProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="State"/> property.
/// </summary>
public static readonly PropertyInfo<string> StateProperty = RegisterProperty<string>(p => p.State, "State");
/// <summary>
/// Gets the State.
/// </summary>
/// <value>The State.</value>
public string State
{
get { return GetProperty(StateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country"/> property.
/// </summary>
public static readonly PropertyInfo<byte?> CountryProperty = RegisterProperty<byte?>(p => p.Country, "Country");
/// <summary>
/// Gets the Country.
/// </summary>
/// <value>The Country.</value>
public byte? Country
{
get { return GetProperty(CountryProperty); }
}
/// <summary>
/// Maintains metadata about child <see cref="Products"/> property.
/// </summary>
public static readonly PropertyInfo<SupplierProductList> ProductsProperty = RegisterProperty<SupplierProductList>(p => p.Products, "Products");
/// <summary>
/// Gets the Products ("lazy load" child property).
/// </summary>
/// <value>The Products.</value>
public SupplierProductList Products
{
get
{
#if ASYNC
return LazyGetPropertyAsync(ProductsProperty, DataPortal.FetchAsync<SupplierProductList>(ReadProperty(SupplierIdProperty)));
#else
return LazyGetProperty(ProductsProperty, () => DataPortal.Fetch<SupplierProductList>(ReadProperty(SupplierIdProperty)));
#endif
}
private set { LoadProperty(ProductsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="SupplierInfoDetail"/> object, based on given parameters.
/// </summary>
/// <param name="supplierId">The SupplierId parameter of the SupplierInfoDetail to fetch.</param>
/// <returns>A reference to the fetched <see cref="SupplierInfoDetail"/> object.</returns>
public static SupplierInfoDetail GetSupplierInfoDetail(int supplierId)
{
return DataPortal.Fetch<SupplierInfoDetail>(supplierId);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="SupplierInfoDetail"/> object, based on given parameters.
/// </summary>
/// <param name="supplierId">The SupplierId parameter of the SupplierInfoDetail to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetSupplierInfoDetail(int supplierId, EventHandler<DataPortalResult<SupplierInfoDetail>> callback)
{
DataPortal.BeginFetch<SupplierInfoDetail>(supplierId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="SupplierInfoDetail"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public SupplierInfoDetail()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="SupplierInfoDetail"/> object from the database, based on given criteria.
/// </summary>
/// <param name="supplierId">The Supplier Id.</param>
protected void DataPortal_Fetch(int supplierId)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
using (var cmd = new SqlCommand("dbo.GetSupplierInfoDetal", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SupplierId", supplierId).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, supplierId);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="SupplierInfoDetail"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SupplierIdProperty, dr.GetInt32("SupplierId"));
LoadProperty(NameProperty, dr.GetString("Name"));
LoadProperty(AddressLine1Property, dr.IsDBNull("AddressLine1") ? null : dr.GetString("AddressLine1"));
LoadProperty(AddressLine2Property, dr.IsDBNull("AddressLine2") ? null : dr.GetString("AddressLine2"));
LoadProperty(ZipCodeProperty, dr.IsDBNull("ZipCode") ? null : dr.GetString("ZipCode"));
LoadProperty(StateProperty, dr.IsDBNull("State") ? null : dr.GetString("State"));
LoadProperty(CountryProperty, (byte?)dr.GetValue("Country"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Hammock.Model;
using Newtonsoft.Json;
namespace TweetSharp
{
#if !SILVERLIGHT && !WINRT
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
[DebuggerDisplay("{User.ScreenName}: {Text}")]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterStatus : PropertyChangedBase,
IComparable<TwitterStatus>,
IEquatable<TwitterStatus>,
ITwitterModel,
ITweetable
{
private DateTime _createdDate;
private long _id;
private string _idStr;
private string _inReplyToScreenName;
private long? _inReplyToStatusId;
private long? _inReplyToUserId;
private bool _isFavorited;
private bool _isRetweeted;
private bool _isTruncated;
private string _source;
private string _text;
private TwitterUser _user;
private TwitterStatus _retweetedStatus;
private TwitterGeoLocation _location;
private string _language;
private TwitterEntities _entities;
private TwitterExtendedEntities _extendedEntities;
private bool? _isPossiblySensitive;
private TwitterPlace _place;
private int _retweetCount;
private int _favoriteCount;
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
[JsonProperty("id_str")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string IdStr
{
get { return _idStr; }
set
{
if (_idStr == value)
{
return;
}
_idStr = value;
OnPropertyChanged("IdStr");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long? InReplyToUserId
{
get { return _inReplyToUserId; }
set
{
if (_inReplyToUserId == value)
{
return;
}
_inReplyToUserId = value;
OnPropertyChanged("InReplyToUserId");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long? InReplyToStatusId
{
get { return _inReplyToStatusId; }
set
{
if (_inReplyToStatusId == value)
{
return;
}
_inReplyToStatusId = value;
OnPropertyChanged("InReplyToStatusId");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string InReplyToScreenName
{
get { return _inReplyToScreenName; }
set
{
if (_inReplyToScreenName == value)
{
return;
}
_inReplyToScreenName = value;
OnPropertyChanged("InReplyToScreenName");
}
}
[JsonProperty("truncated")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool IsTruncated
{
get { return _isTruncated; }
set
{
if (_isTruncated == value)
{
return;
}
_isTruncated = value;
OnPropertyChanged("IsTruncated");
}
}
[JsonProperty("favorited")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool IsFavorited
{
get { return _isFavorited; }
set
{
if (_isFavorited == value)
{
return;
}
_isFavorited = value;
OnPropertyChanged("IsFavorited");
}
}
[JsonProperty("favorite_count")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual int FavoriteCount
{
get
{
return _favoriteCount;
}
set
{
if (_favoriteCount == value)
{
return;
}
_favoriteCount = value;
OnPropertyChanged("FavoriteCount");
}
}
[JsonProperty("retweeted")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool IsRetweeted
{
get { return _isRetweeted; }
set
{
if (_isRetweeted == value)
{
return;
}
_isRetweeted = value;
OnPropertyChanged("IsRetweeted");
}
}
[JsonProperty("retweet_count")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual int RetweetCount
{
get
{
return _retweetCount;
}
set
{
if (_retweetCount == value)
{
return;
}
_retweetCount = value;
OnPropertyChanged("RetweetCount");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Text
{
get { return _text; }
set
{
if (_text == value)
{
return;
}
_text = value;
_textAsHtml = null;
_textDecoded = null;
OnPropertyChanged("Text");
}
}
private string _textAsHtml;
public virtual string TextAsHtml
{
get
{
return (_textAsHtml ?? (_textAsHtml = this.ParseTextWithEntities()));
}
set
{
_textAsHtml = value;
this.OnPropertyChanged("TextAsHtml");
}
}
private string _textDecoded;
public virtual string TextDecoded
{
get
{
if (string.IsNullOrEmpty(Text))
{
return Text;
}
#if WINRT
return _textDecoded ?? (_textDecoded = System.Net.WebUtility.HtmlDecode(Text));
#elif !SILVERLIGHT && !WINDOWS_PHONE
return _textDecoded ?? (_textDecoded = System.Compat.Web.HttpUtility.HtmlDecode(Text));
#elif WINDOWS_PHONE
return _textDecoded ?? (_textDecoded = System.Net.HttpUtility.HtmlDecode(Text));
#else
return _textDecoded ?? (_textDecoded = System.Windows.Browser.HttpUtility.HtmlDecode(Text));
#endif
}
set
{
_textDecoded = value;
OnPropertyChanged("TextDecoded");
}
}
public ITweeter Author
{
get { return User; }
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Source
{
get { return _source; }
set
{
if (_source == value)
{
return;
}
_source = value;
OnPropertyChanged("Source");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterUser User
{
get { return _user; }
set
{
if (_user == value)
{
return;
}
_user = value;
OnPropertyChanged("TwitterUser");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterStatus RetweetedStatus
{
get { return _retweetedStatus; }
set
{
if (_retweetedStatus == value)
{
return;
}
_retweetedStatus = value;
OnPropertyChanged("RetweetedStatus");
}
}
[JsonProperty("created_at")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual DateTime CreatedDate
{
get { return _createdDate; }
set
{
if (_createdDate == value)
{
return;
}
_createdDate = value;
OnPropertyChanged("CreatedDate");
}
}
[JsonProperty("geo")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterGeoLocation Location
{
get { return _location; }
set
{
if (_location == value)
{
return;
}
_location = value;
OnPropertyChanged("Location");
}
}
[JsonProperty("lang")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Language
{
get { return _language; }
set
{
if (_language == value)
{
return;
}
_language = value;
OnPropertyChanged("Language");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterEntities Entities
{
get { return _entities; }
set
{
if (_entities == value)
{
return;
}
_entities = value;
OnPropertyChanged("Entities");
}
}
#if !Smartphone && !NET20
[DataMember]
[JsonProperty("extended_entities")]
#endif
public virtual TwitterExtendedEntities ExtendedEntities
{
get { return _extendedEntities; }
set
{
if (_extendedEntities == value)
{
return;
}
_extendedEntities = value;
OnPropertyChanged("Entities");
}
}
[JsonProperty("possibly_sensitive")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual bool? IsPossiblySensitive
{
get { return _isPossiblySensitive; }
set
{
if (_isPossiblySensitive == value)
{
return;
}
_isPossiblySensitive = value;
OnPropertyChanged("IsPossiblySensitive");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterPlace Place
{
get { return _place; }
set
{
if (_place == value)
{
return;
}
_place = value;
OnPropertyChanged("Place");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string RawSource { get; set; }
#region IComparable<TwitterStatus> Members
public int CompareTo(TwitterStatus other)
{
return other.Id == Id ? 0 : other.Id > Id ? -1 : 1;
}
#endregion
#region IEquatable<TwitterStatus> Members
public bool Equals(TwitterStatus status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.Id == Id;
}
#endregion
public override bool Equals(object status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.GetType() == typeof(TwitterStatus) && Equals((TwitterStatus)status);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public static bool operator ==(TwitterStatus left, TwitterStatus right)
{
return Equals(left, right);
}
public static bool operator !=(TwitterStatus left, TwitterStatus right)
{
return !Equals(left, right);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Testing.DomainModel;
using FluentNHibernate.Testing.Fixtures.Basic;
using FluentNHibernate.Testing.Fixtures.MixedMappingsInSameLocation;
using FluentNHibernate.Testing.Fixtures.MixedMappingsInSameLocation.Mappings;
using NHibernate.Cfg;
using NUnit.Framework;
using static FluentNHibernate.Testing.Cfg.SQLiteFrameworkConfigurationFactory;
namespace FluentNHibernate.Testing.Cfg
{
[TestFixture]
public class ValidFluentConfigurationTests
{
[Test]
public void ExposeConfigurationPassesCfgInstanceIntoAction()
{
Fluently.Configure()
.ExposeConfiguration(cfg =>
{
cfg.ShouldNotBeNull();
cfg.ShouldBeOfType(typeof(Configuration));
});
}
[Test]
public void ExposeConfigurationHasSameCfgInstanceAsPassedInThroughConstructor()
{
var config = new Configuration();
Fluently.Configure(config)
.ExposeConfiguration(cfg => cfg.ShouldEqual(config));
}
[Test]
public void ExposeConfigurationCanBeCalledMultipleTimesWithDifferentBodies()
{
var calls = new List<string>();
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.ExposeConfiguration(cfg => calls.Add("One"))
.ExposeConfiguration(cfg => calls.Add("Two"))
.BuildSessionFactory();
calls.ShouldContain("One");
calls.ShouldContain("Two");
}
[Test]
public void DatabaseSetsPropertiesOnCfg()
{
Fluently.Configure()
.Database(
CreateStandardConfiguration())
.ExposeConfiguration(cfg =>
{
cfg.Properties.ContainsKey("connection.provider").ShouldBeTrue();
});
}
[Test]
public void ExposeConfigurationGetsConfigAfterMappingsHaveBeenApplied()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Record>())
.ExposeConfiguration(cfg =>
{
cfg.ClassMappings.Count.ShouldBeGreaterThan(0);
});
}
[Test]
public void MappingsShouldPassInstanceOfMappingConfigurationToAction()
{
Fluently.Configure()
.Mappings(m =>
{
m.ShouldNotBeNull();
m.ShouldBeOfType(typeof(MappingConfiguration));
});
}
[Test]
public void MappingsCanBeMixedAndDontConflict()
{
var sessionFactory = Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
{
m.FluentMappings.Add<FooMap>();
m.AutoMappings.Add(AutoMap.AssemblyOf<Bar>()
.Where(t => t.Namespace == typeof(Bar).Namespace));
})
.BuildSessionFactory();
sessionFactory.ShouldNotBeNull();
}
[Test]
public void ShouldGetASessionFactoryIfEverythingIsOK()
{
var sessionFactory = Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings.Add<BinaryRecordMap>())
.BuildSessionFactory();
sessionFactory.ShouldNotBeNull();
}
[Test]
public void ShouldGetAConfigurationIfEverythingIsOK()
{
var configuration = Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings.Add<BinaryRecordMap>())
.BuildConfiguration();
configuration.ShouldNotBeNull();
}
[Test]
public void ShouldSetCurrentSessionContext()
{
var configuration = Fluently.Configure()
.CurrentSessionContext("thread_static")
.BuildConfiguration();
configuration.Properties["current_session_context_class"].ShouldEqual("thread_static");
}
[Test]
public void ShouldSetCurrentSessionContextUsingGeneric()
{
var configuration = Fluently.Configure()
.CurrentSessionContext<NHibernate.Context.ThreadStaticSessionContext>()
.BuildConfiguration();
configuration.Properties["current_session_context_class"].ShouldEqual(typeof(NHibernate.Context.ThreadStaticSessionContext).AssemblyQualifiedName);
}
[Test]
public void ShouldSetConnectionIsolationLevel()
{
var configuration = Fluently.Configure()
.Database(
CreateStandardConfiguration(IsolationLevel.ReadUncommitted))
.BuildConfiguration();
configuration.Properties["connection.isolation"].ShouldEqual("ReadUncommitted");
}
[Test]
public void Use_Minimal_Puts_should_set_value_to_const_true()
{
var configuration = Fluently.Configure()
.Cache(x => x.UseMinimalPuts())
.BuildConfiguration();
configuration.Properties.ShouldContain("cache.use_minimal_puts", "true");
}
[Test]
public void Use_Query_Cache_should_set_value_to_const_true()
{
var configuration = Fluently.Configure()
.Cache(x => x.UseQueryCache())
.BuildConfiguration();
configuration.Properties.ShouldContain("cache.use_query_cache", "true");
}
[Test]
public void Query_Cache_Factory_should_set_property_value()
{
var configuration = Fluently.Configure()
.Cache(x => x.QueryCacheFactory("foo"))
.BuildConfiguration();
configuration.Properties.ShouldContain("cache.query_cache_factory", "foo");
}
[Test]
public void Region_Prefix_should_set_property_value()
{
var configuration = Fluently.Configure()
.Cache(x => x.RegionPrefix("foo"))
.BuildConfiguration();
configuration.Properties.ShouldContain("cache.region_prefix", "foo");
}
[Test]
public void Provider_Class_should_set_property_value()
{
var configuration = Fluently.Configure()
.Cache(x => x.ProviderClass("foo"))
.BuildConfiguration();
}
}
[TestFixture]
public class InvalidFluentConfigurationTests
{
private const string ExceptionMessage = "An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.";
private const string ExceptionDatabaseMessage = "Database was not configured through Database method.";
private const string ExceptionMappingMessage = "No mappings were configured through the Mappings method.";
[Test]
public void BuildSessionFactoryShouldThrowIfCalledBeforeAnythingSetup()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.BuildSessionFactory());
ex.Message.ShouldStartWith(ExceptionMessage);
}
[Test]
public void ExceptionShouldContainDbIfDbNotSetup()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.BuildSessionFactory());
ex.PotentialReasons.ShouldContain(ExceptionDatabaseMessage);
}
[Test]
public void ExceptionShouldntContainDbIfDbSetup()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.Database(
CreateStandardConfiguration())
.BuildSessionFactory());
ex.PotentialReasons.Contains(ExceptionDatabaseMessage)
.ShouldBeFalse();
}
[Test]
public void ExceptionShouldContainMappingsIfMappingsNotSetup()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.Database(
CreateStandardConfiguration())
.BuildSessionFactory());
ex.PotentialReasons.ShouldContain(ExceptionMappingMessage);
}
[Test]
public void ExceptionShouldntContainMappingsIfMappingsSetup()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.Database(
CreateStandardConfiguration())
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Record>())
.BuildSessionFactory());
ex.PotentialReasons.Contains(ExceptionMappingMessage)
.ShouldBeFalse();
}
[Test]
public void InnerExceptionSet()
{
var ex = Assert.Throws<FluentConfigurationException>(() =>
Fluently.Configure()
.Database(
CreateStandardConfiguration())
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Record>())
.BuildSessionFactory());
ex.InnerException.ShouldNotBeNull();
}
}
[TestFixture]
public class FluentConfigurationWriteMappingsTests
{
private string ExportPath;
[SetUp]
public void CreateTempDir()
{
ExportPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(ExportPath);
}
[TearDown]
public void DestroyTempDir()
{
Directory.Delete(ExportPath, true);
}
[Test]
public void WritesFluentMappingsOut()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings
.Add<BinaryRecordMap>()
.ExportTo(ExportPath))
.BuildConfiguration();
Directory.GetFiles(ExportPath)
.ShouldContain(HbmFor<BinaryRecord>);
}
[Test]
public void WritesFluentMappingsOutToTextWriter()
{
var stringWriter = new StringWriter();
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings
.Add<BinaryRecordMap>()
.ExportTo(stringWriter))
.BuildConfiguration();
string export = stringWriter.ToString();
export.ShouldNotBeEmpty();
}
[Test]
public void WritesFluentMappingsOutMergedWhenFlagSet()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.MergeMappings()
.FluentMappings
.Add<BinaryRecordMap>()
.ExportTo(ExportPath))
.BuildConfiguration();
Directory.GetFiles(ExportPath)
.ShouldContain(x => Path.GetFileName(x) == "FluentMappings.hbm.xml");
}
[Test]
public void WritesAutoMappingsOut()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.AutoMappings.Add(AutoMap.AssemblyOf<Person>()
.Where(type => type.Namespace == "FluentNHibernate.Testing.Fixtures.Basic"))
.ExportTo(ExportPath))
.BuildSessionFactory();
Directory.GetFiles(ExportPath)
.ShouldContain(HbmFor<Person>);
}
[Test]
public void WritesAutoMappingsOutMergedWhenFlagSet()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.MergeMappings()
.AutoMappings.Add(AutoMap.AssemblyOf<Person>()
.Where(type => type.Namespace == "FluentNHibernate.Testing.Fixtures.Basic"))
.ExportTo(ExportPath))
.BuildSessionFactory();
Directory.GetFiles(ExportPath)
.ShouldContain(x => Path.GetFileName(x) == "AutoMappings.hbm.xml");
}
[Test]
public void WritesBothOut()
{
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
{
m.FluentMappings
.Add<BinaryRecordMap>()
.ExportTo(ExportPath);
m.AutoMappings.Add(AutoMap.Source(new StubTypeSource(typeof(Person)))
.Where(type => type.Namespace == "FluentNHibernate.Testing.Fixtures.Basic"))
.ExportTo(ExportPath);
})
.BuildSessionFactory();
var files = Directory.GetFiles(ExportPath);
files.ShouldContain(HbmFor<BinaryRecord>);
files.ShouldContain(HbmFor<Person>);
}
[Test]
public void DoesNotThrowWhenExportToIsBeforeBuildConfigurationOnCachePartMapping()
{
//Regression test for isue 131
Fluently.Configure()
.Database(
CreateStandardInMemoryConfiguration())
.Mappings(m =>
m.FluentMappings
.Add<CachedRecordMap>()
.ExportTo(ExportPath))
.BuildConfiguration();
}
private static bool HbmFor<T>(string path)
{
return Path.GetFileName(path) == typeof(T).FullName + ".hbm.xml";
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Threading.Tasks;
using Windows.Media.Audio;
using Windows.Media.Render;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace AudioCreation
{
/// <summary>
/// Using the AudioGraph API to playback from a file input.
/// </summary>
public sealed partial class Scenario1_FilePlayback : Page
{
private MainPage rootPage;
private AudioGraph graph;
private AudioFileInputNode fileInput;
private AudioDeviceOutputNode deviceOutput;
public Scenario1_FilePlayback()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
await CreateAudioGraph();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// Destroy the graph if the page is naviated away from
if (graph != null)
{
graph.Dispose();
}
}
private async void File_Click(object sender, RoutedEventArgs e)
{
// Clear any old messages.
rootPage.NotifyUser("", NotifyType.StatusMessage);
// If another file is already loaded into the FileInput node
if (fileInput != null)
{
// Release the file and dispose the contents of the node
fileInput.Dispose();
// Stop playback since a new file is being loaded. Also reset the button UI
if (graphButton.Content.Equals("Stop Graph"))
{
TogglePlay();
}
}
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.FileTypeFilter.Add(".mp3");
filePicker.FileTypeFilter.Add(".wav");
filePicker.FileTypeFilter.Add(".wma");
filePicker.FileTypeFilter.Add(".m4a");
filePicker.ViewMode = PickerViewMode.Thumbnail;
StorageFile file = await filePicker.PickSingleFileAsync();
// File can be null if cancel is hit in the file picker
if(file == null)
{
return;
}
CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file);
if (AudioFileNodeCreationStatus.Success != fileInputResult.Status)
{
// Cannot read input file
rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage);
return;
}
fileInput = fileInputResult.FileInputNode;
if (fileInput.Duration <= TimeSpan.FromSeconds(3))
{
// Imported file is too short
rootPage.NotifyUser("Please pick an audio file which is longer than 3 seconds", NotifyType.ErrorMessage);
fileInput.Dispose();
fileInput = null;
return;
}
fileInput.AddOutgoingConnection(deviceOutput);
fileButton.Background = new SolidColorBrush(Colors.Green);
// Trim the file: set the start time to 3 seconds from the beginning
// fileInput.EndTime can be used to trim from the end of file
fileInput.StartTime = TimeSpan.FromSeconds(3);
// Enable buttons in UI to start graph, loop and change playback speed factor
graphButton.IsEnabled = true;
loopToggle.IsEnabled = true;
playSpeedSlider.IsEnabled = true;
}
private void Graph_Click(object sender, RoutedEventArgs e)
{
TogglePlay();
}
private void TogglePlay()
{
//Toggle playback
if (graphButton.Content.Equals("Start Graph"))
{
graph.Start();
graphButton.Content = "Stop Graph";
audioPipe.Fill = new SolidColorBrush(Colors.Blue);
}
else
{
graph.Stop();
graphButton.Content = "Start Graph";
audioPipe.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49));
}
}
private void PlaySpeedSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (fileInput != null)
{
fileInput.PlaybackSpeedFactor = playSpeedSlider.Value;
}
}
private void LoopToggle_Toggled(object sender, RoutedEventArgs e)
{
// Set loop count to null for infinite looping
// Set loop count to 0 to stop looping after current iteration
// Set loop count to non-zero value for finite looping
if (loopToggle.IsOn)
{
// If turning on looping, make sure the file hasn't finished playback yet
if (fileInput.Position >= fileInput.Duration)
{
// If finished playback, seek back to the start time we set
fileInput.Seek(fileInput.StartTime.Value);
}
fileInput.LoopCount = null; // infinite looping
}
else
{
fileInput.LoopCount = 0; // stop looping
}
}
private async Task CreateAudioGraph()
{
// Create an AudioGraph with default settings
AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
if (result.Status != AudioGraphCreationStatus.Success)
{
// Cannot create graph
rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage);
return;
}
graph = result.Graph;
// Create a device output node
CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
// Cannot create device output node
rootPage.NotifyUser(String.Format("Device Output unavailable because {0}", deviceOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage);
speakerContainer.Background = new SolidColorBrush(Colors.Red);
return;
}
deviceOutput = deviceOutputNodeResult.DeviceOutputNode;
rootPage.NotifyUser("Device Output Node successfully created", NotifyType.StatusMessage);
speakerContainer.Background = new SolidColorBrush(Colors.Green);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
namespace GuiLabs.Utils
{
public struct Pair<T>
{
public Pair(T first, T second)
{
First = first;
Second = second;
}
public T First;
public T Second;
}
public static class Common
{
public static bool BitSet<T>(T enumValue, T bitValue)
{
int val = Convert.ToInt32(enumValue);
int bit = Convert.ToInt32(bitValue);
return (val & bit) == bit;
}
public static void Swap<T>(ref T Value1, ref T Value2)
{
T Temp = Value1;
Value1 = Value2;
Value2 = Temp;
}
public static T Max<T>(T Value1, T Value2)
where T : IComparable
{
if (Value1.CompareTo(Value2) < 0)
{
return Value2;
}
else
{
return Value1;
}
}
public static T Min<T>(T Value1, T Value2)
where T : IComparable
{
if (Value1.CompareTo(Value2) < 0)
{
return Value1;
}
else
{
return Value2;
}
}
public static void EnsureGreater<T>(ref T Value, T ComparedWith)
where T : IComparable
{
if (Value.CompareTo(ComparedWith) < 0)
{
Value = ComparedWith;
}
}
public static void SwapIfGreater<T>(ref T LValue, ref T RValue)
where T : IComparable
{
if (LValue.CompareTo(RValue) > 0)
{
T temp = LValue;
LValue = RValue;
RValue = temp;
}
}
public static string DumpEnvironmentPaths()
{
var paths = Enum.GetValues(typeof(Environment.SpecialFolder))
.Cast<Environment.SpecialFolder>()
.Select(folder => folder + " = " + Environment.GetFolderPath(folder))
.Aggregate((s1, s2) => s1 + Environment.NewLine + s2);
return paths;
}
public static T GetFirstItem<T>(IEnumerable<T> list)
{
T result = default(T);
if (list != null)
{
IEnumerator<T> enumerator = list.GetEnumerator();
if (enumerator != null && enumerator.MoveNext())
{
result = enumerator.Current;
}
}
return result;
}
public static T Head<T>(IEnumerable<T> list)
{
return GetFirstItem(list);
}
public static bool Empty<T>(IEnumerable<T> list)
{
return GetFirstItem(list) == null;
}
public static IEnumerable<T> Tail<T>(IEnumerable<T> list)
{
if (list != null)
{
IEnumerator<T> enumerator = list.GetEnumerator();
if (enumerator != null && enumerator.MoveNext())
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
}
public static double MeasureExecutionTime(Action code)
{
long startTime = Stopwatch.GetTimestamp();
code();
long stopTime = Stopwatch.GetTimestamp();
return (stopTime - startTime) / (double)Stopwatch.Frequency;
}
public static bool Contains<T>(IEnumerable<T> list, T value)
where T : IEquatable<T>
{
foreach (T item in list)
{
if (item.Equals(value))
{
return true;
}
}
return false;
}
public static IEnumerable<T> Filter<T>(ArrayList arrayList)
where T : class
{
foreach (object o in arrayList)
{
T found = o as T;
if (found != null)
{
yield return found;
}
}
}
#region File dialogs
public static string FilterAllFiles = "All files (*.*) |*.*";
public static string GetSaveFileName()
{
return GetSaveFileName(FilterAllFiles);
}
public static string GetOpenFileName()
{
return GetOpenFileName(FilterAllFiles);
}
public static string GetSaveFileName(string filter)
{
if (string.IsNullOrEmpty(filter))
{
filter = FilterAllFiles;
}
SaveFileDialog dialog = new SaveFileDialog();
dialog.InitialDirectory = Application.StartupPath;
dialog.Filter = filter;
if (dialog.ShowDialog() == DialogResult.OK)
{
return dialog.FileName;
}
return string.Empty;
}
public static string GetOpenFileName(string filter)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = filter;
dialog.InitialDirectory = Application.StartupPath;
if (dialog.ShowDialog() == DialogResult.OK)
{
return dialog.FileName;
}
return string.Empty;
}
#endregion
}
public static class Param
{
public static void CheckNotNull(object param)
{
if (param == null)
{
throw new ArgumentNullException();
}
}
public static void CheckNotNull(object param, string paramName)
{
if (param == null)
{
throw new ArgumentNullException(paramName);
}
}
public static void CheckNonEmptyString(string param)
{
if (string.IsNullOrEmpty(param))
{
throw new ArgumentException("String parameter cannot be null.");
}
}
public static void CheckNonEmptyString(string param, string paramName)
{
if (string.IsNullOrEmpty(param))
{
throw new ArgumentException(string.Format("String parameter '{0}' cannot be null.", paramName));
}
}
}
}
| |
// 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.Buffers;
using System.IO;
namespace System.Security.Cryptography
{
public abstract class HashAlgorithm : IDisposable, ICryptoTransform
{
private bool _disposed;
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State = 0;
protected HashAlgorithm() { }
public static HashAlgorithm Create() =>
CryptoConfigForwarder.CreateDefaultHashAlgorithm();
public static HashAlgorithm Create(string hashName) =>
(HashAlgorithm)CryptoConfigForwarder.CreateFromName(hashName);
public virtual int HashSize => HashSizeValue;
public virtual byte[] Hash
{
get
{
if (_disposed)
throw new ObjectDisposedException(null);
if (State != 0)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_HashNotYetFinalized);
return (byte[])HashValue?.Clone();
}
}
public byte[] ComputeHash(byte[] buffer)
{
if (_disposed)
throw new ObjectDisposedException(null);
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
HashCore(buffer, 0, buffer.Length);
return CaptureHashCodeAndReinitialize();
}
public bool TryComputeHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
if (_disposed)
{
throw new ObjectDisposedException(null);
}
if (destination.Length < HashSizeValue/8)
{
bytesWritten = 0;
return false;
}
HashCore(source);
if (!TryHashFinal(destination, out bytesWritten))
{
// The only reason for failure should be that the destination isn't long enough,
// but we checked the size earlier.
throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation);
}
HashValue = null;
Initialize();
return true;
}
public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0 || (count > buffer.Length))
throw new ArgumentException(SR.Argument_InvalidValue);
if ((buffer.Length - count) < offset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(null);
HashCore(buffer, offset, count);
return CaptureHashCodeAndReinitialize();
}
public byte[] ComputeHash(Stream inputStream)
{
if (_disposed)
throw new ObjectDisposedException(null);
// Use ArrayPool.Shared instead of CryptoPool because the array is passed out.
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
HashCore(buffer, 0, bytesRead);
}
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
return CaptureHashCodeAndReinitialize();
}
private byte[] CaptureHashCodeAndReinitialize()
{
HashValue = HashFinal();
// Clone the hash value prior to invoking Initialize in case the user-defined Initialize
// manipulates the array.
byte[] tmp = (byte[])HashValue.Clone();
Initialize();
return tmp;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear()
{
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Although we don't have any resources to dispose at this level,
// we need to continue to throw ObjectDisposedExceptions from CalculateHash
// for compatibility with the desktop framework.
_disposed = true;
}
return;
}
// ICryptoTransform methods
// We assume any HashAlgorithm can take input a byte at a time
public virtual int InputBlockSize => 1;
public virtual int OutputBlockSize => 1;
public virtual bool CanTransformMultipleBlocks => true;
public virtual bool CanReuseTransform => true;
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
// Change the State value
State = 1;
HashCore(inputBuffer, inputOffset, inputCount);
if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)))
{
// We let BlockCopy do the destination array validation
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
}
return inputCount;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = CaptureHashCodeAndReinitialize();
byte[] outputBytes;
if (inputCount != 0)
{
outputBytes = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount);
}
else
{
outputBytes = Array.Empty<byte>();
}
// Reset the State value
State = 0;
return outputBytes;
}
private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
if (inputBuffer == null)
throw new ArgumentNullException(nameof(inputBuffer));
if (inputOffset < 0)
throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (inputCount < 0 || inputCount > inputBuffer.Length)
throw new ArgumentException(SR.Argument_InvalidValue);
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(null);
}
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected abstract byte[] HashFinal();
public abstract void Initialize();
protected virtual void HashCore(ReadOnlySpan<byte> source)
{
// Use ArrayPool.Shared instead of CryptoPool because the array is passed out.
byte[] array = ArrayPool<byte>.Shared.Rent(source.Length);
source.CopyTo(array);
HashCore(array, 0, source.Length);
Array.Clear(array, 0, source.Length);
ArrayPool<byte>.Shared.Return(array);
}
protected virtual bool TryHashFinal(Span<byte> destination, out int bytesWritten)
{
int hashSizeInBytes = HashSizeValue / 8;
if (destination.Length >= hashSizeInBytes)
{
byte[] final = HashFinal();
if (final.Length == hashSizeInBytes)
{
new ReadOnlySpan<byte>(final).CopyTo(destination);
bytesWritten = final.Length;
return true;
}
throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation);
}
bytesWritten = 0;
return false;
}
}
}
| |
#region Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
/*
Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE. */
#endregion
using System;
using System.Collections;
using XihSolutions.DotMSN.Core;
using XihSolutions.DotMSN.DataTransfer;
namespace XihSolutions.DotMSN
{
#region Event argument classes
/// <summary>
/// Used when a new switchboard session is affected.
/// </summary>
public class SBEventArgs : EventArgs
{
/// <summary>
/// </summary>
private SBMessageHandler switchboard;
/// <summary>
/// The affected switchboard
/// </summary>
public SBMessageHandler Switchboard
{
get { return switchboard; }
set { switchboard = value;}
}
/// <summary>
/// Constructor.
/// </summary>
public SBEventArgs(SBMessageHandler switchboard)
{
this.switchboard = switchboard;
}
}
/// <summary>
/// Used when a new switchboard session is created.
/// </summary>
public class SBCreatedEventArgs : EventArgs
{
/// <summary>
/// </summary>
private SBMessageHandler switchboard;
/// <summary>
/// The affected switchboard
/// </summary>
public SBMessageHandler Switchboard
{
get { return switchboard; }
set { switchboard = value;}
}
/// <summary>
/// </summary>
private object initiator;
/// <summary>
/// The object that requested the switchboard. Null if the switchboard session was initiated by a remote client.
/// </summary>
public object Initiator
{
get { return initiator; }
set { initiator = value;}
}
/// <summary>
/// Constructor.
/// </summary>
public SBCreatedEventArgs(SBMessageHandler switchboard, object initiator)
{
this.switchboard = switchboard;
this.initiator = initiator;
}
}
#endregion
#region Delegates
/// <summary>
/// Used when a switchboard is affected.
/// </summary>
public delegate void SBChangedEventHandler(object sender, EventArgs e);
/// <summary>
/// Used when a text message is received from a remote contact.
/// </summary>
public delegate void TextMessageReceivedEventHandler(object sender, TextMessageEventArgs e);
/// <summary>
/// Used when a emoticon definition is received from a remote contact.
/// </summary>
public delegate void EmoticonDefinitionReceivedEventHandler(object sender, EmoticonDefinitionEventArgs e);
/// <summary>
/// Used when a remote contact begins typing.
/// </summary>
public delegate void UserTypingEventHandler(object sender, ContactEventArgs e);
#endregion
/// <summary>
/// Handles the messages from the switchboard server.
/// </summary>
public class SBMessageHandler : IMessageHandler
{
#region Private
/// <summary>
/// </summary>
private SocketMessageProcessor messageProcessor = null;
/// <summary>
/// </summary>
private NSMessageHandler nsMessageHandler = null;
/// <summary>
/// </summary>
private bool invited = false;
/// <summary>
/// </summary>
private EventHandler processorConnectedHandler = null;
/// <summary>
/// </summary>
private EventHandler processorDisconnectedHandler = null;
/// <summary>
/// </summary>
private int sessionId;
/// <summary>
/// </summary>
protected int SessionId
{
get { return sessionId; }
set { sessionId = value;}
}
/// <summary>
/// </summary>
private string sessionHash = "";
/// <summary>
/// The hash identifier used to define this switchboard session.
/// </summary>
protected string SessionHash
{
get { return sessionHash; }
set { sessionHash = value;}
}
/// <summary>
/// </summary>
private bool sessionEstablished = false;
/// <summary>
/// </summary>
private Hashtable contacts = new Hashtable();
/// <summary>
/// Holds track of the invitations we have yet to issue
/// </summary>
private Queue invitationQueue = new Queue();
/// <summary>
/// Supports the p2p framework
/// </summary>
private P2PHandler p2pHandler = null;
#endregion
#region Public Events
/// <summary>
/// Fired when the owner is the only contact left. If the owner leaves too the connection is automatically closed by the server.
/// </summary>
public event SBChangedEventHandler AllContactsLeft;
/// <summary>
/// Fired when the session is closed, either by the server or by the local client.
/// </summary>
public event SBChangedEventHandler SessionClosed;
/// <summary>
/// Occurs when a switchboard connection has been made and the initial handshaking commands are send. This indicates that the session is ready to invite or accept other contacts.
/// </summary>
public event SBChangedEventHandler SessionEstablished;
/// <summary>
/// Fired when a contact joins. In case of a conversation with two people in it this event is called with the remote contact specified in the event argument.
/// </summary>
public event ContactChangedEventHandler ContactJoined;
/// <summary>
/// Fired when a contact leaves the conversation.
/// </summary>
public event ContactChangedEventHandler ContactLeft;
/// <summary>
/// Fired when a message is received from any of the other contacts in the conversation.
/// </summary>
public event TextMessageReceivedEventHandler TextMessageReceived;
/// <summary>
/// Fired when a contact sends a emoticon definition.
/// </summary>
public event EmoticonDefinitionReceivedEventHandler EmoticonDefinitionReceived;
/// <summary>
/// Fired when any of the other contacts is typing a message.
/// </summary>
public event UserTypingEventHandler UserTyping;
/// <summary>
/// Occurs when an exception is thrown while handling the incoming or outgoing messages.
/// </summary>
public event HandlerExceptionEventHandler ExceptionOccurred;
/// <summary>
/// Occurs when the MSN Switchboard Server sends us an error.
/// </summary>
public event ErrorReceivedEventHandler ServerErrorReceived;
/// <summary>
/// Fires the SessionClosed event.
/// </summary>
protected virtual void OnSessionClosed()
{
if(SessionClosed != null)
SessionClosed(this, new EventArgs());
}
/// <summary>
/// Fires the ServerErrorReceived event.
/// </summary>
protected virtual void OnServerErrorReceived(MSNError serverError)
{
if(ServerErrorReceived != null)
ServerErrorReceived(this, new MSNErrorEventArgs(serverError));
}
/// <summary>
/// Fires the SessionEstablished event and processes invitations in the queue.
/// </summary>
protected virtual void OnSessionEstablished()
{
sessionEstablished = true;
if(SessionEstablished != null)
SessionEstablished(this, new EventArgs());
// process ant remaining invitations
ProcessInvitations();
}
/// <summary>
/// Fires the <see cref="ExceptionOccurred"/> event.
/// </summary>
/// <param name="e">The exception which was thrown</param>
protected virtual void OnExceptionOccurred(Exception e)
{
if(ExceptionOccurred != null)
ExceptionOccurred(this, new ExceptionEventArgs(e));
}
/// <summary>
/// Fires the <see cref="ContactJoined"/> event.
/// </summary>
/// <param name="contact">The contact who joined the session.</param>
protected virtual void OnContactJoined(Contact contact)
{
if(ContactJoined != null)
{
ContactJoined(this, new ContactEventArgs(contact));
}
}
/// <summary>
/// Fires the <see cref="ContactLeft"/> event.
/// </summary>
/// <param name="contact">The contact who left the session.</param>
protected virtual void OnContactLeft(Contact contact)
{
if(ContactLeft != null)
{
ContactLeft(this, new ContactEventArgs(contact));
}
}
/// <summary>
/// Fires the <see cref="AllContactsLeft"/> event.
/// </summary>
protected virtual void OnAllContactsLeft()
{
if(AllContactsLeft != null)
{
AllContactsLeft(this, new EventArgs());
}
}
/// <summary>
/// Fires the <see cref="UserTyping"/> event.
/// </summary>
/// <param name="contact">The contact who is typing.</param>
protected virtual void OnUserTyping(Contact contact)
{
// make sure we don't parse the rest of the message in the next loop
if(UserTyping != null)
{
// raise the event
UserTyping(this, new ContactEventArgs(contact));
}
}
/// <summary>
/// Fires the <see cref="UserTyping"/> event.
/// </summary>
/// <param name="message">The emoticon message.</param>
/// <param name="contact">The contact who is sending the definition.</param>
protected virtual void OnEmoticonDefinition(MSGMessage message, Contact contact)
{
EmoticonMessage emoticonMessage = new EmoticonMessage();
emoticonMessage.CreateFromMessage(message);
if(EmoticonDefinitionReceived != null)
{
foreach(Emoticon emoticon in emoticonMessage.Emoticons)
{
EmoticonDefinitionReceived(this, new EmoticonDefinitionEventArgs(contact, emoticon));
}
}
}
/// <summary>
/// Fires the <see cref="TextMessageReceived"/> event.
/// </summary>
/// <param name="message">The message send.</param>
/// <param name="contact">The contact who sended the message.</param>
protected virtual void OnTextMessageReceived(TextMessage message, Contact contact)
{
if(TextMessageReceived != null)
TextMessageReceived(this, new TextMessageEventArgs(message, contact));
}
#endregion
#region Public
/// <summary>
/// </summary>
private SBMessageHandler()
{
}
/// <summary>
/// Called when a switchboard session is created on request of a remote client.
/// </summary>
/// <param name="sessionHash"></param>
/// <param name="sessionId"></param>
public void SetInvitation(string sessionHash, int sessionId)
{
this.sessionId = sessionId;
this.sessionHash = sessionHash;
this.invited = true;
}
/// <summary>
/// Called when a switchboard session is created on request of a local client.
/// </summary>
/// <param name="sessionHash"></param>
public void SetInvitation(string sessionHash)
{
this.sessionHash = sessionHash;
this.invited = false;
}
/// <summary>
/// The nameserver that received the request for the switchboard session
/// </summary>
public NSMessageHandler NSMessageHandler
{
get { return nsMessageHandler; }
set { nsMessageHandler = value;}
}
/// <summary>
/// Implements the P2P framework. This object is automatically created when a succesfull connection was made to the switchboard.
/// </summary>
public P2PHandler P2PHandler
{
get { return p2pHandler; }
set { p2pHandler = value;}
}
/// <summary>
/// Indicates if the local client was invited to the session
/// </summary>
public bool Invited
{
get { return invited; }
}
/// <summary>
/// A collection of all <i>remote</i> contacts present in this session
/// </summary>
public Hashtable Contacts
{
get { return contacts; }
}
/// <summary>
/// Indicates if the session is ready to send/accept commands. E.g. the initial handshaking and identification has been completed.
/// </summary>
public bool IsSessionEstablished
{
get { return sessionEstablished; }
}
/// <summary>
/// The processor to handle the messages
/// </summary>
public IMessageProcessor MessageProcessor
{
get
{
return messageProcessor;
}
set
{
if (processorConnectedHandler == null)
{
// store the new eventhandlers in order to remove them in the future
processorConnectedHandler = new EventHandler(SB9MessageHandler_ProcessorConnectCallback);
processorDisconnectedHandler = new EventHandler(SB9MessageHandler_ProcessorDisconnectCallback);
}
// catch the connect event so we can start sending the USR command upon initiating
((SocketMessageProcessor)value).ConnectionEstablished += processorConnectedHandler;
((SocketMessageProcessor)value).ConnectionClosed += processorDisconnectedHandler;
if (messageProcessor != null)
{
// de-register from the previous message processor
((SocketMessageProcessor)messageProcessor).ConnectionEstablished -= processorConnectedHandler;
((SocketMessageProcessor)messageProcessor).ConnectionClosed -= processorDisconnectedHandler;
}
messageProcessor = (SocketMessageProcessor)value;
}
}
/// <summary>
/// Closes the switchboard session by disconnecting from the server.
/// </summary>
public void Close()
{
if(MessageProcessor != null)
((SocketMessageProcessor)MessageProcessor).Disconnect();
}
#endregion
/// <summary>
/// Called when the message processor has established a connection. This function will
/// begin the login procedure by sending the VER command.
/// </summary>
protected virtual void OnProcessorConnectCallback(IMessageProcessor processor)
{
SendInitialMessage();
}
/// <summary>
/// Called when the message processor has disconnected. This function will
/// set the IsSessionEstablished to false.
/// </summary>
protected virtual void OnProcessorDisconnectCallback(IMessageProcessor processor)
{
sessionEstablished = false;
OnSessionClosed();
}
/// <summary>
/// Calls OnProcessorConnectCallback.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SB9MessageHandler_ProcessorConnectCallback(object sender, EventArgs e)
{
if (Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("Switchboard processor connected.", "SBMessageHandler");
OnProcessorConnectCallback((IMessageProcessor)sender);
}
/// <summary>
/// Calls OnProcessorDisconnectCallback.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SB9MessageHandler_ProcessorDisconnectCallback(object sender, EventArgs e)
{
OnProcessorDisconnectCallback((IMessageProcessor)sender);
}
#region Protected helper methods
/// <summary>
/// Handles all remaining invitations. If no connection is yet established it will do nothing.
/// </summary>
protected virtual void ProcessInvitations()
{
if (Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("Processing invitations for switchboard ..", "SBMessageHandler");
if(IsSessionEstablished)
{
while(invitationQueue.Count > 0)
SendInvitationCommand((string)invitationQueue.Dequeue());
if (Settings.TraceSwitch.TraceVerbose)
System.Diagnostics.Trace.WriteLine("Invitation send", "SBMessageHandler");
}
}
/// <summary>
/// Sends the invitation command to the switchboard server.
/// </summary>
/// <param name="contact"></param>
protected virtual void SendInvitationCommand(string contact)
{
MessageProcessor.SendMessage(new SBMessage("CAL", new string[] { contact } ));
}
#endregion
#region Message sending methods
/// <summary>
/// Invites the specified contact to the switchboard.
/// </summary>
/// <remarks>
/// If there is not yet a connection established the invitation will be stored in a queue and processed as soon as a connection is established.
/// </remarks>
/// <param name="contact">The contact's account to invite.</param>
public virtual void Invite(string contact)
{
invitationQueue.Enqueue(contact);
ProcessInvitations();
}
/// <summary>
/// Sends a plain text message to all other contacts in the conversation.
/// </summary>
/// <remarks>
/// This method wraps the TextMessage object in a SBMessage object and sends it over the network.
/// </remarks>
/// <param name="message">The message to send.</param>
public virtual void SendTextMessage(TextMessage message)
{
SBMessage sbMessage = new SBMessage();
MSGMessage msgMessage = new MSGMessage();
sbMessage.InnerMessage = msgMessage;
msgMessage.InnerMessage = message;
// send it over the network
MessageProcessor.SendMessage(sbMessage);
}
/// <summary>
/// Sends the definition for a list of emoticons to all other contacts in the conversation. The client-programmer must use this function if a text messages uses multiple emoticons in a single message.
/// </summary>
/// <remarks>Use this function before sending text messages which include the emoticon text. You can only send one emoticon message before the textmessage. So make sure that all emoticons used in the textmessage are included.</remarks>
/// <param name="emoticons">A list of emoticon objects.</param>
public virtual void SendEmoticonDefinitions(ArrayList emoticons)
{
SBMessage sbMessage = new SBMessage();
MSGMessage msgMessage = new MSGMessage();
EmoticonMessage emoticonMessage = new EmoticonMessage(emoticons);
msgMessage.InnerMessage = emoticonMessage;
sbMessage.InnerMessage = msgMessage;
// send it over the network
MessageProcessor.SendMessage(sbMessage);
}
/// <summary>
/// Sends a 'user is typing..' message to the switchboard, and is received by all participants.
/// </summary>
public virtual void SendTypingMessage()
{
SBMessage sbMessage = new SBMessage();
sbMessage.Acknowledgement = "U";
MSGMessage msgMessage = new MSGMessage();
msgMessage.MimeHeader["Content-Type"] = "text/x-msmsgscontrol";
msgMessage.MimeHeader["TypingUser"] = NSMessageHandler.Owner.Mail;
sbMessage.InnerMessage = msgMessage;
// send it over the network
MessageProcessor.SendMessage(sbMessage);
}
/// <summary>
/// Send the first message to the server.
/// </summary>
/// <remarks>
/// Depending on the <see cref="Invited"/> field a ANS command (if true), or a USR command (if false) is send.
/// </remarks>
protected virtual void SendInitialMessage()
{
if(Invited)
MessageProcessor.SendMessage(new SBMessage("ANS", new string[] { NSMessageHandler.Owner.Mail, SessionHash, SessionId.ToString(System.Globalization.CultureInfo.InvariantCulture) } ));
else
MessageProcessor.SendMessage(new SBMessage("USR", new string[] { NSMessageHandler.Owner.Mail, SessionHash } ));
}
#endregion
/// <summary>
/// Handles message from the processor.
/// </summary>
/// <remarks>
/// This is one of the most important functions of the class.
/// It handles incoming messages and performs actions based on the commands in the messages.
/// Many commands will affect the data objects in DotMSN, like <see cref="Contact"/> and <see cref="ContactGroup"/>.
/// For example contacts are renamed, contactgroups are added and status is set.
/// Exceptions which occur in this method are redirected via the <see cref="ExceptionOccurred"/> event.
/// </remarks>
/// <param name="sender"></param>
/// <param name="message">The network message received from the notification server</param>
public virtual void HandleMessage(IMessageProcessor sender, NetworkMessage message)
{
try
{
// we expect at least a SBMessage object
SBMessage sbMessage = (SBMessage)message;
switch(sbMessage.Command)
{
case "ANS": { OnANSReceived(sbMessage); break; }
case "BYE": { OnBYEReceived(sbMessage); break; }
case "CAL": { OnCALReceived(sbMessage); break; }
case "IRO": { OnIROReceived(sbMessage); break; }
case "JOI": { OnJOIReceived(sbMessage); break; }
case "MSG": { OnMSGReceived(sbMessage); break; }
case "USR": { OnUSRReceived(sbMessage); break; }
default:
{
// first check whether it is a numeric error command
if(sbMessage.Command[0] >= '0' && sbMessage.Command[0] <= '9')
{
try
{
int errorCode = int.Parse(sbMessage.Command, System.Globalization.CultureInfo.InvariantCulture);
OnServerErrorReceived((MSNError)errorCode);
}
catch(FormatException e)
{
throw new DotMSNException("Exception occurred while parsing an error code received from the switchboard server", e);
}
}
// if not then it is a unknown command:
// do nothing.
break;
}
}
}
catch(Exception e)
{
// notify the client of this exception
OnExceptionOccurred(e);
throw e;
}
}
#region Message handlers
/// <summary>
/// Called when a ANS command has been received.
/// </summary>
/// <remarks>
/// Indicates that the server has replied to our identification ANS command.
/// <code>ANS [Transaction] ['OK']</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnANSReceived(SBMessage message)
{
if(message.CommandValues[1].ToString() == "OK")
{
// we are now ready to invite other contacts. Notify the client of this.
OnSessionEstablished();
}
}
/// <summary>
/// Called when a USR command has been received.
/// </summary>
/// <remarks>
/// Indicates that the server has replied to our identification USR command.
/// <code>USR [Transaction] ['OK'] [account] [name]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnUSRReceived(SBMessage message)
{
if(message.CommandValues[1].ToString() == "OK"
&& NSMessageHandler.Owner.Mail.ToLower(System.Globalization.CultureInfo.InvariantCulture) == message.CommandValues[2].ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture))
{
// update the owner's name. Just to be sure.
NSMessageHandler.Owner.SetName(message.CommandValues[3].ToString());
// we are now ready to invite other contacts. Notify the client of this.
OnSessionEstablished();
}
}
/// <summary>
/// Called when a CAL command has been received.
/// </summary>
/// <remarks>
/// Indicates that the server has replied to our request to invite a contact.
/// <code>CAL [Transaction] ['RINGING'] [sessionId]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnCALReceived(SBMessage message)
{
// this is not very interesting so do nothing at the moment
}
/// <summary>
/// Called when a JOI command has been received.
/// </summary>
/// <remarks>
/// Indicates that a remote contact has joined the session.
/// This will fire the <see cref="ContactJoined"/> event.
/// <code>JOI [account] [name]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnJOIReceived(SBMessage message)
{
// get the contact and update it's name
Contact contact = NSMessageHandler.ContactList.GetContact(message.CommandValues[0].ToString());
contact.SetName(message.CommandValues[1].ToString());
if(Contacts.Contains(contact.Mail) == false)
Contacts.Add(contact.Mail, contact);
// notify the client programmer
OnContactJoined(contact);
}
/// <summary>
/// Called when a BYE command has been received.
/// </summary>
/// <remarks>
/// Indicates that a remote contact has leaved the session.
/// This will fire the <see cref="ContactLeft"/> event. Or, if all contacts have left, the <see cref="AllContactsLeft"/> event.
/// <code>BYE [account]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnBYEReceived(SBMessage message)
{
if(Contacts.ContainsKey(message.CommandValues[0].ToString()))
{
// get the contact and update it's name
Contact contact = NSMessageHandler.ContactList.GetContact(message.CommandValues[0].ToString());
Contacts.Remove(contact.Mail);
// notify the client programmer
OnContactLeft(contact);
if(Contacts.Count == 0)
{
OnAllContactsLeft();
}
}
}
/// <summary>
/// Called when a IRO command has been received.
/// </summary>
/// <remarks>
/// Indicates that a remote contact was already present in the session that was joined.
/// <code>IRO [Transaction] [Current] [Total] [Account] [Name]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnIROReceived(SBMessage message)
{
Contact contact = NSMessageHandler.ContactList.GetContact(message.CommandValues[3].ToString());
// update the name to make sure we have it up-to-date
contact.SetName(message.CommandValues[4].ToString());
if(Contacts.Contains(contact.Mail) == false)
Contacts.Add(contact.Mail, contact);
// notify the client programmer
OnContactJoined(contact);
}
/// <summary>
/// Called when a MSG command has been received.
/// </summary>
/// <remarks>
/// Indicates that a remote contact has send us a message. This can be a plain text message, an invitation, or an application specific message.
/// <code>MSG [Account] [Name] [Bodysize]</code>
/// </remarks>
/// <param name="message"></param>
protected virtual void OnMSGReceived(MSNMessage message)
{
// the MSG command is the most versatile one. These are all the messages
// between clients. Like normal messages, file transfer invitations, P2P messages, etc.
Contact contact = NSMessageHandler.ContactList.GetContact(message.CommandValues[0].ToString());
// update the name to make sure we have it up-to-date
contact.SetName(message.CommandValues[1].ToString());
// get the corresponding SBMSGMessage object
MSGMessage sbMSGMessage = new MSGMessage(message);
switch(sbMSGMessage.MimeHeader["Content-Type"].ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture))
{
#region text/x-msmsgscontrol
case "text/x-msmsgscontrol":
{
// make sure we don't parse the rest of the message in the next loop
OnUserTyping(NSMessageHandler.ContactList.GetContact(sbMSGMessage.MimeHeader["TypingUser"].ToString()));
break;
}
#endregion
#region text/x-msmsgsinvite
case "text/x-msmsgsinvite":
{
break;
}
#endregion
#region application/x-msnmsgrp2p
case "application/x-msnmsgrp2p":
{
break;
}
#endregion
#region text/x-mms-emoticon
case "text/x-mms-emoticon":
{
OnEmoticonDefinition(sbMSGMessage, contact);
break;
}
#endregion
default:
{
#region textual messages
if(sbMSGMessage.MimeHeader["Content-Type"].ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture).IndexOf("text/plain") >= 0)
{
// a normal message has been sent, notify the client programmer
TextMessage msg = new TextMessage();
msg.CreateFromMessage(sbMSGMessage);
OnTextMessageReceived(msg, contact);
}
break;
#endregion
}
}
}
#endregion
}
}
| |
// $Id: mxICanvas2D.cs,v 1.4 2012-04-24 13:56:56 gaudenz Exp $
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace com.mxgraph
{
/// <summary>
/// Defines the requirements for a canvas that paints the vertices and
/// edges of a graph.
/// </summary>
public interface mxICanvas2D
{
/// <summary>
/// Saves the current state of the canvas.
/// </summary>
void Save();
/// <summary>
/// Restores the previous state of the canvas.
/// </summary>
void Restore();
/// <summary>
/// Uniformaly scales the canvas by the given amount.
/// </summary>
/// <param name="value">The new scale value.</param>
void Scale(double value);
/// <summary>
/// Translates the canvas by the given amount.
/// </summary>
/// <param name="dx">X-coordinate of the translation.</param>
/// <param name="dy">Y-coordinate of the translation.</param>
void Translate(double dx, double dy);
/// <summary>
/// Rotates the canvas by the given angle around the given center. This
/// method may add rendering overhead and should be used with care.
/// </summary>
/// <param name="theta">Rotation angle in degrees (0 - 360).</param>
/// <param name="flipH">Specifies if drawing should be flipped horizontally.</param>
/// <param name="flipV">Specifies if drawing should be flipped vertically.</param>
/// <param name="cx">X-coordinate of the center point.</param>
/// <param name="cy">Y-coordinate of the center point.</param>
void Rotate(double theta, bool flipH, bool flipV, double cx, double cy);
/// <summary>
/// Sets the stroke width. This should default to 1 if unset.
/// </summary>
double StrokeWidth
{
set;
}
/// <summary>
/// Sets the stroke color. This should default to mxConstants.NONE if unset.
/// </summary>
string StrokeColor
{
set;
}
/// <summary>
/// Sets the dashed state. This should default to false if unset.
/// </summary>
bool Dashed
{
set;
}
/// <summary>
/// Sets the dash pattern. This should default to "3 3" if unset.
/// </summary>
string DashPattern
{
set;
}
/// <summary>
/// Sets the linecap. This should default to "flat" if unset.
/// </summary>
string LineCap
{
set;
}
/// <summary>
/// Sets the linejoin. This should default to "miter" if unset.
/// </summary>
string LineJoin
{
set;
}
/// <summary>
/// Sets the miterlimit. This should default to 10 if unset.
/// </summary>
double MiterLimit
{
set;
}
/// <summary>
/// Default value mxConstants.DEFAULT_FONTSIZE.
/// </summary>
double FontSize
{
set;
}
/// <summary>
/// Default value "#000000".
/// </summary>
string FontColor
{
set;
}
/// <summary>
/// Default value {@link mxConstants#DEFAULT_FONTFAMILY}.
/// </summary>
string FontFamily
{
set;
}
/// <summary>
/// Default value 0. See {@link mxConstants#STYLE_FONTSTYLE}.
/// </summary>
int FontStyle
{
set;
}
/// <summary>
/// Default value 1. This method may add rendering overhead and should be
/// used with care.
/// </summary>
double Alpha
{
set;
}
/// <summary>
/// Default value {@link mxConstants#NONE}.
/// </summary>
string FillColor
{
set;
}
/// <summary>
/// Prepares the canvas to draw a gradient.
/// </summary>
void SetGradient(string color1, string color2, double x, double y,
double w, double h, string direction);
/// <summary>
/// Prepares the canvas to draw a glass gradient.
/// </summary>
void SetGlassGradient(double x, double y, double w, double h);
/// <summary>
/// Next fill or stroke should draw a rectangle.
/// </summary>
void Rect(double x, double y, double w, double h);
/// <summary>
/// Next fill or stroke should draw a round rectangle.
/// </summary>
void Roundrect(double x, double y, double w, double h, double dx, double dy);
/// <summary>
/// Next fill or stroke should draw an ellipse.
/// </summary>
void Ellipse(double x, double y, double w, double h);
/// <summary>
/// Draws the given image.
/// </summary>
void Image(double x, double y, double w, double h, string src,
bool aspect, bool flipH, bool flipV);
/// <summary>
/// Draws the given string. Possible values for format are empty string for
// plain text and html for HTML markup.
/// </summary>
void Text(double x, double y, double w, double h, string str, string align,
string valign, bool vertical, bool wrap, string format);
/// <summary>
/// Begins a new path.
/// </summary>
void Begin();
/// <summary>
/// Moves to the given path.
/// </summary>
void MoveTo(double x, double y);
/// <summary>
/// Draws a line to the given path.
/// </summary>
void LineTo(double x, double y);
/// <summary>
/// Draws a quadratic curve to the given point.
/// </summary>
void QuadTo(double x1, double y1, double x2, double y2);
/// <summary>
/// Draws a bezier curve to the given point.
/// </summary>
void CurveTo(double x1, double y1, double x2, double y2, double x3,
double y3);
/// <summary>
/// Closes the current path.
/// </summary>
void Close();
/// <summary>
/// Paints the outline of the current path.
/// </summary>
void Stroke();
/// <summary>
/// Fills the current path.
/// </summary>
void Fill();
/// <summary>
/// Fills and paints the outline of the current path.
/// </summary>
void FillAndStroke();
/// <summary>
/// Paints the current path as a shadow.
/// </summary>
void Shadow(string value, bool filled);
/// <summary>
/// Uses the current path for clipping.
/// </summary>
void Clip();
}
}
| |
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 ECalibrationProcedure : IEntity
{
public static event EventHandler<EntityChangedEventArgs> Changed;
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));
}
// 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? ClpDBid;
private string ClpName;
private string ClpDescription;
private bool ClpIsLclChg;
private bool ClpIsActive;
// Textbox limits
public static int ClpNameCharLimit = 50;
public static int ClpDescriptionCharLimit = 255;
// Field-specific error message strings (normally just needed for textbox data)
private string ClpNameErrMsg;
private string ClpDescriptionErrMsg;
// Form level validation message
private string ClpErrMsg;
//--------------------------------------------------------
// Field Properties
//--------------------------------------------------------
// Primary key accessor
public Guid? ID
{
get { return ClpDBid; }
}
public string CalibrationProcedureName
{
get { return ClpName; }
set { ClpName = Util.NullifyEmpty(value); }
}
public string CalibrationProcedureDescription
{
get { return ClpDescription; }
set { ClpDescription = Util.NullifyEmpty(value); }
}
public bool CalibrationProcedureIsLclChg
{
get { return ClpIsLclChg; }
set { ClpIsLclChg = value; }
}
public bool CalibrationProcedureIsActive
{
get { return ClpIsActive; }
set { ClpIsActive = 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 CalibrationProcedureNameErrMsg
{
get { return ClpNameErrMsg; }
}
public string CalibrationProcedureDescriptionErrMsg
{
get { return ClpDescriptionErrMsg; }
}
//--------------------------------------
// Form level Error Message
//--------------------------------------
public string CalibrationProcedureErrMsg
{
get { return ClpErrMsg; }
set { ClpErrMsg = Util.NullifyEmpty(value); }
}
//--------------------------------------
// Textbox Name Length Validation
//--------------------------------------
public bool CalibrationProcedureNameLengthOk(string s)
{
if (s == null) return true;
if (s.Length > ClpNameCharLimit)
{
ClpNameErrMsg = string.Format("Calibration Procedure Names cannot exceed {0} characters", ClpNameCharLimit);
return false;
}
else
{
ClpNameErrMsg = null;
return true;
}
}
public bool CalibrationProcedureDescriptionLengthOk(string s)
{
if (s == null) return true;
if (s.Length > ClpDescriptionCharLimit)
{
ClpDescriptionErrMsg = string.Format("Calibration Procedure Descriptions cannot exceed {0} characters", ClpDescriptionCharLimit);
return false;
}
else
{
ClpDescriptionErrMsg = null;
return true;
}
}
//--------------------------------------
// Field-Specific Validation
// sets and clears error messages
//--------------------------------------
public bool CalibrationProcedureNameValid(string name)
{
bool existingIsInactive;
if (!CalibrationProcedureNameLengthOk(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, ClpDBid, out existingIsInactive))
{
ClpNameErrMsg = existingIsInactive ?
"That Calibration Procedure Name exists but its status has been set to inactive." :
"That Calibration Procedure Name is already in use.";
return false;
}
ClpNameErrMsg = null;
return true;
}
public bool CalibrationProcedureDescriptionValid(string value)
{
if (!CalibrationProcedureDescriptionLengthOk(value)) return false;
ClpDescriptionErrMsg = null;
return true;
}
//--------------------------------------
// Constructors
//--------------------------------------
// Default constructor. Field defaults must be set here.
// Any defaults set by the database will be overridden.
public ECalibrationProcedure()
{
this.ClpIsLclChg = false;
this.ClpIsActive = 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 ECalibrationProcedure(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
ClpDBid,
ClpName,
ClpDescription,
ClpIsLclChg,
ClpIsActive
from CalibrationProcedures
where ClpDBid = @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
ClpDBid = (Guid?)dr[0];
ClpName = (string)dr[1];
ClpDescription = (string)Util.NullForDbNull(dr[2]);
ClpIsLclChg = (bool)dr[3];
ClpIsActive = (bool)dr[4];
}
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) ClpIsLclChg = true;
// first ask the database for a new Guid
cmd.CommandText = "Select Newid()";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
ClpDBid = (Guid?)(cmd.ExecuteScalar());
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", ClpDBid),
new SqlCeParameter("@p1", ClpName),
new SqlCeParameter("@p2", Util.DbNullForNull(ClpDescription)),
new SqlCeParameter("@p3", ClpIsLclChg),
new SqlCeParameter("@p4", ClpIsActive)
});
cmd.CommandText = @"Insert Into CalibrationProcedures (
ClpDBid,
ClpName,
ClpDescription,
ClpIsLclChg,
ClpIsActive
) values (@p0,@p1,@p2,@p3,@p4)";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert Calibration Procedure row");
}
}
else
{
// we are updating an existing record
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", ClpDBid),
new SqlCeParameter("@p1", ClpName),
new SqlCeParameter("@p2", Util.DbNullForNull(ClpDescription)),
new SqlCeParameter("@p3", ClpIsLclChg),
new SqlCeParameter("@p4", ClpIsActive)});
cmd.CommandText =
@"Update CalibrationProcedures
set
ClpName = @p1,
ClpDescription = @p2,
ClpIsLclChg = @p3,
ClpIsActive = @p4
Where ClpDBid = @p0";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to update calibration procedure 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 (!CalibrationProcedureNameValid(CalibrationProcedureName)) return false;
if (!CalibrationProcedureDescriptionValid(CalibrationProcedureDescription)) 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 (ClpDBid == null)
{
CalibrationProcedureErrMsg = "Unable to delete. Record not found.";
return false;
}
if (!ClpIsLclChg && !Globals.IsMasterDB)
{
CalibrationProcedureErrMsg = "Unable to delete because this Calibration Procedure was not added during this outage.\r\nYou may wish to inactivate it instead.";
return false;
}
if (HasSites())
{
CalibrationProcedureErrMsg = "Unable to delete because this Calibration Procedure is the default for one or more sites.";
return false;
}
if (HasOutages())
{
CalibrationProcedureErrMsg = "Unable to delete because this Calibration 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 CalibrationProcedures
where ClpDBid = @p0";
cmd.Parameters.Add("@p0", ClpDBid);
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)
{
CalibrationProcedureErrMsg = "Unable to delete. Please try again later.";
return false;
}
else
{
OnChanged(ID);
return true;
}
}
else
{
CalibrationProcedureErrMsg = null;
return false;
}
}
private bool HasSites()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select SitDBid from Sites
where SitClpID = @p0";
cmd.Parameters.Add("@p0", ClpDBid);
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 OtgDBid from Outages
where OtgClpID = @p0";
cmd.Parameters.Add("@p0", ClpDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
return result != null;
}
//--------------------------------------------------------------------
// Static listing methods which return collections of calibrationprocedures
//--------------------------------------------------------------------
// 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 ECalibrationProcedureCollection ListByName(
bool showactive, bool showinactive, bool addNoSelection)
{
ECalibrationProcedure calibrationprocedure;
ECalibrationProcedureCollection calibrationprocedures = new ECalibrationProcedureCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
ClpDBid,
ClpName,
ClpDescription,
ClpIsLclChg,
ClpIsActive
from CalibrationProcedures";
if (showactive && !showinactive)
qry += " where ClpIsActive = 1";
else if (!showactive && showinactive)
qry += " where ClpIsActive = 0";
qry += " order by ClpName";
cmd.CommandText = qry;
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
calibrationprocedure = new ECalibrationProcedure();
calibrationprocedure.ClpName = "<No Selection>";
calibrationprocedures.Add(calibrationprocedure);
}
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())
{
calibrationprocedure = new ECalibrationProcedure((Guid?)dr[0]);
calibrationprocedure.ClpName = (string)(dr[1]);
calibrationprocedure.ClpDescription = (string)Util.NullForDbNull(dr[2]);
calibrationprocedure.ClpIsLclChg = (bool)(dr[3]);
calibrationprocedure.ClpIsActive = (bool)(dr[4]);
calibrationprocedures.Add(calibrationprocedure);
}
// Finish up
dr.Close();
return calibrationprocedures;
}
// 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.
public static DataView GetDefaultDataView()
{
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
ClpDBid as ID,
ClpName as CalibrationProcedureName,
ClpDescription as CalibrationProcedureDescription,
CASE
WHEN ClpIsLclChg = 0 THEN 'No'
ELSE 'Yes'
END as CalibrationProcedureIsLclChg,
CASE
WHEN ClpIsActive = 0 THEN 'No'
ELSE 'Yes'
END as CalibrationProcedureIsActive
from CalibrationProcedures";
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 ClpIsActive from CalibrationProcedures where ClpName = @p1";
}
else
{
cmd.CommandText = "Select ClpIsActive from CalibrationProcedures where ClpName = @p1 and ClpDBid != @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 (CalibrationProcedureName == null)
{
ClpNameErrMsg = "A unique Calibration Procedure Name is required";
allFilled = false;
}
else
{
ClpNameErrMsg = null;
}
return allFilled;
}
}
//--------------------------------------
// CalibrationProcedure Collection class
//--------------------------------------
public class ECalibrationProcedureCollection : CollectionBase
{
//this event is fired when the collection's items have changed
public event EventHandler Changed;
//this is the constructor of the collection.
public ECalibrationProcedureCollection()
{ }
//the indexer of the collection
public ECalibrationProcedure this[int index]
{
get
{
return (ECalibrationProcedure)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 (ECalibrationProcedure calibrationprocedure in InnerList)
{
if (calibrationprocedure.ID == ID)
return true;
}
return false;
}
//returns the index of an item in the collection
public int IndexOf(ECalibrationProcedure item)
{
return InnerList.IndexOf(item);
}
//adds an item to the collection
public void Add(ECalibrationProcedure item)
{
this.List.Add(item);
OnChanged(EventArgs.Empty);
}
//inserts an item in the collection at a specified index
public void Insert(int index, ECalibrationProcedure item)
{
this.List.Insert(index, item);
OnChanged(EventArgs.Empty);
}
//removes an item from the collection.
public void Remove(ECalibrationProcedure 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.
using System;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
namespace System.Xml
{
// Represents an attribute of the XMLElement object. Valid and default
// values for the attribute are defined in a DTD or schema.
public class XmlAttribute : XmlNode
{
private XmlName _name;
private XmlLinkedNode _lastChild;
internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc)
{
Debug.Assert(name != null);
Debug.Assert(doc != null);
this.parentNode = null;
if (!doc.IsLoading)
{
XmlDocument.CheckName(name.Prefix);
XmlDocument.CheckName(name.LocalName);
}
if (name.LocalName.Length == 0)
throw new ArgumentException(SR.Xdom_Attr_Name);
_name = name;
}
internal int LocalNameHash
{
get { return _name.HashCode; }
}
protected internal XmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc)
: this(doc.AddAttrXmlName(prefix, localName, namespaceURI, null), doc)
{
}
internal XmlName XmlName
{
get { return _name; }
set { _name = value; }
}
// Creates a duplicate of this node.
public override XmlNode CloneNode(bool deep)
{
// CloneNode for attributes is deep irrespective of parameter 'deep' value
Debug.Assert(OwnerDocument != null);
XmlDocument doc = OwnerDocument;
XmlAttribute attr = doc.CreateAttribute(Prefix, LocalName, NamespaceURI);
attr.CopyChildren(doc, this, true);
return attr;
}
// Gets the parent of this node (for nodes that can have parents).
public override XmlNode ParentNode
{
get { return null; }
}
// Gets the name of the node.
public override String Name
{
get { return _name.Name; }
}
// Gets the name of the node without the namespace prefix.
public override String LocalName
{
get { return _name.LocalName; }
}
// Gets the namespace URI of this node.
public override String NamespaceURI
{
get { return _name.NamespaceURI; }
}
// Gets or sets the namespace prefix of this node.
public override String Prefix
{
get { return _name.Prefix; }
set { _name = _name.OwnerDocument.AddAttrXmlName(value, LocalName, NamespaceURI, SchemaInfo); }
}
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return XmlNodeType.Attribute; }
}
// Gets the XmlDocument that contains this node.
public override XmlDocument OwnerDocument
{
get
{
return _name.OwnerDocument;
}
}
// Gets or sets the value of the node.
public override String Value
{
get { return InnerText; }
set { InnerText = value; } //use InnerText which has perf optimization
}
public override IXmlSchemaInfo SchemaInfo
{
get
{
return _name;
}
}
public override String InnerText
{
set
{
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = base.InnerText;
base.InnerText = value;
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
base.InnerText = value;
}
}
}
internal bool PrepareOwnerElementInElementIdAttrMap()
{
XmlDocument ownerDocument = OwnerDocument;
if (ownerDocument.DtdSchemaInfo != null)
{ // DTD exists
XmlElement ownerElement = OwnerElement;
if (ownerElement != null)
{
return ownerElement.Attributes.PrepareParentInElementIdAttrMap(Prefix, LocalName);
}
}
return false;
}
internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText)
{
XmlElement ownerElement = OwnerElement;
if (ownerElement != null)
{
ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText);
}
}
internal override bool IsContainer
{
get { return true; }
}
//the function is provided only at Load time to speed up Load process
internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (_lastChild == null)
{ // if LastNode == null
newNode.next = newNode;
_lastChild = newNode;
newNode.SetParentForLoad(this);
}
else
{
XmlLinkedNode refNode = _lastChild; // refNode = LastNode;
newNode.next = refNode.next;
refNode.next = newNode;
_lastChild = newNode; // LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal override XmlLinkedNode LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
}
internal override bool IsValidChildType(XmlNodeType type)
{
return (type == XmlNodeType.Text) || (type == XmlNodeType.EntityReference);
}
// Gets a value indicating whether the value was explicitly set.
public virtual bool Specified
{
get { return true; }
}
public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.InsertBefore(newChild, refChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.InsertBefore(newChild, refChild);
}
return node;
}
public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.InsertAfter(newChild, refChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.InsertAfter(newChild, refChild);
}
return node;
}
public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.ReplaceChild(newChild, oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.ReplaceChild(newChild, oldChild);
}
return node;
}
public override XmlNode RemoveChild(XmlNode oldChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.RemoveChild(oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.RemoveChild(oldChild);
}
return node;
}
public override XmlNode PrependChild(XmlNode newChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.PrependChild(newChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.PrependChild(newChild);
}
return node;
}
public override XmlNode AppendChild(XmlNode newChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.AppendChild(newChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.AppendChild(newChild);
}
return node;
}
// DOM Level 2
// Gets the XmlElement node that contains this attribute.
public virtual XmlElement OwnerElement
{
get
{
return parentNode as XmlElement;
}
}
// Gets or sets the markup representing just the children of this node.
public override string InnerXml
{
set
{
RemoveAll();
XmlLoader loader = new XmlLoader();
loader.LoadInnerXmlAttribute(this, value);
}
}
// Saves the node to the specified XmlWriter.
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
// Saves all the children of the node to the specified XmlWriter.
public override void WriteContentTo(XmlWriter w)
{
for (XmlNode node = FirstChild; node != null; node = node.NextSibling)
{
node.WriteTo(w);
}
}
public override String BaseURI
{
get
{
if (OwnerElement != null)
return OwnerElement.BaseURI;
return String.Empty;
}
}
internal override void SetParent(XmlNode node)
{
this.parentNode = node;
}
internal override XmlSpace XmlSpace
{
get
{
if (OwnerElement != null)
return OwnerElement.XmlSpace;
return XmlSpace.None;
}
}
internal override String XmlLang
{
get
{
if (OwnerElement != null)
return OwnerElement.XmlLang;
return String.Empty;
}
}
internal override XPathNodeType XPNodeType
{
get
{
if (IsNamespace)
{
return XPathNodeType.Namespace;
}
return XPathNodeType.Attribute;
}
}
internal override string XPLocalName
{
get
{
if (_name.Prefix.Length == 0 && _name.LocalName == "xmlns") return string.Empty;
return _name.LocalName;
}
}
internal bool IsNamespace
{
get
{
return Ref.Equal(_name.NamespaceURI, _name.OwnerDocument.strReservedXmlns);
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the MamIndicadorT class.
/// </summary>
[Serializable]
public partial class MamIndicadorTCollection : ActiveList<MamIndicadorT, MamIndicadorTCollection>
{
public MamIndicadorTCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>MamIndicadorTCollection</returns>
public MamIndicadorTCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
MamIndicadorT o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the MAM_IndicadorT table.
/// </summary>
[Serializable]
public partial class MamIndicadorT : ActiveRecord<MamIndicadorT>, IActiveRecord
{
#region .ctors and Default Settings
public MamIndicadorT()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MamIndicadorT(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MamIndicadorT(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MamIndicadorT(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("MAM_IndicadorT", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdIndicadorT = new TableSchema.TableColumn(schema);
colvarIdIndicadorT.ColumnName = "idIndicadorT";
colvarIdIndicadorT.DataType = DbType.Int32;
colvarIdIndicadorT.MaxLength = 0;
colvarIdIndicadorT.AutoIncrement = true;
colvarIdIndicadorT.IsNullable = false;
colvarIdIndicadorT.IsPrimaryKey = true;
colvarIdIndicadorT.IsForeignKey = false;
colvarIdIndicadorT.IsReadOnly = false;
colvarIdIndicadorT.DefaultSetting = @"";
colvarIdIndicadorT.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdIndicadorT);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = 100;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"('')";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("MAM_IndicadorT",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdIndicadorT")]
[Bindable(true)]
public int IdIndicadorT
{
get { return GetColumnValue<int>(Columns.IdIndicadorT); }
set { SetColumnValue(Columns.IdIndicadorT, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
MamIndicadorT item = new MamIndicadorT();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdIndicadorT,string varDescripcion)
{
MamIndicadorT item = new MamIndicadorT();
item.IdIndicadorT = varIdIndicadorT;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdIndicadorTColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdIndicadorT = @"idIndicadorT";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Code;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Code.Native;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single method in a type definition of a .NET module.
/// </summary>
public class MethodDefinition :
MetadataMember,
IMemberDefinition,
IOwnedCollectionElement<TypeDefinition>,
IMemberRefParent,
ICustomAttributeType,
IHasGenericParameters,
IMemberForwarded,
IHasSecurityDeclaration,
IManagedEntrypoint
{
private readonly LazyVariable<string?> _name;
private readonly LazyVariable<TypeDefinition?> _declaringType;
private readonly LazyVariable<MethodSignature?> _signature;
private readonly LazyVariable<MethodBody?> _methodBody;
private readonly LazyVariable<ImplementationMap?> _implementationMap;
private readonly LazyVariable<MethodSemantics?> _semantics;
private readonly LazyVariable<UnmanagedExportInfo?> _exportInfo;
private IList<ParameterDefinition>? _parameterDefinitions;
private ParameterCollection? _parameters;
private IList<CustomAttribute>? _customAttributes;
private IList<SecurityDeclaration>? _securityDeclarations;
private IList<GenericParameter>? _genericParameters;
/// <summary>
/// Initializes a new method definition.
/// </summary>
/// <param name="token">The token of the method</param>
protected MethodDefinition(MetadataToken token)
: base(token)
{
_name =new LazyVariable<string?>(GetName);
_declaringType = new LazyVariable<TypeDefinition?>(GetDeclaringType);
_signature = new LazyVariable<MethodSignature?>(GetSignature);
_methodBody = new LazyVariable<MethodBody?>(GetBody);
_implementationMap = new LazyVariable<ImplementationMap?>(GetImplementationMap);
_semantics = new LazyVariable<MethodSemantics?>(GetSemantics);
_exportInfo = new LazyVariable<UnmanagedExportInfo?>(GetExportInfo);
}
/// <summary>
/// Creates a new method definition.
/// </summary>
/// <param name="name">The name of the method.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="signature">The signature of the method</param>
/// <remarks>
/// For a valid .NET image, if <see cref="CallingConventionSignature.HasThis"/> of the signature referenced by
/// <paramref name="signature"/> is set, the <see cref="MethodAttributes.Static"/> bit should be unset in
/// <paramref name="attributes"/> and vice versa.
/// </remarks>
public MethodDefinition(string? name, MethodAttributes attributes, MethodSignature? signature)
: this(new MetadataToken(TableIndex.Method, 0))
{
Name = name;
Attributes = attributes;
Signature = signature;
}
/// <summary>
/// Gets or sets the name of the method definition.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the method definition table.
/// </remarks>
public Utf8String? Name
{
get => _name.Value;
set => _name.Value = value;
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the signature of the method This includes the return type, as well as the types of the
/// parameters that this method defines.
/// </summary>
public MethodSignature? Signature
{
get => _signature.Value;
set => _signature.Value = value;
}
/// <inheritdoc />
public string FullName => FullNameGenerator.GetMethodFullName(Name, DeclaringType, Signature);
/// <summary>
/// Gets or sets the attributes associated to the method.
/// </summary>
public MethodAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the method is compiler controlled and cannot be referenced directly.
/// </summary>
public bool IsCompilerControlled
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.CompilerControlled;
set => Attributes = value ? Attributes & ~MethodAttributes.MemberAccessMask : Attributes;
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same enclosing type.
/// </summary>
public bool IsPrivate
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Private : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked family and assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, within the same assembly.
/// </summary>
public bool IsFamilyAndAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamilyAndAssembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.FamilyAndAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same assembly.
/// </summary>
public bool IsAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Assembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same enclosing type, as well as any derived type.
/// </summary>
public bool IsFamily
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Family : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked family or assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, or within the same assembly.
/// </summary>
public bool IsFamilyOrAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamilyOrAssembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.FamilyOrAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked public, and can be accessed by
/// any member having access to the enclosing type.
/// </summary>
public bool IsPublic
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Public : 0);
}
/// <summary>
/// Gets or sets a value indicating the managed method is exported by a thunk to unmanaged code.
/// </summary>
public bool IsUnmanagedExport
{
get => (Attributes & MethodAttributes.UnmanagedExport) != 0;
set => Attributes = (Attributes & ~MethodAttributes.UnmanagedExport)
| (value ? MethodAttributes.UnmanagedExport : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method requires an object instance to access it.
/// </summary>
/// <remarks>
/// This property does not reflect the value of <see cref="CallingConventionSignature.HasThis"/>, nor will it
/// change the value of <see cref="CallingConventionSignature.HasThis"/> if this property is changed. For a
/// valid .NET image, these values should match, however.
/// </remarks>
public bool IsStatic
{
get => (Attributes & MethodAttributes.Static) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Static)
| (value ? MethodAttributes.Static : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked final and cannot be overridden by a derived
/// class.
/// </summary>
public bool IsFinal
{
get => (Attributes & MethodAttributes.Final) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Final)
| (value ? MethodAttributes.Final : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is virtual.
/// </summary>
public bool IsVirtual
{
get => (Attributes & MethodAttributes.Virtual) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Virtual)
| (value ? MethodAttributes.Virtual : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is distinguished by both its name and signature.
/// </summary>
public bool IsHideBySig
{
get => (Attributes & MethodAttributes.HideBySig) != 0;
set => Attributes = (Attributes & ~MethodAttributes.HideBySig)
| (value ? MethodAttributes.HideBySig : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the runtime should reuse an existing slot in the VTable of the
/// enclosing class for this method.
/// </summary>
public bool IsReuseSlot
{
get => (Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.ReuseSlot;
set => Attributes = value ? Attributes & ~MethodAttributes.VtableLayoutMask : Attributes;
}
/// <summary>
/// Gets or sets a value indicating whether the runtime allocate a new slot in the VTable of the
/// enclosing class for this method.
/// </summary>
public bool IsNewSlot
{
get => (Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot;
set => Attributes = (Attributes & ~MethodAttributes.VtableLayoutMask)
| (value ? MethodAttributes.NewSlot : 0);
}
/// <summary>
/// Gets or sets a value indicating the method can only be overridden if it is also accessible.
/// </summary>
public bool CheckAccessOnOverride
{
get => (Attributes & MethodAttributes.CheckAccessOnOverride) != 0;
set => Attributes = (Attributes & ~MethodAttributes.CheckAccessOnOverride)
| (value ? MethodAttributes.CheckAccessOnOverride : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is marked abstract, and should be overridden by a derived class.
/// </summary>
/// <remarks>
/// Methods with this flag set should not have a method body assigned for a valid .NET executable. However,
/// updating this flag will not remove the body of this method, nor does the existence of the method body reflect
/// the value of this property.
/// </remarks>
public bool IsAbstract
{
get => (Attributes & MethodAttributes.Abstract) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Abstract)
| (value ? MethodAttributes.Abstract : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is given a special name.
/// </summary>
public bool IsSpecialName
{
get => (Attributes & MethodAttributes.SpecialName) != 0;
set => Attributes = (Attributes & ~MethodAttributes.SpecialName)
| (value ? MethodAttributes.SpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is given a special name that is used by the runtime.
/// </summary>
public bool IsRuntimeSpecialName
{
get => (Attributes & MethodAttributes.RuntimeSpecialName) != 0;
set => Attributes = (Attributes & ~MethodAttributes.RuntimeSpecialName)
| (value ? MethodAttributes.RuntimeSpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the method contains Platform Invoke information.
/// </summary>
/// <remarks>
/// Methods containing Platform Invoke information should have this flag set. This property does not
/// update automatically however when P/Invoke information is assigned to this method, nor does it reflect
/// the existence of P/Invoke information.
/// </remarks>
public bool IsPInvokeImpl
{
get => (Attributes & MethodAttributes.PInvokeImpl) != 0;
set => Attributes = (Attributes & ~MethodAttributes.PInvokeImpl)
| (value ? MethodAttributes.PInvokeImpl : 0);
}
/// <summary>
/// Gets or sets a value indicating the method has security attributes assigned to it.
/// </summary>
/// <remarks>
/// Methods containing security attributes should have this flag set. This property does not automatically
/// however when attributes are added or removed from this method, nor does it reflect the existence of
/// attributes.
/// </remarks>
public bool HasSecurity
{
get => (Attributes & MethodAttributes.HasSecurity) != 0;
set => Attributes = (Attributes & ~MethodAttributes.HasSecurity)
| (value ? MethodAttributes.HasSecurity : 0);
}
/// <summary>
/// Gets or sets a value indicating themethod calls another method containing security code.
/// </summary>
public bool RequireSecObject
{
get => (Attributes & MethodAttributes.RequireSecObject) != 0;
set => Attributes = (Attributes & ~MethodAttributes.RequireSecObject)
| (value ? MethodAttributes.RequireSecObject : 0);
}
/// <summary>
/// Gets or sets the attributes that describe the implementation of the method body.
/// </summary>
public MethodImplAttributes ImplAttributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using the Common Intermediate Language (CIL).
/// </summary>
public bool IsIL
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL;
set => ImplAttributes = value ? ImplAttributes & ~MethodImplAttributes.CodeTypeMask : ImplAttributes;
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using the Common Intermediate Language (CIL).
/// </summary>
public bool IsNative
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Native;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.Native : 0);
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using OPTIL.
/// </summary>
public bool IsOPTIL
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.OPTIL;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.OPTIL : 0);
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented by the runtime.
/// </summary>
public bool IsRuntime
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Runtime;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.Runtime : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method body is managed by the runtime.
/// </summary>
public bool Managed
{
get => (ImplAttributes & MethodImplAttributes.ManagedMask) == MethodImplAttributes.Managed;
set => ImplAttributes = value ? ImplAttributes & ~MethodImplAttributes.ManagedMask : ImplAttributes;
}
/// <summary>
/// Gets or sets a value indicating whether the method body is not managed by the runtime.
/// </summary>
public bool Unmanaged
{
get => (ImplAttributes & MethodImplAttributes.ManagedMask) == MethodImplAttributes.Unmanaged;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.ManagedMask)
| (value ? MethodImplAttributes.Unmanaged : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method body is forwarded.
/// </summary>
public bool IsForwardReference
{
get => (ImplAttributes & MethodImplAttributes.ForwardRef) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.ForwardRef)
| (value ? MethodImplAttributes.ForwardRef : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the runtime should not optimize the code upon generating native code.
/// </summary>
public bool IsNoOptimization
{
get => (ImplAttributes & MethodImplAttributes.NoOptimization) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.NoOptimization)
| (value ? MethodImplAttributes.NoOptimization : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method's signature is not to be mangled to do HRESULT conversion.
/// </summary>
public bool PreserveSignature
{
get => (ImplAttributes & MethodImplAttributes.PreserveSig) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.PreserveSig)
| (value ? MethodImplAttributes.PreserveSig : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is an internal call into the runtime.
/// </summary>
public bool IsInternalCall
{
get => (ImplAttributes & MethodImplAttributes.InternalCall) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.InternalCall)
| (value ? MethodImplAttributes.InternalCall : 0);
}
/// <summary>
/// Gets or sets a value indicating only one thread can run the method at once.
/// </summary>
public bool IsSynchronized
{
get => (ImplAttributes & MethodImplAttributes.Synchronized) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.Synchronized)
| (value ? MethodImplAttributes.Synchronized : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method can be inlined by the runtime or not.
/// </summary>
public bool NoInlining
{
get => (ImplAttributes & MethodImplAttributes.NoInlining) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.NoInlining)
| (value ? MethodImplAttributes.NoInlining : 0);
}
/// <inheritdoc />
public virtual ModuleDefinition? Module => DeclaringType?.Module;
/// <summary>
/// Gets the type that defines the method.
/// </summary>
public TypeDefinition? DeclaringType
{
get => _declaringType.Value;
set => _declaringType.Value = value;
}
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
ITypeDefOrRef? IMethodDefOrRef.DeclaringType => DeclaringType;
TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
{
get => DeclaringType;
set => DeclaringType = value;
}
/// <summary>
/// Gets a collection of parameter definitions that this method defines.
/// </summary>
/// <remarks>
/// This property might not reflect the list of actual parameters that the method defines and uses according
/// to the method signature. This property only reflects the list that is inferred from the ParamList column
/// in the metadata row. For the actual list of parameters, use the <see cref="Parameters"/> property instead.
/// </remarks>
public IList<ParameterDefinition> ParameterDefinitions
{
get
{
if (_parameterDefinitions is null)
Interlocked.CompareExchange(ref _parameterDefinitions, GetParameterDefinitions(), null);
return _parameterDefinitions;
}
}
/// <summary>
/// Gets a collection of parameters that the method signature defines.
/// </summary>
public ParameterCollection Parameters
{
get
{
if (_parameters is null)
Interlocked.CompareExchange(ref _parameters, new ParameterCollection(this), null);
return _parameters;
}
}
/// <summary>
/// Gets a value indicating whether the method is implemented using a method body. That is, whether the
/// <see cref="MethodBody"/> property is not <c>null</c>.
/// </summary>
[MemberNotNullWhen(true, nameof(MethodBody))]
public bool HasMethodBody => MethodBody is not null;
/// <summary>
/// Gets or sets the body of the method.
/// </summary>
/// <remarks>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public MethodBody? MethodBody
{
get => _methodBody.Value;
set => _methodBody.Value = value;
}
/// <summary>
/// Gets or sets the managed CIL body of the method if available.
/// </summary>
/// <remarks>
/// <para>
/// If this property is set to <c>null</c>, it does not necessarily mean the method does not have a method body.
/// There could be an unmanaged method body assigned instead. See the <see cref="MethodBody"/> or
/// <see cref="HasMethodBody"/> properties instead.
/// </para>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public CilMethodBody? CilMethodBody
{
get => MethodBody as CilMethodBody;
set => MethodBody = value;
}
/// <summary>
/// Gets or sets the unmanaged native body of the method if available.
/// </summary>
/// <remarks>
/// <para>
/// If this property is set to <c>null</c>, it does not necessarily mean the method does not have a method body.
/// There could be a managed body assigned instead, or the current method body reader that the declaring module
/// uses does not support reading a certain type of native method body. See the <see cref="MethodBody"/> or
/// <see cref="HasMethodBody"/> properties instead.
/// </para>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public NativeMethodBody? NativeMethodBody
{
get => MethodBody as NativeMethodBody;
set => MethodBody = value;
}
/// <inheritdoc />
public ImplementationMap? ImplementationMap
{
get => _implementationMap.Value;
set
{
if (value?.MemberForwarded is {})
throw new ArgumentException("Cannot add an implementation map that was already added to another member.");
if (_implementationMap.Value is {})
_implementationMap.Value.MemberForwarded = null;
_implementationMap.Value = value;
if (value is {})
value.MemberForwarded = this;
}
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public IList<SecurityDeclaration> SecurityDeclarations
{
get
{
if (_securityDeclarations is null)
Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null);
return _securityDeclarations;
}
}
/// <inheritdoc />
public IList<GenericParameter> GenericParameters
{
get
{
if (_genericParameters is null)
Interlocked.CompareExchange(ref _genericParameters, GetGenericParameters(), null);
return _genericParameters;
}
}
/// <summary>
/// Gets the semantics associated to this method (if available).
/// </summary>
public MethodSemantics? Semantics
{
get => _semantics.Value;
set => _semantics.Value = value;
}
/// <summary>
/// Gets a value indicating whether the method is a get method for a property.
/// </summary>
public bool IsGetMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Getter) != 0;
/// <summary>
/// Gets a value indicating whether the method is a set method for a property.
/// </summary>
public bool IsSetMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Setter) != 0;
/// <summary>
/// Gets a value indicating whether the method is an add method for an event.
/// </summary>
public bool IsAddMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.AddOn) != 0;
/// <summary>
/// Gets a value indicating whether the method is a remove method for an event.
/// </summary>
public bool IsRemoveMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.RemoveOn) != 0;
/// <summary>
/// Gets a value indicating whether the method is a fire method for an event.
/// </summary>
public bool IsFireMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Fire) != 0;
/// <summary>
/// Gets a value indicating whether the method is a (class) constructor.
/// </summary>
public bool IsConstructor => IsSpecialName && IsRuntimeSpecialName && Name?.Value is ".cctor" or ".ctor";
/// <summary>
/// Gets or sets the unmanaged export info assigned to this method (if available). This can be used to indicate
/// that a method needs to be exported in the final PE file as an unmanaged symbol.
/// </summary>
public UnmanagedExportInfo? ExportInfo
{
get => _exportInfo.Value;
set => _exportInfo.Value = value;
}
MethodDefinition IMethodDescriptor.Resolve() => this;
IMemberDefinition IMemberDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsAccessibleFromType(TypeDefinition type)
{
if (DeclaringType is not { } declaringType || !declaringType.IsAccessibleFromType(type))
return false;
var comparer = new SignatureComparer();
bool isInSameAssembly = comparer.Equals(declaringType.Module, type.Module);
return IsPublic
|| isInSameAssembly && IsAssembly
|| comparer.Equals(DeclaringType, type);
// TODO: check if in the same family of declaring types.
}
/// <summary>
/// Obtains the name of the method definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual string? GetName() => null;
/// <summary>
/// Obtains the declaring type of the method definition.
/// </summary>
/// <returns>The declaring type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DeclaringType"/> property.
/// </remarks>
protected virtual TypeDefinition? GetDeclaringType() => null;
/// <summary>
/// Obtains the signature of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual MethodSignature? GetSignature() => null;
/// <summary>
/// Obtains the parameter definitions of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ParameterDefinitions"/> property.
/// </remarks>
protected virtual IList<ParameterDefinition> GetParameterDefinitions() =>
new OwnedCollection<MethodDefinition, ParameterDefinition>(this);
/// <summary>
/// Obtains the body of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="MethodBody"/> property.
/// </remarks>
protected virtual MethodBody? GetBody() => null;
/// <summary>
/// Obtains the platform invoke information assigned to the method.
/// </summary>
/// <returns>The mapping.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ImplementationMap"/> property.
/// </remarks>
protected virtual ImplementationMap? GetImplementationMap() => null;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the list of security declarations assigned to the member.
/// </summary>
/// <returns>The security declarations</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="SecurityDeclarations"/> property.
/// </remarks>
protected virtual IList<SecurityDeclaration> GetSecurityDeclarations() =>
new OwnedCollection<IHasSecurityDeclaration, SecurityDeclaration>(this);
/// <summary>
/// Obtains the list of generic parameters this member declares.
/// </summary>
/// <returns>The generic parameters</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="GenericParameters"/> property.
/// </remarks>
protected virtual IList<GenericParameter> GetGenericParameters() =>
new OwnedCollection<IHasGenericParameters, GenericParameter>(this);
/// <summary>
/// Obtains the semantics associated to the method (if available).
/// </summary>
/// <returns>The semantics, or <c>null</c> if the method was not assigned semantics.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Semantics"/> property.
/// </remarks>
protected virtual MethodSemantics? GetSemantics() => null;
/// <summary>
/// Obtains the unmanaged export information associated to the method (if available).
/// </summary>
/// <returns>The export information or <c>null</c> if the method was not exported as a native symbol.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ExportInfo"/> property.
/// </remarks>
protected virtual UnmanagedExportInfo? GetExportInfo() => null;
/// <inheritdoc />
public override string ToString() => FullName;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExpressRouteCircuitsOperations.
/// </summary>
public static partial class ExpressRouteCircuitsOperationsExtensions
{
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
public static void Delete(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName)
{
operations.DeleteAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets information about the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of express route circuit.
/// </param>
public static ExpressRouteCircuit Get(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName)
{
return operations.GetAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of express route circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuit> GetAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
public static ExpressRouteCircuit CreateOrUpdate(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuit> CreateOrUpdateAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised ARP table associated with the express route
/// circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsArpTableListResult ListArpTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.ListArpTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised ARP table associated with the express route
/// circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsArpTableListResult> ListArpTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListArpTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised routes table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsRoutesTableListResult ListRoutesTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.ListRoutesTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised routes table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsRoutesTableListResult> ListRoutesTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListRoutesTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised routes table summary associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsRoutesTableSummaryListResult ListRoutesTableSummary(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.ListRoutesTableSummaryAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised routes table summary associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsRoutesTableSummaryListResult> ListRoutesTableSummaryAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListRoutesTableSummaryWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the stats from an express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
public static ExpressRouteCircuitStats GetStats(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName)
{
return operations.GetStatsAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the stats from an express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitStats> GetStatsAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatsWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all stats from an express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
public static ExpressRouteCircuitStats GetPeeringStats(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName)
{
return operations.GetPeeringStatsAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all stats from an express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitStats> GetPeeringStatsAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPeeringStatsWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<ExpressRouteCircuit> List(this IExpressRouteCircuitsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuit>> ListAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ExpressRouteCircuit> ListAll(this IExpressRouteCircuitsOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuit>> ListAllAsync(this IExpressRouteCircuitsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
public static void BeginDelete(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName)
{
operations.BeginDeleteAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
public static ExpressRouteCircuit BeginCreateOrUpdate(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuit> BeginCreateOrUpdateAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised ARP table associated with the express route
/// circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsArpTableListResult BeginListArpTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.BeginListArpTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised ARP table associated with the express route
/// circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsArpTableListResult> BeginListArpTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginListArpTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised routes table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsRoutesTableListResult BeginListRoutesTable(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.BeginListRoutesTableAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised routes table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsRoutesTableListResult> BeginListRoutesTableAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginListRoutesTableWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the currently advertised routes table summary associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
public static ExpressRouteCircuitsRoutesTableSummaryListResult BeginListRoutesTableSummary(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath)
{
return operations.BeginListRoutesTableSummaryAsync(resourceGroupName, circuitName, peeringName, devicePath).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the currently advertised routes table summary associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitsRoutesTableSummaryListResult> BeginListRoutesTableSummaryAsync(this IExpressRouteCircuitsOperations operations, string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginListRoutesTableSummaryWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, devicePath, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExpressRouteCircuit> ListNext(this IExpressRouteCircuitsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuit>> ListNextAsync(this IExpressRouteCircuitsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExpressRouteCircuit> ListAllNext(this IExpressRouteCircuitsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuit>> ListAllNextAsync(this IExpressRouteCircuitsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.Server.IIS.Core
{
internal partial class IISHttpContext
{
private long _consumedBytes;
internal bool ClientDisconnected { get; private set; }
/// <summary>
/// Reads data from the Input pipe to the user.
/// </summary>
/// <param name="memory"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
internal async ValueTask<int> ReadAsync(Memory<byte> memory, CancellationToken cancellationToken)
{
if (!HasStartedConsumingRequestBody)
{
InitializeRequestIO();
}
while (true)
{
var result = await _bodyInputPipe!.Reader.ReadAsync(cancellationToken);
var readableBuffer = result.Buffer;
try
{
if (!readableBuffer.IsEmpty)
{
var actual = Math.Min(readableBuffer.Length, memory.Length);
readableBuffer = readableBuffer.Slice(0, actual);
readableBuffer.CopyTo(memory.Span);
return (int)actual;
}
else if (result.IsCompleted)
{
return 0;
}
}
finally
{
_bodyInputPipe.Reader.AdvanceTo(readableBuffer.End, readableBuffer.End);
}
}
}
internal Task CopyToAsync(Stream destination, CancellationToken cancellationToken)
{
if (!HasStartedConsumingRequestBody)
{
InitializeRequestIO();
}
return _bodyInputPipe!.Reader.CopyToAsync(destination, cancellationToken);
}
/// <summary>
/// Writes data to the output pipe.
/// </summary>
/// <param name="memory"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
internal Task WriteAsync(ReadOnlyMemory<byte> memory, CancellationToken cancellationToken = default(CancellationToken))
{
async Task WriteFirstAsync()
{
await InitializeResponse(flushHeaders: false);
await _bodyOutput.WriteAsync(memory, cancellationToken);
}
return !HasResponseStarted ? WriteFirstAsync() : _bodyOutput.WriteAsync(memory, cancellationToken);
}
/// <summary>
/// Flushes the data in the output pipe
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
internal Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
{
async Task FlushFirstAsync()
{
await InitializeResponse(flushHeaders: true);
await _bodyOutput.FlushAsync(cancellationToken);
}
return !HasResponseStarted ? FlushFirstAsync() : _bodyOutput.FlushAsync(cancellationToken);
}
private async Task ReadBody()
{
Exception? error = null;
try
{
while (true)
{
var memory = _bodyInputPipe!.Writer.GetMemory();
var read = await AsyncIO!.ReadAsync(memory);
// End of body
if (read == 0)
{
break;
}
// Read was not canceled because of incoming write or IO stopping
if (read != -1)
{
_consumedBytes += read;
_bodyInputPipe.Writer.Advance(read);
}
if (_consumedBytes > MaxRequestBodySize)
{
IISBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge);
}
var result = await _bodyInputPipe.Writer.FlushAsync();
if (result.IsCompleted || result.IsCanceled)
{
break;
}
}
}
catch (ConnectionResetException ex)
{
AbortIO(clientDisconnect: true);
error = ex;
}
catch (Exception ex)
{
error = ex;
Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
}
finally
{
_bodyInputPipe!.Writer.Complete(error);
}
}
private async Task WriteBody(bool flush = false)
{
Exception? error = null;
try
{
while (true)
{
var result = await _bodyOutput.Reader.ReadAsync();
var buffer = result.Buffer;
try
{
if (!buffer.IsEmpty)
{
await AsyncIO!.WriteAsync(buffer);
}
// if request is done no need to flush, http.sys would do it for us
if (result.IsCompleted)
{
// When is the reader completed? Is it always after the request pipeline exits? Or can CompleteAsync make it complete early?
if (HasTrailers)
{
SetResponseTrailers();
}
// Done with response, say there is no more data after writing trailers.
await AsyncIO!.FlushAsync(moreData: false);
break;
}
flush |= result.IsCanceled;
if (flush)
{
await AsyncIO!.FlushAsync(moreData: true);
flush = false;
}
}
finally
{
_bodyOutput.Reader.AdvanceTo(buffer.End);
}
}
}
// We want to swallow IO exception and allow app to finish writing
catch (ConnectionResetException)
{
AbortIO(clientDisconnect: true);
}
catch (Exception ex)
{
error = ex;
Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
}
finally
{
_bodyOutput.Reader.Complete(error);
}
}
internal void AbortIO(bool clientDisconnect)
{
var shouldScheduleCancellation = false;
lock (_abortLock)
{
if (_requestAborted)
{
return;
}
shouldScheduleCancellation = _abortedCts != null;
_requestAborted = true;
}
lock (_contextLock)
{
ClientDisconnected = clientDisconnect;
}
if (clientDisconnect)
{
Log.ConnectionDisconnect(_logger, ((IHttpConnectionFeature)this).ConnectionId);
}
_bodyOutput.Complete();
if (shouldScheduleCancellation)
{
// Potentially calling user code. CancelRequestAbortedToken logs any exceptions.
CancelRequestAbortedToken();
}
}
private void CancelRequestAbortedToken()
{
ThreadPool.UnsafeQueueUserWorkItem(ctx =>
{
try
{
CancellationTokenSource? localAbortCts = null;
lock (ctx._abortLock)
{
if (ctx._abortedCts != null)
{
localAbortCts = ctx._abortedCts;
ctx._abortedCts = null;
}
}
// If we cancel the cts, we don't dispose as people may still be using
// the cts. It also isn't necessary to dispose a canceled cts.
localAbortCts?.Cancel();
}
catch (Exception ex)
{
Log.ApplicationError(_logger, ((IHttpConnectionFeature)this).ConnectionId, TraceIdentifier!, ex); // TODO: Can TraceIdentifier be null?
}
}, this, preferLocal: false);
}
public void Abort(Exception reason)
{
_bodyOutput.Abort(reason);
_streams.Abort(reason);
NativeMethods.HttpCloseConnection(_requestNativeHandle);
AbortIO(clientDisconnect: false);
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="CustomerLabelServiceClient"/> instances.</summary>
public sealed partial class CustomerLabelServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerLabelServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerLabelServiceSettings"/>.</returns>
public static CustomerLabelServiceSettings GetDefault() => new CustomerLabelServiceSettings();
/// <summary>Constructs a new <see cref="CustomerLabelServiceSettings"/> object with default settings.</summary>
public CustomerLabelServiceSettings()
{
}
private CustomerLabelServiceSettings(CustomerLabelServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerLabelSettings = existing.GetCustomerLabelSettings;
MutateCustomerLabelsSettings = existing.MutateCustomerLabelsSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerLabelServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerLabelServiceClient.GetCustomerLabel</c> and <c>CustomerLabelServiceClient.GetCustomerLabelAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerLabelServiceClient.MutateCustomerLabels</c> and
/// <c>CustomerLabelServiceClient.MutateCustomerLabelsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerLabelServiceSettings"/> object.</returns>
public CustomerLabelServiceSettings Clone() => new CustomerLabelServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerLabelServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CustomerLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerLabelServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerLabelServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerLabelServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerLabelServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerLabelServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerLabelServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerLabelServiceClient Build()
{
CustomerLabelServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerLabelServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerLabelServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerLabelServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerLabelServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerLabelServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerLabelServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerLabelServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerLabelService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on customers.
/// </remarks>
public abstract partial class CustomerLabelServiceClient
{
/// <summary>
/// The default endpoint for the CustomerLabelService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerLabelService scopes.</summary>
/// <remarks>
/// The default CustomerLabelService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerLabelServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerLabelServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerLabelServiceClient"/>.</returns>
public static stt::Task<CustomerLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerLabelServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerLabelServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CustomerLabelServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerLabelServiceClient"/>.</returns>
public static CustomerLabelServiceClient Create() => new CustomerLabelServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerLabelServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerLabelServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerLabelServiceClient"/>.</returns>
internal static CustomerLabelServiceClient Create(grpccore::CallInvoker callInvoker, CustomerLabelServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerLabelService.CustomerLabelServiceClient grpcClient = new CustomerLabelService.CustomerLabelServiceClient(callInvoker);
return new CustomerLabelServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerLabelService client</summary>
public virtual CustomerLabelService.CustomerLabelServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabel(new GetCustomerLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabelAsync(new GetCustomerLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(gagvr::CustomerLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabel(new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(gagvr::CustomerLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabelAsync(new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(gagvr::CustomerLabelName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerLabelsResponse MutateCustomerLabels(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerLabelsResponse MutateCustomerLabels(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerLabels(new MutateCustomerLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerLabelsAsync(new MutateCustomerLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, st::CancellationToken cancellationToken) =>
MutateCustomerLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerLabelService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on customers.
/// </remarks>
public sealed partial class CustomerLabelServiceClientImpl : CustomerLabelServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel> _callGetCustomerLabel;
private readonly gaxgrpc::ApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse> _callMutateCustomerLabels;
/// <summary>
/// Constructs a client wrapper for the CustomerLabelService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CustomerLabelServiceSettings"/> used within this client.</param>
public CustomerLabelServiceClientImpl(CustomerLabelService.CustomerLabelServiceClient grpcClient, CustomerLabelServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerLabelServiceSettings effectiveSettings = settings ?? CustomerLabelServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerLabel = clientHelper.BuildApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel>(grpcClient.GetCustomerLabelAsync, grpcClient.GetCustomerLabel, effectiveSettings.GetCustomerLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerLabel);
Modify_GetCustomerLabelApiCall(ref _callGetCustomerLabel);
_callMutateCustomerLabels = clientHelper.BuildApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse>(grpcClient.MutateCustomerLabelsAsync, grpcClient.MutateCustomerLabels, effectiveSettings.MutateCustomerLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerLabels);
Modify_MutateCustomerLabelsApiCall(ref _callMutateCustomerLabels);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerLabelApiCall(ref gaxgrpc::ApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel> call);
partial void Modify_MutateCustomerLabelsApiCall(ref gaxgrpc::ApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse> call);
partial void OnConstruction(CustomerLabelService.CustomerLabelServiceClient grpcClient, CustomerLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerLabelService client</summary>
public override CustomerLabelService.CustomerLabelServiceClient GrpcClient { get; }
partial void Modify_GetCustomerLabelRequest(ref GetCustomerLabelRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerLabelsRequest(ref MutateCustomerLabelsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CustomerLabel GetCustomerLabel(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerLabelRequest(ref request, ref callSettings);
return _callGetCustomerLabel.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerLabelRequest(ref request, ref callSettings);
return _callGetCustomerLabel.Async(request, callSettings);
}
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerLabelsResponse MutateCustomerLabels(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerLabelsRequest(ref request, ref callSettings);
return _callMutateCustomerLabels.Sync(request, callSettings);
}
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerLabelsRequest(ref request, ref callSettings);
return _callMutateCustomerLabels.Async(request, callSettings);
}
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// XMsClientRequestIdOperations operations.
/// </summary>
internal partial class XMsClientRequestIdOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IXMsClientRequestIdOperations
{
/// <summary>
/// Initializes a new instance of the XMsClientRequestIdOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal XMsClientRequestIdOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method that overwrites x-ms-client-request header with value
/// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/method/").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
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>
/// Get method that overwrites x-ms-client-request header with value
/// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
/// </summary>
/// <param name='xMsClientRequestId'>
/// This should appear as a method parameter, use value
/// '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> ParamGetWithHttpMessagesAsync(string xMsClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (xMsClientRequestId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "xMsClientRequestId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("xMsClientRequestId", xMsClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ParamGet", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/via-param/method/").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (xMsClientRequestId != null)
{
if (_httpRequest.Headers.Contains("x-ms-client-request-id"))
{
_httpRequest.Headers.Remove("x-ms-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", xMsClientRequestId);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Glass.Mapper.Sc.RenderField;
using Glass.Mapper.Sc.Web.Ui;
using Sitecore.Mvc.Configuration;
using Sitecore.Shell.Applications.Dialogs.ItemLister;
using Sitecore.Data.Items;
namespace Glass.Mapper.Sc.Web.Mvc
{
/// <summary>
///
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class GlassView<TModel> : WebViewPage<TModel> where TModel : class
{
protected IRenderingContext RenderingContext { get; set; }
public static bool HasDataSource<T>() where T : class
{
if (Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull == null || Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering == null)
return false;
//this has been taken from Sitecore.Mvc.Presentation.Rendering class
#if (SC70)
return Sitecore.Context.Database.GetItem(Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource) != null;
#else
return MvcSettings.ItemLocator.GetItem(Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource) != null;
#endif
}
/// <summary>
///
/// </summary>
public IGlassHtml GlassHtml { get; private set; }
public ISitecoreContext SitecoreContext { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is in editing mode.
/// </summary>
/// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value>
public bool IsInEditingMode
{
get { return Sc.GlassHtml.IsInEditingMode; }
}
/// <summary>
/// Returns either the item specified by the DataSource or the current context item
/// </summary>
/// <value>The layout item.</value>
public Item LayoutItem
{
get
{
return DataSourceItem ?? ContextItem;
}
}
/// <summary>
/// Returns either the item specified by the current context item
/// </summary>
/// <value>The layout item.</value>
public Item ContextItem
{
get { return global::Sitecore.Context.Item; }
}
/// <summary>
/// Returns the item specificed by the data source only. Returns null if no datasource set
/// </summary>
public Item DataSourceItem
{
get
{
return RenderingContext.HasDataSource ? Sitecore.Context.Database.GetItem(RenderingContext.GetDataSource()) : null;
}
}
/// <summary>
/// Returns the Context Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetContextItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(ContextItem, isLazy, inferType);
}
/// <summary>
/// Returns the Data Source Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetDataSourceItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(DataSourceItem, isLazy, inferType);
}
/// <summary>
/// Returns the Layout Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetLayoutItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(LayoutItem, isLazy, inferType);
}
/// <summary>
/// Inits the helpers.
/// </summary>
public override void InitHelpers()
{
base.InitHelpers();
SitecoreContext = Sc.SitecoreContext.GetFromHttpContext();
GlassHtml = new GlassHtml(SitecoreContext);
RenderingContext = new RenderingContextMvcWrapper();
if (Model == null && this.ViewData.Model == null)
{
this.ViewData.Model = GetModel();
}
}
protected virtual TModel GetModel()
{
if (RenderingContext.HasDataSource)
{
return SitecoreContext.Cast<TModel>(DataSourceItem);
}
else
{
return SitecoreContext.Cast<TModel>(ContextItem);
}
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="model">The model object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"> </param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T model, Expression<Func<T, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(model, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam>
/// <param name="model">The model object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T model, Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(model, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <param name="outputHeightWidth">Indicates if the height and width attributes should be rendered to the HTML element</param>
/// <returns></returns>
public virtual HtmlString RenderImage<T>(T model, Expression<Func<T, object>> field,
object parameters = null,
bool isEditable = false,
bool outputHeightWidth = false)
{
return new HtmlString(GlassHtml.RenderImage<T>(model, field, parameters, isEditable, outputHeightWidth));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(model, field, attributes, isEditable, contents));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"></param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(Expression<Func<TModel, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(
Expression<Func<TModel, object>> field, Expression<Func<TModel, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <returns></returns>
public virtual HtmlString RenderImage(Expression<Func<TModel, object>> field,
object parameters = null,
bool isEditable = false,
bool outputHeightWidth = false)
{
return new HtmlString(GlassHtml.RenderImage(Model, field, parameters, isEditable, outputHeightWidth ));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink(Expression<Func<TModel, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(this.Model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink(Expression<Func<TModel, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(this.Model, field, attributes, isEditable, contents));
}
/// <summary>
/// Returns an Sitecore Edit Frame
/// </summary>
/// <param name="model">The model</param>
/// <param name="path">The path.</param>
/// <param name="output">The stream to write the editframe output to. If the value is null the HttpContext Response Stream is used.</param>
/// <returns>
/// GlassEditFrame.
/// </returns>
public GlassEditFrame BeginEditFrame<T>(T model, string title = null, params Expression<Func<T, object>>[] fields)
where T : class
{
return GlassHtml.EditFrame(model, title, this.Output, fields);
}
/// <summary>
/// Begins the edit frame.
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="dataSource">The data source.</param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string buttons, string dataSource)
{
return GlassHtml.EditFrame(string.Empty, buttons, dataSource, this.Output);
}
/// <summary>
/// Begins the edit frame.
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="dataSource">The data source.</param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string buttons, string dataSource, string title)
{
return GlassHtml.EditFrame(title, buttons, dataSource, this.Output);
}
/// <summary>
/// Creates an Edit Frame using the Default Buttons list
/// </summary>
/// <param name="dataSource"></param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string dataSource)
{
return GlassHtml.EditFrame(string.Empty, GlassEditFrame.DefaultEditButtons, dataSource, this.Output);
}
/// <summary>
/// Creates an edit frame using the current context item
/// </summary>
/// <returns></returns>
public GlassEditFrame BeginEditFrame()
{
var frame = new GlassEditFrame(string.Empty, GlassEditFrame.DefaultEditButtons, this.Output);
frame.RenderFirstPart();
return frame;
}
public T GetRenderingParameters<T>() where T : class
{
string renderingParameters = RenderingContext.GetRenderingParameters();
return renderingParameters.HasValue() ? GlassHtml.GetRenderingParameters<T>(renderingParameters) : null;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="HelloARController.cs" company="Google LLC">
//
// Copyright 2020 Google LLC. 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.HelloAR
{
using System.Collections.Generic;
using GoogleARCore;
using GoogleARCore.Examples.Common;
using UnityEngine;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
// Set up touch input propagation while using Instant Preview in the editor.
using Input = InstantPreviewInput;
#endif
/// <summary>
/// Controls the HelloAR example.
/// </summary>
public class HelloARController : MonoBehaviour
{
/// <summary>
/// The Depth Setting Menu.
/// </summary>
public DepthMenu DepthMenu;
/// <summary>
/// The first-person camera being used to render the passthrough camera image (i.e. AR
/// background).
/// </summary>
public Camera FirstPersonCamera;
/// <summary>
/// A prefab to place when a raycast from a user touch hits a vertical plane.
/// </summary>
public GameObject GameObjectVerticalPlanePrefab;
/// <summary>
/// A prefab to place when a raycast from a user touch hits a horizontal plane.
/// </summary>
public GameObject GameObjectHorizontalPlanePrefab;
/// <summary>
/// A prefab to place when a raycast from a user touch hits a feature point.
/// </summary>
public GameObject GameObjectPointPrefab;
/// <summary>
/// The rotation in degrees need to apply to prefab when it is placed.
/// </summary>
private const float k_PrefabRotation = 180.0f;
/// <summary>
/// True if the app is in the process of quitting due to an ARCore connection error,
/// otherwise false.
/// </summary>
private bool m_IsQuitting = false;
/// <summary>
/// The Unity Awake() method.
/// </summary>
public void Awake()
{
// Enable ARCore to target 60fps camera capture frame rate on supported devices.
// Note, Application.targetFrameRate is ignored when QualitySettings.vSyncCount != 0.
Application.targetFrameRate = 60;
}
/// <summary>
/// The Unity Update() method.
/// </summary>
public void Update()
{
_UpdateApplicationLifecycle();
if (DepthMenu != null && !DepthMenu.CanPlaceAsset())
{
return;
}
// If the player has not touched the screen, we are done with this update.
Touch touch;
if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
{
return;
}
// Should not handle input if the player is pointing on UI.
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
return;
}
// Raycast against the location the player touched to search for planes.
TrackableHit hit;
TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
TrackableHitFlags.FeaturePointWithSurfaceNormal;
if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
{
// Use hit pose and camera pose to check if hittest is from the
// back of the plane, if it is, no need to create the anchor.
if ((hit.Trackable is DetectedPlane) &&
Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
hit.Pose.rotation * Vector3.up) < 0)
{
Debug.Log("Hit at back of the current DetectedPlane");
}
else
{
if (DepthMenu != null)
{
// Show depth card window if necessary.
DepthMenu.ConfigureDepthBeforePlacingFirstAsset();
}
// Choose the prefab based on the Trackable that got hit.
GameObject prefab;
if (hit.Trackable is FeaturePoint)
{
prefab = GameObjectPointPrefab;
}
else if (hit.Trackable is DetectedPlane)
{
DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
{
prefab = GameObjectVerticalPlanePrefab;
}
else
{
prefab = GameObjectHorizontalPlanePrefab;
}
}
else
{
prefab = GameObjectHorizontalPlanePrefab;
}
// Instantiate prefab at the hit pose.
var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
// Compensate for the hitPose rotation facing away from the raycast (i.e.
// camera).
gameObject.transform.Rotate(0, k_PrefabRotation, 0, Space.Self);
// Create an anchor to allow ARCore to track the hitpoint as understanding of
// the physical world evolves.
var anchor = hit.Trackable.CreateAnchor(hit.Pose);
// Make game object a child of the anchor.
gameObject.transform.parent = anchor.transform;
}
}
}
/// <summary>
/// Check and update the application lifecycle.
/// </summary>
private void _UpdateApplicationLifecycle()
{
// Exit the app when the 'back' button is pressed.
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
// Only allow the screen to sleep when not tracking.
if (Session.Status != SessionStatus.Tracking)
{
Screen.sleepTimeout = SleepTimeout.SystemSetting;
}
else
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
if (m_IsQuitting)
{
return;
}
// Quit if ARCore was unable to connect and give Unity some time for the toast to
// appear.
if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
{
_ShowAndroidToastMessage("Camera permission is needed to run this application.");
m_IsQuitting = true;
Invoke("_DoQuit", 0.5f);
}
else if (Session.Status.IsError())
{
_ShowAndroidToastMessage(
"ARCore encountered a problem connecting. Please start the app again.");
m_IsQuitting = true;
Invoke("_DoQuit", 0.5f);
}
}
/// <summary>
/// Actually quit the application.
/// </summary>
private void _DoQuit()
{
Application.Quit();
}
/// <summary>
/// Show an Android toast message.
/// </summary>
/// <param name="message">Message string to show in the toast.</param>
private void _ShowAndroidToastMessage(string message)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity =
unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
if (unityActivity != null)
{
AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
AndroidJavaObject toastObject =
toastClass.CallStatic<AndroidJavaObject>(
"makeText", unityActivity, message, 0);
toastObject.Call("show");
}));
}
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using IronPython.Hosting;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.Scripting.Hosting;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.MockVsTests;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsMockTests {
[TestClass]
public class CompletionTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
public void GetApplicableSpanTest() {
var text = "if fob.oar(eggs, spam<=ham) :";
using (var view = new PythonEditor(text)) {
var snapshot = view.CurrentSnapshot;
// We check the applicable span at every index in the string.
var expected = new[] {
"if", "if", "if",
"fob", "fob", "fob", "fob",
"oar", "oar", "oar", "oar",
"eggs", "eggs", "eggs", "eggs", "eggs",
"", // between ',' and ' '
"spam", "spam", "spam", "spam", "spam",
"", // between '<' and '='
"ham", "ham", "ham", "ham",
"", // between ')' and ' '
"", // between ' ' and ':'
"", // between ':' and EOL
};
for (int i = 0; i < text.Length; ++i) {
var span = snapshot.GetApplicableSpan(i);
if (span == null) {
Assert.AreEqual(expected[i], "", text.Substring(0, i) + "|" + text.Substring(i));
} else {
Assert.AreEqual(expected[i], span.GetText(snapshot), text.Substring(0, i) + "|" + text.Substring(i));
}
}
}
}
[TestMethod, Priority(1)]
public void CtrlSpaceCompletions() {
using (var view = new PythonEditor()) {
view.Text = @"def f(param1, param2):
g()";
AssertUtil.ContainsAtLeast(view.GetCompletionsAfter("g("), "param1", "param2");
view.Text = @"def f(param1, param2):
g(param1, )";
AssertUtil.ContainsAtLeast(view.GetCompletionsAfter("g(param1, "), "param1", "param2");
// verify Ctrl-Space inside of a function gives proper completions
foreach (var codeSnippet in new[] { @"def f():
pass", @"def f():
x = (2 + 3)
pass
", @"def f():
yield (2 + 3)
pass" }) {
Debug.WriteLine(String.Format("Testing {0}", codeSnippet));
view.Text = codeSnippet;
AssertUtil.ContainsAtLeast(view.GetCompletions(codeSnippet.IndexOf("\r\n pass")), "min", "assert");
}
}
}
[TestMethod, Priority(1)]
public void KeywordCompletions() {
using (var view = new PythonEditor(version: PythonLanguageVersion.V35)) {
var completionList = new HashSet<string>(view.GetCompletions(0));
// not in a function
AssertUtil.DoesntContain(completionList, "yield");
AssertUtil.DoesntContain(completionList, "return");
AssertUtil.DoesntContain(completionList, "await");
AssertUtil.ContainsAtLeast(completionList, "assert", "and", "async");
var code = @"def f():
|
pass";
view.Text = code.Replace("|", "");
AssertUtil.ContainsAtLeast(view.GetCompletions(code.IndexOf("|")), "yield", "return", "async", "await");
view.Text = "x = (abc, oar, )";
completionList = new HashSet<string>(view.GetCompletionsAfter("oar, "));
AssertUtil.ContainsAtLeast(completionList, "and");
AssertUtil.DoesntContain(completionList, "def");
}
}
[TestMethod, Priority(1)]
public void KeywordOrIdentifierCompletions() {
// http://pytools.codeplex.com/workitem/560
string code = @"
def h():
yiel
def f():
yield
def g():
yield_
yield_expression = 42
";
using (var view = new PythonEditor(code)) {
var completionList = view.GetCompletionsAfter("yield_");
AssertUtil.DoesntContain(completionList, "yield");
AssertUtil.Contains(completionList, "yield_expression");
completionList = view.GetCompletionsAfter("yield");
AssertUtil.Contains(completionList, "yield");
AssertUtil.Contains(completionList, "yield_expression");
completionList = view.GetCompletionsAfter("yiel");
AssertUtil.Contains(completionList, "yield");
AssertUtil.Contains(completionList, "yield_expression");
}
}
[TestMethod, Priority(1)]
public void LambdaCompletions() {
// https://github.com/Microsoft/PTVS/issues/1000
string code = @"
l = (lambda b:b)
l(42)
";
using (var view = new PythonEditor(code)) {
var completionList = view.GetCompletionsAfter(":");
AssertUtil.Contains(completionList, "b");
}
}
[TestMethod, Priority(1)]
public void TrueFalseNoneCompletions() {
// http://pytools.codeplex.com/workitem/1905
foreach (var version in new[] { PythonLanguageVersion.V27, PythonLanguageVersion.V33 }) {
using (var view = new PythonEditor(version: version)) {
var completionList = view.GetCompletionList(0);
var trueItems = completionList.Where(t => t.DisplayText == "True").ToArray();
var falseItems = completionList.Where(t => t.DisplayText == "False").ToArray();
var noneItems = completionList.Where(t => t.DisplayText == "None").ToArray();
Assert.AreEqual(1, trueItems.Count());
Assert.AreEqual(1, falseItems.Count());
Assert.AreEqual(1, noneItems.Count());
if (version.Is3x()) {
Assert.AreEqual("Keyword", trueItems[0].IconAutomationText);
Assert.AreEqual("Keyword", falseItems[0].IconAutomationText);
} else {
Assert.AreEqual("Constant", trueItems[0].IconAutomationText);
Assert.AreEqual("Constant", falseItems[0].IconAutomationText);
}
Assert.AreEqual("Keyword", noneItems[0].IconAutomationText);
}
}
}
[TestMethod, Priority(1)]
public void CtrlSpaceAfterKeyword() {
// http://pytools.codeplex.com/workitem/560
string code = @"
def h():
return
print
";
using (var vs = new MockVs()) {
AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("return "), code), "any");
AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("print "), code), "any");
}
}
[TestMethod, Priority(1)]
public void CtrlSpaceAfterNumber() {
// http://pytools.codeplex.com/workitem/2323
string code = @"
2
2.
2..
2.0.
";
using (var vs = new MockVs()) {
AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2"), code));
AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2."), code));
AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.."), code), "real", "imag");
AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.0."), code), "real", "imag");
}
}
[TestMethod, Priority(1)]
public void ExceptionCompletions() {
using (var vs = new MockVs()) {
foreach (string code in new[] {
@"import sys
raise |",
@"import sys
raise (|",
@"import sys
try:
pass
except |",
@"import sys
try:
pass
except (|",
@"import sys
try:
pass
except (ValueError, |"}) {
var completionList = GetCompletions(vs, code.IndexOf("|"), code.Replace("|", "")).ToArray();
AssertUtil.ContainsAtLeast(completionList,
"Exception",
"KeyboardInterrupt",
"GeneratorExit",
"StopIteration",
"SystemExit",
"sys"
);
AssertUtil.DoesntContain(completionList, "Warning");
AssertUtil.DoesntContain(completionList, "str");
AssertUtil.DoesntContain(completionList, "int");
}
foreach (string code in new[] {
@"import sys
raise (sys.",
@"import sys
try:
pass
except (sys."}) {
var completionList = GetCompletions(vs, code.IndexOfEnd("sys."), code).ToArray();
AssertUtil.DoesntContain(completionList, "Exception");
AssertUtil.DoesntContain(completionList, "KeyboardInterrupt");
AssertUtil.DoesntContain(completionList, "GeneratorExit");
AssertUtil.DoesntContain(completionList, "StopIteration");
AssertUtil.DoesntContain(completionList, "SystemExit");
AssertUtil.ContainsAtLeast(completionList,
"modules",
"path",
"version"
);
}
}
}
[TestMethod, Priority(1)]
public void MemberCompletions() {
using (var view = new PythonEditor("x = 2\r\nx.")) {
// TODO: Negative tests
TestMemberCompletion(view, -1, "x");
// combining various partial expressions with previous expressions
var prefixes = new[] { "", "(", "a = ", "f(", "l[", "{", "if " };
var exprs = new[] {
"f(a=x).",
"x[0].",
"x(0).",
"x.",
"x.y.",
"f(x[2]).",
"f(x, y).",
"f({2:3}).",
"f(a + b).",
"f(a or b).",
"{2:3}.",
"f(x if False else y).",
"(\r\nx\r\n).",
};
foreach (var prefix in prefixes) {
foreach (var expr in exprs) {
string test = prefix + expr;
Console.WriteLine(" -- {0}", test);
view.Text = test;
TestMemberCompletion(view, -1, expr.TrimEnd('.'));
}
}
}
}
[TestMethod, Priority(1)]
public void SignatureHelp() {
var prefixes = new[] { "", "(", "a = ", "f(", "l[", "{", "if " };
var sigs = new[] {
new { Expr = "f(", Param = 0, Function="f" } ,
new { Expr = "f(1,", Param = 1, Function="f" },
new { Expr = "f(1, 2,", Param = 2, Function="f" },
new { Expr = "f(1, (1, 2),", Param = 2, Function="f" },
new { Expr = "f(1, a + b,", Param = 2, Function="f" },
new { Expr = "f(1, a or b,", Param = 2, Function="f" },
new { Expr = "f(1, a if True else b,", Param = 2, Function="f" },
new { Expr = "a.f(1, a if True else b,", Param = 2, Function="a.f" },
new { Expr = "a().f(1, a if True else b,", Param = 2, Function="a().f" },
new { Expr = "a(2, 3, 4).f(1, a if True else b,", Param = 2, Function="a(2, 3, 4).f" },
new { Expr = "a(2, (3, 4), 4).f(1, a if True else b,", Param = 2, Function="a(2, (3, 4), 4).f" },
new { Expr = "f(lambda a, b, c: 42", Param = 0, Function="f" } ,
new { Expr = "f(lambda a, b, c", Param = 0, Function="f" } ,
new { Expr = "f(lambda a: lambda b, c: 42", Param = 0, Function="f" } ,
new { Expr = "f(z, lambda a, b, c: 42", Param = 1, Function="f" } ,
new { Expr = "f(z, lambda a, b, c", Param = 1, Function="f" } ,
new { Expr = "f(z, lambda a: lambda b, c: 42", Param = 1, Function="f" } ,
new { Expr = "f([a for b in c", Param = 0, Function="f" },
// No function for f(( because ReverseExpressionParser will stop at the unmatched (
new { Expr = "f((a for b in c", Param = 0, Function="" },
new { Expr = "f({a for b in c", Param = 0, Function="f" },
new { Expr = "f([a for b in c],", Param = 1, Function="f" },
new { Expr = "f((a for b in c),", Param = 1, Function="f" },
new { Expr = "f({a for b in c},", Param = 1, Function="f" },
new { Expr = "f(0, [a for b in c],", Param = 2, Function="f" },
new { Expr = "f(0, (a for b in c),", Param = 2, Function="f" },
new { Expr = "f(0, {a for b in c},", Param = 2, Function="f" },
new { Expr = "f([1,2", Param = 0, Function="f" },
new { Expr = "f([1,2,", Param = 0, Function="f" },
new { Expr = "f({1:2,", Param = 0, Function="f" },
new { Expr = "f({1,", Param = 0, Function="f" },
new { Expr = "f({1:2", Param = 0, Function="f" },
};
using (var view = new PythonEditor()) {
foreach (var prefix in prefixes) {
foreach (var sig in sigs) {
var test = prefix + sig.Expr;
Console.WriteLine(" -- {0}", test);
view.Text = test;
var snapshot = view.CurrentSnapshot;
SignatureAnalysis res = null;
view.VS.InvokeSync(() => {
res = view.VS.GetPyService().GetSignatures(
view.View.TextView,
snapshot,
snapshot.CreateTrackingSpan(snapshot.Length, 0, SpanTrackingMode.EdgeInclusive)
);
});
Assert.IsNotNull(res);
Assert.AreEqual(sig.Function, res.Text, test);
Assert.AreEqual(sig.Param, res.ParameterIndex, test);
}
}
}
}
[TestMethod, Priority(1)]
public void SignatureHelpStarArgs() {
SignatureAnalysis sigResult = null;
using (var view = new PythonEditor(@"def f(a, *b, c=None): pass
f(1, 2, 3, 4,")) {
for (int retries = 3; retries >= 0; --retries) {
TestSignature(view, -1, "f", 4, out sigResult);
if (retries == 0) {
Assert.IsTrue(sigResult.Signatures.Count >= 1, "No signature analysis results");
} else if (sigResult.Signatures.Count >= 1) {
break;
}
Console.WriteLine("Retry {0}", retries);
view.Text = view.Text;
}
Assert.AreEqual("*b", sigResult.Signatures[0].CurrentParameter.Name);
}
}
[TestMethod, Priority(1)]
public void ImportCompletions() {
using (var view = new PythonEditor()) {
view.Text ="import ";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "sys");
view.Text ="import sys";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "sys");
view.Text ="import sys ";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "as");
view.Text ="import sys as";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "as");
view.Text ="import sys as s, ";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "sys");
view.Text ="import sys, ";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "datetime");
view.Text ="import sys, da";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "datetime");
}
}
[TestMethod, Priority(1)]
public void FromImportCompletions() {
using (var view = new PythonEditor()) {
view.Text = "from ";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "nt", "sys");
view.Text = "from s";
var completions = view.GetCompletions(-1);
AssertUtil.ContainsAtLeast(completions, "sys");
AssertUtil.DoesntContain(completions, "nt");
view.Text = "from sys ";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "import");
view.Text = "from sys import";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "import");
view.Text = "from sys import ";
AssertUtil.ContainsAtLeast(view.GetCompletions(-1),
"*", // Contains *
"settrace", // Contains functions
"api_version" // Contains data members
);
view.Text = "from sys.";
// There will be one completion saying that there are no completions
Assert.AreEqual(1, view.GetCompletions(-1).Count());
// Error case - no completions
view.Text = "from sys. import ";
AssertUtil.ContainsExactly(view.GetCompletions(-1));
view.Text = "from sys import settrace ";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "as");
view.Text = "from sys import settrace as";
AssertUtil.ContainsExactly(view.GetCompletions(-1), "as");
view.Text = "from sys import settrace,";
completions = view.GetCompletions(-1);
AssertUtil.ContainsAtLeast(completions, "api_version", "settrace");
AssertUtil.DoesntContain(completions, "*");
// No more completions after a *
view.Text = "from sys import *, ";
AssertUtil.ContainsExactly(view.GetCompletions(-1));
view.Text = "from sys import settrace as ";
AssertUtil.ContainsExactly(view.GetCompletions(-1));
view.Text = "from sys import settrace as st ";
AssertUtil.ContainsExactly(view.GetCompletions(-1));
view.Text = "from sys import settrace as st, ";
completions = view.GetCompletions(-1);
AssertUtil.ContainsAtLeast(completions, "api_version", "settrace");
AssertUtil.DoesntContain(completions, "*");
}
}
[TestMethod, Priority(1)]
public void FromOSPathImportCompletions2x() {
using (var vs = new MockVs())
using (var db = MockCompletionDB.Create(PythonLanguageVersion.V27, "os", "ntpath", "posixpath", "os2emxpath")) {
OSPathImportTest(vs, db);
}
}
[TestMethod, Priority(1)]
public void FromOSPathImportCompletions3x() {
using (var vs = new MockVs())
using (var db = MockCompletionDB.Create(PythonLanguageVersion.V33, "os", "ntpath", "posixpath", "os2emxpath")) {
OSPathImportTest(vs, db);
}
}
private static void OSPathImportTest(MockVs vs, MockCompletionDB db) {
var code = "from ";
AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "os", "sys");
code = "from o";
var completions = GetCompletions(vs, -1, code, db.Factory);
AssertUtil.ContainsAtLeast(completions, "os");
AssertUtil.DoesntContain(completions, "sys");
code = "from os ";
AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");
code = "from os import";
AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");
code = "from os import ";
AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "path");
code = "from os.";
AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "path");
code = "from os.path import ";
AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "abspath", "relpath");
var allNames = new HashSet<string>();
allNames.UnionWith(GetCompletions(vs, -1, "from ntpath import ", db.Factory));
allNames.UnionWith(GetCompletions(vs, -1, "from posixpath import ", db.Factory));
code = "from os.path import ";
AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), allNames);
}
[TestMethod, Priority(1)]
public void FromImportMultilineCompletions() {
using (var vs = new MockVs()) {
var code = "from sys import (";
var completions = GetCompletions(vs, -1, code);
AssertUtil.ContainsAtLeast(completions, "settrace", "api_version");
AssertUtil.DoesntContain(completions, "*");
code = "from nt import (\r\n ";
completions = GetCompletions(vs, -1, code);
AssertUtil.ContainsAtLeast(completions, "abort", "W_OK");
AssertUtil.DoesntContain(completions, "*");
code = "from nt import (getfilesystemencoding,\r\n ";
completions = GetCompletions(vs, -1, code);
AssertUtil.ContainsAtLeast(completions, "abort", "W_OK");
AssertUtil.DoesntContain(completions, "*");
// Need a comma for more completions
code = "from sys import (settrace\r\n ";
AssertUtil.ContainsExactly(GetCompletions(vs, -1, code), "as");
}
}
private static IEnumerable<string> GetCompletionNames(CompletionSet completions) {
foreach (var comp in completions.Completions) {
yield return comp.InsertionText;
}
}
private static IEnumerable<string> GetCompletionNames(CompletionAnalysis analysis) {
return GetCompletionNames(analysis.GetCompletions(new MockGlyphService()));
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void Scenario_CompletionInTripleQuotedString() {
string code = @"
'''
import
from
except
@
sys.
'''
";
using (var view = new PythonEditor(code)) {
for (int i = code.IndexOfEnd("'''"); i < code.LastIndexOf("'''"); ++i) {
AssertUtil.ContainsExactly(view.GetCompletions(i));
}
}
}
[TestMethod, Priority(1)]
public void GotoDefinition() {
using (var vs = new MockVs()) {
string code = @"
class C:
def fff(self): pass
C().fff";
//var emptyAnalysis = AnalyzeExpression(0, code);
//AreEqual(emptyAnalysis.Expression, "");
for (int i = -1; i >= -3; i--) {
var analysis = AnalyzeExpression(vs, i, code);
Assert.AreEqual("C().fff", analysis.Expression);
}
var classAnalysis = AnalyzeExpression(vs, -6, code);
Assert.AreEqual("C()", classAnalysis.Expression);
var defAnalysis = AnalyzeExpression(vs, code.IndexOf("def fff") + 4, code);
Assert.AreEqual("fff", defAnalysis.Expression);
}
}
[TestMethod, Priority(1)]
public void QuickInfo() {
string code = @"
x = ""ABCDEFGHIJKLMNOPQRSTUVWYXZ""
cls._parse_block(ast.expr)
f(a,
(b, c, d),
e)
def f():
""""""helpful information
""""""
while True:
pass
lambda larg1, larg2: None";
using (var view = new PythonEditor(code)) {
// we get the appropriate subexpression
TestQuickInfo(view, code.IndexOf("cls."), code.IndexOf("cls.") + 4, "cls: <unknown type>");
TestQuickInfo(view, code.IndexOf("cls.") + 4 + 1, code.IndexOf("cls.") + 4 + 1 + 11, "cls._parse_block: <unknown type>");
TestQuickInfo(view, code.IndexOf("cls.") + 4 + 1 + 11 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4, "ast: <unknown type>");
TestQuickInfo(view, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1 + 3, "ast.expr: <unknown type>");
TestQuickInfo(view, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1 + 3 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 5 + 3 + 1 + 1, "cls._parse_block(ast.expr): <unknown type>");
// the whole string shows up in quick info
TestQuickInfo(view, code.IndexOf("x = ") + 4, code.IndexOf("x = ") + 4 + 28, "\"ABCDEFGHIJKLMNOPQRSTUVWYXZ\": str");
// trailing new lines don't show up in quick info
TestQuickInfo(view, code.IndexOf("def f") + 4, code.IndexOf("def f") + 5, "f: def file.f()\r\nhelpful information");
// keywords don't show up in quick info
TestQuickInfo(view, code.IndexOf("while True:"), code.IndexOf("while True:") + 5);
// 'lambda' keyword doesn't show up in quick info
TestQuickInfo(view, code.IndexOf("lambda"), code.IndexOf("lambda") + 6);
// but its arguments do
TestQuickInfo(view, code.IndexOf("larg1"), code.IndexOf("larg1") + 5, "larg1: <unknown type>");
TestQuickInfo(view, code.IndexOf("larg2"), code.IndexOf("larg2") + 5, "larg2: <unknown type>");
// multiline function, hover at the close paren
TestQuickInfo(view, code.IndexOf("e)") + 1, code.IndexOf("e)") + 2, @"f(a,
(b, c, d),
e): <unknown type>");
}
}
[TestMethod, Priority(1)]
public void NormalOverrideCompletions() {
using (var view2 = new PythonEditor(version: PythonLanguageVersion.V27))
using (var view3 = new PythonEditor(version: PythonLanguageVersion.V33)) {
foreach (var code in new[] {
@"class Fob(object):
def func_a(self, a=100): pass
def func_b(self, b, *p, **kw): pass
class Baz(Fob):
def None
",
@"class Fob(object):
def func_a(self, a=100): pass
class Oar(Fob):
def func_b(self, b, *p, **kw): pass
class Baz(Oar):
def None
",
@"class Fob(object):
def func_a(self, a=100): pass
class Oar(object):
def func_b(self, b, *p, **kw): pass
class Baz(Fob, Oar):
def None
",
@"class Fob(object):
def func_a(self, a=100): pass
def func_b(self, b, *p, **kw): pass
def func_c(self): pass
class Baz(Fob):
def func_c(self): pass
def None
",
@"class Fob(object):
def func_a(self, a=100): pass
def func_c(self): pass
class Oar(Fob):
def func_b(self, b, *p, **kw): pass
class Baz(Oar):
def func_c(self): pass
def None
",
@"class Fob(object):
def func_a(self, a=100): pass
class Oar(object):
def func_b(self, b, *p, **kw): pass
def func_c(self): pass
class Baz(Fob, Oar):
def func_c(self): pass
def None
"}) {
view2.Text = code;
Console.WriteLine(code);
AssertUtil.ContainsAtLeast(
view2.GetCompletionList(code.IndexOf("None")).Select(c => c.InsertionText),
@"func_a(self, a = 100):
return super(Baz, self).func_a(a)",
@"func_b(self, b, *p, **kw):
return super(Baz, self).func_b(b, *p, **kw)"
);
view3.Text = code;
AssertUtil.ContainsAtLeast(
view3.GetCompletionList(code.IndexOf("None")).Select(c => c.InsertionText),
@"func_a(self, a = 100):
return super().func_a(a)",
@"func_b(self, b, *p, **kw):
return super().func_b(b, *p, **kw)"
);
}
}
}
[TestMethod, Priority(1)]
public void BuiltinOverrideCompletions() {
using (var view2 = new PythonEditor(version: PythonLanguageVersion.V27))
using (var view3 = new PythonEditor(version: PythonLanguageVersion.V33)) {
view2.Text = view3.Text = @"class Fob(str):
def
";
AssertUtil.ContainsAtLeast(
view2.GetCompletionListAfter("def ").Select(c => c.InsertionText),
@"capitalize(self):
return super(Fob, self).capitalize()",
@"index(self, sub, start, end):
return super(Fob, self).index(sub, start, end)"
);
AssertUtil.ContainsAtLeast(
view3.GetCompletionListAfter("def ").Select(x => x.InsertionText),
@"capitalize(self):
return super().capitalize()",
@"index(self, sub, start, end):
return super().index(sub, start, end)"
);
view2.Text = view3.Text = @"class Fob(str, list):
def
";
AssertUtil.Contains(
view2.GetCompletionListAfter("def ").Select(c => c.InsertionText),
@"index(self, sub, start, end):
return super(Fob, self).index(sub, start, end)"
);
AssertUtil.Contains(
view3.GetCompletionListAfter("def ").Select(c => c.InsertionText),
@"index(self, sub, start, end):
return super().index(sub, start, end)"
);
view2.Text = view3.Text = @"class Fob(list, str):
def
";
AssertUtil.Contains(
view2.GetCompletionListAfter("def ").Select(c => c.InsertionText),
@"index(self, item, start, stop):
return super(Fob, self).index(item, start, stop)"
);
AssertUtil.Contains(
view3.GetCompletionListAfter("def ").Select(c => c.InsertionText),
@"index(self, item, start, stop):
return super().index(item, start, stop)"
);
}
}
[TestMethod, Priority(1)]
public void OverridesWithMismatchedAnalysis() {
// Here we create a buffer and analyze. We then add some newlines
// and a def, expecting completions from A (int). Because the def
// has moved down into class B, GetCompletions() rolls it back
// to find out where in the analysis to look - without this, we
// would get completions for dict rather than int.
var code = @"
class A(int):
pass
class B(dict):
pass
";
using (var vs = new MockVs()) {
var editText = "\r\n\r\n\r\n def ";
var editInsert = code.IndexOf("pass") + 4;
var completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");
AssertUtil.ContainsAtLeast(completions, "bit_length", "conjugate");
AssertUtil.DoesntContain(completions, "keys");
editText = "\r\n\r\n\r\n\r\n\r\n def ";
editInsert = code.IndexOf("pass", editInsert) + 4;
completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");
AssertUtil.ContainsAtLeast(completions, "keys", "__contains__");
AssertUtil.DoesntContain(completions, "bit_length");
}
}
[TestMethod, Priority(1)]
public void HideAdvancedMembers() {
using (var view = new PythonEditor()) {
// No text - expect all non-advanced members
AssertUtil.ContainsExactly(HideAdvancedMembersHelper(view, "", "a", "b", "__c__", "__d_e__", "_f_"),
"a", "b", "_f_"
);
// Matches one item, so we should only see that
AssertUtil.ContainsExactly(HideAdvancedMembersHelper(view, "a", "a", "b", "__c__", "__d_e__", "_f_"),
"a"
);
// Matches one hidden item - expect all non-advanced members
AssertUtil.ContainsExactly(HideAdvancedMembersHelper(view, "c", "a", "b", "__c__", "__d_e__", "_f_"),
"a", "b", "_f_"
);
// Matches one item and advanced members
AssertUtil.ContainsExactly(HideAdvancedMembersHelper(view, "__", "a", "b", "__c__", "__d_e__", "_f_"),
"_f_",
"__c__",
"__d_e__"
);
}
}
private IEnumerable<string> HideAdvancedMembersHelper(PythonEditor view, string text, params string[] completions) {
view.Text = text;
var snapshot = view.CurrentSnapshot;
var set = new FuzzyCompletionSet(
"Test Completions",
"Test Completions",
snapshot.CreateTrackingSpan(0, snapshot.Length, SpanTrackingMode.EdgeInclusive),
completions.Select(c => new DynamicallyVisibleCompletion(c)),
new CompletionOptions { HideAdvancedMembers = true, IntersectMembers = false },
CompletionComparer.UnderscoresLast
);
set.Filter();
return set.Completions.Select(c => c.DisplayText).ToList();
}
private static IEnumerable<string> GenerateText(int lines, int width, string prefix = "") {
var rand = new Random();
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.(), '\"";
for (int i = 0; i < lines; ++i) {
yield return prefix + new String(Enumerable.Repeat(0, width - prefix.Length)
.Select(_ => rand.Next(VALID_CHARS.Length))
.Select(j => VALID_CHARS[j])
.ToArray()
);
}
}
[TestMethod, Priority(1)]
public void CompletionWithLongDocString() {
using (var vs = new MockVs()) {
var docString = GenerateText(100, 72, " ").ToArray();
string code = @"
def func(a):
'''" + string.Join(Environment.NewLine, docString) + @"'''
pass
";
// Because there is an extra line added for the Quick Info we only
// want the first 29 lines of the docstring. For signature docs,
// we'll cut to 15 lines.
var expected1 = string.Join(Environment.NewLine, docString.Take(29)) + Environment.NewLine + "...";
var expected2 = string.Join(Environment.NewLine, docString.Take(15)).TrimStart() + Environment.NewLine + "...";
using (var view = new PythonEditor(code)) {
TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);
SignatureAnalysis sigs;
view.Text += "func(";
TestSignature(view, -1, "func", 0, out sigs);
Assert.AreEqual(1, sigs.Signatures.Count);
Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
}
docString = GenerateText(100, 250, " ").ToArray();
code = @"
def func(a):
'''" + string.Join(Environment.NewLine, docString) + @"'''
pass
";
using (var view = new PythonEditor(code)) {
// The long lines cause us to truncate sooner.
expected1 = string.Join(Environment.NewLine, docString.Take(15)) + Environment.NewLine + "...";
expected2 = string.Join(Environment.NewLine, docString.Take(8)).TrimStart() + Environment.NewLine + "...";
TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);
SignatureAnalysis sigs;
view.Text += "func(";
TestSignature(view, -1, "func", 0, out sigs);
Assert.AreEqual(1, sigs.Signatures.Count);
Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
}
}
}
[TestMethod, Priority(1)]
public void ClassCompletionOutsideFunction() {
// Note that "eggs_and_spam" is longer than the indentation of each
// scope.
string code = @"
eggs_and_spam = 'abc'
class Spam(object):
eggs_and_spam = 123
def f(self, eggs_and_spam = 3.14):
#1
pass
#2
#3
";
using (var view = new PythonEditor()) {
view.Text = code.Replace("#1", "eggs_and_spam.");
var completionList = view.GetCompletionsAfter("eggs_and_spam.");
AssertUtil.ContainsAtLeast(completionList, "real", "imag");
AssertUtil.DoesntContain(completionList, "lower");
view.Text = code.Replace("#2", "eggs_and_spam.");
AssertUtil.ContainsAtLeast(view.GetCompletionsAfter("eggs_and_spam."), "bit_length");
view.Text = code.Replace("#3", "eggs_and_spam.");
AssertUtil.ContainsAtLeast(view.GetCompletionsAfter("eggs_and_spam."), "lower", "center");
}
}
[TestMethod, Priority(1)]
public void ArgumentNameCompletion() {
const string code = @"
def f(param1 = 123, param2 : int = 234):
pass
x = f(";
using (var view = new PythonEditor(code)) {
view.Text = view.Text;
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "param1", "param2");
AssertUtil.DoesntContain(view.GetCompletions(0), "param1");
}
}
[TestMethod, Priority(1)]
public void MethodArgumentNameCompletion() {
const string code = @"
class MyClass:
def f(self, param1 = 123, param2 : int = 234):
pass
m = MyClass()
x = m.f(";
using (var view = new PythonEditor(code)) {
for (int retries = 3; retries >= 0; --retries) {
var sigs = GetSignatureAnalysis(view, code.Length - 1);
if (sigs.Signatures.Count > 0) {
break;
}
Console.WriteLine("Retry {0}", retries);
view.Text = view.Text;
}
AssertUtil.ContainsAtLeast(view.GetCompletions(-1), "param1", "param2");
AssertUtil.DoesntContain(view.GetCompletions(0), "param1");
}
}
[TestMethod, Priority(1)]
public void YieldFromExpressionCompletion() {
const string code = @"
def f():
yield 1
return 1
def g():
f().
yield from f().
(yield from f()).
";
using (var view = new PythonEditor(code, PythonLanguageVersion.V35)) {
AssertUtil.CheckCollection(view.GetCompletionsAfter("f()."),
new[] { "next", "send", "throw" },
new[] { "real", "imag" }
);
AssertUtil.CheckCollection(view.GetCompletionsAfter("yield from f()."),
new[] { "next", "send", "throw" },
new[] { "real", "imag" }
);
AssertUtil.CheckCollection(view.GetCompletionsAfter("(yield from f())."),
new[] { "real", "imag" },
new[] { "next", "send", "throw" }
);
}
}
[TestMethod, Priority(1)]
public void AwaitExpressionCompletion() {
const string code = @"
async def f():
return 1
async def g():
f().
await f().
(await f()).";
using (var view = new PythonEditor(code, PythonLanguageVersion.V35)) {
AssertUtil.CheckCollection(view.GetCompletionsAfter("f()."),
new[] { "next", "send", "throw" },
new[] { "real", "imag" }
);
AssertUtil.CheckCollection(view.GetCompletionsAfter("await f()."),
new[] { "next", "send", "throw" },
new[] { "real", "imag" }
);
AssertUtil.CheckCollection(view.GetCompletionsAfter("(await f())."),
new[] { "real", "imag" },
new[] { "next", "send", "throw" }
);
}
}
private static IEnumerable<string> EditAndGetCompletions(
MockVs vs,
string code,
string editText,
int editInsert,
string completeAfter,
PythonLanguageVersion version = PythonLanguageVersion.V27
) {
using (var view = new PythonEditor(code, version, vs)) {
view.AdvancedOptions.HideAdvancedMembers = false;
var snapshot = view.CurrentSnapshot;
ITextVersion afterEditVersion = null;
ManualResetEvent mre = new ManualResetEvent(false);
view.View.TextView.TextBuffer.RegisterForNewAnalysis(entry => {
if (afterEditVersion != null &&
entry.TryGetBufferParser().GetAnalysisVersion(snapshot.TextBuffer).VersionNumber >= afterEditVersion.VersionNumber) {
mre.Set();
}
});
view.View.MoveCaret(new SnapshotPoint(snapshot, editInsert));
view.Type(editText);
afterEditVersion = view.CurrentSnapshot.Version;
if (!mre.WaitOne(10000)) {
Assert.Fail("Failed to wait for new analysis");
}
var newSnapshot = view.CurrentSnapshot;
Assert.AreNotSame(snapshot, newSnapshot);
return view.GetCompletionsAfter(completeAfter);
}
}
private static void TestQuickInfo(PythonEditor view, int start, int end, params string[] expected) {
var snapshot = view.CurrentSnapshot;
for (int i = start; i < end; i++) {
List<object> quickInfo = new List<object>();
ITrackingSpan span;
QuickInfoSource.AugmentQuickInfoWorker(
quickInfo,
VsProjectAnalyzer.GetQuickInfoAsync(
view.VS.ServiceProvider,
view.View.TextView,
new SnapshotPoint(snapshot, start)
).Result,
out span
);
Assert.AreEqual(expected.Length, quickInfo.Count);
for (int j = 0; j < expected.Length; j++) {
Assert.AreEqual(expected[j], quickInfo[j]);
}
}
}
private static ExpressionAnalysis AnalyzeExpression(MockVs vs, int location, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
if (location < 0) {
location += code.Length + 1;
}
using (var view = new PythonEditor(code, version, vs)) {
var snapshot = view.CurrentSnapshot;
ExpressionAnalysis expr = null;
vs.InvokeSync(() => {
expr = vs.GetPyService().AnalyzeExpression(
view.View.TextView,
snapshot,
snapshot.CreateTrackingSpan(location, location < snapshot.Length ? 1 : 0, SpanTrackingMode.EdgeInclusive),
false
);
});
return expr;
}
}
private static void TestMemberCompletion(PythonEditor view, int index, string expectedExpression) {
var snapshot = view.CurrentSnapshot;
if (index < 0) {
index += snapshot.Length + 1;
}
CompletionAnalysis context = null;
view.VS.InvokeSync(() => {
context = view.VS.GetPyService().GetCompletions(
null,
view.View.TextView,
snapshot,
snapshot.GetApplicableSpan(index) ?? snapshot.CreateTrackingSpan(index, 0, SpanTrackingMode.EdgeInclusive),
snapshot.CreateTrackingPoint(index, PointTrackingMode.Negative),
new CompletionOptions()
);
});
Assert.IsInstanceOfType(context, typeof(NormalCompletionAnalysis));
var normalContext = (NormalCompletionAnalysis)context;
string text;
SnapshotSpan statementExtent;
Assert.IsTrue(normalContext.GetPrecedingExpression(out text, out statementExtent));
Assert.AreEqual(expectedExpression, text);
}
private static SignatureAnalysis GetSignatureAnalysis(PythonEditor view, int index) {
var snapshot = view.CurrentSnapshot;
SignatureAnalysis sigs = null;
view.VS.InvokeSync(() => {
sigs = view.VS.GetPyService().GetSignatures(
view.View.TextView,
snapshot,
snapshot.CreateTrackingSpan(index, 1, SpanTrackingMode.EdgeInclusive)
);
});
return sigs;
}
private static void TestSignature(PythonEditor view, int location, string expectedExpression, int paramIndex, out SignatureAnalysis sigs) {
if (location < 0) {
location = view.CurrentSnapshot.Length + location;
}
sigs = GetSignatureAnalysis(view, location);
Assert.AreEqual(expectedExpression, sigs.Text, view.Text);
Assert.AreEqual(paramIndex, sigs.ParameterIndex, view.Text);
}
private static List<Completion> GetCompletionList(MockVs vs, int index, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
using (var view = new PythonEditor(code, version, vs)) {
return view.GetCompletionList(index);
}
}
private static IEnumerable<string> GetCompletions(MockVs vs, int index, string code, IPythonInterpreterFactory factory) {
using (var view = new PythonEditor(code, vs: vs, factory: factory)) {
return view.GetCompletions(index);
}
}
private static IEnumerable<string> GetCompletions(MockVs vs, int index, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
using (var view = new PythonEditor(code, version, vs)) {
return view.GetCompletions(index);
}
}
}
}
| |
using System;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.DomainModel.Mapping
{
// ignoring warning for obsolete SubClass
#pragma warning disable 612,618
[TestFixture]
public class SubClassTester
{
[Test]
public void CreateDiscriminator()
{
new MappingTester<SecondMappedObject>()
.ForMapping(map => map.DiscriminateSubClassesOnColumn<string>("Type"))
.Element("class/discriminator").HasAttribute("type", "String")
.Element("class/discriminator/column").HasAttribute("name", "Type");
}
[Test]
public void CanUseDefaultDiscriminatorValue()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(sc => sc.Map(x => x.Name)))
.Element("class/subclass")
.DoesntHaveAttribute("discriminator-value");
}
[Test]
public void ShouldSetTheName()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("red", sc => { }))
.Element("//subclass").HasAttribute("name", typeof(SecondMappedObject).AssemblyQualifiedName);
}
[Test]
public void MapsProperty()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(sc => sc.Map(x => x.Name)))
.Element("//subclass/property").HasAttribute("name", "Name");
}
[Test]
public void SubClassLazy()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(sc => sc.LazyLoad()))
.Element("//subclass").HasAttribute("lazy", "true");
}
[Test]
public void SubClassNotLazy()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(sc => sc.Not.LazyLoad()))
.Element("//subclass").HasAttribute("lazy", "false");
}
[Test]
public void CanSpecifyProxyByType()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.Proxy(typeof(ProxyClass))))
.Element("class/subclass").HasAttribute("proxy", typeof(ProxyClass).AssemblyQualifiedName);
}
[Test]
public void CanSpecifyProxyByTypeInstance()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.Proxy<ProxyClass>()))
.Element("class/subclass").HasAttribute("proxy", typeof(ProxyClass).AssemblyQualifiedName);
}
[Test]
public void CanSpecifyDynamicUpdate()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.DynamicUpdate()))
.Element("class/subclass").HasAttribute("dynamic-update", "true");
}
[Test]
public void CanSpecifyDynamicInsert()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.DynamicInsert()))
.Element("class/subclass").HasAttribute("dynamic-insert", "true");
}
[Test]
public void CanSpecifySelectBeforeUpdate()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.SelectBeforeUpdate()))
.Element("class/subclass").HasAttribute("select-before-update", "true");
}
[Test]
public void CanSpecifyAbstract()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("columnName", sm => sm.Abstract()))
.Element("class/subclass").HasAttribute("abstract", "true");
}
[Test]
public void CanSpecifySpecialNullValue()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(DiscriminatorValue.Null, sm => { }))
.Element("class/subclass").HasAttribute("discriminator-value", "null");
}
[Test]
public void CanSpecifySpecialNotNullValue()
{
new MappingTester<MappedObject>()
.ForMapping(m =>
m.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>(DiscriminatorValue.NotNull, sm => { }))
.Element("class/subclass").HasAttribute("discriminator-value", "not null");
}
[Test]
public void MapsComponent()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.Component(x => x.Component, c => { })))
.Element("//subclass/component").Exists();
}
[Test]
public void MapsDynamicComponent()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.DynamicComponent(x => x.Dictionary, c => { })))
.Element("//subclass/dynamic-component").Exists();
}
[Test]
public void MapsHasMany()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.HasMany(x => x.Children)))
.Element("//subclass/bag").Exists();
}
[Test]
public void MapsHasManyToMany()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.HasManyToMany(x => x.Children)))
.Element("//subclass/bag").Exists();
}
[Test]
public void MapsHasOne()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.HasOne(x => x.Parent)))
.Element("//subclass/one-to-one").Exists();
}
[Test]
public void MapsReferences()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.References(x => x.Parent)))
.Element("//subclass/many-to-one").Exists();
}
[Test]
public void MapsReferencesAny()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc =>
sc.ReferencesAny(x => x.Parent)
.IdentityType(x => x.Id)
.EntityIdentifierColumn("col")
.EntityTypeColumn("col")))
.Element("//subclass/any").Exists();
}
[Test]
public void MapsSubSubclass()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc => sc.SubClass<SecondMappedObject>(sc2 => { })))
.Element("//subclass/subclass").Exists();
}
[Test]
public void SubSubclassIsLast()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<MappedObject>(sc =>
{
sc.SubClass<SecondMappedObject>(sc2 => { });
sc.Map(x => x.Name);
}))
.Element("//subclass/subclass").ShouldBeInParentAtPosition(1);
}
[Test]
public void SubclassShouldNotHaveDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn<string>("Type")
.SubClass<SecondMappedObject>("red", m =>
{
m.Map(x => x.Name);
m.SubClass<SecondMappedObject>("blue", m2 =>
{});
}))
.Element("//subclass/discriminator").DoesntExist();
}
[Test]
public void CreateDiscriminatorValueAtClassLevel()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type", "Foo")
.SubClass<SecondMappedObject>("Bar", m => m.Map(x => x.Name)))
.Element("class")
.HasAttribute("discriminator-value", "Foo");
}
[Test]
public void DiscriminatorAssumesStringIfNoTypeSupplied()
{
new MappingTester<MappedObject>()
.ForMapping(map => map.DiscriminateSubClassesOnColumn("Type"))
.Element("class/discriminator")
.HasAttribute("type", "String");
}
[Test]
public void CanSpecifyForceOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.AlwaysSelectWithValue())
.Element("class/discriminator")
.HasAttribute("force", "true");
}
[Test]
public void CanSpecifyNotForcedOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Not.AlwaysSelectWithValue())
.Element("class/discriminator")
.HasAttribute("force", "false");
}
[Test]
public void CanSpecifyReadOnlyOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.ReadOnly())
.Element("class/discriminator")
.HasAttribute("insert", "false");
}
[Test]
public void CanSpecifyNotReadOnlyOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Not.ReadOnly())
.Element("class/discriminator")
.HasAttribute("insert", "true");
}
[Test]
public void CanSpecifyNullableOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Nullable())
.Element("class/discriminator/column").HasAttribute("not-null", "false");
}
[Test]
public void CanSpecifyNotNullableOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Not.Nullable())
.Element("class/discriminator/column").HasAttribute("not-null", "true");
}
[Test]
public void CanSpecifyFormulaOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Formula("formula"))
.Element("class/discriminator")
.HasAttribute("formula", "formula");
}
[Test]
public void CanSpecifyLengthOnDiscriminator()
{
new MappingTester<MappedObject>()
.ForMapping(map =>
map.DiscriminateSubClassesOnColumn("Type")
.Length(1234))
.Element("class/discriminator/column")
.HasAttribute("length", "1234");
}
private class ProxyClass
{}
}
#pragma warning restore 612,618
}
| |
using System.Security;
using System.Security.Permissions;
namespace System.Windows.Threading
{
/// <summary>
/// Additional information provided about a dispatcher.
/// </summary>
public sealed class DispatcherHooks
{
/// <summary>
/// An event indicating the the dispatcher has no more operations to process.
/// </summary>
/// <remarks>
/// Note that this event will be raised by the dispatcher thread when
/// there is no more pending work to do.
/// <P/>
/// Note also that this event could come before the last operation is
/// invoked, because that is when we determine that the queue is empty.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _dispatcherInactive
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event EventHandler DispatcherInactive
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_dispatcherInactive += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_dispatcherInactive -= value;
}
}
}
/// <summary>
/// An event indicating that an operation was posted to the dispatcher.
/// </summary>
/// <remarks>
/// Typically this is due to the BeginInvoke API, but the Invoke API can
/// also cause this if any priority other than DispatcherPriority.Send is
/// specified, or if the destination dispatcher is owned by a different
/// thread.
/// <P/>
/// Note that any thread can post operations, so this event can be
/// raised by any thread.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _operationPosted
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event DispatcherHookEventHandler OperationPosted
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_operationPosted += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_operationPosted -= value;
}
}
}
/// <summary>
/// An event indicating that an operation is about to be invoked.
/// </summary>
/// <remarks>
/// Typically this is due to the BeginInvoke API, but the Invoke API can
/// also cause this if any priority other than DispatcherPriority.Send is
/// specified, or if the destination dispatcher is owned by a different
/// thread.
/// <P/>
/// Note that any thread can post operations, so this event can be
/// raised by any thread.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _operationPosted
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event DispatcherHookEventHandler OperationStarted
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_operationStarted += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_operationStarted -= value;
}
}
}
/// <summary>
/// An event indicating that an operation was completed.
/// </summary>
/// <remarks>
/// Note that with the new async model, operations can cooperate in
/// cancelation, and any exceptions are contained. This event is
/// raised in all cases. You need to check the status of both the
/// operation and the associated task to infer the final state.
///
/// Note that this event will be raised by the dispatcher thread after
/// the operation has completed.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _operationCompleted
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event DispatcherHookEventHandler OperationCompleted
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_operationCompleted += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_operationCompleted -= value;
}
}
}
/// <summary>
/// An event indicating that the priority of an operation was changed.
/// </summary>
/// <remarks>
/// Note that any thread can change the priority of operations,
/// so this event can be raised by any thread.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _operationPriorityChanged
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event DispatcherHookEventHandler OperationPriorityChanged
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_operationPriorityChanged += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_operationPriorityChanged -= value;
}
}
}
/// <summary>
/// An event indicating that an operation was aborted.
/// </summary>
/// <remarks>
/// Note that any thread can abort an operation, so this event
/// can be raised by any thread.
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: accesses _operationAborted
/// TreatAsSafe: link-demands
/// </SecurityNote>
public event DispatcherHookEventHandler OperationAborted
{
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
add
{
lock(_instanceLock)
{
_operationAborted += value;
}
}
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
remove
{
lock(_instanceLock)
{
_operationAborted -= value;
}
}
}
// Only we can create these things.
internal DispatcherHooks()
{
}
/// <SecurityNote>
/// Critical: accesses _operationAborted
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseDispatcherInactive(Dispatcher dispatcher)
{
EventHandler dispatcherInactive = _dispatcherInactive;
if(dispatcherInactive != null)
{
dispatcherInactive(dispatcher, EventArgs.Empty);
}
}
/// <SecurityNote>
/// Critical: accesses _operationPosted
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseOperationPosted(Dispatcher dispatcher, DispatcherOperation operation)
{
DispatcherHookEventHandler operationPosted = _operationPosted;
if(operationPosted != null)
{
operationPosted(dispatcher, new DispatcherHookEventArgs(operation));
}
}
/// <SecurityNote>
/// Critical: accesses _operationStarted
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseOperationStarted(Dispatcher dispatcher, DispatcherOperation operation)
{
DispatcherHookEventHandler operationStarted = _operationStarted;
if(operationStarted != null)
{
operationStarted(dispatcher, new DispatcherHookEventArgs(operation));
}
}
/// <SecurityNote>
/// Critical: accesses _operationCompleted
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseOperationCompleted(Dispatcher dispatcher, DispatcherOperation operation)
{
DispatcherHookEventHandler operationCompleted = _operationCompleted;
if(operationCompleted != null)
{
operationCompleted(dispatcher, new DispatcherHookEventArgs(operation));
}
}
/// <SecurityNote>
/// Critical: accesses _operationPriorityChanged
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseOperationPriorityChanged(Dispatcher dispatcher, DispatcherOperation operation)
{
DispatcherHookEventHandler operationPriorityChanged = _operationPriorityChanged;
if(operationPriorityChanged != null)
{
operationPriorityChanged(dispatcher, new DispatcherHookEventArgs(operation));
}
}
/// <SecurityNote>
/// Critical: accesses _operationAborted
/// TreatAsSafe: no exposure
/// </SecurityNote>
[SecurityCritical]
internal void RaiseOperationAborted(Dispatcher dispatcher, DispatcherOperation operation)
{
DispatcherHookEventHandler operationAborted = _operationAborted;
if(operationAborted != null)
{
operationAborted(dispatcher, new DispatcherHookEventArgs(operation));
}
}
private object _instanceLock = new object();
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private EventHandler _dispatcherInactive;
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private DispatcherHookEventHandler _operationPosted;
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private DispatcherHookEventHandler _operationStarted;
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private DispatcherHookEventHandler _operationCompleted;
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private DispatcherHookEventHandler _operationPriorityChanged;
/// <SecurityNote>
/// Do not expose to partially trusted code.
/// </SecurityNote>
[SecurityCritical]
private DispatcherHookEventHandler _operationAborted;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// ----------------------------------------------------------------------
// Contents: Entry points for managed PowerShell plugin worker used to
// host powershell in a WSMan service.
// ----------------------------------------------------------------------
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Internal;
using System.Globalization;
namespace System.Management.Automation.Remoting
{
// TODO: Does this comment still apply?
// The following complex delegate + native function pointer model is used
// because of a problem with GCRoot. GCRoots cannot hold reference to the
// AppDomain that created it. In the IIS hosting scenario, there may be
// cases where multiple AppDomains exist in the same hosting process. In such
// cases if GCRoot is used, CLR will pick up the first AppDomain in the list
// to get the managed handle. Delegates are not just function pointers, they
// also contain a reference to the AppDomain that created it. However the catch
// is that delegates must be marshalled into their respective unmanaged function
// pointers (otherwise we end up storing the delegate into a GCRoot).
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="extraInfo">PCWSTR.</param>
/// <param name="startupInfo">WSMAN_SHELL_STARTUP_INFO*.</param>
/// <param name="inboundShellInformation">WSMAN_DATA*.</param>
internal delegate void WSMPluginShellDelegate( // TODO: Rename to WSManPluginShellDelegate once I remove the MC++ module.
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
[MarshalAs(UnmanagedType.LPWStr)] string extraInfo,
IntPtr startupInfo,
IntPtr inboundShellInformation);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="shellContext">PVOID.</param>
internal delegate void WSMPluginReleaseShellContextDelegate(
IntPtr pluginContext,
IntPtr shellContext);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="inboundConnectInformation">WSMAN_DATA* optional.</param>
internal delegate void WSMPluginConnectDelegate(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr inboundConnectInformation);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandLine">PCWSTR.</param>
/// <param name="arguments">WSMAN_COMMAND_ARG_SET*.</param>
internal delegate void WSMPluginCommandDelegate(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
[MarshalAs(UnmanagedType.LPWStr)] string commandLine,
IntPtr arguments);
/// <summary>
/// Delegate that is passed to native layer for callback on operation shutdown notifications.
/// </summary>
/// <param name="shutdownContext">IntPtr.</param>
internal delegate void WSMPluginOperationShutdownDelegate(
IntPtr shutdownContext);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID.</param>
internal delegate void WSMPluginReleaseCommandContextDelegate(
IntPtr pluginContext,
IntPtr shellContext,
IntPtr commandContext);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID.</param>
/// <param name="stream">PCWSTR.</param>
/// <param name="inboundData">WSMAN_DATA*.</param>
internal delegate void WSMPluginSendDelegate(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
[MarshalAs(UnmanagedType.LPWStr)] string stream,
IntPtr inboundData);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="streamSet">WSMAN_STREAM_ID_SET* optional.</param>
internal delegate void WSMPluginReceiveDelegate(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr streamSet);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="code">PCWSTR.</param>
internal delegate void WSMPluginSignalDelegate(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
[MarshalAs(UnmanagedType.LPWStr)] string code);
/// <summary>
/// Callback that handles shell shutdown notification events.
/// </summary>
/// <param name="state"></param>
/// <param name="timedOut"></param>
internal delegate void WaitOrTimerCallbackDelegate(
IntPtr state,
bool timedOut);
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
internal delegate void WSMShutdownPluginDelegate(
IntPtr pluginContext);
/// <summary>
/// </summary>
internal sealed class WSManPluginEntryDelegates : IDisposable
{
#region Private Members
// Holds the delegate pointers in a structure that has identical layout to the native structure.
private WSManPluginEntryDelegatesInternal _unmanagedStruct = new WSManPluginEntryDelegatesInternal();
internal WSManPluginEntryDelegatesInternal UnmanagedStruct
{
get { return _unmanagedStruct; }
}
// Flag: Has Dispose already been called?
private bool _disposed = false;
/// <summary>
/// GC handle which prevents garbage collector from collecting this delegate.
/// </summary>
private GCHandle _pluginShellGCHandle;
private GCHandle _pluginReleaseShellContextGCHandle;
private GCHandle _pluginCommandGCHandle;
private GCHandle _pluginReleaseCommandContextGCHandle;
private GCHandle _pluginSendGCHandle;
private GCHandle _pluginReceiveGCHandle;
private GCHandle _pluginSignalGCHandle;
private GCHandle _pluginConnectGCHandle;
private GCHandle _shutdownPluginGCHandle;
private GCHandle _WSMPluginOperationShutdownGCHandle;
#endregion
#region Constructor
/// <summary>
/// Initializes the delegate struct for later use.
/// </summary>
internal WSManPluginEntryDelegates()
{
populateDelegates();
}
#endregion
#region IDisposable Methods
/// <summary>
/// Internal implementation of Dispose pattern callable by consumers.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
if (_disposed)
return;
// Free any unmanaged objects here.
this.CleanUpDelegates();
_disposed = true;
}
/// <summary>
/// Use C# destructor syntax for finalization code.
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~WSManPluginEntryDelegates()
{
Dispose(false);
}
#endregion IDisposable Methods
/// <summary>
/// Creates delegates and populates the managed version of the
/// structure that will be passed to unmanaged callers.
/// </summary>
private void populateDelegates()
{
// if a delegate is re-located by a garbage collection, it will not affect
// the underlaying managed callback, so Alloc is used to add a reference
// to the delegate, allowing relocation of the delegate, but preventing
// disposal. Using GCHandle without pinning reduces fragmentation potential
// of the managed heap.
{
WSMPluginShellDelegate pluginShell = new WSMPluginShellDelegate(WSManPluginManagedEntryWrapper.WSManPluginShell);
_pluginShellGCHandle = GCHandle.Alloc(pluginShell);
// marshal the delegate to a unmanaged function pointer so that AppDomain reference is stored correctly.
// Populate the outgoing structure so the caller has access to the entry points
_unmanagedStruct.wsManPluginShellCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShell);
}
{
WSMPluginReleaseShellContextDelegate pluginReleaseShellContext = new WSMPluginReleaseShellContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseShellContext);
_pluginReleaseShellContextGCHandle = GCHandle.Alloc(pluginReleaseShellContext);
_unmanagedStruct.wsManPluginReleaseShellContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseShellContext);
}
{
WSMPluginCommandDelegate pluginCommand = new WSMPluginCommandDelegate(WSManPluginManagedEntryWrapper.WSManPluginCommand);
_pluginCommandGCHandle = GCHandle.Alloc(pluginCommand);
_unmanagedStruct.wsManPluginCommandCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginCommand);
}
{
WSMPluginReleaseCommandContextDelegate pluginReleaseCommandContext = new WSMPluginReleaseCommandContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseCommandContext);
_pluginReleaseCommandContextGCHandle = GCHandle.Alloc(pluginReleaseCommandContext);
_unmanagedStruct.wsManPluginReleaseCommandContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseCommandContext);
}
{
WSMPluginSendDelegate pluginSend = new WSMPluginSendDelegate(WSManPluginManagedEntryWrapper.WSManPluginSend);
_pluginSendGCHandle = GCHandle.Alloc(pluginSend);
_unmanagedStruct.wsManPluginSendCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSend);
}
{
WSMPluginReceiveDelegate pluginReceive = new WSMPluginReceiveDelegate(WSManPluginManagedEntryWrapper.WSManPluginReceive);
_pluginReceiveGCHandle = GCHandle.Alloc(pluginReceive);
_unmanagedStruct.wsManPluginReceiveCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReceive);
}
{
WSMPluginSignalDelegate pluginSignal = new WSMPluginSignalDelegate(WSManPluginManagedEntryWrapper.WSManPluginSignal);
_pluginSignalGCHandle = GCHandle.Alloc(pluginSignal);
_unmanagedStruct.wsManPluginSignalCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSignal);
}
{
WSMPluginConnectDelegate pluginConnect = new WSMPluginConnectDelegate(WSManPluginManagedEntryWrapper.WSManPluginConnect);
_pluginConnectGCHandle = GCHandle.Alloc(pluginConnect);
_unmanagedStruct.wsManPluginConnectCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginConnect);
}
{
WSMShutdownPluginDelegate shutdownPlugin = new WSMShutdownPluginDelegate(WSManPluginManagedEntryWrapper.ShutdownPlugin);
_shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin);
_unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin);
}
if (!Platform.IsWindows)
{
WSMPluginOperationShutdownDelegate pluginShutDownDelegate = new WSMPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown);
_WSMPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate);
_unmanagedStruct.wsManPluginShutdownCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShutDownDelegate);
}
}
/// <summary>
/// </summary>
private void CleanUpDelegates()
{
// Free GCHandles so that the memory they point to may be unpinned (garbage collected)
if (_pluginShellGCHandle != null)
{
_pluginShellGCHandle.Free();
_pluginReleaseShellContextGCHandle.Free();
_pluginCommandGCHandle.Free();
_pluginReleaseCommandContextGCHandle.Free();
_pluginSendGCHandle.Free();
_pluginReceiveGCHandle.Free();
_pluginSignalGCHandle.Free();
_pluginConnectGCHandle.Free();
_shutdownPluginGCHandle.Free();
if (!Platform.IsWindows)
{
_WSMPluginOperationShutdownGCHandle.Free();
}
}
}
/// <summary>
/// Structure definition to match the native one.
/// NOTE: The layout of this structure must be IDENTICAL between here and PwrshPluginWkr_Ptrs in pwrshplugindefs.h!
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class WSManPluginEntryDelegatesInternal
{
/// <summary>
/// WsManPluginShutdownPluginCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginShutdownPluginCallbackNative;
/// <summary>
/// WSManPluginShellCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginShellCallbackNative;
/// <summary>
/// WSManPluginReleaseShellContextCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginReleaseShellContextCallbackNative;
/// <summary>
/// WSManPluginCommandCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginCommandCallbackNative;
/// <summary>
/// WSManPluginReleaseCommandContextCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginReleaseCommandContextCallbackNative;
/// <summary>
/// WSManPluginSendCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginSendCallbackNative;
/// <summary>
/// WSManPluginReceiveCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginReceiveCallbackNative;
/// <summary>
/// WSManPluginSignalCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginSignalCallbackNative;
/// <summary>
/// WSManPluginConnectCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginConnectCallbackNative;
/// <summary>
/// WSManPluginCommandCallbackNative.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr wsManPluginShutdownCallbackNative;
}
}
/// <summary>
/// Class containing the public static managed entry functions that are callable from outside
/// the module.
/// </summary>
public sealed class WSManPluginManagedEntryWrapper
{
/// <summary>
/// Constructor is private because it only contains static members and properties.
/// </summary>
private WSManPluginManagedEntryWrapper() { }
/// <summary>
/// Immutable container that holds the delegates and their unmanaged pointers.
/// </summary>
internal static WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates();
#region Managed Entry Points
/// <summary>
/// Called only once after the assembly is loaded..This is used to perform
/// various initializations.
/// </summary>
/// <param name="wkrPtrs">IntPtr to WSManPluginEntryDelegates.WSManPluginEntryDelegatesInternal.</param>
/// <returns>0 = Success, 1 = Failure.</returns>
public static int InitPlugin(
IntPtr wkrPtrs)
{
if (IntPtr.Zero == wkrPtrs)
{
return WSManPluginConstants.ExitCodeFailure;
}
#if !CORECLR
// For long-path support, Full .NET requires some AppContext switches;
// (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
// internally in .NET they are cached once retrieved and are typically hit very early during an application run;
// so per .NET team's recommendation, we are setting them as soon as we enter managed code.
// We build against CLR4.5 so we can run on Win7/Win8, but we want to use apis added to CLR 4.6, so we use reflection
try
{
Type appContextType = Type.GetType("System.AppContext"); // type is in mscorlib, so it is sufficient to supply the type name qualified by its namespace
object[] blockLongPathsSwitch = new object[] { "Switch.System.IO.BlockLongPaths", false };
object[] useLegacyPathHandlingSwitch = new object[] { "Switch.System.IO.UseLegacyPathHandling", false };
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, blockLongPathsSwitch, CultureInfo.InvariantCulture);
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, useLegacyPathHandlingSwitch, CultureInfo.InvariantCulture);
}
catch (Exception)
{
// If there are any non-critical exceptions (e.g. we are running on CLR prior to 4.6.2), we won't be able to use long paths
}
#endif
Marshal.StructureToPtr<WSManPluginEntryDelegates.WSManPluginEntryDelegatesInternal>(workerPtrs.UnmanagedStruct, wkrPtrs, false);
return WSManPluginConstants.ExitCodeSuccess;
}
/// <summary>
/// Called only once during shutdown. This is used to perform various deinitializations.
/// </summary>
/// <param name="pluginContext">PVOID.</param>
public static void ShutdownPlugin(
IntPtr pluginContext)
{
WSManPluginInstance.PerformShutdown(pluginContext);
if (workerPtrs != null)
{
workerPtrs.Dispose();
}
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="inboundConnectInformation">WSMAN_DATA* optional.</param>
public static void WSManPluginConnect(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr inboundConnectInformation)
{
if (IntPtr.Zero == pluginContext)
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"pluginContext",
"WSManPluginConnect")
);
return;
}
WSManPluginInstance.PerformWSManPluginConnect(pluginContext, requestDetails, flags, shellContext, commandContext, inboundConnectInformation);
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="extraInfo">PCWSTR.</param>
/// <param name="startupInfo">WSMAN_SHELL_STARTUP_INFO*.</param>
/// <param name="inboundShellInformation">WSMAN_DATA*.</param>
public static void WSManPluginShell(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
[MarshalAs(UnmanagedType.LPWStr)] string extraInfo,
IntPtr startupInfo,
IntPtr inboundShellInformation)
{
if (IntPtr.Zero == pluginContext)
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"pluginContext",
"WSManPluginShell")
);
return;
}
#if(DEBUG)
// In debug builds, allow remote runspaces to wait for debugger attach
if (Environment.GetEnvironmentVariable("__PSRemoteRunspaceWaitForDebugger", EnvironmentVariableTarget.Machine) != null)
{
bool debuggerAttached = false;
while (!debuggerAttached)
{
System.Threading.Thread.Sleep(100);
}
}
#endif
WSManPluginInstance.PerformWSManPluginShell(pluginContext, requestDetails, flags, extraInfo, startupInfo, inboundShellInformation);
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="shellContext">PVOID.</param>
public static void WSManPluginReleaseShellContext(
IntPtr pluginContext,
IntPtr shellContext)
{
// NO-OP..as our plugin does not own the memory related
// to shellContext and so there is nothing to release
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandLine">PCWSTR.</param>
/// <param name="arguments">WSMAN_COMMAND_ARG_SET* optional.</param>
public static void WSManPluginCommand(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
[MarshalAs(UnmanagedType.LPWStr)] string commandLine,
IntPtr arguments)
{
if (IntPtr.Zero == pluginContext)
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"Plugin Context",
"WSManPluginCommand")
);
return;
}
WSManPluginInstance.PerformWSManPluginCommand(pluginContext, requestDetails, flags, shellContext, commandLine, arguments);
}
/// <summary>
/// Operation shutdown notification that was registered with the native layer for each of the shellCreate operations.
/// </summary>
/// <param name="shutdownContext">IntPtr.</param>
public static void WSManPSShutdown(
IntPtr shutdownContext)
{
GCHandle gch = GCHandle.FromIntPtr(shutdownContext);
EventWaitHandle eventHandle = (EventWaitHandle)gch.Target;
eventHandle.Set();
gch.Free();
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID.</param>
public static void WSManPluginReleaseCommandContext(
IntPtr pluginContext,
IntPtr shellContext,
IntPtr commandContext)
{
// NO-OP..as our plugin does not own the memory related
// to commandContext and so there is nothing to release.
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID.</param>
/// <param name="stream">PCWSTR.</param>
/// <param name="inboundData">WSMAN_DATA*.</param>
public static void WSManPluginSend(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
[MarshalAs(UnmanagedType.LPWStr)] string stream,
IntPtr inboundData)
{
if (IntPtr.Zero == pluginContext)
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"Plugin Context",
"WSManPluginSend")
);
return;
}
WSManPluginInstance.PerformWSManPluginSend(pluginContext, requestDetails, flags, shellContext, commandContext, stream, inboundData);
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="streamSet">WSMAN_STREAM_ID_SET* optional.</param>
public static void WSManPluginReceive(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
IntPtr streamSet)
{
if (IntPtr.Zero == pluginContext)
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"Plugin Context",
"WSManPluginReceive")
);
return;
}
WSManPluginInstance.PerformWSManPluginReceive(pluginContext, requestDetails, flags, shellContext, commandContext, streamSet);
}
/// <summary>
/// </summary>
/// <param name="pluginContext">PVOID.</param>
/// <param name="requestDetails">WSMAN_PLUGIN_REQUEST*.</param>
/// <param name="flags">DWORD.</param>
/// <param name="shellContext">PVOID.</param>
/// <param name="commandContext">PVOID optional.</param>
/// <param name="code">PCWSTR.</param>
public static void WSManPluginSignal(
IntPtr pluginContext,
IntPtr requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
[MarshalAs(UnmanagedType.LPWStr)] string code)
{
if ((IntPtr.Zero == pluginContext) || (IntPtr.Zero == shellContext))
{
WSManPluginInstance.ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullPluginContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullPluginContext,
"Plugin Context",
"WSManPluginSignal")
);
return;
}
WSManPluginInstance.PerformWSManPluginSignal(pluginContext, requestDetails, flags, shellContext, commandContext, code);
}
/// <summary>
/// Callback used to register with thread pool to notify when a plugin operation shuts down.
/// Conforms to:
/// public delegate void WaitOrTimerCallback( Object state, bool timedOut )
/// </summary>
/// <param name="operationContext">PVOID.</param>
/// <param name="timedOut">BOOLEAN.</param>
/// <returns></returns>
public static void PSPluginOperationShutdownCallback(
object operationContext,
bool timedOut)
{
if (operationContext == null)
{
return;
}
WSManPluginOperationShutdownContext context = (WSManPluginOperationShutdownContext)operationContext;
context.isShuttingDown = true;
WSManPluginInstance.PerformCloseOperation(context);
}
#endregion
}
/// <summary>
/// This is a thin wrapper around WSManPluginManagedEntryWrapper.InitPlugin()
/// so that it can be called from native COM code in a non-static context.
///
/// This was done to get around an FXCop error: AvoidStaticMembersInComVisibleTypes.
/// </summary>
public sealed class WSManPluginManagedEntryInstanceWrapper : IDisposable
{
#region IDisposable
// Flag: Has Dispose already been called?
private bool _disposed = false;
/// <summary>
/// Internal implementation of Dispose pattern callable by consumers.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
if (_disposed)
return;
// Free any unmanaged objects here.
_initDelegateHandle.Free();
_disposed = true;
}
/// <summary>
/// Use C# destructor syntax for finalization code.
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~WSManPluginManagedEntryInstanceWrapper()
{
Dispose(false);
}
#endregion
#region Delegate Handling
/// <summary>
/// Matches signature for WSManPluginManagedEntryWrapper.InitPlugin.
/// </summary>
/// <param name="wkrPtrs"></param>
/// <returns></returns>
private delegate int InitPluginDelegate(
IntPtr wkrPtrs);
/// <summary>
/// Prevents the delegate object from being garbage collected so it can be passed to the native code.
/// </summary>
private GCHandle _initDelegateHandle;
/// <summary>
/// Entry point for native code that cannot call static methods.
/// </summary>
/// <returns>A function pointer for the static entry point for the WSManPlugin initialization function.</returns>
public IntPtr GetEntryDelegate()
{
InitPluginDelegate initDelegate = new InitPluginDelegate(WSManPluginManagedEntryWrapper.InitPlugin);
_initDelegateHandle = GCHandle.Alloc(initDelegate);
return Marshal.GetFunctionPointerForDelegate(initDelegate);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AppendBlobWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Blob.Protocol;
internal sealed class AppendBlobWriter : TransferReaderWriterBase
{
private volatile State state;
private volatile bool hasWork;
private AzureBlobLocation destLocation;
private CloudAppendBlob appendBlob;
private long expectedOffset = 0;
/// <summary>
/// To indicate whether the destination already exist before this writing.
/// If no, when try to set destination's attribute, should get its attributes first.
/// </summary>
private bool destExist = false;
public AppendBlobWriter(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.destLocation = this.SharedTransferData.TransferJob.Destination as AzureBlobLocation;
this.appendBlob = this.destLocation.Blob as CloudAppendBlob;
Debug.Assert(null != this.appendBlob, "The destination is not an append blob while initializing a AppendBlobWriter instance.");
this.state = State.FetchAttributes;
this.hasWork = true;
}
public override bool HasWork
{
get
{
return this.hasWork &&
((State.FetchAttributes == this.state) ||
(State.Create == this.state) ||
(State.UploadBlob == this.state && this.SharedTransferData.AvailableData.ContainsKey(this.expectedOffset)) ||
(State.Commit == this.state && null != this.SharedTransferData.Attributes));
}
}
public override bool IsFinished
{
get
{
return State.Error == this.state || State.Finished == this.state;
}
}
private enum State
{
FetchAttributes,
Create,
UploadBlob,
Commit,
Error,
Finished
};
public override async Task DoWorkInternalAsync()
{
switch (this.state)
{
case State.FetchAttributes:
await this.FetchAttributesAsync();
break;
case State.Create:
await this.CreateAsync();
break;
case State.UploadBlob:
await this.UploadBlobAsync();
break;
case State.Commit:
await this.CommitAsync();
break;
case State.Error:
default:
break;
}
}
private async Task FetchAttributesAsync()
{
Debug.Assert(
this.state == State.FetchAttributes,
"FetchAttributesAsync called, but state isn't FetchAttributes",
"Current state is {0}",
this.state);
this.hasWork = false;
if (this.SharedTransferData.TotalLength > Constants.MaxBlockBlobFileSize)
{
string exceptionMessage = string.Format(
CultureInfo.CurrentCulture,
Resources.BlobFileSizeTooLargeException,
Utils.BytesToHumanReadableSize(this.SharedTransferData.TotalLength),
Resources.AppendBlob,
Utils.BytesToHumanReadableSize(Constants.MaxBlockBlobFileSize));
throw new TransferException(
TransferErrorCode.UploadSourceFileSizeTooLarge,
exceptionMessage);
}
bool existingBlob = !this.Controller.IsForceOverwrite;
if (!this.Controller.IsForceOverwrite)
{
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
this.destLocation.CheckedAccessCondition);
try
{
await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
this.destExist = true;
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception e) when (e is StorageException || e.InnerException is StorageException)
{
var se = e as StorageException ?? e.InnerException as StorageException;
#else
catch (StorageException se)
{
#endif
// Getting a storage exception is expected if the blob doesn't
// exist. In this case we won't error out, but set the
// existingBlob flag to false to indicate we're uploading
// a new blob instead of overwriting an existing blob.
if (null != se.RequestInformation &&
se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
existingBlob = false;
}
else if (null != se &&
(0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase)))
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch);
}
else
{
throw;
}
}
}
this.HandleFetchAttributesResult(existingBlob);
}
private void HandleFetchAttributesResult(bool existingBlob)
{
this.destLocation.CheckedAccessCondition = true;
if (!this.Controller.IsForceOverwrite)
{
// If destination file exists, query user whether to overwrite it.
this.Controller.CheckOverwrite(
existingBlob,
this.SharedTransferData.TransferJob.Source.Instance,
this.appendBlob);
}
this.Controller.UpdateProgressAddBytesTransferred(0);
if (existingBlob)
{
if (this.appendBlob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (this.appendBlob.Properties.BlobType != BlobType.AppendBlob)
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch);
}
}
// We do check point consistency validation in reader, so directly use it here.
SingleObjectCheckpoint checkpoint = this.SharedTransferData.TransferJob.CheckPoint;
if ((null != checkpoint.TransferWindow)
&& (checkpoint.TransferWindow.Any()))
{
checkpoint.TransferWindow.Sort();
this.expectedOffset = checkpoint.TransferWindow[0];
}
else
{
this.expectedOffset = checkpoint.EntryTransferOffset;
}
if (0 == this.expectedOffset)
{
this.state = State.Create;
}
else
{
if (!this.Controller.IsForceOverwrite && !existingBlob)
{
throw new TransferException(Resources.DestinationChangedException);
}
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
}
this.hasWork = true;
}
private async Task CreateAsync()
{
Debug.Assert(State.Create == this.state, "Calling CreateAsync, state should be Create");
this.hasWork = false;
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
true);
await this.appendBlob.CreateOrReplaceAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions, true),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
this.hasWork = true;
}
private async Task UploadBlobAsync()
{
Debug.Assert(State.UploadBlob == this.state, "Calling UploadBlobAsync, state should be UploadBlob");
this.hasWork = false;
TransferData transferData = null;
if (!this.SharedTransferData.AvailableData.TryRemove(this.expectedOffset, out transferData))
{
this.hasWork = true;
return;
}
if (null != transferData)
{
using (transferData)
{
long currentOffset = this.expectedOffset;
this.expectedOffset += transferData.Length;
transferData.Stream = new MemoryStream(transferData.MemoryBuffer, 0, transferData.Length);
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true) ?? new AccessCondition();
accessCondition.IfAppendPositionEqual = currentOffset;
bool needToCheckContent = false;
try
{
await this.appendBlob.AppendBlockAsync(transferData.Stream,
null,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception e) when (e is StorageException || e.InnerException is StorageException)
{
var se = e as StorageException ?? e.InnerException as StorageException;
#else
catch (StorageException se)
{
#endif
if ((null != se.RequestInformation) &&
((int)HttpStatusCode.PreconditionFailed == se.RequestInformation.HttpStatusCode) &&
(null != se.RequestInformation.ExtendedErrorInformation) &&
(se.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition))
{
needToCheckContent = true;
}
else
{
throw;
}
}
if (needToCheckContent &&
(!await this.ValidateUploadedChunkAsync(transferData.MemoryBuffer, currentOffset, (long)transferData.Length)))
{
throw new InvalidOperationException(Resources.DestinationChangedException);
}
this.Controller.UpdateProgress(() =>
{
lock (this.SharedTransferData.TransferJob.CheckPoint.TransferWindowLock)
{
this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Remove(currentOffset);
}
this.SharedTransferData.TransferJob.Transfer.UpdateJournal();
// update progress
this.Controller.UpdateProgressAddBytesTransferred(transferData.Length);
});
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
this.hasWork = true;
}
}
}
private async Task CommitAsync()
{
Debug.Assert(State.Commit == this.state, "Calling CommitAsync, state should be Commit");
this.hasWork = false;
BlobRequestOptions blobRequestOptions = Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
if (!this.Controller.IsForceOverwrite && !this.destExist)
{
await this.appendBlob.FetchAttributesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
}
var originalMetadata = new Dictionary<string, string>(this.appendBlob.Metadata);
Utils.SetAttributes(this.appendBlob, this.SharedTransferData.Attributes);
await this.Controller.SetCustomAttributesAsync(this.appendBlob);
await this.appendBlob.SetPropertiesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
if (!originalMetadata.DictionaryEquals(this.appendBlob.Metadata))
{
await this.appendBlob.SetMetadataAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
}
this.SetFinish();
}
private async Task<bool> ValidateUploadedChunkAsync(byte[] currentData, long startOffset, long length)
{
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
this.destExist = true;
if (this.appendBlob.Properties.Length != (startOffset + length))
{
return false;
}
byte[] buffer = new byte[length];
// Do not expect any exception here.
await this.appendBlob.DownloadRangeToByteArrayAsync(
buffer,
0,
startOffset,
length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
for (int i = 0; i < length; ++i)
{
if (currentData[i] != buffer[i])
{
return false;
}
}
return true;
}
private void SetFinish()
{
this.state = State.Finished;
this.NotifyFinished(null);
this.hasWork = false;
}
}
}
| |
using GeckoUBL.Ubl21.Udt;
namespace GeckoUBL.Ubl21.Cac
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("ChildConsignment", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
public class ConsignmentType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType CarrierAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ConsigneeAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ConsignorAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType FreightForwarderAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType BrokerAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ContractedCarrierAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType PerformingCarrierAssignedID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SummaryDescription", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] SummaryDescription { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType TotalInvoiceAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType DeclaredCustomsValueAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TariffDescription", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] TariffDescription { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType TariffCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType InsurancePremiumAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType GrossWeightMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType NetWeightMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType NetNetWeightMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType ChargeableWeightMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType GrossVolumeMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType NetVolumeMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public MeasureType LoadingLengthMeasure { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Remarks", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] Remarks { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType HazardousRiskIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType AnimalFoodIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType HumanFoodIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType LivestockIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType BulkCargoIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType ContainerizedIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType GeneralCargoIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType SpecialSecurityIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType ThirdPartyPayerIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("CarrierServiceInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] CarrierServiceInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("CustomsClearanceServiceInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] CustomsClearanceServiceInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ForwarderServiceInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] ForwarderServiceInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SpecialServiceInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] SpecialServiceInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType SequenceID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType ShippingPriorityLevelCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType HandlingCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("HandlingInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] HandlingInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Information", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] Information { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType TotalGoodsItemQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType TotalTransportHandlingUnitQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType InsuranceValueAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType DeclaredForCarriageValueAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType DeclaredStatisticsValueAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public AmountType FreeOnBoardValueAmount { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("SpecialInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] SpecialInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType SplitConsignmentIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DeliveryInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] DeliveryInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType ConsignmentQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType ConsolidatableIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("HaulageInstructions", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] HaulageInstructions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType LoadingSequenceID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType ChildConsignmentQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType TotalPackagesQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ConsolidatedShipment")]
public ShipmentType[] ConsolidatedShipment { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("CustomsDeclaration")]
public CustomsDeclarationType[] CustomsDeclaration { get; set; }
/// <remarks/>
public TransportEventType RequestedPickupTransportEvent { get; set; }
/// <remarks/>
public TransportEventType RequestedDeliveryTransportEvent { get; set; }
/// <remarks/>
public TransportEventType PlannedPickupTransportEvent { get; set; }
/// <remarks/>
public TransportEventType PlannedDeliveryTransportEvent { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Status")]
public StatusType[] Status { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ChildConsignment")]
public ConsignmentType[] ChildConsignment { get; set; }
/// <remarks/>
public PartyType ConsigneeParty { get; set; }
/// <remarks/>
public PartyType ExporterParty { get; set; }
/// <remarks/>
public PartyType ConsignorParty { get; set; }
/// <remarks/>
public PartyType ImporterParty { get; set; }
/// <remarks/>
public PartyType CarrierParty { get; set; }
/// <remarks/>
public PartyType FreightForwarderParty { get; set; }
/// <remarks/>
public PartyType NotifyParty { get; set; }
/// <remarks/>
public PartyType OriginalDespatchParty { get; set; }
/// <remarks/>
public PartyType FinalDeliveryParty { get; set; }
/// <remarks/>
public PartyType PerformingCarrierParty { get; set; }
/// <remarks/>
public PartyType SubstituteCarrierParty { get; set; }
/// <remarks/>
public PartyType LogisticsOperatorParty { get; set; }
/// <remarks/>
public PartyType TransportAdvisorParty { get; set; }
/// <remarks/>
public PartyType HazardousItemNotificationParty { get; set; }
/// <remarks/>
public PartyType InsuranceParty { get; set; }
/// <remarks/>
public PartyType MortgageHolderParty { get; set; }
/// <remarks/>
public PartyType BillOfLadingHolderParty { get; set; }
/// <remarks/>
public CountryType OriginalDepartureCountry { get; set; }
/// <remarks/>
public CountryType FinalDestinationCountry { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TransitCountry")]
public CountryType[] TransitCountry { get; set; }
/// <remarks/>
public ContractType TransportContract { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TransportEvent")]
public TransportEventType[] TransportEvent { get; set; }
/// <remarks/>
public TransportationServiceType OriginalDespatchTransportationService { get; set; }
/// <remarks/>
public TransportationServiceType FinalDeliveryTransportationService { get; set; }
/// <remarks/>
public DeliveryTermsType DeliveryTerms { get; set; }
/// <remarks/>
public PaymentTermsType PaymentTerms { get; set; }
/// <remarks/>
public PaymentTermsType CollectPaymentTerms { get; set; }
/// <remarks/>
public PaymentTermsType DisbursementPaymentTerms { get; set; }
/// <remarks/>
public PaymentTermsType PrepaidPaymentTerms { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("FreightAllowanceCharge")]
public AllowanceChargeType[] FreightAllowanceCharge { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ExtraAllowanceCharge")]
public AllowanceChargeType[] ExtraAllowanceCharge { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("MainCarriageShipmentStage")]
public ShipmentStageType[] MainCarriageShipmentStage { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PreCarriageShipmentStage")]
public ShipmentStageType[] PreCarriageShipmentStage { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("OnCarriageShipmentStage")]
public ShipmentStageType[] OnCarriageShipmentStage { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TransportHandlingUnit")]
public TransportHandlingUnitType[] TransportHandlingUnit { get; set; }
/// <remarks/>
public LocationType1 FirstArrivalPortLocation { get; set; }
/// <remarks/>
public LocationType1 LastExitPortLocation { get; set; }
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using RedditSharp.Things;
using System.Collections.Generic;
namespace RedditSharp
{
/// <summary>
/// Class to communicate with Reddit.com
/// </summary>
public class Reddit
{
#region Constant Urls
private const string SslLoginUrl = "https://ssl.reddit.com/api/login";
private const string LoginUrl = "/api/login/username";
private const string UserInfoUrl = "/user/{0}/about.json";
private const string MeUrl = "/api/me.json";
private const string OAuthMeUrl = "/api/v1/me.json";
private const string SubredditAboutUrl = "/r/{0}/about.json";
private const string ComposeMessageUrl = "/api/compose";
private const string RegisterAccountUrl = "/api/register";
private const string GetThingUrl = "/api/info.json?id={0}";
private const string GetCommentUrl = "/r/{0}/comments/{1}/foo/{2}.json";
private const string GetPostUrl = "{0}.json";
private const string DomainUrl = "www.reddit.com";
private const string OAuthDomainUrl = "oauth.reddit.com";
private const string SearchUrl = "/search.json?q={0}&restrict_sr=off&sort={1}&t={2}";
private const string UrlSearchPattern = "url:'{0}'";
#endregion
#region Static Variables
static Reddit()
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = WebAgent.RateLimitMode.Pace;
WebAgent.Protocol = "http";
WebAgent.RootDomain = "www.reddit.com";
}
#endregion
internal readonly IWebAgent _webAgent;
/// <summary>
/// Captcha solver instance to use when solving captchas.
/// </summary>
public ICaptchaSolver CaptchaSolver;
/// <summary>
/// The authenticated user for this instance.
/// </summary>
public AuthenticatedUser User { get; set; }
/// <summary>
/// Sets the Rate Limiting Mode of the underlying WebAgent
/// </summary>
public WebAgent.RateLimitMode RateLimit
{
get { return WebAgent.RateLimit; }
set { WebAgent.RateLimit = value; }
}
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
/// Gets the FrontPage using the current Reddit instance.
/// </summary>
public Subreddit FrontPage
{
get { return Subreddit.GetFrontPage(this); }
}
/// <summary>
/// Gets /r/All using the current Reddit instance.
/// </summary>
public Subreddit RSlashAll
{
get { return Subreddit.GetRSlashAll(this); }
}
public Reddit()
{
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
_webAgent = new WebAgent();
CaptchaSolver = new ConsoleCaptchaSolver();
}
public Reddit(WebAgent.RateLimitMode limitMode) : this()
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = limitMode;
WebAgent.RootDomain = "www.reddit.com";
}
public Reddit(string username, string password, bool useSsl = true) : this()
{
LogIn(username, password, useSsl);
}
public Reddit(string accessToken) : this()
{
WebAgent.Protocol = "https";
WebAgent.RootDomain = OAuthDomainUrl;
_webAgent.AccessToken = accessToken;
InitOrUpdateUser();
}
/// <summary>
/// Logs in the current Reddit instance.
/// </summary>
/// <param name="username">The username of the user to log on to.</param>
/// <param name="password">The password of the user to log on to.</param>
/// <param name="useSsl">Whether to use SSL or not. (default: true)</param>
/// <returns></returns>
public AuthenticatedUser LogIn(string username, string password, bool useSsl = true)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
_webAgent.Cookies = new CookieContainer();
HttpWebRequest request;
if (useSsl)
request = _webAgent.CreatePost(SslLoginUrl);
else
request = _webAgent.CreatePost(LoginUrl);
var stream = request.GetRequestStream();
if (useSsl)
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json"
});
}
else
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json",
op = "login"
});
}
stream.Close();
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result)["json"];
if (json["errors"].Count() != 0)
throw new AuthenticationException("Incorrect login.");
InitOrUpdateUser();
return User;
}
public RedditUser GetUser(string name)
{
var request = _webAgent.CreateGet(string.Format(UserInfoUrl, name));
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new RedditUser().Init(this, json, _webAgent);
}
/// <summary>
/// Initializes the User property if it's null,
/// otherwise replaces the existing user object
/// with a new one fetched from reddit servers.
/// </summary>
public void InitOrUpdateUser()
{
var request = _webAgent.CreateGet(string.IsNullOrEmpty(_webAgent.AccessToken) ? MeUrl : OAuthMeUrl);
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
User = new AuthenticatedUser().Init(this, json, _webAgent);
}
#region Obsolete Getter Methods
[Obsolete("Use User property instead")]
public AuthenticatedUser GetMe()
{
return User;
}
#endregion Obsolete Getter Methods
public Subreddit GetSubreddit(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
return GetThing<Subreddit>(string.Format(SubredditAboutUrl, name));
}
public List<Post> GetMultireddit(string path)
{
var url = string.Format("http://www.reddit.com/{0}.json", path);
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var jk = JToken.Parse(data);
var json = jk["data"]["children"].ToArray();
var lists = new List<Post>();
foreach (var item in json)
{
lists.Add(new Post().Init(this, item, _webAgent));
}
return lists;
}
public Domain GetDomain(string domain)
{
if (!domain.StartsWith("http://") && !domain.StartsWith("https://"))
domain = "http://" + domain;
var uri = new Uri(domain);
return new Domain(this, uri, _webAgent);
}
public JToken GetToken(Uri uri)
{
var url = uri.AbsoluteUri;
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
var request = _webAgent.CreateGet(string.Format(GetPostUrl, url));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return json[0]["data"]["children"].First;
}
public Post GetPost(Uri uri)
{
return new Post().Init(this, GetToken(uri), _webAgent);
}
public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "")
{
if (User == null)
throw new Exception("User can not be null.");
var request = _webAgent.CreatePost(ComposeMessageUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
subject,
text = body,
to,
uh = User.Modhash,
iden = captchaId,
captcha = captchaAnswer
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
ICaptchaSolver solver = CaptchaSolver; // Prevent race condition
if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
{
captchaId = json["json"]["captcha"].ToString();
CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));
if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer);
}
}
/// <summary>
/// Registers a new Reddit user
/// </summary>
/// <param name="userName">The username for the new account.</param>
/// <param name="passwd">The password for the new account.</param>
/// <param name="email">The optional recovery email for the new account.</param>
/// <returns>The newly created user account</returns>
public AuthenticatedUser RegisterAccount(string userName, string passwd, string email = "")
{
var request = _webAgent.CreatePost(RegisterAccountUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
email = email,
passwd = passwd,
passwd2 = passwd,
user = userName
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new AuthenticatedUser().Init(this, json, _webAgent);
// TODO: Error
}
public Thing GetThingByFullname(string fullname)
{
var request = _webAgent.CreateGet(string.Format(GetThingUrl, fullname));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json["data"]["children"][0], _webAgent);
}
public Comment GetComment(string subreddit, string name, string linkName)
{
try
{
if (linkName.StartsWith("t3_"))
linkName = linkName.Substring(3);
if (name.StartsWith("t1_"))
name = name.Substring(3);
var request = _webAgent.CreateGet(string.Format(GetCommentUrl, subreddit, linkName, name));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json[1]["data"]["children"][0], _webAgent) as Comment;
}
catch (WebException)
{
return null;
}
}
public Listing<T> SearchByUrl<T>(string url) where T : Thing
{
var urlSearchQuery = string.Format(UrlSearchPattern, url);
return Search<T>(urlSearchQuery);
}
public Listing<T> Search<T>(string query) where T : Thing
{
return new Listing<T>(this, string.Format(SearchUrl, query, "relevance", "all"), _webAgent);
}
#region Helpers
protected internal T GetThing<T>(string url) where T : Thing
{
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return (T)Thing.Parse(this, json, _webAgent);
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class FileManager {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// MessageBoxUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel MessageBoxUpdatePanel;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// gvFilesID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal gvFilesID;
/// <summary>
/// cmdUpload control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdUpload;
/// <summary>
/// Img1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Img1;
/// <summary>
/// locUpload control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locUpload;
/// <summary>
/// cmdCreateFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdCreateFile;
/// <summary>
/// Img2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Img2;
/// <summary>
/// locCreateFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCreateFile;
/// <summary>
/// cmdCreateFolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdCreateFolder;
/// <summary>
/// Img3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Img3;
/// <summary>
/// locCreateFolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCreateFolder;
/// <summary>
/// Image8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image8;
/// <summary>
/// cmdCreateAccessDB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdCreateAccessDB;
/// <summary>
/// Image2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image2;
/// <summary>
/// locCreateAccessDB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCreateAccessDB;
/// <summary>
/// Image9 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image9;
/// <summary>
/// cmdZipFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdZipFiles;
/// <summary>
/// Image3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image3;
/// <summary>
/// locZip control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locZip;
/// <summary>
/// cmdUnzipFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdUnzipFiles;
/// <summary>
/// Image4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image4;
/// <summary>
/// locUnzip control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locUnzip;
/// <summary>
/// Image10 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image10;
/// <summary>
/// cmdCopyFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdCopyFiles;
/// <summary>
/// Image5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image5;
/// <summary>
/// locCopy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCopy;
/// <summary>
/// cmdMoveFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdMoveFiles;
/// <summary>
/// Image6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image6;
/// <summary>
/// locMove control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMove;
/// <summary>
/// cmdDeleteFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton cmdDeleteFiles;
/// <summary>
/// Image7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image7;
/// <summary>
/// locDelete control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDelete;
/// <summary>
/// UploadFilePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel UploadFilePanel;
/// <summary>
/// fileUpload1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload fileUpload1;
/// <summary>
/// fileUpload2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload fileUpload2;
/// <summary>
/// fileUpload3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload fileUpload3;
/// <summary>
/// fileUpload4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload fileUpload4;
/// <summary>
/// fileUpload5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload fileUpload5;
/// <summary>
/// btnUpload control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnUpload;
/// <summary>
/// btnCancelUpload control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelUpload;
/// <summary>
/// UploadModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender UploadModal;
/// <summary>
/// CopyFilesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel CopyFilesPanel;
/// <summary>
/// lblDestinationFolder1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDestinationFolder1;
/// <summary>
/// copyDestination control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileLookup copyDestination;
/// <summary>
/// btnCopy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCopy;
/// <summary>
/// btnCancelCopy control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelCopy;
/// <summary>
/// CopyFilesModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender CopyFilesModal;
/// <summary>
/// MoveFilesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel MoveFilesPanel;
/// <summary>
/// lblDestinationFolder2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDestinationFolder2;
/// <summary>
/// moveDestination control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileLookup moveDestination;
/// <summary>
/// btnMove control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnMove;
/// <summary>
/// btnCancelMove control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelMove;
/// <summary>
/// MoveFilesModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender MoveFilesModal;
/// <summary>
/// CreateFilePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel CreateFilePanel;
/// <summary>
/// lblFileName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFileName;
/// <summary>
/// txtFileName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileNameControl txtFileName;
/// <summary>
/// lblFileContentOptional control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFileContentOptional;
/// <summary>
/// txtFileContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFileContent;
/// <summary>
/// btnCreateFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCreateFile;
/// <summary>
/// btnCancelCreateFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelCreateFile;
/// <summary>
/// CreateFileModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender CreateFileModal;
/// <summary>
/// CreateFolderPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel CreateFolderPanel;
/// <summary>
/// lblFolderName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFolderName;
/// <summary>
/// txtFolderName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileNameControl txtFolderName;
/// <summary>
/// btnCreateFolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCreateFolder;
/// <summary>
/// btnCancelCreateFolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelCreateFolder;
/// <summary>
/// CreateFolderModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender CreateFolderModal;
/// <summary>
/// ZipFilesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ZipFilesPanel;
/// <summary>
/// lblZIPArchiveName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblZIPArchiveName;
/// <summary>
/// txtZipName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileNameControl txtZipName;
/// <summary>
/// btnZip control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnZip;
/// <summary>
/// btnCancelZip control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelZip;
/// <summary>
/// ZipFilesModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender ZipFilesModal;
/// <summary>
/// CreateDatabasePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel CreateDatabasePanel;
/// <summary>
/// lblDatabaseName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDatabaseName;
/// <summary>
/// txtDatabaseName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileNameControl txtDatabaseName;
/// <summary>
/// btnCreateDatabase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCreateDatabase;
/// <summary>
/// btnCancelCreateDatabase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelCreateDatabase;
/// <summary>
/// CreateDatabaseModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender CreateDatabaseModal;
/// <summary>
/// DeleteFilesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel DeleteFilesPanel;
/// <summary>
/// lblDeleteConfirmation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDeleteConfirmation;
/// <summary>
/// btnDeleteFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnDeleteFiles;
/// <summary>
/// btnCancelDeleteFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelDeleteFiles;
/// <summary>
/// DeleteFilesModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender DeleteFilesModal;
/// <summary>
/// FilesUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel FilesUpdatePanel;
/// <summary>
/// Image1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image1;
/// <summary>
/// path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Repeater path;
/// <summary>
/// filesProgress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdateProgress filesProgress;
/// <summary>
/// selectAll control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox selectAll;
/// <summary>
/// locFileName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locFileName;
/// <summary>
/// locSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locSize;
/// <summary>
/// locModified control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locModified;
/// <summary>
/// gvFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvFiles;
/// <summary>
/// litPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litPath;
/// <summary>
/// odsFilesPaged control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ObjectDataSource odsFilesPaged;
/// <summary>
/// EditFilePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel EditFilePanel;
/// <summary>
/// lblFileEncoding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFileEncoding;
/// <summary>
/// ddlFileEncodings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlFileEncodings;
/// <summary>
/// lblFileContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFileContent;
/// <summary>
/// txtEditFileContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtEditFileContent;
/// <summary>
/// btnSaveEditFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSaveEditFile;
/// <summary>
/// btnCancelEditFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelEditFile;
/// <summary>
/// btnEditFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnEditFile;
/// <summary>
/// EditFileModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender EditFileModal;
/// <summary>
/// RenameFilePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel RenameFilePanel;
/// <summary>
/// lblNewName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblNewName;
/// <summary>
/// txtRenameFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.FileNameControl txtRenameFile;
/// <summary>
/// btnRename control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnRename;
/// <summary>
/// btnCancelRename control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelRename;
/// <summary>
/// btnRenameFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnRenameFile;
/// <summary>
/// RenameFileModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender RenameFileModal;
/// <summary>
/// PermissionsFilePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PermissionsFilePanel;
/// <summary>
/// gvFilePermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvFilePermissions;
/// <summary>
/// chkReplaceChildPermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkReplaceChildPermissions;
/// <summary>
/// btnSetPermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSetPermissions;
/// <summary>
/// btnCancelPermissions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelPermissions;
/// <summary>
/// btnSetPermissionsFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSetPermissionsFile;
/// <summary>
/// PermissionsFileModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender PermissionsFileModal;
/// <summary>
/// lblDiskSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblDiskSpace;
/// <summary>
/// Quota1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.Quota Quota1;
/// <summary>
/// btnRecalcDiskspace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnRecalcDiskspace;
}
}
| |
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsCompositeBoolIntClient
{
using System.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for IntModel.
/// </summary>
public static partial class IntModelExtensions
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetNull(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<int?> GetNullAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetInvalid(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<int?> GetInvalidAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetOverflowInt32(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<int?> GetOverflowInt32Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetUnderflowInt32(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<int?> GetUnderflowInt32Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetOverflowInt64(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<long?> GetOverflowInt64Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetUnderflowInt64(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<long?> GetUnderflowInt64Async(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax32(this IIntModel operations, int intBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutMax32Async(this IIntModel operations, int intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax64(this IIntModel operations, long intBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutMax64Async(this IIntModel operations, long intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin32(this IIntModel operations, int intBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutMin32Async(this IIntModel operations, int intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin64(this IIntModel operations, long intBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutMin64Async(this IIntModel operations, long intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUnixTime(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.DateTime?> GetUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutUnixTimeDate(this IIntModel operations, System.DateTime intBody)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PutUnixTimeDateAsync(this IIntModel operations, System.DateTime intBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetInvalidUnixTime(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.DateTime?> GetInvalidUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetNullUnixTime(this IIntModel operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.DateTime?> GetNullUnixTimeAsync(this IIntModel operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Dataload
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Datastream;
using NUnit.Framework;
/// <summary>
/// Data streamer tests.
/// </summary>
public sealed class DataStreamerTest
{
/** Cache name. */
private const string CacheName = "partitioned";
/** Node. */
private IIgnite _grid;
/** Node 2. */
private IIgnite _grid2;
/** Cache. */
private ICache<int, int?> _cache;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
_grid = Ignition.Start(TestUtils.GetTestConfiguration());
_grid2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid1"
});
_cache = _grid.CreateCache<int, int?>(CacheName);
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
for (int i = 0; i < 100; i++)
_cache.Remove(i);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid);
}
/// <summary>
/// Test data streamer property configuration. Ensures that at least no exceptions are thrown.
/// </summary>
[Test]
public void TestPropertyPropagation()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
Assert.IsTrue(ldr.AllowOverwrite);
ldr.AllowOverwrite = false;
Assert.IsFalse(ldr.AllowOverwrite);
ldr.SkipStore = true;
Assert.IsTrue(ldr.SkipStore);
ldr.SkipStore = false;
Assert.IsFalse(ldr.SkipStore);
ldr.PerNodeBufferSize = 1;
Assert.AreEqual(1, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 2;
Assert.AreEqual(2, ldr.PerNodeBufferSize);
ldr.PerNodeParallelOperations = 1;
Assert.AreEqual(1, ldr.PerNodeParallelOperations);
ldr.PerNodeParallelOperations = 2;
Assert.AreEqual(2, ldr.PerNodeParallelOperations);
}
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemove()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
// Additions.
ldr.AddData(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
ldr.AddData(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
// Removal.
ldr.RemoveData(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
// Mixed.
ldr.AddData(5, 5);
ldr.RemoveData(2);
ldr.AddData(new KeyValuePair<int, int>(7, 7));
ldr.AddData(6, 6);
ldr.RemoveData(4);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.AddData(new KeyValuePair<int, int>(8, 8));
ldr.RemoveData(3);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
}
/// <summary>
/// Test "tryFlush".
/// </summary>
[Test]
public void TestTryFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.TryFlush();
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test buffer size adjustments.
/// </summary>
[Test]
public void TestBufferSize()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
const int timeout = 5000;
var part1 = GetPrimaryPartitionKeys(_grid, 4);
var part2 = GetPrimaryPartitionKeys(_grid2, 4);
var task = ldr.AddData(part1[0], part1[0]);
Thread.Sleep(100);
Assert.IsFalse(task.IsCompleted);
ldr.PerNodeBufferSize = 2;
ldr.AddData(part2[0], part2[0]);
ldr.AddData(part1[1], part1[1]);
Assert.IsTrue(ldr.AddData(part2[1], part2[1]).Wait(timeout));
Assert.IsTrue(task.Wait(timeout));
Assert.AreEqual(part1[0], _cache.Get(part1[0]));
Assert.AreEqual(part1[1], _cache.Get(part1[1]));
Assert.AreEqual(part2[0], _cache.Get(part2[0]));
Assert.AreEqual(part2[1], _cache.Get(part2[1]));
Assert.IsTrue(ldr.AddData(new[]
{
new KeyValuePair<int, int>(part1[2], part1[2]),
new KeyValuePair<int, int>(part1[3], part1[3]),
new KeyValuePair<int, int>(part2[2], part2[2]),
new KeyValuePair<int, int>(part2[3], part2[3])
}).Wait(timeout));
Assert.AreEqual(part1[2], _cache.Get(part1[2]));
Assert.AreEqual(part1[3], _cache.Get(part1[3]));
Assert.AreEqual(part2[2], _cache.Get(part2[2]));
Assert.AreEqual(part2[3], _cache.Get(part2[3]));
}
}
/// <summary>
/// Gets the primary partition keys.
/// </summary>
private static int[] GetPrimaryPartitionKeys(IIgnite ignite, int count)
{
var affinity = ignite.GetAffinity(CacheName);
var localNode = ignite.GetCluster().GetLocalNode();
var part = affinity.GetPrimaryPartitions(localNode).First();
return Enumerable.Range(0, int.MaxValue)
.Where(k => affinity.GetPartition(k) == part)
.Take(count)
.ToArray();
}
/// <summary>
/// Test close.
/// </summary>
[Test]
public void TestClose()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.Close(false);
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test close with cancellation.
/// </summary>
[Test]
public void TestCancel()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.Close(true);
fut.Wait();
Assert.IsFalse(_cache.ContainsKey(1));
}
}
/// <summary>
/// Tests that streamer gets collected when there are no references to it.
/// </summary>
[Test]
public void TestFinalizer()
{
var streamer = _grid.GetDataStreamer<int, int>(CacheName);
var streamerRef = new WeakReference(streamer);
Assert.IsNotNull(streamerRef.Target);
// ReSharper disable once RedundantAssignment
streamer = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(streamerRef.Target);
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.AddData(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.AddData(2, 2);
ldr.AutoFlushFrequency = long.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.AddData(3, 3);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test flush before stop.
fut = ldr.AddData(4, 4);
ldr.AutoFlushFrequency = 0;
fut.Wait();
// Test flush after second turn on.
fut = ldr.AddData(5, 5);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
}
/// <summary>
/// Test multithreaded behavior.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestMultithreaded()
{
int entriesPerThread = 100000;
int threadCnt = 8;
for (int i = 0; i < 5; i++)
{
_cache.Clear();
Assert.AreEqual(0, _cache.GetSize());
Stopwatch watch = new Stopwatch();
watch.Start();
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.PerNodeBufferSize = 1024;
int ctr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref ctr);
int startIdx = (threadIdx - 1) * entriesPerThread;
int endIdx = startIdx + entriesPerThread;
for (int j = startIdx; j < endIdx; j++)
{
// ReSharper disable once AccessToDisposedClosure
ldr.AddData(j, j);
if (j % 100000 == 0)
Console.WriteLine("Put [thread=" + threadIdx + ", cnt=" + j + ']');
}
}, threadCnt);
}
Console.WriteLine("Iteration " + i + ": " + watch.ElapsedMilliseconds);
watch.Reset();
for (int j = 0; j < threadCnt * entriesPerThread; j++)
Assert.AreEqual(j, j);
}
}
/// <summary>
/// Tests custom receiver.
/// </summary>
[Test]
public void TestStreamReceiver()
{
TestStreamReceiver(new StreamReceiverBinarizable());
TestStreamReceiver(new StreamReceiverSerializable());
}
/// <summary>
/// Tests StreamVisitor.
/// </summary>
[Test]
public void TestStreamVisitor()
{
TestStreamReceiver(new StreamVisitor<int, int>((c, e) => c.Put(e.Key, e.Value + 1)));
}
/// <summary>
/// Tests StreamTransformer.
/// </summary>
[Test]
public void TestStreamTransformer()
{
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorSerializable()));
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorBinarizable()));
}
/// <summary>
/// Tests specified receiver.
/// </summary>
private void TestStreamReceiver(IStreamReceiver<int, int> receiver)
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Receiver = new StreamReceiverBinarizable();
ldr.Receiver = receiver; // check double assignment
Assert.AreEqual(ldr.Receiver, receiver);
for (var i = 0; i < 100; i++)
ldr.AddData(i, i);
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, _cache.Get(i));
}
}
/// <summary>
/// Tests the stream receiver in keepBinary mode.
/// </summary>
[Test]
public void TestStreamReceiverKeepBinary()
{
// ReSharper disable once LocalVariableHidesMember
var cache = _grid.GetCache<int, BinarizableEntry>(CacheName);
using (var ldr0 = _grid.GetDataStreamer<int, int>(CacheName))
using (var ldr = ldr0.WithKeepBinary<int, IBinaryObject>())
{
ldr.Receiver = new StreamReceiverKeepBinary();
ldr.AllowOverwrite = true;
for (var i = 0; i < 100; i++)
ldr.AddData(i, _grid.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry {Val = i}));
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, cache.Get(i).Val);
}
}
/// <summary>
/// Test binarizable receiver.
/// </summary>
private class StreamReceiverBinarizable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test binary receiver.
/// </summary>
[Serializable]
private class StreamReceiverKeepBinary : IStreamReceiver<int, IBinaryObject>
{
/** <inheritdoc /> */
public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries)
{
var binary = cache.Ignite.GetBinary();
cache.PutAll(entries.ToDictionary(x => x.Key, x =>
binary.ToBinary<IBinaryObject>(new BinarizableEntry
{
Val = x.Value.Deserialize<BinarizableEntry>().Val + 1
})));
}
}
/// <summary>
/// Test serializable receiver.
/// </summary>
[Serializable]
private class StreamReceiverSerializable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test entry processor.
/// </summary>
[Serializable]
private class EntryProcessorSerializable : ICacheEntryProcessor<int, int, int, int>
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
}
/// <summary>
/// Test entry processor.
/// </summary>
private class EntryProcessorBinarizable : ICacheEntryProcessor<int, int, int, int>, IBinarizable
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
public int Val { get; set; }
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Tests.Bson;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
[TestFixture]
public class JPathExecuteTests : TestFixtureBase
{
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWildcardProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1),
new JProperty("Blah2", 2));
IList<JToken> t = o.SelectTokens("$.*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void QuoteName()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("['Blah']");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Index 1 not valid on JObject.",
() => { o.SelectToken("[1]", true); });
}
[Test]
public void EvaluateWildcardIndexOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Index * not valid on JObject.",
() => { o.SelectToken("[*]", true); });
}
[Test]
public void EvaluateSliceOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Array slice is not valid on JObject.",
() => { o.SelectToken("[:]", true); });
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
public void EvaluateMultipleResultsError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Path returned multiple tokens.",
() => { a.SelectToken("[0, 1]"); });
}
[Test]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Property 'BlahBlah' not valid on JArray.",
() => { a.SelectToken("BlahBlah", true); });
}
[Test]
public void EvaluateNoResultsWithMultipleArrayIndexes()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Index 9 outside the bounds of JArray.",
() => { a.SelectToken("[9,10]", true); });
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxerWithError()
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(
@"Index 1 outside the bounds of JConstructor.",
() => { c.SelectToken("[1]", true); });
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxer()
{
JConstructor c = new JConstructor("Blah");
Assert.IsNull(c.SelectToken("[1]"));
}
[Test]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
"Property 'Missing' does not exist on JObject.",
() => { o.SelectToken("Missing", true); });
}
[Test]
public void EvaluateMissingPropertyIndexWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
"Property 'Missing' does not exist on JObject.",
() => { o.SelectToken("['Missing','Missing2']", true); });
}
[Test]
public void EvaluateMultiPropertyIndexOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Properties 'Missing', 'Missing2' not valid on JArray.",
() => { a.SelectToken("['Missing','Missing2']", true); });
}
[Test]
public void EvaluateArraySliceWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Array slice of 99 to * returned no results.",
() => { a.SelectToken("[99:]", true); });
ExceptionAssert.Throws<JsonException>(
"Array slice of 1 to -19 returned no results.",
() => { a.SelectToken("[1:-19]", true); });
ExceptionAssert.Throws<JsonException>(
"Array slice of * to -19 returned no results.",
() => { a.SelectToken("[:-19]", true); });
a = new JArray();
ExceptionAssert.Throws<JsonException>(
"Array slice of * to * returned no results.",
() => { a.SelectToken("[:]", true); });
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
public void EvaluateArrayOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Index 1000 outside the bounds of JArray.",
() => { a.SelectToken("[1000].Ha", true); });
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateArraySlice()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
IList<JToken> t = null;
t = a.SelectTokens("[-3:]").ToList();
Assert.AreEqual(3, t.Count);
Assert.AreEqual(7, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(9, (int)t[2]);
t = a.SelectTokens("[-1:-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(9, (int)t[0]);
t = a.SelectTokens("[-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(8, (int)t[0]);
t = a.SelectTokens("[1:1]").ToList();
Assert.AreEqual(0, t.Count);
t = a.SelectTokens("[1:2]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(2, (int)t[0]);
t = a.SelectTokens("[::-1]").ToList();
Assert.AreEqual(9, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(7, (int)t[2]);
Assert.AreEqual(6, (int)t[3]);
Assert.AreEqual(5, (int)t[4]);
Assert.AreEqual(4, (int)t[5]);
Assert.AreEqual(3, (int)t[6]);
Assert.AreEqual(2, (int)t[7]);
Assert.AreEqual(1, (int)t[8]);
t = a.SelectTokens("[::-2]").ToList();
Assert.AreEqual(5, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(7, (int)t[1]);
Assert.AreEqual(5, (int)t[2]);
Assert.AreEqual(3, (int)t[3]);
Assert.AreEqual(1, (int)t[4]);
}
[Test]
public void EvaluateWildcardArray()
{
JArray a = new JArray(1, 2, 3, 4);
List<JToken> t = a.SelectTokens("[*]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.AreEqual(3, (int)t[2]);
Assert.AreEqual(4, (int)t[3]);
}
[Test]
public void EvaluateArrayMultipleIndexes()
{
JArray a = new JArray(1, 2, 3, 4);
IEnumerable<JToken> t = a.SelectTokens("[1,2,0]");
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Count());
Assert.AreEqual(2, (int)t.ElementAt(0));
Assert.AreEqual(3, (int)t.ElementAt(1));
Assert.AreEqual(1, (int)t.ElementAt(2));
}
[Test]
public void EvaluateScan()
{
JObject o1 = new JObject{ {"Name", 1} };
JObject o2 = new JObject{ {"Name", 2} };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void EvaluateWildcardScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(5, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
}
[Test]
public void EvaluateScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3]));
}
[Test]
public void EvaluateWildcardScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(9, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
Assert.IsTrue(JToken.DeepEquals(o3, t[5]));
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7]));
Assert.AreEqual(3, (int)t[8]);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new[] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void ExistsQuery()
{
JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0]));
}
[Test]
public void EqualsQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", "ho")),
new JObject(new JProperty("hi", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0]));
}
[Test]
public void NotEqualsQuery()
{
JArray a = new JArray(
new JArray(new JObject(new JProperty("hi", "ho"))),
new JArray(new JObject(new JProperty("hi", "ha"))));
IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0]));
}
[Test]
public void NoPathQuery()
{
JArray a = new JArray(1, 2, 3);
IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(2, (int)t[0]);
Assert.AreEqual(3, (int)t[1]);
}
[Test]
public void MultipleQueries()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
// json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/
// first query resolves array to ints
// int has no children to query
IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(0, t.Count);
}
[Test]
public void GreaterQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
[Test]
public void GreaterQueryBigInteger()
{
JArray a = new JArray(
new JObject(new JProperty("hi", new BigInteger(1))),
new JObject(new JProperty("hi", new BigInteger(2))),
new JObject(new JProperty("hi", new BigInteger(3))));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#endif
[Test]
public void GreaterOrEqualQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 2.0)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3]));
}
[Test]
public void NestedQuery()
{
JArray a = new JArray(
new JObject(
new JProperty("name", "Bad Boys"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "Independence Day"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "The Rock"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Nick Cage")))))
);
IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual("Bad Boys", (string)t[0]);
Assert.AreEqual("Independence Day", (string)t[1]);
}
[Test]
public void PathWithConstructor()
{
JArray a = JArray.Parse(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]");
JValue v = (JValue)a.SelectToken("[1].Property2[1][0]");
Assert.AreEqual(1L, v.Value);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using Xamarin.Utilities;
namespace Xamarin.Auth
{
/// <summary>
/// Type of method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal delegate Task<string> GetUsernameAsyncFunc (IDictionary<string, string> accountProperties);
#else
public delegate Task<string> GetUsernameAsyncFunc (IDictionary<string, string> accountProperties);
#endif
/// <summary>
/// OAuth 1.0 authenticator.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class OAuth1Authenticator : WebAuthenticator
#else
public class OAuth1Authenticator : WebAuthenticator
#endif
{
string consumerKey;
string consumerSecret;
Uri requestTokenUrl;
Uri authorizeUrl;
Uri accessTokenUrl;
Uri callbackUrl;
GetUsernameAsyncFunc getUsernameAsync;
string token;
string tokenSecret;
string verifier;
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.OAuth1Authenticator"/> class.
/// </summary>
/// <param name='consumerKey'>
/// Consumer key.
/// </param>
/// <param name='consumerSecret'>
/// Consumer secret.
/// </param>
/// <param name='requestTokenUrl'>
/// Request token URL.
/// </param>
/// <param name='authorizeUrl'>
/// Authorize URL.
/// </param>
/// <param name='accessTokenUrl'>
/// Access token URL.
/// </param>
/// <param name='callbackUrl'>
/// Callback URL.
/// </param>
/// <param name='getUsernameAsync'>
/// Method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </param>
public OAuth1Authenticator (string consumerKey, string consumerSecret, Uri requestTokenUrl, Uri authorizeUrl, Uri accessTokenUrl, Uri callbackUrl, GetUsernameAsyncFunc getUsernameAsync = null)
{
if (string.IsNullOrEmpty (consumerKey)) {
throw new ArgumentException ("consumerKey must be provided", "consumerKey");
}
this.consumerKey = consumerKey;
if (string.IsNullOrEmpty (consumerSecret)) {
throw new ArgumentException ("consumerSecret must be provided", "consumerSecret");
}
this.consumerSecret = consumerSecret;
if (requestTokenUrl == null) {
throw new ArgumentNullException ("requestTokenUrl");
}
this.requestTokenUrl = requestTokenUrl;
if (authorizeUrl == null) {
throw new ArgumentNullException ("authorizeUrl");
}
this.authorizeUrl = authorizeUrl;
if (accessTokenUrl == null) {
throw new ArgumentNullException ("accessTokenUrl");
}
this.accessTokenUrl = accessTokenUrl;
if (callbackUrl == null) {
throw new ArgumentNullException ("callbackUrl");
}
this.callbackUrl = callbackUrl;
this.getUsernameAsync = getUsernameAsync;
this.HttpWebClientFrameworkType = Auth.HttpWebClientFrameworkType.WebRequest;
}
/// <summary>
/// Method that returns the initial URL to be displayed in the web browser.
/// </summary>
/// <returns>
/// A task that will return the initial URL.
/// </returns>
public override Task<Uri> GetInitialUrlAsync () {
var req = OAuth1.CreateRequest (
"GET",
requestTokenUrl,
new Dictionary<string, string>() {
{ "oauth_callback", callbackUrl.AbsoluteUri },
},
consumerKey,
consumerSecret,
"");
if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
{
return req.GetResponseAsync().ContinueWith(respTask =>
{
var content = respTask.Result.GetResponseText();
var r = WebEx.FormDecode(content);
token = r["oauth_token"];
tokenSecret = r["oauth_token_secret"];
string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?";
var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString(token);
return new Uri(url);
});
}
else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
{
throw new NotImplementedException("HttpClient implementation!");
}
return null;
}
/// <summary>
/// Event handler that watches for the callback URL to be loaded.
/// </summary>
/// <param name='url'>
/// The URL of the loaded page.
/// </param>
public override void OnPageLoaded (Uri url)
{
if (url.Host == callbackUrl.Host && url.AbsolutePath == callbackUrl.AbsolutePath) {
var query = url.Query;
var r = WebEx.FormDecode (query);
r.TryGetValue ("oauth_verifier", out verifier);
GetAccessTokenAsync ().ContinueWith (getTokenTask => {
if (getTokenTask.IsCanceled) {
OnCancelled ();
} else if (getTokenTask.IsFaulted) {
OnError (getTokenTask.Exception);
}
}, TaskContinuationOptions.NotOnRanToCompletion);
}
}
Task GetAccessTokenAsync ()
{
var requestParams = new Dictionary<string, string> {
{ "oauth_token", token }
};
if (verifier != null)
requestParams["oauth_verifier"] = verifier;
var req = OAuth1.CreateRequest (
"GET",
accessTokenUrl,
requestParams,
consumerKey,
consumerSecret,
tokenSecret);
if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
{
return req.GetResponseAsync().ContinueWith(respTask =>
{
var content = respTask.Result.GetResponseText();
var accountProperties = WebEx.FormDecode(content);
accountProperties["oauth_consumer_key"] = consumerKey;
accountProperties["oauth_consumer_secret"] = consumerSecret;
if (getUsernameAsync != null)
{
getUsernameAsync(accountProperties).ContinueWith(uTask =>
{
if (uTask.IsFaulted)
{
OnError(uTask.Exception);
}
else
{
OnSucceeded(uTask.Result, accountProperties);
}
});
}
else
{
OnSucceeded("", accountProperties);
}
});
}
else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
{
throw new NotImplementedException("HttpClient implementation!");
}
return null;
}
public HttpWebClientFrameworkType HttpWebClientFrameworkType
{
get;
set;
}
}
}
| |
namespace StockSharp.Algo.Storages.Csv
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Messages;
/// <summary>
/// The interface for presentation in the form of list of trade objects, received from the external storage.
/// </summary>
public interface ICsvEntityList
{
/// <summary>
/// The time delayed action.
/// </summary>
DelayAction DelayAction { get; set; }
/// <summary>
/// Initialize the storage.
/// </summary>
/// <param name="errors">Possible errors.</param>
void Init(IList<Exception> errors);
}
/// <summary>
/// List of trade objects, received from the CSV storage.
/// </summary>
/// <typeparam name="TKey">Key type.</typeparam>
/// <typeparam name="TEntity">Entity type.</typeparam>
public abstract class CsvEntityList<TKey, TEntity> : SynchronizedList<TEntity>, IStorageEntityList<TEntity>, ICsvEntityList
where TEntity : class
{
private readonly Dictionary<TKey, TEntity> _items = new();
/// <summary>
/// The CSV storage of trading objects.
/// </summary>
protected CsvEntityRegistry Registry { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CsvEntityList{TKey,TEntity}"/>.
/// </summary>
/// <param name="registry">The CSV storage of trading objects.</param>
/// <param name="fileName">CSV file name.</param>
protected CsvEntityList(CsvEntityRegistry registry, string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Registry = registry ?? throw new ArgumentNullException(nameof(registry));
FileName = Path.Combine(Registry.Path, fileName);
}
/// <summary>
/// CSV file name.
/// </summary>
public string FileName { get; }
#region IStorageEntityList<T>
private DelayAction.IGroup<CsvFileWriter> _delayActionGroup;
private DelayAction _delayAction;
/// <inheritdoc cref="ICsvEntityList" />
public DelayAction DelayAction
{
get => _delayAction;
set
{
if (_delayAction == value)
return;
if (_delayAction != null)
{
_delayAction.DeleteGroup(_delayActionGroup);
_delayActionGroup = null;
}
_delayAction = value;
if (_delayAction != null)
{
_delayActionGroup = _delayAction.CreateGroup(() =>
{
var stream = new TransactionFileStream(FileName, FileMode.OpenOrCreate);
stream.Seek(0, SeekOrigin.End);
return new CsvFileWriter(stream, Registry.Encoding);
});
}
}
}
/// <inheritdoc />
void IStorageEntityList<TEntity>.WaitFlush()
{
_delayActionGroup?.WaitFlush(false);
}
TEntity IStorageEntityList<TEntity>.ReadById(object id)
{
lock (SyncRoot)
return _items.TryGetValue(NormalizedKey(id));
}
private TKey GetNormalizedKey(TEntity entity)
{
return NormalizedKey(GetKey(entity));
}
private static readonly bool _isSecId = typeof(TKey) == typeof(SecurityId);
private static TKey NormalizedKey(object key)
{
if (key is string str)
{
str = str.ToLowerInvariant();
if (_isSecId)
{
// backward compatibility when SecurityList accept as a key string
key = str.ToSecurityId();
}
else
key = str;
}
return (TKey)key;
}
/// <inheritdoc />
public void Save(TEntity entity)
{
Save(entity, false);
}
/// <summary>
/// Save object into storage.
/// </summary>
/// <param name="entity">Trade object.</param>
/// <param name="forced">Forced update.</param>
public virtual void Save(TEntity entity, bool forced)
{
lock (SyncRoot)
{
var item = _items.TryGetValue(GetNormalizedKey(entity));
if (item == null)
{
Add(entity);
return;
}
else if (IsChanged(entity, forced))
UpdateCache(entity);
else
return;
WriteMany(_items.Values.ToArray());
}
}
#endregion
/// <summary>
/// Is <paramref name="entity"/> changed.
/// </summary>
/// <param name="entity">Trade object.</param>
/// <param name="forced">Forced update.</param>
/// <returns>Is changed.</returns>
protected virtual bool IsChanged(TEntity entity, bool forced)
{
return true;
}
/// <summary>
/// Get key from trade object.
/// </summary>
/// <param name="item">Trade object.</param>
/// <returns>The key.</returns>
protected abstract TKey GetKey(TEntity item);
/// <summary>
/// Write data into CSV.
/// </summary>
/// <param name="writer">CSV writer.</param>
/// <param name="data">Trade object.</param>
protected abstract void Write(CsvFileWriter writer, TEntity data);
/// <summary>
/// Read data from CSV.
/// </summary>
/// <param name="reader">CSV reader.</param>
/// <returns>Trade object.</returns>
protected abstract TEntity Read(FastCsvReader reader);
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public override bool Contains(TEntity item)
{
lock (SyncRoot)
return _items.ContainsKey(GetNormalizedKey(item));
}
/// <summary>
///
/// </summary>
/// <param name="item">Trade object.</param>
/// <returns></returns>
protected override bool OnAdding(TEntity item)
{
lock (SyncRoot)
{
if (!_items.TryAdd2(GetNormalizedKey(item), item))
return false;
AddCache(item);
_delayActionGroup.Add(Write, item);
}
return base.OnAdding(item);
}
/// <summary>
///
/// </summary>
/// <param name="item">Trade object.</param>
protected override void OnRemoved(TEntity item)
{
base.OnRemoved(item);
lock (SyncRoot)
{
_items.Remove(GetNormalizedKey(item));
RemoveCache(item);
WriteMany(_items.Values.ToArray());
}
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
protected void OnRemovedRange(IEnumerable<TEntity> items)
{
lock (SyncRoot)
{
foreach (var item in items)
{
_items.Remove(GetNormalizedKey(item));
RemoveCache(item);
}
WriteMany(_items.Values.ToArray());
}
}
/// <summary>
///
/// </summary>
protected override void OnCleared()
{
base.OnCleared();
lock (SyncRoot)
{
_items.Clear();
ClearCache();
_delayActionGroup.Add(writer => writer.Writer.Truncate());
}
}
/// <summary>
/// Write data into storage.
/// </summary>
/// <param name="values">Trading objects.</param>
private void WriteMany(TEntity[] values)
{
_delayActionGroup.Add((writer, state) =>
{
writer.Writer.Truncate();
foreach (var item in state)
Write(writer, item);
}, values, compareStates: (v1, v2) =>
{
if (v1 == null)
return v2 == null;
if (v2 == null)
return false;
if (v1.Length != v2.Length)
return false;
return v1.SequenceEqual(v2);
});
}
void ICsvEntityList.Init(IList<Exception> errors)
{
if (errors == null)
throw new ArgumentNullException(nameof(errors));
if (!File.Exists(FileName))
return;
Do.Invariant(() =>
{
using (var stream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var reader = new FastCsvReader(stream, Registry.Encoding);
var hasDuplicates = false;
var currErrors = 0;
while (reader.NextLine())
{
try
{
var item = Read(reader);
var key = GetNormalizedKey(item);
lock (SyncRoot)
{
if (_items.TryAdd2(key, item))
{
InnerCollection.Add(item);
AddCache(item);
}
else
hasDuplicates = true;
}
currErrors = 0;
}
catch (Exception ex)
{
if (errors.Count < 100)
errors.Add(ex);
currErrors++;
if (currErrors >= 1000)
break;
}
}
if (!hasDuplicates)
return;
try
{
lock (SyncRoot)
{
stream.SetLength(0);
using (var writer = new CsvFileWriter(stream, Registry.Encoding))
{
foreach (var item in InnerCollection)
Write(writer, item);
}
}
}
catch (Exception ex)
{
errors.Add(ex);
}
}
});
InnerCollection.ForEach(OnAdded);
}
/// <summary>
/// Clear cache.
/// </summary>
protected virtual void ClearCache()
{
}
/// <summary>
/// Add item to cache.
/// </summary>
/// <param name="item">New item.</param>
protected virtual void AddCache(TEntity item)
{
}
/// <summary>
/// Update item in cache.
/// </summary>
/// <param name="item">Item.</param>
protected virtual void UpdateCache(TEntity item)
{
}
/// <summary>
/// Remove item from cache.
/// </summary>
/// <param name="item">Item.</param>
protected virtual void RemoveCache(TEntity item)
{
}
/// <inheritdoc />
public override string ToString()
{
return FileName;
}
}
}
| |
using System.Linq;
namespace System.Collections
{
/// <summary>
/// Provides methods for querying information from an <see cref="IEnumerable"/> object.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Determines whether the <see cref="IEnumerable"/> contains any elements.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <returns><c>true</c> if the <see cref="IEnumerable"/> contains any elements; otherwise, <c>false</c>.</returns>
public static bool Any(this IEnumerable enumerable)
{
if (enumerable == null)
return false;
foreach (var item in enumerable)
{
return true;
}
return false;
}
/// <summary>
/// Determines whether any element in the <see cref="IEnumerable"/> satisfies a condition.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns><c>true</c> if any element in the <see cref="IEnumerable"/> satisfies the condition; otherwise, <c>false</c>.</returns>
public static bool Any(this IEnumerable enumerable, Func<object, bool> predicate)
{
if (enumerable == null)
return false;
foreach (var item in enumerable)
{
if (predicate == null || predicate.Invoke(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the number of elements contained within the <see cref="IEnumerable"/>.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <returns>The number of elements in the <see cref="IEnumerable"/>.</returns>
public static int Count(this IEnumerable enumerable)
{
return enumerable == null ? 0 : Enumerable.Count(enumerable.Cast<object>());
}
/// <summary>
/// Returns the element at the specified index within the <see cref="IEnumerable"/>.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <param name="index">The index of the element to return.</param>
/// <returns>The element at the specified index.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the index equals or exceeds the
/// number of elements in the <see cref="IEnumerable"/> -or- when the index is less than 0.</exception>
public static object ElementAt(this IEnumerable enumerable, int index)
{
if (enumerable == null)
return null;
int i = 0;
foreach (var item in enumerable)
{
if (i++ == index)
{
return item;
}
}
throw new ArgumentOutOfRangeException("index");
}
/// <summary>
/// Returns the first element in the <see cref="IEnumerable"/> or <c>null</c> if there are no elements.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <returns>The first element in the <see cref="IEnumerable"/> -or- <c>null</c> if there are no elements.</returns>
public static object FirstOrDefault(this IEnumerable enumerable)
{
if (enumerable == null)
return null;
foreach (var item in enumerable)
{
return item;
}
return null;
}
/// <summary>
/// Returns the first element in the <see cref="IEnumerable"/> that satisfies a condition or <c>null</c> if no such element is found.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The first element in the <see cref="IEnumerable"/> that satisfies the condition -or- <c>null</c> if no such element is found.</returns>
public static object FirstOrDefault(this IEnumerable enumerable, Func<object, bool> predicate)
{
if (enumerable == null)
return null;
foreach (var item in enumerable)
{
if (predicate == null || predicate.Invoke(item))
{
return item;
}
}
return null;
}
/// <summary>
/// Returns the index at which the specified element resides within the <see cref="IEnumerable"/>.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <param name="element">The element to return the index of.</param>
/// <returns>The index of the element -or- -1 if the element is not found in the collection.</returns>
public static int IndexOf(this IEnumerable enumerable, object element)
{
if (enumerable == null)
return -1;
int i = 0;
foreach (var item in enumerable)
{
if ((item == null && element == null) || (item != null && item.Equals(element)))
{
return i;
}
i++;
}
return -1;
}
/// <summary>
/// Returns the last element in the <see cref="IEnumerable"/> or <c>null</c> if there are no elements.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <returns>The last element in the <see cref="IEnumerable"/> -or- <c>null</c> if there are no elements.</returns>
public static object LastOrDefault(this IEnumerable enumerable)
{
if (enumerable == null)
return null;
object obj = null;
foreach (var item in enumerable)
{
obj = item;
}
return obj;
}
/// <summary>
/// Returns the last element in the <see cref="IEnumerable"/> that satisfies a condition or <c>null</c> if no such element is found.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable"/> object.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The last element in the <see cref="IEnumerable"/> that satisfies the condition -or- <c>null</c> if no such element is found.</returns>
public static object LastOrDefault(this IEnumerable enumerable, Func<object, bool> predicate)
{
if (enumerable == null)
return null;
object obj = null;
foreach (var item in enumerable)
{
if (predicate == null || predicate.Invoke(item))
{
obj = item;
}
}
return obj;
}
}
}
namespace System.Collections.Generic
{
/// <summary>
/// Provides methods for querying information from an <see cref="IEnumerable"/> object.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Returns the index of the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable<T>"/> object.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The index of the first element that satisfies the condition.</returns>
public static int IndexOf<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
if (enumerable == null)
return -1;
int i = 0;
foreach (var item in enumerable)
{
if (predicate == null || predicate.Invoke(item))
{
return i;
}
i++;
}
return -1;
}
/// <summary>
/// Returns the index of the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable<T>"/> object.</param>
/// <param name="startIndex">The zero-based starting index of the search. The search proceeds from the start index to the end of the sequence.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The index of the first element that satisfies the condition.</returns>
public static int IndexOf<T>(this IEnumerable<T> enumerable, int startIndex, Func<T, bool> predicate)
{
if (enumerable == null)
return -1;
int i = 0;
foreach (var item in enumerable)
{
if (i >= startIndex && (predicate == null || predicate.Invoke(item)))
{
return i;
}
i++;
}
return -1;
}
/// <summary>
/// Returns the index of the last element in a sequence that satisfies a specified condition.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable<T>"/> object.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The index of the last element that satisfies the condition.</returns>
public static int LastIndexOf<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
if (enumerable == null)
return -1;
int i = 0;
int lastIndex = -1;
foreach (var item in enumerable)
{
if (predicate == null || predicate.Invoke(item))
{
lastIndex = i;
}
i++;
}
return lastIndex;
}
/// <summary>
/// Returns the index of the last element in a sequence that satisfies a specified condition.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable<T>"/> object.</param>
/// <param name="startIndex">The zero-based starting index of the search. The search proceeds from the start index to the beginning of the sequence.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>The index of the last element that satisfies the condition.</returns>
public static int LastIndexOf<T>(this IEnumerable<T> enumerable, int startIndex, Func<T, bool> predicate)
{
if (enumerable == null)
return -1;
int i = 0;
int lastIndex = -1;
foreach (var item in enumerable)
{
if (i <= startIndex && (predicate == null || predicate.Invoke(item)))
{
lastIndex = i;
}
i++;
}
return lastIndex;
}
/// <summary>
/// Determines whether two <see cref="IEnumerable<T>"/> objects have equivalent contents.
/// </summary>
/// <typeparam name="T">The enumerable type parameter.</typeparam>
/// <param name="first">The first enumerable to check.</param>
/// <param name="second">The second enumerable to check.</param>
/// <param name="orderMatters"><c>true</c> to compare elements by order and contents; otherwise <c>false</c> to compare just contents</param>
/// <returns><c>true</c> if the enumerables are equivalent; otherwise <c>false</c>.</returns>
public static bool Equivalent<T>(this IEnumerable<T> first, IEnumerable<T> second, bool orderMatters)
{
if (first == null)
return second == null;
if (second == null)
return false;
if (ReferenceEquals(first, second))
return true;
var firstCollection = first as ICollection<T>;
var secondCollection = second as ICollection<T>;
if (firstCollection != null && secondCollection != null)
{
if (firstCollection.Count != secondCollection.Count)
return false;
if (firstCollection.Count == 0)
return true;
}
int firstCount;
int secondCount;
var firstElementCounts = GetElementCounts(first, out firstCount);
var secondElementCounts = GetElementCounts(second, out secondCount);
if (firstCount != secondCount)
return false;
for (int i = 0; i < firstElementCounts.Count; i++)
{
var kvp = (KeyValuePair<T, int>)firstElementCounts.ElementAt(i);
firstCount = kvp.Value;
if (orderMatters)
{
var secondKvp = (KeyValuePair<T, int>)secondElementCounts.ElementAt(i);
secondCount = secondKvp.Key.Equals(kvp.Key) ? secondKvp.Value : -1;
}
else
{
secondElementCounts.TryGetValue(kvp.Key, out secondCount);
}
if (firstCount != secondCount)
return false;
}
return firstElementCounts.Count > 0 || secondElementCounts.Count == 0;
}
private static Dictionary<T, int> GetElementCounts<T>(IEnumerable<T> enumerable, out int nullCount)
{
var dictionary = new Dictionary<T, int>();
nullCount = 0;
foreach (T element in enumerable)
{
if (element == null)
{
nullCount++;
}
else
{
int num;
dictionary.TryGetValue(element, out num);
num++;
dictionary[element] = num;
}
}
return dictionary;
}
}
}
| |
using System.Windows.Forms;
namespace EveOPreview.View
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>s
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.ToolStripMenuItem RestoreWindowMenuItem;
System.Windows.Forms.ToolStripMenuItem ExitMenuItem;
System.Windows.Forms.ToolStripMenuItem TitleMenuItem;
System.Windows.Forms.ToolStripSeparator SeparatorMenuItem;
System.Windows.Forms.TabControl ContentTabControl;
System.Windows.Forms.TabPage GeneralTabPage;
System.Windows.Forms.Panel GeneralSettingsPanel;
System.Windows.Forms.TabPage ThumbnailTabPage;
System.Windows.Forms.Panel ThumbnailSettingsPanel;
System.Windows.Forms.Label HeigthLabel;
System.Windows.Forms.Label WidthLabel;
System.Windows.Forms.Label OpacityLabel;
System.Windows.Forms.Panel ZoomSettingsPanel;
System.Windows.Forms.Label ZoomFactorLabel;
System.Windows.Forms.Label ZoomAnchorLabel;
System.Windows.Forms.TabPage OverlayTabPage;
System.Windows.Forms.Panel OverlaySettingsPanel;
System.Windows.Forms.TabPage ClientsTabPage;
System.Windows.Forms.Panel ClientsPanel;
System.Windows.Forms.Label ThumbnailsListLabel;
System.Windows.Forms.TabPage AboutTabPage;
System.Windows.Forms.Panel AboutPanel;
System.Windows.Forms.Label DocumentationLinkLabel;
System.Windows.Forms.Label DescriptionLabel;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
System.Windows.Forms.Label NameLabel;
this.MinimizeInactiveClientsCheckBox = new System.Windows.Forms.CheckBox();
this.EnableClientLayoutTrackingCheckBox = new System.Windows.Forms.CheckBox();
this.HideActiveClientThumbnailCheckBox = new System.Windows.Forms.CheckBox();
this.ShowThumbnailsAlwaysOnTopCheckBox = new System.Windows.Forms.CheckBox();
this.HideThumbnailsOnLostFocusCheckBox = new System.Windows.Forms.CheckBox();
this.EnablePerClientThumbnailsLayoutsCheckBox = new System.Windows.Forms.CheckBox();
this.MinimizeToTrayCheckBox = new System.Windows.Forms.CheckBox();
this.ThumbnailsWidthNumericEdit = new System.Windows.Forms.NumericUpDown();
this.ThumbnailsHeightNumericEdit = new System.Windows.Forms.NumericUpDown();
this.ThumbnailOpacityTrackBar = new System.Windows.Forms.TrackBar();
this.ZoomTabPage = new System.Windows.Forms.TabPage();
this.ZoomAnchorPanel = new System.Windows.Forms.Panel();
this.ZoomAanchorNWRadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorNRadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorNERadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorWRadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorSERadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorCRadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorSRadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorERadioButton = new System.Windows.Forms.RadioButton();
this.ZoomAanchorSWRadioButton = new System.Windows.Forms.RadioButton();
this.EnableThumbnailZoomCheckBox = new System.Windows.Forms.CheckBox();
this.ThumbnailZoomFactorNumericEdit = new System.Windows.Forms.NumericUpDown();
this.HighlightColorLabel = new System.Windows.Forms.Label();
this.ActiveClientHighlightColorButton = new System.Windows.Forms.Panel();
this.EnableActiveClientHighlightCheckBox = new System.Windows.Forms.CheckBox();
this.ShowThumbnailOverlaysCheckBox = new System.Windows.Forms.CheckBox();
this.ShowThumbnailFramesCheckBox = new System.Windows.Forms.CheckBox();
this.ThumbnailsList = new System.Windows.Forms.CheckedListBox();
this.VersionLabel = new System.Windows.Forms.Label();
this.DocumentationLink = new System.Windows.Forms.LinkLabel();
this.NotifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.TrayMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
RestoreWindowMenuItem = new System.Windows.Forms.ToolStripMenuItem();
ExitMenuItem = new System.Windows.Forms.ToolStripMenuItem();
TitleMenuItem = new System.Windows.Forms.ToolStripMenuItem();
SeparatorMenuItem = new System.Windows.Forms.ToolStripSeparator();
ContentTabControl = new System.Windows.Forms.TabControl();
GeneralTabPage = new System.Windows.Forms.TabPage();
GeneralSettingsPanel = new System.Windows.Forms.Panel();
ThumbnailTabPage = new System.Windows.Forms.TabPage();
ThumbnailSettingsPanel = new System.Windows.Forms.Panel();
HeigthLabel = new System.Windows.Forms.Label();
WidthLabel = new System.Windows.Forms.Label();
OpacityLabel = new System.Windows.Forms.Label();
ZoomSettingsPanel = new System.Windows.Forms.Panel();
ZoomFactorLabel = new System.Windows.Forms.Label();
ZoomAnchorLabel = new System.Windows.Forms.Label();
OverlayTabPage = new System.Windows.Forms.TabPage();
OverlaySettingsPanel = new System.Windows.Forms.Panel();
ClientsTabPage = new System.Windows.Forms.TabPage();
ClientsPanel = new System.Windows.Forms.Panel();
ThumbnailsListLabel = new System.Windows.Forms.Label();
AboutTabPage = new System.Windows.Forms.TabPage();
AboutPanel = new System.Windows.Forms.Panel();
DocumentationLinkLabel = new System.Windows.Forms.Label();
DescriptionLabel = new System.Windows.Forms.Label();
NameLabel = new System.Windows.Forms.Label();
ContentTabControl.SuspendLayout();
GeneralTabPage.SuspendLayout();
GeneralSettingsPanel.SuspendLayout();
ThumbnailTabPage.SuspendLayout();
ThumbnailSettingsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailsWidthNumericEdit)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailsHeightNumericEdit)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailOpacityTrackBar)).BeginInit();
this.ZoomTabPage.SuspendLayout();
ZoomSettingsPanel.SuspendLayout();
this.ZoomAnchorPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailZoomFactorNumericEdit)).BeginInit();
OverlayTabPage.SuspendLayout();
OverlaySettingsPanel.SuspendLayout();
ClientsTabPage.SuspendLayout();
ClientsPanel.SuspendLayout();
AboutTabPage.SuspendLayout();
AboutPanel.SuspendLayout();
this.TrayMenu.SuspendLayout();
this.SuspendLayout();
//
// RestoreWindowMenuItem
//
RestoreWindowMenuItem.Name = "RestoreWindowMenuItem";
RestoreWindowMenuItem.Size = new System.Drawing.Size(199, 30);
RestoreWindowMenuItem.Text = "Restore";
RestoreWindowMenuItem.Click += new System.EventHandler(this.RestoreMainForm_Handler);
//
// ExitMenuItem
//
ExitMenuItem.Name = "ExitMenuItem";
ExitMenuItem.Size = new System.Drawing.Size(199, 30);
ExitMenuItem.Text = "Exit";
ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItemClick_Handler);
//
// TitleMenuItem
//
TitleMenuItem.Enabled = false;
TitleMenuItem.Name = "TitleMenuItem";
TitleMenuItem.Size = new System.Drawing.Size(199, 30);
TitleMenuItem.Text = "EVE-O Preview";
//
// SeparatorMenuItem
//
SeparatorMenuItem.Name = "SeparatorMenuItem";
SeparatorMenuItem.Size = new System.Drawing.Size(196, 6);
//
// ContentTabControl
//
ContentTabControl.Alignment = System.Windows.Forms.TabAlignment.Left;
ContentTabControl.Controls.Add(GeneralTabPage);
ContentTabControl.Controls.Add(ThumbnailTabPage);
ContentTabControl.Controls.Add(this.ZoomTabPage);
ContentTabControl.Controls.Add(OverlayTabPage);
ContentTabControl.Controls.Add(ClientsTabPage);
ContentTabControl.Controls.Add(AboutTabPage);
ContentTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
ContentTabControl.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed;
ContentTabControl.ItemSize = new System.Drawing.Size(35, 120);
ContentTabControl.Location = new System.Drawing.Point(0, 0);
ContentTabControl.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ContentTabControl.Multiline = true;
ContentTabControl.Name = "ContentTabControl";
ContentTabControl.SelectedIndex = 0;
ContentTabControl.Size = new System.Drawing.Size(585, 335);
ContentTabControl.SizeMode = System.Windows.Forms.TabSizeMode.Fixed;
ContentTabControl.TabIndex = 6;
ContentTabControl.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ContentTabControl_DrawItem);
//
// GeneralTabPage
//
GeneralTabPage.BackColor = System.Drawing.SystemColors.Control;
GeneralTabPage.Controls.Add(GeneralSettingsPanel);
GeneralTabPage.Location = new System.Drawing.Point(124, 4);
GeneralTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
GeneralTabPage.Name = "GeneralTabPage";
GeneralTabPage.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5);
GeneralTabPage.Size = new System.Drawing.Size(457, 327);
GeneralTabPage.TabIndex = 0;
GeneralTabPage.Text = "General";
//
// GeneralSettingsPanel
//
GeneralSettingsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
GeneralSettingsPanel.Controls.Add(this.MinimizeInactiveClientsCheckBox);
GeneralSettingsPanel.Controls.Add(this.EnableClientLayoutTrackingCheckBox);
GeneralSettingsPanel.Controls.Add(this.HideActiveClientThumbnailCheckBox);
GeneralSettingsPanel.Controls.Add(this.ShowThumbnailsAlwaysOnTopCheckBox);
GeneralSettingsPanel.Controls.Add(this.HideThumbnailsOnLostFocusCheckBox);
GeneralSettingsPanel.Controls.Add(this.EnablePerClientThumbnailsLayoutsCheckBox);
GeneralSettingsPanel.Controls.Add(this.MinimizeToTrayCheckBox);
GeneralSettingsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
GeneralSettingsPanel.Location = new System.Drawing.Point(4, 5);
GeneralSettingsPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
GeneralSettingsPanel.Name = "GeneralSettingsPanel";
GeneralSettingsPanel.Size = new System.Drawing.Size(449, 317);
GeneralSettingsPanel.TabIndex = 18;
//
// MinimizeInactiveClientsCheckBox
//
this.MinimizeInactiveClientsCheckBox.AutoSize = true;
this.MinimizeInactiveClientsCheckBox.Location = new System.Drawing.Point(12, 122);
this.MinimizeInactiveClientsCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.MinimizeInactiveClientsCheckBox.Name = "MinimizeInactiveClientsCheckBox";
this.MinimizeInactiveClientsCheckBox.Size = new System.Drawing.Size(239, 24);
this.MinimizeInactiveClientsCheckBox.TabIndex = 24;
this.MinimizeInactiveClientsCheckBox.Text = "Minimize inactive EVE clients";
this.MinimizeInactiveClientsCheckBox.UseVisualStyleBackColor = true;
this.MinimizeInactiveClientsCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// EnableClientLayoutTrackingCheckBox
//
this.EnableClientLayoutTrackingCheckBox.AutoSize = true;
this.EnableClientLayoutTrackingCheckBox.Location = new System.Drawing.Point(12, 48);
this.EnableClientLayoutTrackingCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.EnableClientLayoutTrackingCheckBox.Name = "EnableClientLayoutTrackingCheckBox";
this.EnableClientLayoutTrackingCheckBox.Size = new System.Drawing.Size(182, 24);
this.EnableClientLayoutTrackingCheckBox.TabIndex = 19;
this.EnableClientLayoutTrackingCheckBox.Text = "Track client locations";
this.EnableClientLayoutTrackingCheckBox.UseVisualStyleBackColor = true;
this.EnableClientLayoutTrackingCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// HideActiveClientThumbnailCheckBox
//
this.HideActiveClientThumbnailCheckBox.AutoSize = true;
this.HideActiveClientThumbnailCheckBox.Checked = true;
this.HideActiveClientThumbnailCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.HideActiveClientThumbnailCheckBox.Location = new System.Drawing.Point(12, 85);
this.HideActiveClientThumbnailCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.HideActiveClientThumbnailCheckBox.Name = "HideActiveClientThumbnailCheckBox";
this.HideActiveClientThumbnailCheckBox.Size = new System.Drawing.Size(266, 24);
this.HideActiveClientThumbnailCheckBox.TabIndex = 20;
this.HideActiveClientThumbnailCheckBox.Text = "Hide preview of active EVE client";
this.HideActiveClientThumbnailCheckBox.UseVisualStyleBackColor = true;
this.HideActiveClientThumbnailCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ShowThumbnailsAlwaysOnTopCheckBox
//
this.ShowThumbnailsAlwaysOnTopCheckBox.AutoSize = true;
this.ShowThumbnailsAlwaysOnTopCheckBox.Checked = true;
this.ShowThumbnailsAlwaysOnTopCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowThumbnailsAlwaysOnTopCheckBox.Location = new System.Drawing.Point(12, 159);
this.ShowThumbnailsAlwaysOnTopCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ShowThumbnailsAlwaysOnTopCheckBox.Name = "ShowThumbnailsAlwaysOnTopCheckBox";
this.ShowThumbnailsAlwaysOnTopCheckBox.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowThumbnailsAlwaysOnTopCheckBox.Size = new System.Drawing.Size(197, 24);
this.ShowThumbnailsAlwaysOnTopCheckBox.TabIndex = 21;
this.ShowThumbnailsAlwaysOnTopCheckBox.Text = "Previews always on top";
this.ShowThumbnailsAlwaysOnTopCheckBox.UseVisualStyleBackColor = true;
this.ShowThumbnailsAlwaysOnTopCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// HideThumbnailsOnLostFocusCheckBox
//
this.HideThumbnailsOnLostFocusCheckBox.AutoSize = true;
this.HideThumbnailsOnLostFocusCheckBox.Checked = true;
this.HideThumbnailsOnLostFocusCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.HideThumbnailsOnLostFocusCheckBox.Location = new System.Drawing.Point(12, 196);
this.HideThumbnailsOnLostFocusCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.HideThumbnailsOnLostFocusCheckBox.Name = "HideThumbnailsOnLostFocusCheckBox";
this.HideThumbnailsOnLostFocusCheckBox.Size = new System.Drawing.Size(340, 24);
this.HideThumbnailsOnLostFocusCheckBox.TabIndex = 22;
this.HideThumbnailsOnLostFocusCheckBox.Text = "Hide previews when EVE client is not active";
this.HideThumbnailsOnLostFocusCheckBox.UseVisualStyleBackColor = true;
this.HideThumbnailsOnLostFocusCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// EnablePerClientThumbnailsLayoutsCheckBox
//
this.EnablePerClientThumbnailsLayoutsCheckBox.AutoSize = true;
this.EnablePerClientThumbnailsLayoutsCheckBox.Checked = true;
this.EnablePerClientThumbnailsLayoutsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.EnablePerClientThumbnailsLayoutsCheckBox.Location = new System.Drawing.Point(12, 233);
this.EnablePerClientThumbnailsLayoutsCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.EnablePerClientThumbnailsLayoutsCheckBox.Name = "EnablePerClientThumbnailsLayoutsCheckBox";
this.EnablePerClientThumbnailsLayoutsCheckBox.Size = new System.Drawing.Size(272, 24);
this.EnablePerClientThumbnailsLayoutsCheckBox.TabIndex = 23;
this.EnablePerClientThumbnailsLayoutsCheckBox.Text = "Unique layout for each EVE client";
this.EnablePerClientThumbnailsLayoutsCheckBox.UseVisualStyleBackColor = true;
this.EnablePerClientThumbnailsLayoutsCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// MinimizeToTrayCheckBox
//
this.MinimizeToTrayCheckBox.AutoSize = true;
this.MinimizeToTrayCheckBox.Location = new System.Drawing.Point(12, 11);
this.MinimizeToTrayCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.MinimizeToTrayCheckBox.Name = "MinimizeToTrayCheckBox";
this.MinimizeToTrayCheckBox.Size = new System.Drawing.Size(205, 24);
this.MinimizeToTrayCheckBox.TabIndex = 18;
this.MinimizeToTrayCheckBox.Text = "Minimize to System Tray";
this.MinimizeToTrayCheckBox.UseVisualStyleBackColor = true;
this.MinimizeToTrayCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ThumbnailTabPage
//
ThumbnailTabPage.BackColor = System.Drawing.SystemColors.Control;
ThumbnailTabPage.Controls.Add(ThumbnailSettingsPanel);
ThumbnailTabPage.Location = new System.Drawing.Point(124, 4);
ThumbnailTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ThumbnailTabPage.Name = "ThumbnailTabPage";
ThumbnailTabPage.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5);
ThumbnailTabPage.Size = new System.Drawing.Size(457, 327);
ThumbnailTabPage.TabIndex = 1;
ThumbnailTabPage.Text = "Thumbnail";
//
// ThumbnailSettingsPanel
//
ThumbnailSettingsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
ThumbnailSettingsPanel.Controls.Add(HeigthLabel);
ThumbnailSettingsPanel.Controls.Add(WidthLabel);
ThumbnailSettingsPanel.Controls.Add(this.ThumbnailsWidthNumericEdit);
ThumbnailSettingsPanel.Controls.Add(this.ThumbnailsHeightNumericEdit);
ThumbnailSettingsPanel.Controls.Add(this.ThumbnailOpacityTrackBar);
ThumbnailSettingsPanel.Controls.Add(OpacityLabel);
ThumbnailSettingsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
ThumbnailSettingsPanel.Location = new System.Drawing.Point(4, 5);
ThumbnailSettingsPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ThumbnailSettingsPanel.Name = "ThumbnailSettingsPanel";
ThumbnailSettingsPanel.Size = new System.Drawing.Size(449, 317);
ThumbnailSettingsPanel.TabIndex = 19;
//
// HeigthLabel
//
HeigthLabel.AutoSize = true;
HeigthLabel.Location = new System.Drawing.Point(12, 88);
HeigthLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
HeigthLabel.Name = "HeigthLabel";
HeigthLabel.Size = new System.Drawing.Size(133, 20);
HeigthLabel.TabIndex = 24;
HeigthLabel.Text = "Thumbnail Heigth";
//
// WidthLabel
//
WidthLabel.AutoSize = true;
WidthLabel.Location = new System.Drawing.Point(12, 51);
WidthLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
WidthLabel.Name = "WidthLabel";
WidthLabel.Size = new System.Drawing.Size(127, 20);
WidthLabel.TabIndex = 23;
WidthLabel.Text = "Thumbnail Width";
//
// ThumbnailsWidthNumericEdit
//
this.ThumbnailsWidthNumericEdit.BackColor = System.Drawing.SystemColors.Window;
this.ThumbnailsWidthNumericEdit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ThumbnailsWidthNumericEdit.CausesValidation = false;
this.ThumbnailsWidthNumericEdit.Increment = new decimal(new int[] {
10,
0,
0,
0});
this.ThumbnailsWidthNumericEdit.Location = new System.Drawing.Point(158, 48);
this.ThumbnailsWidthNumericEdit.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ThumbnailsWidthNumericEdit.Maximum = new decimal(new int[] {
999999,
0,
0,
0});
this.ThumbnailsWidthNumericEdit.Name = "ThumbnailsWidthNumericEdit";
this.ThumbnailsWidthNumericEdit.Size = new System.Drawing.Size(72, 26);
this.ThumbnailsWidthNumericEdit.TabIndex = 21;
this.ThumbnailsWidthNumericEdit.Value = new decimal(new int[] {
100,
0,
0,
0});
this.ThumbnailsWidthNumericEdit.ValueChanged += new System.EventHandler(this.ThumbnailSizeChanged_Handler);
//
// ThumbnailsHeightNumericEdit
//
this.ThumbnailsHeightNumericEdit.BackColor = System.Drawing.SystemColors.Window;
this.ThumbnailsHeightNumericEdit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ThumbnailsHeightNumericEdit.CausesValidation = false;
this.ThumbnailsHeightNumericEdit.Increment = new decimal(new int[] {
10,
0,
0,
0});
this.ThumbnailsHeightNumericEdit.Location = new System.Drawing.Point(158, 85);
this.ThumbnailsHeightNumericEdit.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ThumbnailsHeightNumericEdit.Maximum = new decimal(new int[] {
99999999,
0,
0,
0});
this.ThumbnailsHeightNumericEdit.Name = "ThumbnailsHeightNumericEdit";
this.ThumbnailsHeightNumericEdit.Size = new System.Drawing.Size(72, 26);
this.ThumbnailsHeightNumericEdit.TabIndex = 22;
this.ThumbnailsHeightNumericEdit.Value = new decimal(new int[] {
70,
0,
0,
0});
this.ThumbnailsHeightNumericEdit.ValueChanged += new System.EventHandler(this.ThumbnailSizeChanged_Handler);
//
// ThumbnailOpacityTrackBar
//
this.ThumbnailOpacityTrackBar.AutoSize = false;
this.ThumbnailOpacityTrackBar.LargeChange = 10;
this.ThumbnailOpacityTrackBar.Location = new System.Drawing.Point(92, 9);
this.ThumbnailOpacityTrackBar.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ThumbnailOpacityTrackBar.Maximum = 100;
this.ThumbnailOpacityTrackBar.Minimum = 20;
this.ThumbnailOpacityTrackBar.Name = "ThumbnailOpacityTrackBar";
this.ThumbnailOpacityTrackBar.Size = new System.Drawing.Size(286, 34);
this.ThumbnailOpacityTrackBar.TabIndex = 20;
this.ThumbnailOpacityTrackBar.TickFrequency = 10;
this.ThumbnailOpacityTrackBar.Value = 20;
this.ThumbnailOpacityTrackBar.ValueChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// OpacityLabel
//
OpacityLabel.AutoSize = true;
OpacityLabel.Location = new System.Drawing.Point(12, 14);
OpacityLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
OpacityLabel.Name = "OpacityLabel";
OpacityLabel.Size = new System.Drawing.Size(62, 20);
OpacityLabel.TabIndex = 19;
OpacityLabel.Text = "Opacity";
//
// ZoomTabPage
//
this.ZoomTabPage.BackColor = System.Drawing.SystemColors.Control;
this.ZoomTabPage.Controls.Add(ZoomSettingsPanel);
this.ZoomTabPage.Location = new System.Drawing.Point(124, 4);
this.ZoomTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomTabPage.Name = "ZoomTabPage";
this.ZoomTabPage.Size = new System.Drawing.Size(457, 327);
this.ZoomTabPage.TabIndex = 2;
this.ZoomTabPage.Text = "Zoom";
//
// ZoomSettingsPanel
//
ZoomSettingsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
ZoomSettingsPanel.Controls.Add(ZoomFactorLabel);
ZoomSettingsPanel.Controls.Add(this.ZoomAnchorPanel);
ZoomSettingsPanel.Controls.Add(ZoomAnchorLabel);
ZoomSettingsPanel.Controls.Add(this.EnableThumbnailZoomCheckBox);
ZoomSettingsPanel.Controls.Add(this.ThumbnailZoomFactorNumericEdit);
ZoomSettingsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
ZoomSettingsPanel.Location = new System.Drawing.Point(0, 0);
ZoomSettingsPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ZoomSettingsPanel.Name = "ZoomSettingsPanel";
ZoomSettingsPanel.Size = new System.Drawing.Size(457, 327);
ZoomSettingsPanel.TabIndex = 36;
//
// ZoomFactorLabel
//
ZoomFactorLabel.AutoSize = true;
ZoomFactorLabel.Location = new System.Drawing.Point(12, 51);
ZoomFactorLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
ZoomFactorLabel.Name = "ZoomFactorLabel";
ZoomFactorLabel.Size = new System.Drawing.Size(100, 20);
ZoomFactorLabel.TabIndex = 39;
ZoomFactorLabel.Text = "Zoom Factor";
//
// ZoomAnchorPanel
//
this.ZoomAnchorPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorNWRadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorNRadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorNERadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorWRadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorSERadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorCRadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorSRadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorERadioButton);
this.ZoomAnchorPanel.Controls.Add(this.ZoomAanchorSWRadioButton);
this.ZoomAnchorPanel.Location = new System.Drawing.Point(122, 83);
this.ZoomAnchorPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAnchorPanel.Name = "ZoomAnchorPanel";
this.ZoomAnchorPanel.Size = new System.Drawing.Size(114, 111);
this.ZoomAnchorPanel.TabIndex = 38;
//
// ZoomAanchorNWRadioButton
//
this.ZoomAanchorNWRadioButton.AutoSize = true;
this.ZoomAanchorNWRadioButton.Location = new System.Drawing.Point(4, 5);
this.ZoomAanchorNWRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorNWRadioButton.Name = "ZoomAanchorNWRadioButton";
this.ZoomAanchorNWRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorNWRadioButton.TabIndex = 0;
this.ZoomAanchorNWRadioButton.TabStop = true;
this.ZoomAanchorNWRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorNWRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorNRadioButton
//
this.ZoomAanchorNRadioButton.AutoSize = true;
this.ZoomAanchorNRadioButton.Location = new System.Drawing.Point(46, 5);
this.ZoomAanchorNRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorNRadioButton.Name = "ZoomAanchorNRadioButton";
this.ZoomAanchorNRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorNRadioButton.TabIndex = 1;
this.ZoomAanchorNRadioButton.TabStop = true;
this.ZoomAanchorNRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorNRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorNERadioButton
//
this.ZoomAanchorNERadioButton.AutoSize = true;
this.ZoomAanchorNERadioButton.Location = new System.Drawing.Point(88, 5);
this.ZoomAanchorNERadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorNERadioButton.Name = "ZoomAanchorNERadioButton";
this.ZoomAanchorNERadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorNERadioButton.TabIndex = 2;
this.ZoomAanchorNERadioButton.TabStop = true;
this.ZoomAanchorNERadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorNERadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorWRadioButton
//
this.ZoomAanchorWRadioButton.AutoSize = true;
this.ZoomAanchorWRadioButton.Location = new System.Drawing.Point(4, 45);
this.ZoomAanchorWRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorWRadioButton.Name = "ZoomAanchorWRadioButton";
this.ZoomAanchorWRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorWRadioButton.TabIndex = 3;
this.ZoomAanchorWRadioButton.TabStop = true;
this.ZoomAanchorWRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorWRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorSERadioButton
//
this.ZoomAanchorSERadioButton.AutoSize = true;
this.ZoomAanchorSERadioButton.Location = new System.Drawing.Point(88, 85);
this.ZoomAanchorSERadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorSERadioButton.Name = "ZoomAanchorSERadioButton";
this.ZoomAanchorSERadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorSERadioButton.TabIndex = 8;
this.ZoomAanchorSERadioButton.TabStop = true;
this.ZoomAanchorSERadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorSERadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorCRadioButton
//
this.ZoomAanchorCRadioButton.AutoSize = true;
this.ZoomAanchorCRadioButton.Location = new System.Drawing.Point(46, 45);
this.ZoomAanchorCRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorCRadioButton.Name = "ZoomAanchorCRadioButton";
this.ZoomAanchorCRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorCRadioButton.TabIndex = 4;
this.ZoomAanchorCRadioButton.TabStop = true;
this.ZoomAanchorCRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorCRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorSRadioButton
//
this.ZoomAanchorSRadioButton.AutoSize = true;
this.ZoomAanchorSRadioButton.Location = new System.Drawing.Point(46, 85);
this.ZoomAanchorSRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorSRadioButton.Name = "ZoomAanchorSRadioButton";
this.ZoomAanchorSRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorSRadioButton.TabIndex = 7;
this.ZoomAanchorSRadioButton.TabStop = true;
this.ZoomAanchorSRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorSRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorERadioButton
//
this.ZoomAanchorERadioButton.AutoSize = true;
this.ZoomAanchorERadioButton.Location = new System.Drawing.Point(88, 45);
this.ZoomAanchorERadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorERadioButton.Name = "ZoomAanchorERadioButton";
this.ZoomAanchorERadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorERadioButton.TabIndex = 5;
this.ZoomAanchorERadioButton.TabStop = true;
this.ZoomAanchorERadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorERadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAanchorSWRadioButton
//
this.ZoomAanchorSWRadioButton.AutoSize = true;
this.ZoomAanchorSWRadioButton.Location = new System.Drawing.Point(4, 85);
this.ZoomAanchorSWRadioButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ZoomAanchorSWRadioButton.Name = "ZoomAanchorSWRadioButton";
this.ZoomAanchorSWRadioButton.Size = new System.Drawing.Size(21, 20);
this.ZoomAanchorSWRadioButton.TabIndex = 6;
this.ZoomAanchorSWRadioButton.TabStop = true;
this.ZoomAanchorSWRadioButton.UseVisualStyleBackColor = true;
this.ZoomAanchorSWRadioButton.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ZoomAnchorLabel
//
ZoomAnchorLabel.AutoSize = true;
ZoomAnchorLabel.Location = new System.Drawing.Point(12, 88);
ZoomAnchorLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
ZoomAnchorLabel.Name = "ZoomAnchorLabel";
ZoomAnchorLabel.Size = new System.Drawing.Size(60, 20);
ZoomAnchorLabel.TabIndex = 40;
ZoomAnchorLabel.Text = "Anchor";
//
// EnableThumbnailZoomCheckBox
//
this.EnableThumbnailZoomCheckBox.AutoSize = true;
this.EnableThumbnailZoomCheckBox.Checked = true;
this.EnableThumbnailZoomCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.EnableThumbnailZoomCheckBox.Location = new System.Drawing.Point(12, 11);
this.EnableThumbnailZoomCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.EnableThumbnailZoomCheckBox.Name = "EnableThumbnailZoomCheckBox";
this.EnableThumbnailZoomCheckBox.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.EnableThumbnailZoomCheckBox.Size = new System.Drawing.Size(141, 24);
this.EnableThumbnailZoomCheckBox.TabIndex = 36;
this.EnableThumbnailZoomCheckBox.Text = "Zoom on hover";
this.EnableThumbnailZoomCheckBox.UseVisualStyleBackColor = true;
this.EnableThumbnailZoomCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ThumbnailZoomFactorNumericEdit
//
this.ThumbnailZoomFactorNumericEdit.BackColor = System.Drawing.SystemColors.Window;
this.ThumbnailZoomFactorNumericEdit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ThumbnailZoomFactorNumericEdit.Location = new System.Drawing.Point(122, 48);
this.ThumbnailZoomFactorNumericEdit.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ThumbnailZoomFactorNumericEdit.Maximum = new decimal(new int[] {
10,
0,
0,
0});
this.ThumbnailZoomFactorNumericEdit.Minimum = new decimal(new int[] {
2,
0,
0,
0});
this.ThumbnailZoomFactorNumericEdit.Name = "ThumbnailZoomFactorNumericEdit";
this.ThumbnailZoomFactorNumericEdit.Size = new System.Drawing.Size(57, 26);
this.ThumbnailZoomFactorNumericEdit.TabIndex = 37;
this.ThumbnailZoomFactorNumericEdit.Value = new decimal(new int[] {
2,
0,
0,
0});
this.ThumbnailZoomFactorNumericEdit.ValueChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// OverlayTabPage
//
OverlayTabPage.BackColor = System.Drawing.SystemColors.Control;
OverlayTabPage.Controls.Add(OverlaySettingsPanel);
OverlayTabPage.Location = new System.Drawing.Point(124, 4);
OverlayTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
OverlayTabPage.Name = "OverlayTabPage";
OverlayTabPage.Size = new System.Drawing.Size(457, 327);
OverlayTabPage.TabIndex = 3;
OverlayTabPage.Text = "Overlay";
//
// OverlaySettingsPanel
//
OverlaySettingsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
OverlaySettingsPanel.Controls.Add(this.HighlightColorLabel);
OverlaySettingsPanel.Controls.Add(this.ActiveClientHighlightColorButton);
OverlaySettingsPanel.Controls.Add(this.EnableActiveClientHighlightCheckBox);
OverlaySettingsPanel.Controls.Add(this.ShowThumbnailOverlaysCheckBox);
OverlaySettingsPanel.Controls.Add(this.ShowThumbnailFramesCheckBox);
OverlaySettingsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
OverlaySettingsPanel.Location = new System.Drawing.Point(0, 0);
OverlaySettingsPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
OverlaySettingsPanel.Name = "OverlaySettingsPanel";
OverlaySettingsPanel.Size = new System.Drawing.Size(457, 327);
OverlaySettingsPanel.TabIndex = 25;
//
// HighlightColorLabel
//
this.HighlightColorLabel.AutoSize = true;
this.HighlightColorLabel.Location = new System.Drawing.Point(8, 120);
this.HighlightColorLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.HighlightColorLabel.Name = "HighlightColorLabel";
this.HighlightColorLabel.Size = new System.Drawing.Size(46, 20);
this.HighlightColorLabel.TabIndex = 29;
this.HighlightColorLabel.Text = "Color";
//
// ActiveClientHighlightColorButton
//
this.ActiveClientHighlightColorButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ActiveClientHighlightColorButton.Location = new System.Drawing.Point(63, 118);
this.ActiveClientHighlightColorButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ActiveClientHighlightColorButton.Name = "ActiveClientHighlightColorButton";
this.ActiveClientHighlightColorButton.Size = new System.Drawing.Size(138, 25);
this.ActiveClientHighlightColorButton.TabIndex = 28;
this.ActiveClientHighlightColorButton.Click += new System.EventHandler(this.ActiveClientHighlightColorButton_Click);
//
// EnableActiveClientHighlightCheckBox
//
this.EnableActiveClientHighlightCheckBox.AutoSize = true;
this.EnableActiveClientHighlightCheckBox.Checked = true;
this.EnableActiveClientHighlightCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.EnableActiveClientHighlightCheckBox.Location = new System.Drawing.Point(12, 85);
this.EnableActiveClientHighlightCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.EnableActiveClientHighlightCheckBox.Name = "EnableActiveClientHighlightCheckBox";
this.EnableActiveClientHighlightCheckBox.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.EnableActiveClientHighlightCheckBox.Size = new System.Drawing.Size(183, 24);
this.EnableActiveClientHighlightCheckBox.TabIndex = 27;
this.EnableActiveClientHighlightCheckBox.Text = "Highlight active client";
this.EnableActiveClientHighlightCheckBox.UseVisualStyleBackColor = true;
this.EnableActiveClientHighlightCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ShowThumbnailOverlaysCheckBox
//
this.ShowThumbnailOverlaysCheckBox.AutoSize = true;
this.ShowThumbnailOverlaysCheckBox.Checked = true;
this.ShowThumbnailOverlaysCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowThumbnailOverlaysCheckBox.Location = new System.Drawing.Point(12, 11);
this.ShowThumbnailOverlaysCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ShowThumbnailOverlaysCheckBox.Name = "ShowThumbnailOverlaysCheckBox";
this.ShowThumbnailOverlaysCheckBox.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowThumbnailOverlaysCheckBox.Size = new System.Drawing.Size(128, 24);
this.ShowThumbnailOverlaysCheckBox.TabIndex = 25;
this.ShowThumbnailOverlaysCheckBox.Text = "Show overlay";
this.ShowThumbnailOverlaysCheckBox.UseVisualStyleBackColor = true;
this.ShowThumbnailOverlaysCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ShowThumbnailFramesCheckBox
//
this.ShowThumbnailFramesCheckBox.AutoSize = true;
this.ShowThumbnailFramesCheckBox.Checked = true;
this.ShowThumbnailFramesCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowThumbnailFramesCheckBox.Location = new System.Drawing.Point(12, 48);
this.ShowThumbnailFramesCheckBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ShowThumbnailFramesCheckBox.Name = "ShowThumbnailFramesCheckBox";
this.ShowThumbnailFramesCheckBox.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowThumbnailFramesCheckBox.Size = new System.Drawing.Size(128, 24);
this.ShowThumbnailFramesCheckBox.TabIndex = 26;
this.ShowThumbnailFramesCheckBox.Text = "Show frames";
this.ShowThumbnailFramesCheckBox.UseVisualStyleBackColor = true;
this.ShowThumbnailFramesCheckBox.CheckedChanged += new System.EventHandler(this.OptionChanged_Handler);
//
// ClientsTabPage
//
ClientsTabPage.BackColor = System.Drawing.SystemColors.Control;
ClientsTabPage.Controls.Add(ClientsPanel);
ClientsTabPage.Location = new System.Drawing.Point(124, 4);
ClientsTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ClientsTabPage.Name = "ClientsTabPage";
ClientsTabPage.Size = new System.Drawing.Size(457, 327);
ClientsTabPage.TabIndex = 4;
ClientsTabPage.Text = "Active Clients";
//
// ClientsPanel
//
ClientsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
ClientsPanel.Controls.Add(this.ThumbnailsList);
ClientsPanel.Controls.Add(ThumbnailsListLabel);
ClientsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
ClientsPanel.Location = new System.Drawing.Point(0, 0);
ClientsPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
ClientsPanel.Name = "ClientsPanel";
ClientsPanel.Size = new System.Drawing.Size(457, 327);
ClientsPanel.TabIndex = 32;
//
// ThumbnailsList
//
this.ThumbnailsList.BackColor = System.Drawing.SystemColors.Window;
this.ThumbnailsList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ThumbnailsList.CheckOnClick = true;
this.ThumbnailsList.Dock = System.Windows.Forms.DockStyle.Bottom;
this.ThumbnailsList.FormattingEnabled = true;
this.ThumbnailsList.IntegralHeight = false;
this.ThumbnailsList.Location = new System.Drawing.Point(0, 49);
this.ThumbnailsList.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ThumbnailsList.Name = "ThumbnailsList";
this.ThumbnailsList.Size = new System.Drawing.Size(455, 276);
this.ThumbnailsList.TabIndex = 34;
this.ThumbnailsList.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.ThumbnailsList_ItemCheck_Handler);
//
// ThumbnailsListLabel
//
ThumbnailsListLabel.AutoSize = true;
ThumbnailsListLabel.Location = new System.Drawing.Point(12, 14);
ThumbnailsListLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
ThumbnailsListLabel.Name = "ThumbnailsListLabel";
ThumbnailsListLabel.Size = new System.Drawing.Size(238, 20);
ThumbnailsListLabel.TabIndex = 33;
ThumbnailsListLabel.Text = "Thumbnails (check to force hide)";
//
// AboutTabPage
//
AboutTabPage.BackColor = System.Drawing.SystemColors.Control;
AboutTabPage.Controls.Add(AboutPanel);
AboutTabPage.Location = new System.Drawing.Point(124, 4);
AboutTabPage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
AboutTabPage.Name = "AboutTabPage";
AboutTabPage.Size = new System.Drawing.Size(457, 327);
AboutTabPage.TabIndex = 5;
AboutTabPage.Text = "About";
//
// AboutPanel
//
AboutPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
AboutPanel.Controls.Add(DocumentationLinkLabel);
AboutPanel.Controls.Add(DescriptionLabel);
AboutPanel.Controls.Add(this.VersionLabel);
AboutPanel.Controls.Add(NameLabel);
AboutPanel.Controls.Add(this.DocumentationLink);
AboutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
AboutPanel.Location = new System.Drawing.Point(0, 0);
AboutPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
AboutPanel.Name = "AboutPanel";
AboutPanel.Size = new System.Drawing.Size(457, 327);
AboutPanel.TabIndex = 2;
//
// DocumentationLinkLabel
//
DocumentationLinkLabel.AutoSize = true;
DocumentationLinkLabel.Location = new System.Drawing.Point(0, 242);
DocumentationLinkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
DocumentationLinkLabel.Name = "DocumentationLinkLabel";
DocumentationLinkLabel.Padding = new System.Windows.Forms.Padding(12, 5, 12, 5);
DocumentationLinkLabel.Size = new System.Drawing.Size(336, 30);
DocumentationLinkLabel.TabIndex = 6;
DocumentationLinkLabel.Text = "For more information visit the forum thread:";
//
// DescriptionLabel
//
DescriptionLabel.Location = new System.Drawing.Point(0, 63);
DescriptionLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
DescriptionLabel.Name = "DescriptionLabel";
DescriptionLabel.Padding = new System.Windows.Forms.Padding(12, 5, 12, 5);
DescriptionLabel.Size = new System.Drawing.Size(392, 178);
DescriptionLabel.TabIndex = 5;
DescriptionLabel.Text = resources.GetString("DescriptionLabel.Text");
//
// VersionLabel
//
this.VersionLabel.AutoSize = true;
this.VersionLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.VersionLabel.Location = new System.Drawing.Point(200, 14);
this.VersionLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.VersionLabel.Name = "VersionLabel";
this.VersionLabel.Size = new System.Drawing.Size(69, 29);
this.VersionLabel.TabIndex = 4;
this.VersionLabel.Text = "1.0.0";
//
// NameLabel
//
NameLabel.AutoSize = true;
NameLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
NameLabel.Location = new System.Drawing.Point(6, 14);
NameLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
NameLabel.Name = "NameLabel";
NameLabel.Size = new System.Drawing.Size(193, 29);
NameLabel.TabIndex = 3;
NameLabel.Text = "EVE-O Preview";
//
// DocumentationLink
//
this.DocumentationLink.Location = new System.Drawing.Point(0, 266);
this.DocumentationLink.Margin = new System.Windows.Forms.Padding(45, 5, 4, 5);
this.DocumentationLink.Name = "DocumentationLink";
this.DocumentationLink.Padding = new System.Windows.Forms.Padding(12, 5, 12, 5);
this.DocumentationLink.Size = new System.Drawing.Size(393, 51);
this.DocumentationLink.TabIndex = 2;
this.DocumentationLink.TabStop = true;
this.DocumentationLink.Text = "to be set from prresenter to be set from prresenter to be set from prresenter to " +
"be set from prresenter";
this.DocumentationLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.DocumentationLinkClicked_Handler);
//
// NotifyIcon
//
this.NotifyIcon.ContextMenuStrip = this.TrayMenu;
this.NotifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("NotifyIcon.Icon")));
this.NotifyIcon.Text = "EVE-O Preview";
this.NotifyIcon.Visible = true;
this.NotifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.RestoreMainForm_Handler);
//
// TrayMenu
//
this.TrayMenu.ImageScalingSize = new System.Drawing.Size(24, 24);
this.TrayMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
TitleMenuItem,
RestoreWindowMenuItem,
SeparatorMenuItem,
ExitMenuItem});
this.TrayMenu.Name = "contextMenuStrip1";
this.TrayMenu.Size = new System.Drawing.Size(200, 100);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(585, 335);
this.Controls.Add(ContentTabControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(0);
this.MaximizeBox = false;
this.Name = "MainForm";
this.Text = "EVE-O Preview";
this.TopMost = true;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormClosing_Handler);
this.Load += new System.EventHandler(this.MainFormResize_Handler);
this.Resize += new System.EventHandler(this.MainFormResize_Handler);
ContentTabControl.ResumeLayout(false);
GeneralTabPage.ResumeLayout(false);
GeneralSettingsPanel.ResumeLayout(false);
GeneralSettingsPanel.PerformLayout();
ThumbnailTabPage.ResumeLayout(false);
ThumbnailSettingsPanel.ResumeLayout(false);
ThumbnailSettingsPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailsWidthNumericEdit)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailsHeightNumericEdit)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailOpacityTrackBar)).EndInit();
this.ZoomTabPage.ResumeLayout(false);
ZoomSettingsPanel.ResumeLayout(false);
ZoomSettingsPanel.PerformLayout();
this.ZoomAnchorPanel.ResumeLayout(false);
this.ZoomAnchorPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ThumbnailZoomFactorNumericEdit)).EndInit();
OverlayTabPage.ResumeLayout(false);
OverlaySettingsPanel.ResumeLayout(false);
OverlaySettingsPanel.PerformLayout();
ClientsTabPage.ResumeLayout(false);
ClientsPanel.ResumeLayout(false);
ClientsPanel.PerformLayout();
AboutTabPage.ResumeLayout(false);
AboutPanel.ResumeLayout(false);
AboutPanel.PerformLayout();
this.TrayMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private NotifyIcon NotifyIcon;
private ContextMenuStrip TrayMenu;
private TabPage ZoomTabPage;
private CheckBox EnableClientLayoutTrackingCheckBox;
private CheckBox HideActiveClientThumbnailCheckBox;
private CheckBox ShowThumbnailsAlwaysOnTopCheckBox;
private CheckBox HideThumbnailsOnLostFocusCheckBox;
private CheckBox EnablePerClientThumbnailsLayoutsCheckBox;
private CheckBox MinimizeToTrayCheckBox;
private NumericUpDown ThumbnailsWidthNumericEdit;
private NumericUpDown ThumbnailsHeightNumericEdit;
private TrackBar ThumbnailOpacityTrackBar;
private Panel ZoomAnchorPanel;
private RadioButton ZoomAanchorNWRadioButton;
private RadioButton ZoomAanchorNRadioButton;
private RadioButton ZoomAanchorNERadioButton;
private RadioButton ZoomAanchorWRadioButton;
private RadioButton ZoomAanchorSERadioButton;
private RadioButton ZoomAanchorCRadioButton;
private RadioButton ZoomAanchorSRadioButton;
private RadioButton ZoomAanchorERadioButton;
private RadioButton ZoomAanchorSWRadioButton;
private CheckBox EnableThumbnailZoomCheckBox;
private NumericUpDown ThumbnailZoomFactorNumericEdit;
private Label HighlightColorLabel;
private Panel ActiveClientHighlightColorButton;
private CheckBox EnableActiveClientHighlightCheckBox;
private CheckBox ShowThumbnailOverlaysCheckBox;
private CheckBox ShowThumbnailFramesCheckBox;
private CheckedListBox ThumbnailsList;
private LinkLabel DocumentationLink;
private Label VersionLabel;
private CheckBox MinimizeInactiveClientsCheckBox;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrInt64()
{
var test = new SimpleBinaryOpTest__OrInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrInt64
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[ElementCount];
private static Int64[] _data2 = new Int64[ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64> _dataTable;
static SimpleBinaryOpTest__OrInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__OrInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Or(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Or(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Or(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrInt64();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
if ((long)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((long)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using Axiom.Runtime.Instructions;
namespace Axiom.Runtime
{
public class AMProgram : AbstractProgram
{
private Hashtable _labelOccurrence = new Hashtable();
private int _numberOfArguments;
public int NumberOfArguments
{
get { return _numberOfArguments; }
set { _numberOfArguments = value; }
}
private ProgramNode _p;
public ProgramNode P
{
get { return _p; }
set { _p = value; }
}
private ProgramNode _cp;
public ProgramNode CP
{
get { return _cp; }
set { _cp = value; }
}
private ProgramNode _programTop;
private ProgramNode _program;
public ProgramNode Program
{
get { return _program; }
set { _program = value; }
}
public void AddProgramNode(ProgramNode node)
{
if (_program == null)
{
_program = node;
_programTop = _program;
return;
}
_programTop.Next = node;
_programTop = _programTop.Next;
}
public void AddInstruction(AbstractInstruction instruction)
{
if (_program == null)
{
_program = new ProgramNode(instruction);
_programTop = _program;
_p = _program;
return;
}
_programTop.Next = new ProgramNode(instruction);
_programTop = _programTop.Next;
}
public void Next()
{
_p = _p.Next;
}
public ProgramClause this[string procedureName]
{
get { return (ProgramClause)_labels[procedureName]; }
}
public override void Initialize(ArrayList program)
{
foreach (AbstractInstruction i in program)
{
if (i.Name() == "procedure")
{
ProcedureInstruction p = (ProcedureInstruction)i;
ProgramClause pClause = new ProgramClause(p.ProcedureName, p.Arity);
AddLabel(pClause.Name + "/" + pClause.Arity, pClause);
}
else
{
AddInstruction(i);
}
}
_p = _program;
}
public override bool Stop()
{
return (_p == null || _p.Instruction.Name().Equals("halt"));
}
public override AbstractInstruction CurrentInstruction()
{
return _p.Instruction;
}
public bool IsDefined(string label)
{
return _labels.ContainsKey(label);
}
public void AddLabel(string label, ProgramClause procedure)
{
if (!_labels.ContainsKey(label))
{
_labels.Add(label, procedure);
_labelOccurrence[label] = 1;
AddProgramNode(procedure);
}
else
{
AddLabelAndPatchPredicates(label, procedure);
int i = (int)_labelOccurrence[label];
i++;
_labelOccurrence[label] = i;
}
}
private void AddLabelAndPatchPredicates(string label, ProgramClause procedure)
{
AMInstructionSet instructionSet = new AMInstructionSet();
int occurrence = (int)_labelOccurrence[label];
if (occurrence == 1)
{
ProgramClause p = (ProgramClause)_labels[label];
string nextLabelName = p.Name + "%" + occurrence + "/" + p.Arity;
p.Instruction = instructionSet.CreateInstruction("try_me_else", nextLabelName);
ProgramClause newClause = new ProgramClause(nextLabelName, p.Arity, instructionSet.CreateInstruction("trust_me"));
p.NextPredicate = newClause;
AddProgramNode(newClause);
_labels[nextLabelName] = newClause;
}
else
{
ProgramClause pc = (ProgramClause)_labels[label];
string nextLabelName = pc.Name + "%" + occurrence + "/" + pc.Arity;
ProgramClause lastLabel = this[pc.Name + "%" + (occurrence - 1) + "/" + pc.Arity];
lastLabel.Instruction = instructionSet.CreateInstruction("retry_me_else", nextLabelName);
ProgramClause newClause = new ProgramClause(nextLabelName, pc.Arity, instructionSet.CreateInstruction("trust_me"));
lastLabel.NextPredicate = newClause;
AddProgramNode(newClause);
_labels[nextLabelName] = newClause;
}
}
private Hashtable _labels = new Hashtable();
public void AssertFirst(string predicateName, int arity, ArrayList code)
{
AMInstructionSet iset = new AMInstructionSet();
if (!_labels.ContainsKey(predicateName + "/" + arity))
{
AddLabel(predicateName + "/" + arity, new ProgramClause(predicateName, arity));
_labelOccurrence[predicateName + "/" + arity] = 1;
// add instructions
return;
}
string pLabel = predicateName + "/" + arity;
int occurrence = (int)_labelOccurrence[predicateName + "/" + arity];
if (occurrence == 1)
{
ProgramClause oldPredicate = (ProgramClause)_labels[pLabel];
oldPredicate.Instruction = iset.CreateInstruction("trust_me");
string nextLabel = predicateName + "%" + occurrence + "/" + arity;
oldPredicate.Name = nextLabel;
_labels[nextLabel] = oldPredicate;
ProgramClause newFirst = new ProgramClause(predicateName, arity, iset.CreateInstruction("try_me_else", nextLabel));
newFirst.NextPredicate = oldPredicate;
_labels[pLabel] = newFirst;
occurrence++;
_labelOccurrence[pLabel] = occurrence;
AddProgramNode(newFirst);
foreach (AbstractInstruction inst in code)
{
AddInstruction(inst);
}
}
else
{
ProgramClause oldFirst = (ProgramClause)_labels[pLabel];
ProgramClause newFirst = new ProgramClause(predicateName, arity, iset.CreateInstruction("try_me_else", predicateName + "%1/" + arity));
newFirst.NextPredicate = oldFirst;
oldFirst.Name = predicateName + "%1/" + arity;
oldFirst.Instruction = iset.CreateInstruction("retry_me_else", predicateName + "%2/" + arity);
_labels[pLabel] = newFirst;
AddProgramNode(newFirst);
foreach (AbstractInstruction inst in code)
{
AddInstruction(inst);
}
occurrence++;
_labelOccurrence[pLabel] = occurrence;
PatchPredicates(predicateName, arity, oldFirst);
}
}
private void PatchPredicates(string predicateName, int arity, ProgramClause oldFirst)
{
AMInstructionSet iset = new AMInstructionSet();
int i = 1;
ProgramClause clause = null;
for (clause = oldFirst; clause.Instruction.Name() != "trust_me"; clause = clause.NextPredicate)
{
clause.Name = predicateName + "%" + i + "/" + arity;
if (clause.Instruction.Name() != "try_me_else")
{
clause.Instruction = iset.CreateInstruction("retry_me_else", predicateName + "%" + (i + 1) + "/" + arity);
}
_labels[predicateName + "%" + i + "/" + arity] = clause;
i++;
}
// patch the last predicate also
clause.Name = predicateName + "%" + i + "/" + arity;
_labels[predicateName + "%" + i + "/" + arity] = clause;
}
public void AssertLast(string predicateName, int arity, ArrayList code)
{
AddLabel(predicateName + "/" + arity, new ProgramClause(predicateName, arity));
foreach (AbstractInstruction inst in code)
{
AddInstruction(inst);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using Orleans.Configuration;
using Orleans.Providers.Azure;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Orleans.Storage
{
/// <summary>
/// Simple storage provider for writing grain state data to Azure blob storage in JSON format.
/// </summary>
public class AzureBlobGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
{
private JsonSerializerSettings jsonSettings;
private CloudBlobContainer container;
private ILogger logger;
private readonly string name;
private AzureBlobStorageOptions options;
private SerializationManager serializationManager;
private IGrainFactory grainFactory;
private ITypeResolver typeResolver;
private ILoggerFactory loggerFactory;
/// <summary> Default constructor </summary>
public AzureBlobGrainStorage(
string name,
AzureBlobStorageOptions options,
SerializationManager serializationManager,
IGrainFactory grainFactory,
ITypeResolver typeResolver,
ILoggerFactory loggerFactory)
{
this.name = name;
this.options = options;
this.serializationManager = serializationManager;
this.grainFactory = grainFactory;
this.typeResolver = typeResolver;
this.loggerFactory = loggerFactory;
this.logger = this.loggerFactory.CreateLogger($"{typeof(AzureTableGrainStorageFactory).FullName}.{name}");
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public async Task ReadStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Reading, "Reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
try
{
var blob = container.GetBlockBlobReference(blobName);
byte[] contents;
try
{
using (var stream = new MemoryStream())
{
await blob.DownloadToStreamAsync(stream).ConfigureAwait(false);
contents = stream.ToArray();
}
}
catch (StorageException exception) when (exception.IsBlobNotFound())
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobNotFound, "BlobNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
return;
}
catch (StorageException exception) when (exception.IsContainerNotFound())
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "ContainerNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
return;
}
if (contents == null || contents.Length == 0)
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobEmpty, "BlobEmpty reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
return;
}
grainState.State = this.ConvertFromStorageFormat(contents);
grainState.ETag = blob.Properties.ETag;
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Read: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ReadError,
string.Format("Error reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
private static string GetBlobName(string grainType, GrainReference grainId)
{
return string.Format("{0}-{1}.json", grainType, grainId.ToKeyString());
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
try
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Writing, "Writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
var (contents, mimeType) = ConvertToStorageFormat(grainState.State);;
var blob = container.GetBlockBlobReference(blobName);
blob.Properties.ContentType = mimeType;
await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, blob);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Written: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_WriteError,
string.Format("Error writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
/// <summary> Clear / Delete state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public async Task ClearStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
try
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ClearingData, "Clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
var blob = container.GetBlockBlobReference(blobName);
await DoOptimisticUpdate(() => blob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, AccessCondition.GenerateIfMatchCondition(grainState.ETag), null, null),
blob, grainState.ETag).ConfigureAwait(false);
grainState.ETag = null;
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Cleared, "Cleared: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, blob.Properties.ETag, blobName, container.Name);
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ClearError,
string.Format("Error clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
private async Task WriteStateAndCreateContainerIfNotExists(string grainType, GrainReference grainId, IGrainState grainState, byte[] contents, CloudBlockBlob blob)
{
try
{
await DoOptimisticUpdate(() => blob.UploadFromByteArrayAsync(contents, 0, contents.Length, AccessCondition.GenerateIfMatchCondition(grainState.ETag), null, null),
blob, grainState.ETag).ConfigureAwait(false);
grainState.ETag = blob.Properties.ETag;
}
catch (StorageException exception) when (exception.IsContainerNotFound())
{
// if the container does not exist, create it, and make another attempt
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "Creating container: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blob.Name, container.Name);
await container.CreateIfNotExistsAsync().ConfigureAwait(false);
await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, blob).ConfigureAwait(false);
}
}
private static async Task DoOptimisticUpdate(Func<Task> updateOperation, CloudBlob blob, string currentETag)
{
try
{
await updateOperation.Invoke().ConfigureAwait(false);
}
catch (StorageException ex) when (ex.IsPreconditionFailed() || ex.IsConflict())
{
throw new InconsistentStateException($"Blob storage condition not Satisfied. BlobName: {blob.Name}, Container: {blob.Container?.Name}, CurrentETag: {currentETag}", "Unknown", currentETag, ex);
}
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureBlobGrainStorage>(this.name), this.options.InitStage, Init);
}
/// <summary> Initialization function for this storage provider. </summary>
private async Task Init(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
try
{
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}");
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString));
this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
var account = CloudStorageAccount.Parse(this.options.ConnectionString);
var blobClient = account.CreateCloudBlobClient();
container = blobClient.GetContainerReference(this.options.ContainerName);
await container.CreateIfNotExistsAsync().ConfigureAwait(false);
stopWatch.Stop();
this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
}
catch (Exception ex)
{
stopWatch.Stop();
this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
throw;
}
}
/// <summary>
/// Serialize to the configured storage format, either binary or JSON.
/// </summary>
/// <param name="grainState">The grain state data to be serialized</param>
/// <remarks>
/// See:
/// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
/// for more on the JSON serializer.
/// </remarks>
private (byte[], string) ConvertToStorageFormat(object grainState)
{
byte[] data;
string mimeType;
if (this.options.UseJson)
{
data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(grainState, this.jsonSettings));
mimeType = "application/json";
}
else
{
data = this.serializationManager.SerializeToByteArray(grainState);
mimeType = "application/octet-stream";
}
return (data, mimeType);
}
/// <summary>
/// Deserialize from the configured storage format, either binary or JSON.
/// </summary>
/// <param name="contents">The serialized contents.</param>
/// <remarks>
/// See:
/// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
/// for more on the JSON serializer.
/// </remarks>
private object ConvertFromStorageFormat(byte[] contents)
{
object result;
if (this.options.UseJson)
{
var str = Encoding.UTF8.GetString(contents);
result = JsonConvert.DeserializeObject<object>(str, this.jsonSettings);
}
else
{
result = this.serializationManager.DeserializeFromByteArray<object>(contents);
}
return result;
}
}
public static class AzureBlobGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AzureBlobStorageOptions>>();
return ActivatorUtilities.CreateInstance<AzureBlobGrainStorage>(services, name, optionsMonitor.Get(name));
}
}
}
| |
// <copyright file="GPGSUtil.cs" company="Google Inc.">
// Copyright (C) 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.
// </copyright>
// Keep this even on unsupported configurations.
namespace GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Utility class to perform various tasks in the editor.
/// </summary>
public static class GPGSUtil
{
/// <summary>Property key for project settings.</summary>
public const string SERVICEIDKEY = "App.NearbdServiceId";
/// <summary>Property key for project settings.</summary>
public const string APPIDKEY = "proj.AppId";
/// <summary>Property key for project settings.</summary>
public const string CLASSDIRECTORYKEY = "proj.classDir";
/// <summary>Property key for project settings.</summary>
public const string CLASSNAMEKEY = "proj.ConstantsClassName";
/// <summary>Property key for project settings.</summary>
public const string WEBCLIENTIDKEY = "and.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSCLIENTIDKEY = "ios.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSBUNDLEIDKEY = "ios.BundleId";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDRESOURCEKEY = "and.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDSETUPDONEKEY = "android.SetupDone";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDBUNDLEIDKEY = "and.BundleId";
/// <summary>Property key for project settings.</summary>
public const string IOSRESOURCEKEY = "ios.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string IOSSETUPDONEKEY = "ios.SetupDone";
/// <summary>Property key for plugin version.</summary>
public const string PLUGINVERSIONKEY = "proj.pluginVersion";
/// <summary>Property key for nearby settings done.</summary>
public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone";
/// <summary>Property key for project settings.</summary>
public const string LASTUPGRADEKEY = "lastUpgrade";
/// <summary>Constant for token replacement</summary>
private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__";
/// <summary>Constant for token replacement</summary>
private const string APPIDPLACEHOLDER = "__APP_ID__";
/// <summary>Constant for token replacement</summary>
private const string CLASSNAMEPLACEHOLDER = "__Class__";
/// <summary>Constant for token replacement</summary>
private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__";
/// <summary>Constant for token replacement</summary>
private const string PLUGINVERSIONPLACEHOLDER = "__PLUGIN_VERSION__";
/// <summary>Constant for require google plus token replacement</summary>
private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__";
/// <summary>Property key for project settings.</summary>
private const string TOKENPERMISSIONKEY = "proj.tokenPermissions";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__";
/// <summary>Constant for token replacement</summary>
private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__";
/// <summary>
/// The game info file path. This is a generated file.
/// </summary>
private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs";
/// <summary>
/// The map of replacements for filling in code templates. The
/// key is the string that appears in the template as a placeholder,
/// the value is the key into the GPGSProjectSettings.
/// </summary>
private static Dictionary<string, string> replacements =
new Dictionary<string, string>()
{
{ SERVICEIDPLACEHOLDER, SERVICEIDKEY },
{ APPIDPLACEHOLDER, APPIDKEY },
{ CLASSNAMEPLACEHOLDER, CLASSNAMEKEY },
{ WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY },
{ IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY },
{ IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY },
{ PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY}
};
/// <summary>
/// Replaces / in file path to be the os specific separator.
/// </summary>
/// <returns>The path.</returns>
/// <param name="path">Path with correct separators.</param>
public static string SlashesToPlatformSeparator(string path)
{
return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
}
/// <summary>
/// Reads the file.
/// </summary>
/// <returns>The file contents. The slashes are corrected.</returns>
/// <param name="filePath">File path.</param>
public static string ReadFile(string filePath)
{
filePath = SlashesToPlatformSeparator(filePath);
if (!File.Exists(filePath))
{
Alert("Plugin error: file not found: " + filePath);
return null;
}
StreamReader sr = new StreamReader(filePath);
string body = sr.ReadToEnd();
sr.Close();
return body;
}
/// <summary>
/// Reads the editor template.
/// </summary>
/// <returns>The editor template contents.</returns>
/// <param name="name">Name of the template in the editor directory.</param>
public static string ReadEditorTemplate(string name)
{
return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt"));
}
/// <summary>
/// Writes the file.
/// </summary>
/// <param name="file">File path - the slashes will be corrected.</param>
/// <param name="body">Body of the file to write.</param>
public static void WriteFile(string file, string body)
{
file = SlashesToPlatformSeparator(file);
using (var wr = new StreamWriter(file, false))
{
wr.Write(body);
}
}
/// <summary>
/// Validates the string to be a valid nearby service id.
/// </summary>
/// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns>
/// <param name="s">string to test.</param>
public static bool LooksLikeValidServiceId(string s)
{
if (s.Length < 3)
{
return false;
}
foreach (char c in s)
{
if (!char.IsLetterOrDigit(c) && c != '.')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid app identifier.
/// </summary>
/// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidAppId(string s)
{
if (s.Length < 5)
{
return false;
}
foreach (char c in s)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid client identifier.
/// </summary>
/// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidClientId(string s)
{
return s.EndsWith(".googleusercontent.com");
}
/// <summary>
/// Looks the like a valid bundle identifier.
/// </summary>
/// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidBundleId(string s)
{
return s.Length > 3;
}
/// <summary>
/// Looks like a valid package.
/// </summary>
/// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidPackageName(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new Exception("cannot be empty");
}
string[] parts = s.Split(new char[] { '.' });
foreach (string p in parts)
{
char[] bytes = p.ToCharArray();
for (int i = 0; i < bytes.Length; i++)
{
if (i == 0 && !char.IsLetter(bytes[i]))
{
throw new Exception("each part must start with a letter");
}
else if (char.IsWhiteSpace(bytes[i]))
{
throw new Exception("cannot contain spaces");
}
else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_')
{
throw new Exception("must be alphanumeric or _");
}
}
}
return parts.Length >= 1;
}
/// <summary>
/// Determines if is setup done.
/// </summary>
/// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns>
public static bool IsSetupDone()
{
bool doneSetup = true;
#if UNITY_ANDROID
doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(APPIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with AppId. " +
"Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
#elif (UNITY_IPHONE && !NO_GPGS)
doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(IOSCLIENTIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with Client Id. " +
"Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
#endif
return doneSetup;
}
/// <summary>
/// Makes legal identifier from string.
/// Returns a legal C# identifier from the given string. The transformations are:
/// - spaces => underscore _
/// - punctuation => empty string
/// - leading numbers are prefixed with underscore.
/// </summary>
/// <returns>the id</returns>
/// <param name="key">Key to convert to an identifier.</param>
public static string MakeIdentifier(string key)
{
string s;
string retval = string.Empty;
if (string.IsNullOrEmpty(key))
{
return "_";
}
s = key.Trim().Replace(' ', '_');
foreach (char c in s)
{
if (char.IsLetterOrDigit(c) || c == '_')
{
retval += c;
}
}
return retval;
}
/// <summary>
/// Displays an error dialog.
/// </summary>
/// <param name="s">the message</param>
public static void Alert(string s)
{
Alert(GPGSStrings.Error, s);
}
/// <summary>
/// Displays a dialog with the given title and message.
/// </summary>
/// <param name="title">the title.</param>
/// <param name="message">the message.</param>
public static void Alert(string title, string message)
{
EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok);
}
/// <summary>
/// Gets the android sdk path.
/// </summary>
/// <returns>The android sdk path.</returns>
public static string GetAndroidSdkPath()
{
string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
{
sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
}
return sdkPath;
}
/// <summary>
/// Determines if the android sdk exists.
/// </summary>
/// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns>
public static bool HasAndroidSdk()
{
string sdkPath = GetAndroidSdkPath();
return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
}
/// <summary>
/// Gets the unity major version.
/// </summary>
/// <returns>The unity major version.</returns>
public static int GetUnityMajorVersion()
{
#if UNITY_5
string majorVersion = Application.unityVersion.Split('.')[0];
int ver;
if (!int.TryParse(majorVersion, out ver))
{
ver = 0;
}
return ver;
#elif UNITY_4_6
return 4;
#else
return 0;
#endif
}
/// <summary>
/// Checks for the android manifest file exsistance.
/// </summary>
/// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns>
public static bool AndroidManifestExists()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
return File.Exists(destFilename);
}
/// <summary>
/// Generates the android manifest.
/// </summary>
public static void GenerateAndroidManifest()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
// Generate AndroidManifest.xml
string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
Dictionary<string, string> overrideValues =
new Dictionary<string, string>();
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value, overrideValues);
manifestBody = manifestBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(destFilename, manifestBody);
GPGSUtil.UpdateGameInfo();
}
/// <summary>
/// Writes the resource identifiers file. This file contains the
/// resource ids copied (downloaded?) from the play game app console.
/// </summary>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="resourceKeys">Resource keys.</param>
public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys)
{
string constantsValues = string.Empty;
string[] parts = className.Split('.');
string dirName = classDirectory;
if (string.IsNullOrEmpty(dirName))
{
dirName = "Assets";
}
string nameSpace = string.Empty;
for (int i = 0; i < parts.Length - 1; i++)
{
dirName += "/" + parts[i];
if (nameSpace != string.Empty)
{
nameSpace += ".";
}
nameSpace += parts[i];
}
EnsureDirExists(dirName);
foreach (DictionaryEntry ent in resourceKeys)
{
string key = MakeIdentifier((string)ent.Key);
constantsValues += " public const string " +
key + " = \"" + ent.Value + "\"; // <GPGSID>\n";
}
string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants");
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACESTARTPLACEHOLDER,
"namespace " + nameSpace + "\n{");
}
else
{
fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty);
}
fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]);
fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues);
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACEENDPLACEHOLDER,
"}");
}
else
{
fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty);
}
WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody);
}
/// <summary>
/// Updates the game info file. This is a generated file containing the
/// app and client ids.
/// </summary>
public static void UpdateGameInfo()
{
string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo");
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value);
fileBody = fileBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(GameInfoPath, fileBody);
}
/// <summary>
/// Ensures the dir exists.
/// </summary>
/// <param name="dir">Directory to check.</param>
public static void EnsureDirExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
/// <summary>
/// Deletes the dir if exists.
/// </summary>
/// <param name="dir">Directory to delete.</param>
public static void DeleteDirIfExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
}
/// <summary>
/// Gets the Google Play Services library version. This is only
/// needed for Unity versions less than 5.
/// </summary>
/// <returns>The GPS version.</returns>
/// <param name="libProjPath">Lib proj path.</param>
private static int GetGPSVersion(string libProjPath)
{
string versionFile = libProjPath + "/res/values/version.xml";
XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile));
bool inResource = false;
int version = -1;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "integer")
{
if ("google_play_services_version".Equals(
reader.GetAttribute("name")))
{
reader.Read();
Debug.Log("Read version string: " + reader.Value);
version = Convert.ToInt32(reader.Value);
}
}
}
reader.Close();
return version;
}
}
}
| |
//
// GraphicViewDemo.cs
// Programmation.Xam.Graphics2D
//
// Created by David Dancy on 23/01/2015.
// Copyright (c) 2015 Programmation Pty Limited. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
using System;
using System.Drawing;
using Foundation;
using UIKit;
using CoreGraphics;
namespace Programmation.Xam.Graphics2D
{
[Register ("GraphicViewDemo")]
public class GraphicViewDemo : NSObject
{
//// Initialization
static GraphicViewDemo()
{
// Colors Initialization
NoneColor = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 0.000f);
XamBlueColor = UIColor.FromRGBA(0.168f, 0.518f, 0.825f, 1.000f);
}
//// Colors
public static UIColor NoneColor { get; private set; }
public static UIColor XamBlueColor { get; private set; }
//// Drawing Methods
public static void DrawXamarinlogo()
{
//// Page-1
{
//// xamarin-logo
{
//// Logo Drawing
UIBezierPath logoPath = new UIBezierPath();
logoPath.MoveTo(new CGPoint(201.83f, 127.22f));
logoPath.AddLineTo(new CGPoint(191.51f, 107.43f));
logoPath.AddLineTo(new CGPoint(180.96f, 127.22f));
logoPath.AddLineTo(new CGPoint(169.62f, 127.22f));
logoPath.AddLineTo(new CGPoint(185.7f, 101.68f));
logoPath.AddLineTo(new CGPoint(171.23f, 76.29f));
logoPath.AddLineTo(new CGPoint(182.73f, 76.29f));
logoPath.AddLineTo(new CGPoint(192.12f, 95.58f));
logoPath.AddLineTo(new CGPoint(202.3f, 76.29f));
logoPath.AddLineTo(new CGPoint(212.82f, 76.29f));
logoPath.AddLineTo(new CGPoint(197.95f, 101.52f));
logoPath.AddLineTo(new CGPoint(213.06f, 127.22f));
logoPath.AddLineTo(new CGPoint(201.83f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(238.62f, 127.22f));
logoPath.AddLineTo(new CGPoint(238.62f, 121.68f));
logoPath.AddLineTo(new CGPoint(238.46f, 121.68f));
logoPath.AddCurveToPoint(new CGPoint(226.56f, 128.21f), new CGPoint(235.66f, 126.03f), new CGPoint(231.69f, 128.21f));
logoPath.AddCurveToPoint(new CGPoint(217.22f, 124.98f), new CGPoint(222.61f, 128.21f), new CGPoint(219.5f, 127.13f));
logoPath.AddCurveToPoint(new CGPoint(213.8f, 116.26f), new CGPoint(214.94f, 122.81f), new CGPoint(213.8f, 119.9f));
logoPath.AddCurveToPoint(new CGPoint(226.96f, 102.93f), new CGPoint(213.8f, 108.44f), new CGPoint(218.19f, 104.0f));
logoPath.AddLineTo(new CGPoint(238.69f, 101.31f));
logoPath.AddCurveToPoint(new CGPoint(231.08f, 93.1f), new CGPoint(238.69f, 95.84f), new CGPoint(236.16f, 93.1f));
logoPath.AddCurveToPoint(new CGPoint(217.73f, 97.58f), new CGPoint(226.24f, 93.1f), new CGPoint(221.79f, 94.59f));
logoPath.AddLineTo(new CGPoint(217.73f, 89.56f));
logoPath.AddCurveToPoint(new CGPoint(224.25f, 87.08f), new CGPoint(219.25f, 88.64f), new CGPoint(221.42f, 87.82f));
logoPath.AddCurveToPoint(new CGPoint(232.02f, 85.98f), new CGPoint(227.1f, 86.35f), new CGPoint(229.69f, 85.98f));
logoPath.AddCurveToPoint(new CGPoint(247.57f, 101.71f), new CGPoint(242.38f, 85.98f), new CGPoint(247.57f, 91.22f));
logoPath.AddLineTo(new CGPoint(247.57f, 127.22f));
logoPath.AddLineTo(new CGPoint(238.62f, 127.22f));
logoPath.AddLineTo(new CGPoint(238.62f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(230.02f, 108.78f));
logoPath.AddCurveToPoint(new CGPoint(224.32f, 110.79f), new CGPoint(227.32f, 109.13f), new CGPoint(225.42f, 109.79f));
logoPath.AddCurveToPoint(new CGPoint(222.72f, 115.31f), new CGPoint(223.25f, 111.76f), new CGPoint(222.72f, 113.27f));
logoPath.AddCurveToPoint(new CGPoint(224.56f, 119.44f), new CGPoint(222.72f, 116.99f), new CGPoint(223.33f, 118.37f));
logoPath.AddCurveToPoint(new CGPoint(229.39f, 121.01f), new CGPoint(225.79f, 120.49f), new CGPoint(227.4f, 121.01f));
logoPath.AddCurveToPoint(new CGPoint(236.06f, 118.22f), new CGPoint(232.09f, 121.01f), new CGPoint(234.31f, 120.08f));
logoPath.AddCurveToPoint(new CGPoint(238.69f, 111.26f), new CGPoint(237.82f, 116.36f), new CGPoint(238.69f, 114.04f));
logoPath.AddLineTo(new CGPoint(238.69f, 107.64f));
logoPath.AddLineTo(new CGPoint(230.02f, 108.78f));
logoPath.AddLineTo(new CGPoint(230.02f, 108.78f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(305.45f, 127.22f));
logoPath.AddLineTo(new CGPoint(305.45f, 104.5f));
logoPath.AddCurveToPoint(new CGPoint(303.69f, 96.16f), new CGPoint(305.45f, 100.75f), new CGPoint(304.86f, 97.97f));
logoPath.AddCurveToPoint(new CGPoint(297.48f, 93.41f), new CGPoint(302.53f, 94.33f), new CGPoint(300.47f, 93.41f));
logoPath.AddCurveToPoint(new CGPoint(291.48f, 96.71f), new CGPoint(295.1f, 93.41f), new CGPoint(293.1f, 94.51f));
logoPath.AddCurveToPoint(new CGPoint(289.04f, 104.62f), new CGPoint(289.85f, 98.89f), new CGPoint(289.04f, 101.52f));
logoPath.AddLineTo(new CGPoint(289.04f, 127.22f));
logoPath.AddLineTo(new CGPoint(279.97f, 127.22f));
logoPath.AddLineTo(new CGPoint(279.97f, 103.71f));
logoPath.AddCurveToPoint(new CGPoint(272.08f, 93.41f), new CGPoint(279.97f, 96.85f), new CGPoint(277.34f, 93.41f));
logoPath.AddCurveToPoint(new CGPoint(266.0f, 96.52f), new CGPoint(269.62f, 93.41f), new CGPoint(267.59f, 94.45f));
logoPath.AddCurveToPoint(new CGPoint(263.64f, 104.62f), new CGPoint(264.43f, 98.59f), new CGPoint(263.64f, 101.29f));
logoPath.AddLineTo(new CGPoint(263.64f, 127.22f));
logoPath.AddLineTo(new CGPoint(254.57f, 127.22f));
logoPath.AddLineTo(new CGPoint(254.57f, 86.96f));
logoPath.AddLineTo(new CGPoint(263.64f, 86.96f));
logoPath.AddLineTo(new CGPoint(263.64f, 93.18f));
logoPath.AddLineTo(new CGPoint(263.8f, 93.18f));
logoPath.AddCurveToPoint(new CGPoint(276.52f, 85.98f), new CGPoint(266.7f, 88.38f), new CGPoint(270.94f, 85.98f));
logoPath.AddCurveToPoint(new CGPoint(283.58f, 88.1f), new CGPoint(279.19f, 85.98f), new CGPoint(281.54f, 86.69f));
logoPath.AddCurveToPoint(new CGPoint(287.94f, 93.88f), new CGPoint(285.65f, 89.49f), new CGPoint(287.1f, 91.42f));
logoPath.AddCurveToPoint(new CGPoint(301.45f, 85.98f), new CGPoint(291.0f, 88.62f), new CGPoint(295.51f, 85.98f));
logoPath.AddCurveToPoint(new CGPoint(314.56f, 102.34f), new CGPoint(310.19f, 85.98f), new CGPoint(314.56f, 91.43f));
logoPath.AddLineTo(new CGPoint(314.56f, 127.22f));
logoPath.AddLineTo(new CGPoint(305.45f, 127.22f));
logoPath.AddLineTo(new CGPoint(305.45f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(344.71f, 127.22f));
logoPath.AddLineTo(new CGPoint(344.71f, 121.68f));
logoPath.AddLineTo(new CGPoint(344.55f, 121.68f));
logoPath.AddCurveToPoint(new CGPoint(332.66f, 128.21f), new CGPoint(341.75f, 126.03f), new CGPoint(337.79f, 128.21f));
logoPath.AddCurveToPoint(new CGPoint(323.31f, 124.98f), new CGPoint(328.71f, 128.21f), new CGPoint(325.59f, 127.13f));
logoPath.AddCurveToPoint(new CGPoint(319.9f, 116.26f), new CGPoint(321.04f, 122.81f), new CGPoint(319.9f, 119.9f));
logoPath.AddCurveToPoint(new CGPoint(333.05f, 102.93f), new CGPoint(319.9f, 108.44f), new CGPoint(324.28f, 104.0f));
logoPath.AddLineTo(new CGPoint(344.79f, 101.31f));
logoPath.AddCurveToPoint(new CGPoint(337.17f, 93.1f), new CGPoint(344.79f, 95.84f), new CGPoint(342.25f, 93.1f));
logoPath.AddCurveToPoint(new CGPoint(323.82f, 97.58f), new CGPoint(332.33f, 93.1f), new CGPoint(327.88f, 94.59f));
logoPath.AddLineTo(new CGPoint(323.82f, 89.56f));
logoPath.AddCurveToPoint(new CGPoint(330.34f, 87.08f), new CGPoint(325.34f, 88.64f), new CGPoint(327.51f, 87.82f));
logoPath.AddCurveToPoint(new CGPoint(338.12f, 85.98f), new CGPoint(333.19f, 86.35f), new CGPoint(335.79f, 85.98f));
logoPath.AddCurveToPoint(new CGPoint(353.66f, 101.71f), new CGPoint(348.48f, 85.98f), new CGPoint(353.66f, 91.22f));
logoPath.AddLineTo(new CGPoint(353.66f, 127.22f));
logoPath.AddLineTo(new CGPoint(344.71f, 127.22f));
logoPath.AddLineTo(new CGPoint(344.71f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(336.11f, 108.78f));
logoPath.AddCurveToPoint(new CGPoint(330.42f, 110.79f), new CGPoint(333.42f, 109.13f), new CGPoint(331.52f, 109.79f));
logoPath.AddCurveToPoint(new CGPoint(328.81f, 115.31f), new CGPoint(329.35f, 111.76f), new CGPoint(328.81f, 113.27f));
logoPath.AddCurveToPoint(new CGPoint(330.66f, 119.44f), new CGPoint(328.81f, 116.99f), new CGPoint(329.43f, 118.37f));
logoPath.AddCurveToPoint(new CGPoint(335.48f, 121.01f), new CGPoint(331.89f, 120.49f), new CGPoint(333.5f, 121.01f));
logoPath.AddCurveToPoint(new CGPoint(342.16f, 118.22f), new CGPoint(338.18f, 121.01f), new CGPoint(340.41f, 120.08f));
logoPath.AddCurveToPoint(new CGPoint(344.79f, 111.26f), new CGPoint(343.91f, 116.36f), new CGPoint(344.79f, 114.04f));
logoPath.AddLineTo(new CGPoint(344.79f, 107.64f));
logoPath.AddLineTo(new CGPoint(336.11f, 108.78f));
logoPath.AddLineTo(new CGPoint(336.11f, 108.78f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(384.04f, 95.81f));
logoPath.AddCurveToPoint(new CGPoint(378.78f, 94.43f), new CGPoint(382.55f, 94.89f), new CGPoint(380.8f, 94.43f));
logoPath.AddCurveToPoint(new CGPoint(372.38f, 97.82f), new CGPoint(376.16f, 94.43f), new CGPoint(374.03f, 95.56f));
logoPath.AddCurveToPoint(new CGPoint(369.95f, 106.62f), new CGPoint(370.76f, 100.07f), new CGPoint(369.95f, 103.01f));
logoPath.AddLineTo(new CGPoint(369.95f, 127.22f));
logoPath.AddLineTo(new CGPoint(360.88f, 127.22f));
logoPath.AddLineTo(new CGPoint(360.88f, 86.96f));
logoPath.AddLineTo(new CGPoint(369.95f, 86.96f));
logoPath.AddLineTo(new CGPoint(369.95f, 94.79f));
logoPath.AddLineTo(new CGPoint(370.1f, 94.79f));
logoPath.AddCurveToPoint(new CGPoint(380.39f, 86.26f), new CGPoint(372.04f, 89.1f), new CGPoint(375.47f, 86.26f));
logoPath.AddCurveToPoint(new CGPoint(384.04f, 86.81f), new CGPoint(381.99f, 86.26f), new CGPoint(383.2f, 86.44f));
logoPath.AddLineTo(new CGPoint(384.04f, 95.81f));
logoPath.AddLineTo(new CGPoint(384.04f, 95.81f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(393.07f, 77.96f));
logoPath.AddCurveToPoint(new CGPoint(389.14f, 76.47f), new CGPoint(391.53f, 77.96f), new CGPoint(390.22f, 77.46f));
logoPath.AddCurveToPoint(new CGPoint(387.53f, 72.73f), new CGPoint(388.07f, 75.44f), new CGPoint(387.53f, 74.2f));
logoPath.AddCurveToPoint(new CGPoint(389.14f, 68.92f), new CGPoint(387.53f, 71.21f), new CGPoint(388.07f, 69.94f));
logoPath.AddCurveToPoint(new CGPoint(393.07f, 67.38f), new CGPoint(390.22f, 67.9f), new CGPoint(391.53f, 67.38f));
logoPath.AddCurveToPoint(new CGPoint(397.04f, 68.96f), new CGPoint(394.64f, 67.38f), new CGPoint(395.96f, 67.91f));
logoPath.AddCurveToPoint(new CGPoint(398.64f, 72.73f), new CGPoint(398.11f, 69.98f), new CGPoint(398.64f, 71.24f));
logoPath.AddCurveToPoint(new CGPoint(397.04f, 76.47f), new CGPoint(398.64f, 74.2f), new CGPoint(398.11f, 75.44f));
logoPath.AddCurveToPoint(new CGPoint(393.07f, 77.96f), new CGPoint(395.96f, 77.46f), new CGPoint(394.64f, 77.96f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(388.44f, 127.22f));
logoPath.AddLineTo(new CGPoint(388.44f, 86.96f));
logoPath.AddLineTo(new CGPoint(397.51f, 86.96f));
logoPath.AddLineTo(new CGPoint(397.51f, 127.22f));
logoPath.AddLineTo(new CGPoint(388.44f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(431.78f, 127.22f));
logoPath.AddLineTo(new CGPoint(431.78f, 104.62f));
logoPath.AddCurveToPoint(new CGPoint(423.73f, 93.41f), new CGPoint(431.78f, 97.15f), new CGPoint(429.1f, 93.41f));
logoPath.AddCurveToPoint(new CGPoint(416.94f, 96.52f), new CGPoint(421.04f, 93.41f), new CGPoint(418.77f, 94.45f));
logoPath.AddCurveToPoint(new CGPoint(414.23f, 104.34f), new CGPoint(415.14f, 98.56f), new CGPoint(414.23f, 101.17f));
logoPath.AddLineTo(new CGPoint(414.23f, 127.22f));
logoPath.AddLineTo(new CGPoint(405.16f, 127.22f));
logoPath.AddLineTo(new CGPoint(405.16f, 86.96f));
logoPath.AddLineTo(new CGPoint(414.23f, 86.96f));
logoPath.AddLineTo(new CGPoint(414.23f, 93.41f));
logoPath.AddLineTo(new CGPoint(414.39f, 93.41f));
logoPath.AddCurveToPoint(new CGPoint(427.42f, 85.98f), new CGPoint(417.32f, 88.46f), new CGPoint(421.67f, 85.98f));
logoPath.AddCurveToPoint(new CGPoint(440.85f, 102.49f), new CGPoint(436.38f, 85.98f), new CGPoint(440.85f, 91.49f));
logoPath.AddLineTo(new CGPoint(440.85f, 127.22f));
logoPath.AddLineTo(new CGPoint(431.78f, 127.22f));
logoPath.AddLineTo(new CGPoint(431.78f, 127.22f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(71.43f, 56.0f));
logoPath.AddCurveToPoint(new CGPoint(64.59f, 59.97f), new CGPoint(68.68f, 56.01f), new CGPoint(65.98f, 57.57f));
logoPath.AddLineTo(new CGPoint(43.02f, 97.53f));
logoPath.AddCurveToPoint(new CGPoint(43.02f, 105.47f), new CGPoint(41.66f, 99.93f), new CGPoint(41.66f, 103.07f));
logoPath.AddLineTo(new CGPoint(64.59f, 143.03f));
logoPath.AddCurveToPoint(new CGPoint(71.43f, 147.0f), new CGPoint(65.98f, 145.43f), new CGPoint(68.68f, 146.99f));
logoPath.AddLineTo(new CGPoint(114.57f, 147.0f));
logoPath.AddCurveToPoint(new CGPoint(121.41f, 143.03f), new CGPoint(117.32f, 146.99f), new CGPoint(120.02f, 145.43f));
logoPath.AddLineTo(new CGPoint(142.98f, 105.47f));
logoPath.AddCurveToPoint(new CGPoint(142.98f, 97.53f), new CGPoint(144.34f, 103.07f), new CGPoint(144.34f, 99.93f));
logoPath.AddLineTo(new CGPoint(121.41f, 59.97f));
logoPath.AddCurveToPoint(new CGPoint(114.57f, 56.0f), new CGPoint(120.02f, 57.57f), new CGPoint(117.32f, 56.01f));
logoPath.AddLineTo(new CGPoint(71.43f, 56.0f));
logoPath.ClosePath();
logoPath.MoveTo(new CGPoint(71.82f, 77.98f));
logoPath.AddCurveToPoint(new CGPoint(72.0f, 77.98f), new CGPoint(71.88f, 77.97f), new CGPoint(71.94f, 77.97f));
logoPath.AddLineTo(new CGPoint(79.44f, 77.98f));
logoPath.AddCurveToPoint(new CGPoint(80.26f, 78.46f), new CGPoint(79.77f, 77.98f), new CGPoint(80.09f, 78.18f));
logoPath.AddLineTo(new CGPoint(92.88f, 101.02f));
logoPath.AddCurveToPoint(new CGPoint(93.0f, 101.38f), new CGPoint(92.94f, 101.13f), new CGPoint(92.98f, 101.25f));
logoPath.AddCurveToPoint(new CGPoint(93.12f, 101.02f), new CGPoint(93.02f, 101.25f), new CGPoint(93.06f, 101.13f));
logoPath.AddLineTo(new CGPoint(105.71f, 78.46f));
logoPath.AddCurveToPoint(new CGPoint(106.55f, 77.98f), new CGPoint(105.88f, 78.17f), new CGPoint(106.22f, 77.98f));
logoPath.AddLineTo(new CGPoint(114.0f, 77.98f));
logoPath.AddCurveToPoint(new CGPoint(114.84f, 79.4f), new CGPoint(114.65f, 77.98f), new CGPoint(115.15f, 78.82f));
logoPath.AddLineTo(new CGPoint(102.52f, 101.5f));
logoPath.AddLineTo(new CGPoint(114.84f, 123.57f));
logoPath.AddCurveToPoint(new CGPoint(114.0f, 125.02f), new CGPoint(115.18f, 124.16f), new CGPoint(114.67f, 125.03f));
logoPath.AddLineTo(new CGPoint(106.55f, 125.02f));
logoPath.AddCurveToPoint(new CGPoint(105.71f, 124.51f), new CGPoint(106.21f, 125.02f), new CGPoint(105.87f, 124.81f));
logoPath.AddLineTo(new CGPoint(93.12f, 101.95f));
logoPath.AddCurveToPoint(new CGPoint(93.0f, 101.59f), new CGPoint(93.06f, 101.84f), new CGPoint(93.02f, 101.72f));
logoPath.AddCurveToPoint(new CGPoint(92.88f, 101.95f), new CGPoint(92.98f, 101.72f), new CGPoint(92.94f, 101.84f));
logoPath.AddLineTo(new CGPoint(80.26f, 124.51f));
logoPath.AddCurveToPoint(new CGPoint(79.44f, 125.02f), new CGPoint(80.1f, 124.81f), new CGPoint(79.78f, 125.01f));
logoPath.AddLineTo(new CGPoint(72.0f, 125.02f));
logoPath.AddCurveToPoint(new CGPoint(71.16f, 123.57f), new CGPoint(71.33f, 125.03f), new CGPoint(70.82f, 124.16f));
logoPath.AddLineTo(new CGPoint(83.48f, 101.5f));
logoPath.AddLineTo(new CGPoint(71.16f, 79.4f));
logoPath.AddCurveToPoint(new CGPoint(71.82f, 77.98f), new CGPoint(70.86f, 78.87f), new CGPoint(71.23f, 78.09f));
logoPath.AddLineTo(new CGPoint(71.82f, 77.98f));
logoPath.ClosePath();
logoPath.MiterLimit = 4.0f;
logoPath.UsesEvenOddFillRule = true;
GraphicViewDemo.XamBlueColor.SetFill();
logoPath.Fill();
}
}
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Workflow.ComponentModel;
namespace System.Workflow.Activities.Rules
{
internal static class RuleDecompiler
{
#region Decompile literals
internal static void DecompileObjectLiteral(StringBuilder decompilation, object primitiveValue)
{
if (primitiveValue == null)
{
decompilation.Append("null");
}
else
{
Type primitiveType = primitiveValue.GetType();
if (primitiveType == typeof(string))
DecompileStringLiteral(decompilation, (string)primitiveValue);
else if (primitiveType == typeof(char))
DecompileCharacterLiteral(decompilation, (char)primitiveValue);
else if (primitiveType == typeof(long))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "L");
else if (primitiveType == typeof(uint))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "U");
else if (primitiveType == typeof(ulong))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "UL");
else if (primitiveType == typeof(float))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'f');
else if (primitiveType == typeof(double))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'd');
else if (primitiveType == typeof(decimal))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'm');
else
decompilation.Append(primitiveValue.ToString());
}
}
private static void DecompileFloatingPointLiteral(StringBuilder decompilation, object value, char suffix)
{
// Make sure decimal point isn't converted to a comma in European locales.
string svalue = Convert.ToString(value, CultureInfo.InvariantCulture);
decompilation.Append(svalue);
if (suffix == 'd')
{
// Don't append 'd' suffixes, they're ugly. Only if the string-ified value contains
// no decimal and no exponent do we need to append a ".0" to make it a double (as
// opposed to an integer).
bool hasDecimal = svalue.IndexOf('.') >= 0;
bool hasExponent = svalue.IndexOfAny(new char[] { 'e', 'E' }) >= 0;
if (!hasDecimal && !hasExponent)
decompilation.Append(".0");
}
else
{
decompilation.Append(suffix);
}
}
private static void DecompileSuffixedIntegerLiteral(StringBuilder decompilation, object value, string suffix)
{
decompilation.Append(value.ToString());
decompilation.Append(suffix);
}
private static void DecompileStringLiteral(StringBuilder decompilation, string strValue)
{
decompilation.Append("\"");
for (int i = 0; i < strValue.Length; ++i)
{
char c = strValue[i];
// is this character a surrogate pair?
if ((char.IsHighSurrogate(c)) && (i + 1 < strValue.Length) && (char.IsLowSurrogate(strValue[i + 1])))
{
// yes, so leave the two characters unchanged
decompilation.Append(c);
++i;
decompilation.Append(strValue[i]);
}
else
AppendCharacter(decompilation, c, '"');
}
decompilation.Append("\"");
}
private static void DecompileCharacterLiteral(StringBuilder decompilation, char charValue)
{
decompilation.Append("'");
AppendCharacter(decompilation, charValue, '\'');
decompilation.Append("'");
}
private static void AppendCharacter(StringBuilder decompilation, char charValue, char quoteCharacter)
{
if (charValue == quoteCharacter)
{
decompilation.Append("\\");
decompilation.Append(quoteCharacter);
}
else if (charValue == '\\')
{
decompilation.Append("\\\\");
}
else if ((charValue >= ' ' && charValue < '\u007f') || char.IsLetterOrDigit(charValue) || char.IsPunctuation(charValue))
{
decompilation.Append(charValue);
}
else
{
string escapeSequence = null;
switch (charValue)
{
case '\0':
escapeSequence = "\\0";
break;
case '\n':
escapeSequence = "\\n";
break;
case '\r':
escapeSequence = "\\r";
break;
case '\b':
escapeSequence = "\\b";
break;
case '\a':
escapeSequence = "\\a";
break;
case '\t':
escapeSequence = "\\t";
break;
case '\f':
escapeSequence = "\\f";
break;
case '\v':
escapeSequence = "\\v";
break;
}
if (escapeSequence != null)
{
decompilation.Append(escapeSequence);
}
else
{
decompilation.Append("\\u");
UInt16 cv = (UInt16)charValue;
for (int i = 12; i >= 0; i -= 4)
{
int mask = 0xF << i;
byte c = (byte)((cv & mask) >> i);
decompilation.Append("0123456789ABCDEF"[c]);
}
}
}
}
#endregion
#region Type decompilation
internal static string DecompileType(Type type)
{
if (type == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
DecompileType_Helper(sb, type);
return sb.ToString();
}
private static void DecompileType_Helper(StringBuilder decompilation, Type type)
{
int i;
if (type.HasElementType)
{
DecompileType_Helper(decompilation, type.GetElementType());
if (type.IsArray)
{
decompilation.Append("[");
decompilation.Append(',', type.GetArrayRank() - 1);
decompilation.Append("]");
}
else if (type.IsByRef)
{
decompilation.Append('&');
}
else if (type.IsPointer)
{
decompilation.Append('*');
}
}
else
{
string typeName = type.FullName;
if (typeName == null) // Full name may be null for an unbound generic.
typeName = type.Name;
typeName = UnmangleTypeName(typeName);
decompilation.Append(typeName);
if (type.IsGenericType)
{
decompilation.Append("<");
Type[] typeArgs = type.GetGenericArguments();
DecompileType_Helper(decompilation, typeArgs[0]); // decompile the first type arg
for (i = 1; i < typeArgs.Length; ++i)
{
decompilation.Append(", ");
DecompileType_Helper(decompilation, typeArgs[i]);
}
decompilation.Append(">");
}
}
}
internal static void DecompileType(StringBuilder decompilation, CodeTypeReference typeRef)
{
// Remove any back-tick decorations on generic types, if present.
string baseType = UnmangleTypeName(typeRef.BaseType);
decompilation.Append(baseType);
if (typeRef.TypeArguments != null && typeRef.TypeArguments.Count > 0)
{
decompilation.Append("<");
bool first = true;
foreach (CodeTypeReference argTypeRef in typeRef.TypeArguments)
{
if (!first)
decompilation.Append(", ");
first = false;
DecompileType(decompilation, argTypeRef);
}
decompilation.Append(">");
}
if (typeRef.ArrayRank > 0)
{
do
{
decompilation.Append("[");
for (int i = 1; i < typeRef.ArrayRank; ++i)
decompilation.Append(",");
decompilation.Append("]");
typeRef = typeRef.ArrayElementType;
} while (typeRef.ArrayRank > 0);
}
}
private static Dictionary<string, string> knownTypeMap = InitializeKnownTypeMap();
private static Dictionary<string, string> InitializeKnownTypeMap()
{
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("System.Char", "char");
map.Add("System.Byte", "byte");
map.Add("System.SByte", "sbyte");
map.Add("System.Int16", "short");
map.Add("System.UInt16", "ushort");
map.Add("System.Int32", "int");
map.Add("System.UInt32", "uint");
map.Add("System.Int64", "long");
map.Add("System.UInt64", "ulong");
map.Add("System.Single", "float");
map.Add("System.Double", "double");
map.Add("System.Decimal", "decimal");
map.Add("System.Boolean", "bool");
map.Add("System.String", "string");
map.Add("System.Object", "object");
map.Add("System.Void", "void");
return map;
}
private static string TryReplaceKnownTypes(string typeName)
{
string newTypeName = null;
if (!knownTypeMap.TryGetValue(typeName, out newTypeName))
newTypeName = typeName;
return newTypeName;
}
private static string UnmangleTypeName(string typeName)
{
int tickIndex = typeName.IndexOf('`');
if (tickIndex > 0)
typeName = typeName.Substring(0, tickIndex);
// Replace the '+' for a nested type with a '.'
typeName = typeName.Replace('+', '.');
typeName = TryReplaceKnownTypes(typeName);
return typeName;
}
#endregion
#region Method decompilation
internal static string DecompileMethod(MethodInfo method)
{
if (method == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
string operatorName;
DecompileType_Helper(sb, method.DeclaringType);
sb.Append('.');
if (knownOperatorMap.TryGetValue(method.Name, out operatorName))
sb.Append(operatorName);
else
sb.Append(method.Name);
sb.Append('(');
ParameterInfo[] parms = method.GetParameters();
for (int i = 0; i < parms.Length; ++i)
{
DecompileType_Helper(sb, parms[i].ParameterType);
if (i != parms.Length - 1)
sb.Append(", ");
}
sb.Append(')');
return sb.ToString();
}
private static Dictionary<string, string> knownOperatorMap = InitializeKnownOperatorMap();
private static Dictionary<string, string> InitializeKnownOperatorMap()
{
Dictionary<string, string> map = new Dictionary<string, string>(27);
// unary operators
map.Add("op_UnaryPlus", "operator +");
map.Add("op_UnaryNegation", "operator -");
map.Add("op_OnesComplement", "operator ~");
map.Add("op_LogicalNot", "operator !");
map.Add("op_Increment", "operator ++");
map.Add("op_Decrement", "operator --");
map.Add("op_True", "operator true");
map.Add("op_False", "operator false");
map.Add("op_Implicit", "implicit operator");
map.Add("op_Explicit", "explicit operator");
// binary operators
map.Add("op_Equality", "operator ==");
map.Add("op_Inequality", "operator !=");
map.Add("op_GreaterThan", "operator >");
map.Add("op_GreaterThanOrEqual", "operator >=");
map.Add("op_LessThan", "operator <");
map.Add("op_LessThanOrEqual", "operator <=");
map.Add("op_Addition", "operator +");
map.Add("op_Subtraction", "operator -");
map.Add("op_Multiply", "operator *");
map.Add("op_Division", "operator /");
map.Add("op_IntegerDivision", "operator \\");
map.Add("op_Modulus", "operator %");
map.Add("op_LeftShift", "operator <<");
map.Add("op_RightShift", "operator >>");
map.Add("op_BitwiseAnd", "operator &");
map.Add("op_BitwiseOr", "operator |");
map.Add("op_ExclusiveOr", "operator ^");
return map;
}
#endregion
#region Operator Precedence
// These operations are sorted in order of precedence, lowest-to-highest
private enum Operation
{
RootExpression,
LogicalOr, // ||
LogicalAnd, // &&
BitwiseOr, // |
BitwiseAnd, // &
Equality, // == !=
Comparitive, // < <= > >=
Additive, // + -
Multiplicative, // * / %
Unary, // - ! (cast)
Postfix, // field/property ref and method call
NoParentheses // Highest
}
private delegate Operation ComputePrecedence(CodeExpression expresssion);
private static Dictionary<Type, ComputePrecedence> precedenceMap = InitializePrecedenceMap();
private static Dictionary<Type, ComputePrecedence> InitializePrecedenceMap()
{
Dictionary<Type, ComputePrecedence> map = new Dictionary<Type, ComputePrecedence>(7);
map.Add(typeof(CodeBinaryOperatorExpression), GetBinaryPrecedence);
map.Add(typeof(CodeCastExpression), GetCastPrecedence);
map.Add(typeof(CodeFieldReferenceExpression), GetPostfixPrecedence);
map.Add(typeof(CodePropertyReferenceExpression), GetPostfixPrecedence);
map.Add(typeof(CodeMethodInvokeExpression), GetPostfixPrecedence);
map.Add(typeof(CodeObjectCreateExpression), GetPostfixPrecedence);
map.Add(typeof(CodeArrayCreateExpression), GetPostfixPrecedence);
return map;
}
private static Operation GetPostfixPrecedence(CodeExpression expression)
{
return Operation.Postfix;
}
private static Operation GetCastPrecedence(CodeExpression expression)
{
return Operation.Unary;
}
private static Operation GetBinaryPrecedence(CodeExpression expression)
{
CodeBinaryOperatorExpression binaryExpr = (CodeBinaryOperatorExpression)expression;
Operation operation = Operation.NoParentheses;
switch (binaryExpr.Operator)
{
case CodeBinaryOperatorType.Multiply:
case CodeBinaryOperatorType.Divide:
case CodeBinaryOperatorType.Modulus:
operation = Operation.Multiplicative;
break;
case CodeBinaryOperatorType.Subtract:
case CodeBinaryOperatorType.Add:
operation = Operation.Additive;
break;
case CodeBinaryOperatorType.LessThan:
case CodeBinaryOperatorType.LessThanOrEqual:
case CodeBinaryOperatorType.GreaterThan:
case CodeBinaryOperatorType.GreaterThanOrEqual:
operation = Operation.Comparitive;
break;
case CodeBinaryOperatorType.IdentityEquality:
case CodeBinaryOperatorType.ValueEquality:
case CodeBinaryOperatorType.IdentityInequality:
operation = Operation.Equality;
break;
case CodeBinaryOperatorType.BitwiseAnd:
operation = Operation.BitwiseAnd;
break;
case CodeBinaryOperatorType.BitwiseOr:
operation = Operation.BitwiseOr;
break;
case CodeBinaryOperatorType.BooleanAnd:
operation = Operation.LogicalAnd;
break;
case CodeBinaryOperatorType.BooleanOr:
operation = Operation.LogicalOr;
break;
default:
string message = string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, binaryExpr.Operator.ToString());
NotSupportedException exception = new NotSupportedException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr;
throw exception;
}
return operation;
}
private static Operation GetPrecedence(CodeExpression expression)
{
// Assume the operation needs no parentheses.
Operation operation = Operation.NoParentheses;
ComputePrecedence computePrecedence;
if (precedenceMap.TryGetValue(expression.GetType(), out computePrecedence))
operation = computePrecedence(expression);
return operation;
}
internal static bool MustParenthesize(CodeExpression childExpr, CodeExpression parentExpr)
{
// No parent... we're at the root, so no need to parenthesize the root.
if (parentExpr == null)
return false;
Operation childOperation = GetPrecedence(childExpr);
Operation parentOperation = GetPrecedence(parentExpr);
if (parentOperation == childOperation)
{
CodeBinaryOperatorExpression parentBinary = parentExpr as CodeBinaryOperatorExpression;
if (parentBinary != null)
{
if (childExpr == parentBinary.Right)
{
// Something like 2 - (3 - 4) needs parentheses.
return true;
}
else
{
// Something like (2 - 3) - 4 doesn't need parentheses.
return false;
}
}
else
{
return false;
}
}
else if (parentOperation > childOperation)
{
return true;
}
else
{
return false;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using GameLibrary.Dependencies.Physics;
using GameLibrary.Dependencies.Physics.Collision;
using GameLibrary.Dependencies.Physics.Dynamics.Joints;
using GameLibrary.Dependencies.Physics.Dynamics;
using GameLibrary.Dependencies.Physics.Dynamics.Contacts;
using GameLibrary.Dependencies.Physics.Collision.Shapes;
using GameLibrary.Dependencies.Physics.Common;
using GameLibrary.Dependencies.Physics.Controllers;
using GameLibrary.Dependencies.Entities;
namespace GameLibrary.Helpers
{
/// <summary>
/// A debug view that works in XNA.
/// A debug view shows you what happens inside the physics engine. You can view
/// bodies, joints, fixtures and more.
/// </summary>
public class DebugViewXNA : DebugView, IDisposable
{
//Drawing
private PrimitiveBatch _primitiveBatch;
private SpriteBatch _batch;
private SpriteFont _font;
private GraphicsDevice _device;
private Vector2[] _tempVertices = new Vector2[Settings.MaxPolygonVertices];
private List<StringData> _stringData;
private List<StringData> _worldStringData;
private Camera _camera;
private Matrix _localProjection;
private Matrix _localView;
//Shapes
public Color DefaultShapeColor = new Color(0.9f, 0.7f, 0.7f);
public Color InactiveShapeColor = new Color(0.5f, 0.5f, 0.3f);
public Color KinematicShapeColor = new Color(0.5f, 0.5f, 0.9f);
public Color SleepingShapeColor = new Color(0.6f, 0.6f, 0.6f);
public Color StaticShapeColor = new Color(0.5f, 0.9f, 0.5f);
public Color TextColor = Color.LightGreen;
//Contacts
private int _pointCount;
private const int MaxContactPoints = 2048;
private ContactPoint[] _points = new ContactPoint[MaxContactPoints];
//Debug panel
#if XBOX
public Vector2 DebugPanelPosition = new Vector2(55, 100);
#else
public Vector2 DebugPanelPosition = new Vector2(40, 100);
#endif
private int _max;
private int _avg;
private int _min;
/// <summary>
/// UserData to be displayed on the debug panel.
/// </summary>
public Dictionary<string, object> DebugPanelUserData;
//Performance graph
public bool AdaptiveLimits = true;
public float ValuesToGraph = 500;
public float MinimumValue = -1000;
public float MaximumValue = 1000;
private List<float> _graphTotalValues = new List<float>();
private List<float> _graphPhysicsValues = new List<float>();
private List<float> _graphEntitiesValues = new List<float>();
#if XBOX
public Rectangle PerformancePanelBounds = new Rectangle(305, 100, 200, 100);
#else
public Rectangle PerformancePanelBounds = new Rectangle(300, 100, 200, 100);
#endif
private Vector2[] _background = new Vector2[4];
public bool Enabled = true;
#if XBOX || WINDOWS_PHONE
public const int CircleSegments = 16;
#else
public const int CircleSegments = 32;
#endif
public DebugViewXNA(EntityWorld world, Camera camera)
: base(world)
{
world.ContactManager.PreSolve += PreSolve;
//Default flags
AppendFlags(DebugViewFlags.Shape);
AppendFlags(DebugViewFlags.Controllers);
AppendFlags(DebugViewFlags.Joint);
DebugPanelUserData = new Dictionary<string, object>();
this._camera = camera;
}
public void BeginCustomDraw()
{
Matrix proj = _camera.SimProjection, view = _camera.SimView;
BeginCustomDraw(ref proj, ref view);
}
public void BeginCustomDraw(ref Matrix projection, ref Matrix view)
{
_primitiveBatch.Begin(ref projection, ref view);
}
public void EndCustomDraw()
{
_primitiveBatch.End();
}
#region IDisposable Members
public void Dispose()
{
World.ContactManager.PreSolve -= PreSolve;
}
#endregion
private void PreSolve(Contact contact, ref Manifold oldManifold)
{
if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints)
{
Manifold manifold = contact.Manifold;
if (manifold.PointCount == 0)
{
return;
}
Fixture fixtureA = contact.FixtureA;
FixedArray2<PointState> state1, state2;
Collision.GetPointStates(out state1, out state2, ref oldManifold, ref manifold);
FixedArray2<Vector2> points;
Vector2 normal;
contact.GetWorldManifold(out normal, out points);
for (int i = 0; i < manifold.PointCount && _pointCount < MaxContactPoints; ++i)
{
if (fixtureA == null)
{
_points[i] = new ContactPoint();
}
ContactPoint cp = _points[_pointCount];
cp.Position = points[i];
cp.Normal = normal;
cp.State = state2[i];
_points[_pointCount] = cp;
++_pointCount;
}
}
}
/// <summary>
/// Call this to draw shapes and other debug draw data.
/// </summary>
private void DrawDebugData()
{
if ((Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape)
{
foreach (PhysicsBody b in World.BodyList)
{
if (b.UserData != null && b.UserData is Entity) //Draw the name of the entity
DrawString(true, (int)ConvertUnits.ToDisplayUnits(b.WorldCenter.X), (int)ConvertUnits.ToDisplayUnits(b.WorldCenter.Y), "[" + (b.UserData as Entity).Id + "] " + (b.UserData as Entity).Tag.ToString(), Color.LightSalmon, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
Transform xf;
b.GetTransform(out xf);
foreach (Fixture f in b.FixtureList)
{
if (b.Enabled == false)
{
DrawShape(f, xf, InactiveShapeColor);
}
else if (b.BodyType == BodyType.Static)
{
DrawShape(f, xf, StaticShapeColor);
}
else if (b.BodyType == BodyType.Kinematic)
{
DrawShape(f, xf, KinematicShapeColor);
}
else if (b.Awake == false)
{
DrawShape(f, xf, SleepingShapeColor);
}
else
{
DrawShape(f, xf, DefaultShapeColor);
}
}
}
}
if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints)
{
const float axisScale = 0.3f;
for (int i = 0; i < _pointCount; ++i)
{
ContactPoint point = _points[i];
if (point.State == PointState.Add)
{
// Add
DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.95f, 0.3f));
}
else if (point.State == PointState.Persist)
{
// Persist
DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.3f, 0.95f));
}
if ((Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals)
{
Vector2 p1 = point.Position;
Vector2 p2 = p1 + axisScale * point.Normal;
DrawSegment(p1, p2, new Color(0.4f, 0.9f, 0.4f));
}
}
_pointCount = 0;
}
if ((Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints)
{
foreach (PhysicsBody body in World.BodyList)
{
foreach (Fixture f in body.FixtureList)
{
PolygonShape polygon = f.Shape as PolygonShape;
if (polygon != null)
{
Transform xf;
body.GetTransform(out xf);
for (int i = 0; i < polygon.Vertices.Count; i++)
{
Vector2 tmp = MathUtils.Multiply(ref xf, polygon.Vertices[i]);
DrawPoint(tmp, 0.1f, Color.LightSalmon);
}
}
}
}
}
if ((Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint)
{
foreach (PhysicsJoint j in World.JointList)
{
DrawJoint(j);
}
}
if ((Flags & DebugViewFlags.Pair) == DebugViewFlags.Pair)
{
Color color = new Color(0.3f, 0.9f, 0.9f);
for (int i = 0; i < World.ContactManager.ContactList.Count; i++)
{
Contact c = World.ContactManager.ContactList[i];
Fixture fixtureA = c.FixtureA;
Fixture fixtureB = c.FixtureB;
AABB aabbA;
fixtureA.GetAABB(out aabbA, 0);
AABB aabbB;
fixtureB.GetAABB(out aabbB, 0);
Vector2 cA = aabbA.Center;
Vector2 cB = aabbB.Center;
DrawSegment(cA, cB, color);
}
}
if ((Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB)
{
Color color = new Color(0.9f, 0.3f, 0.9f);
IBroadPhase bp = World.ContactManager.BroadPhase;
foreach (PhysicsBody b in World.BodyList)
{
if (b.Enabled == false)
{
continue;
}
foreach (Fixture f in b.FixtureList)
{
for (int t = 0; t < f.ProxyCount; ++t)
{
FixtureProxy proxy = f.Proxies[t];
AABB aabb;
bp.GetFatAABB(proxy.ProxyId, out aabb);
DrawAABB(ref aabb, color);
}
}
}
}
if ((Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass)
{
foreach (PhysicsBody b in World.BodyList)
{
Transform xf;
b.GetTransform(out xf);
xf.Position = b.WorldCenter;
DrawTransform(ref xf);
}
}
if ((Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers)
{
for (int i = 0; i < World.ControllerList.Count; i++)
{
Controller controller = World.ControllerList[i];
BuoyancyController buoyancy = controller as BuoyancyController;
if (buoyancy != null)
{
AABB container = buoyancy.Container;
DrawAABB(ref container, Color.LightBlue);
}
}
}
if ((Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel)
{
DrawDebugPanel();
}
}
List<float> _graphAvgTotalValues = new List<float>();
private void DrawPerformanceGraph()
{
_graphTotalValues.Add(World.PhysicsUpdateTime + World.EntitySystemUpdateTime);
_graphEntitiesValues.Add(World.EntitySystemUpdateTime);
_graphPhysicsValues.Add(World.PhysicsUpdateTime);
if (_graphTotalValues.Count > ValuesToGraph + 1)
_graphTotalValues.RemoveAt(0);
if (_graphEntitiesValues.Count > ValuesToGraph + 1)
_graphEntitiesValues.RemoveAt(0);
if (_graphPhysicsValues.Count > ValuesToGraph + 1)
_graphPhysicsValues.RemoveAt(0);
if (_graphAvgTotalValues.Count > ValuesToGraph + 1)
_graphAvgTotalValues.RemoveAt(0);
float x = PerformancePanelBounds.X;
float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph;
float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top;
float yAxis = (PerformancePanelBounds.Bottom +
(MinimumValue / (MaximumValue - MinimumValue)) * yScale);
// we must have at least 2 values to start rendering
if (_graphTotalValues.Count > 2)
{
_max = (int)_graphTotalValues.Max();
_avg = (int)_graphTotalValues.Average();
_graphAvgTotalValues.Add(_avg);
_min = (int)_graphEntitiesValues.Min();
if (AdaptiveLimits)
{
MaximumValue = _graphAvgTotalValues[0]*2;
MinimumValue = -500;
}
#region Draw Total
x = PerformancePanelBounds.X;
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphTotalValues.Count - 1; i > 0; i--)
{
float y1 = yAxis -
((_graphTotalValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = yAxis -
((_graphTotalValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 =
new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 =
new Vector2(
MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.LightGreen);
x += deltaX;
}
#endregion
#region Draw Physics
x = PerformancePanelBounds.X;
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphPhysicsValues.Count - 1; i > 0; i--)
{
float y1 = yAxis -
((_graphPhysicsValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = yAxis -
((_graphPhysicsValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 =
new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 =
new Vector2(
MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.LightBlue);
x += deltaX;
}
#endregion
#region Draw Entities
x = PerformancePanelBounds.X;
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphEntitiesValues.Count - 1; i > 0; i--)
{
float y1 = yAxis -
((_graphEntitiesValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = yAxis -
((_graphEntitiesValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 =
new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 =
new Vector2(
MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.LightSalmon);
x += deltaX;
}
#endregion
#region Draw Average
x = PerformancePanelBounds.X;
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphAvgTotalValues.Count - 1; i > 0; i--)
{
float y1 = yAxis -
((_graphAvgTotalValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = yAxis -
((_graphAvgTotalValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 =
new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 =
new Vector2(
MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right),
MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.White);
x += deltaX;
}
#endregion
}
float avgAxis;
if (_graphAvgTotalValues.Count > 0)
avgAxis = yAxis -
((_graphAvgTotalValues.Last() / (MaximumValue - MinimumValue)) * yScale)-4;
else
avgAxis = PerformancePanelBounds.Center.Y - 4;
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, "Max: " + _max, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
DrawString(PerformancePanelBounds.Right + 10, (int)MathHelper.Clamp(avgAxis, PerformancePanelBounds.Top, yAxis), "Avg: " + _avg, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, "Min: " + _min, Color.LightSalmon, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
//Draw background.
_background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y);
_background[1] = new Vector2(PerformancePanelBounds.X,
PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width,
PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width,
PerformancePanelBounds.Y);
DrawSolidPolygon(_background, 4, Color.DarkGray, true);
#region Draw Zero
DrawSegment(new Vector2(PerformancePanelBounds.X, yAxis),
new Vector2(PerformancePanelBounds.X - 8, yAxis),
Color.White);
DrawString(PerformancePanelBounds.X - 8, (int)yAxis - 12, "0", Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
#endregion
}
private void DrawDebugPanel()
{
int fixtures = 0;
for (int i = 0; i < World.BodyList.Count; i++)
{
fixtures += World.BodyList[i].FixtureList.Count;
}
int x = (int)DebugPanelPosition.X;
int y = (int)DebugPanelPosition.Y;
DrawString(x, y, "Objects:");
DrawString(x, y, "\n- Bodies: " + World.BodyList.Count +
"\n- Fixtures: " + fixtures +
"\n- Contacts: " + World.ContactList.Count +
"\n- Joints: " + World.JointList.Count +
"\n- Controllers: " + World.ControllerList.Count +
"\n- Proxies: " + World.ProxyCount, Color.LightBlue);
DrawString(x, y, "\n\n\n\n\n\n\n- Entities: " + World.EntityManager.ActiveEntitiesCount, Color.LightSalmon);
DrawString(x + 110, y, "Update Time: " + (_graphEntitiesValues.Average() + _graphPhysicsValues.Average()).ToString());
DrawString(x + 110, y, "\n --Physics: " + _graphPhysicsValues.Average() +
"\n - Body: " + World.SolveUpdateTime +
"\n - Contact: " + World.ContactsUpdateTime +
"\n - CCD: " + World.ContinuousPhysicsTime +
"\n - Joint: " + World.Island.JointUpdateTime +
"\n - Controller: " + World.ControllersUpdateTime, Color.LightBlue);
DrawString(x + 110, y, "\n\n\n\n\n\n\n --Entity: " + _graphEntitiesValues.Average(), Color.LightSalmon);
if (DebugPanelUserData.Count > 0)
{
DrawString(x, y+130, "UserData:" + _GetUserDataString(), Color.Green);
}
}
internal string _GetUserDataString()
{
string outputString = "";
foreach (string Key in DebugPanelUserData.Keys)
outputString += "\n- " + Key + ": " + DebugPanelUserData[Key].ToString();
return outputString;
}
public void DrawAABB(ref AABB aabb, Color color)
{
Vector2[] verts = new Vector2[4];
verts[0] = new Vector2(aabb.LowerBound.X, aabb.LowerBound.Y);
verts[1] = new Vector2(aabb.UpperBound.X, aabb.LowerBound.Y);
verts[2] = new Vector2(aabb.UpperBound.X, aabb.UpperBound.Y);
verts[3] = new Vector2(aabb.LowerBound.X, aabb.UpperBound.Y);
DrawPolygon(verts, 4, color);
}
private void DrawJoint(PhysicsJoint joint)
{
if (!joint.Enabled)
return;
PhysicsBody b1 = joint.BodyA;
PhysicsBody b2 = joint.BodyB;
Transform xf1, xf2;
b1.GetTransform(out xf1);
Vector2 x2 = Vector2.Zero;
// WIP David
if (!joint.IsFixedType())
{
b2.GetTransform(out xf2);
x2 = xf2.Position;
}
Vector2 p1 = joint.WorldAnchorA;
Vector2 p2 = joint.WorldAnchorB;
Vector2 x1 = xf1.Position;
Color color = new Color(0.5f, 0.8f, 0.8f);
switch (joint.JointType)
{
case JointType.Distance:
DrawSegment(p1, p2, color);
break;
case JointType.Pulley:
PulleyJoint pulley = (PulleyJoint)joint;
Vector2 s1 = pulley.GroundAnchorA;
Vector2 s2 = pulley.GroundAnchorB;
DrawSegment(s1, p1, color);
DrawSegment(s2, p2, color);
DrawSegment(s1, s2, color);
break;
case JointType.FixedMouse:
DrawPoint(p1, 0.5f, new Color(0.0f, 1.0f, 0.0f));
DrawSegment(p1, p2, new Color(0.8f, 0.8f, 0.8f));
break;
case JointType.Revolute:
//DrawSegment(x2, p1, color);
DrawSegment(p2, p1, color);
DrawSolidCircle(p2, 0.1f, Vector2.Zero, Color.LightSalmon);
DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.LightBlue);
break;
case JointType.FixedAngle:
//Should not draw anything.
break;
case JointType.FixedRevolute:
DrawSegment(x1, p1, color);
DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.Pink);
break;
case JointType.FixedLine:
DrawSegment(x1, p1, color);
DrawSegment(p1, p2, color);
break;
case JointType.FixedDistance:
DrawSegment(x1, p1, color);
DrawSegment(p1, p2, color);
break;
case JointType.FixedPrismatic:
DrawSegment(x1, p1, color);
DrawSegment(p1, p2, color);
break;
case JointType.Gear:
DrawSegment(x1, x2, color);
break;
//case JointType.Weld:
// break;
default:
DrawSegment(x1, p1, color);
DrawSegment(p1, p2, color);
DrawSegment(x2, p2, color);
break;
}
}
public void DrawShape(Fixture fixture, Transform xf, Color color)
{
switch (fixture.ShapeType)
{
case ShapeType.Circle:
{
CircleShape circle = (CircleShape)fixture.Shape;
Vector2 center = MathUtils.Multiply(ref xf, circle.Position);
float radius = circle.Radius;
Vector2 axis = xf.R.Col1;
DrawSolidCircle(center, radius, axis, color);
}
break;
case ShapeType.Polygon:
{
PolygonShape poly = (PolygonShape)fixture.Shape;
int vertexCount = poly.Vertices.Count;
Debug.Assert(vertexCount <= Settings.MaxPolygonVertices);
for (int i = 0; i < vertexCount; ++i)
{
_tempVertices[i] = MathUtils.Multiply(ref xf, poly.Vertices[i]);
}
DrawSolidPolygon(_tempVertices, vertexCount, color);
}
break;
case ShapeType.Edge:
{
EdgeShape edge = (EdgeShape)fixture.Shape;
Vector2 v1 = MathUtils.Multiply(ref xf, edge.Vertex1);
Vector2 v2 = MathUtils.Multiply(ref xf, edge.Vertex2);
DrawSegment(v1, v2, color);
}
break;
case ShapeType.Loop:
{
LoopShape loop = (LoopShape)fixture.Shape;
int count = loop.Vertices.Count;
Vector2 v1 = MathUtils.Multiply(ref xf, loop.Vertices[count - 1]);
DrawCircle(v1, 0.05f, color);
for (int i = 0; i < count; ++i)
{
Vector2 v2 = MathUtils.Multiply(ref xf, loop.Vertices[i]);
DrawSegment(v1, v2, color);
v1 = v2;
}
}
break;
}
}
public override void DrawPolygon(Vector2[] vertices, int count, float red, float green, float blue)
{
DrawPolygon(vertices, count, new Color(red, green, blue));
}
public void DrawPolygon(Vector2[] vertices, int count, Color color)
{
if (!_primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
for (int i = 0; i < count - 1; i++)
{
_primitiveBatch.AddVertex(vertices[i], color, PrimitiveType.LineList);
_primitiveBatch.AddVertex(vertices[i + 1], color, PrimitiveType.LineList);
}
_primitiveBatch.AddVertex(vertices[count - 1], color, PrimitiveType.LineList);
_primitiveBatch.AddVertex(vertices[0], color, PrimitiveType.LineList);
}
public override void DrawSolidPolygon(Vector2[] vertices, int count, float red, float green, float blue)
{
DrawSolidPolygon(vertices, count, new Color(red, green, blue), true);
}
public void DrawSolidPolygon(Vector2[] vertices, int count, Color color)
{
DrawSolidPolygon(vertices, count, color, true);
}
public void DrawSolidPolygon(Vector2[] vertices, int count, Color color, bool outline)
{
if (!_primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
if (count == 2)
{
DrawPolygon(vertices, count, color);
return;
}
Color colorFill = color * (outline ? 0.5f : 1.0f);
for (int i = 1; i < count - 1; i++)
{
_primitiveBatch.AddVertex(vertices[0], colorFill, PrimitiveType.TriangleList);
_primitiveBatch.AddVertex(vertices[i], colorFill, PrimitiveType.TriangleList);
_primitiveBatch.AddVertex(vertices[i + 1], colorFill, PrimitiveType.TriangleList);
}
if (outline)
{
DrawPolygon(vertices, count, color);
}
}
public override void DrawCircle(Vector2 center, float radius, float red, float green, float blue)
{
DrawCircle(center, radius, new Color(red, green, blue));
}
public void DrawCircle(Vector2 center, float radius, Color color)
{
if (!_primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
const double increment = Math.PI * 2.0 / CircleSegments;
double theta = 0.0;
for (int i = 0; i < CircleSegments; i++)
{
Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
Vector2 v2 = center +
radius *
new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment));
_primitiveBatch.AddVertex(v1, color, PrimitiveType.LineList);
_primitiveBatch.AddVertex(v2, color, PrimitiveType.LineList);
theta += increment;
}
}
public override void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, float red, float green,
float blue)
{
DrawSolidCircle(center, radius, axis, new Color(red, green, blue));
}
public void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, Color color)
{
if (!_primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
const double increment = Math.PI * 2.0 / CircleSegments;
double theta = 0.0;
Color colorFill = color * 0.5f;
Vector2 v0 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
theta += increment;
for (int i = 1; i < CircleSegments - 1; i++)
{
Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
Vector2 v2 = center +
radius *
new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment));
_primitiveBatch.AddVertex(v0, colorFill, PrimitiveType.TriangleList);
_primitiveBatch.AddVertex(v1, colorFill, PrimitiveType.TriangleList);
_primitiveBatch.AddVertex(v2, colorFill, PrimitiveType.TriangleList);
theta += increment;
}
DrawCircle(center, radius, color);
DrawSegment(center, center + axis * radius, color);
}
public override void DrawSegment(Vector2 start, Vector2 end, float red, float green, float blue)
{
DrawSegment(start, end, new Color(red, green, blue));
}
public void DrawSegment(Vector2 start, Vector2 end, Color color)
{
if (!_primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
_primitiveBatch.AddVertex(start, color, PrimitiveType.LineList);
_primitiveBatch.AddVertex(end, color, PrimitiveType.LineList);
}
public override void DrawTransform(ref Transform transform)
{
const float axisScale = 0.4f;
Vector2 p1 = transform.Position;
Vector2 p2 = p1 + axisScale * transform.R.Col1;
DrawSegment(p1, p2, Color.LightSalmon);
p2 = p1 + axisScale * transform.R.Col2;
DrawSegment(p1, p2, Color.LightGreen);
}
public void DrawPoint(Vector2 p, float size, Color color)
{
Vector2[] verts = new Vector2[4];
float hs = size / 2.0f;
verts[0] = p + new Vector2(-hs, -hs);
verts[1] = p + new Vector2(hs, -hs);
verts[2] = p + new Vector2(hs, hs);
verts[3] = p + new Vector2(-hs, hs);
DrawSolidPolygon(verts, 4, color, true);
}
public void DrawString(int x, int y, string s, params object[] args)
{
this.DrawString( x, y, s, TextColor, args);
}
public void DrawString(int x, int y, string s, Color color, params object[] args)
{
_stringData.Add(new StringData(x, y, s, args, color));
}
public void DrawString(bool drawInWorld, int x, int y, string s, Color color, params object[] args)
{
if (drawInWorld)
_worldStringData.Add(new StringData(x, y, s, args, color));
else
_stringData.Add(new StringData(x, y, s, args, color));
}
public void DrawArrow(Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator,
Color color)
{
// Draw connection segment between start- and end-point
DrawSegment(start, end, color);
// Precalculate halfwidth
float halfWidth = width / 2;
// Create directional reference
Vector2 rotation = (start - end);
rotation.Normalize();
// Calculate angle of directional vector
float angle = (float)Math.Atan2(rotation.X, -rotation.Y);
// Create matrix for rotation
Matrix rotMatrix = Matrix.CreateRotationZ(angle);
// Create translation matrix for end-point
Matrix endMatrix = Matrix.CreateTranslation(end.X, end.Y, 0);
// Setup arrow end shape
Vector2[] verts = new Vector2[3];
verts[0] = new Vector2(0, 0);
verts[1] = new Vector2(-halfWidth, -length);
verts[2] = new Vector2(halfWidth, -length);
// Rotate end shape
Vector2.Transform(verts, ref rotMatrix, verts);
// Translate end shape
Vector2.Transform(verts, ref endMatrix, verts);
// Draw arrow end shape
DrawSolidPolygon(verts, 3, color, false);
if (drawStartIndicator)
{
// Create translation matrix for start
Matrix startMatrix = Matrix.CreateTranslation(start.X, start.Y, 0);
// Setup arrow start shape
Vector2[] baseVerts = new Vector2[4];
baseVerts[0] = new Vector2(-halfWidth, length / 4);
baseVerts[1] = new Vector2(halfWidth, length / 4);
baseVerts[2] = new Vector2(halfWidth, 0);
baseVerts[3] = new Vector2(-halfWidth, 0);
// Rotate start shape
Vector2.Transform(baseVerts, ref rotMatrix, baseVerts);
// Translate start shape
Vector2.Transform(baseVerts, ref startMatrix, baseVerts);
// Draw start shape
DrawSolidPolygon(baseVerts, 4, color, false);
}
}
public void RenderDebugData(ref Matrix projection, ref Matrix view)
{
if (!Enabled)
{
return;
}
//Nothing is enabled - don't draw the debug view.
if (Flags == 0)
return;
_device.RasterizerState = RasterizerState.CullNone;
_device.DepthStencilState = DepthStencilState.Default;
_primitiveBatch.Begin(ref projection, ref view);
DrawDebugData();
_primitiveBatch.End();
if ((Flags & DebugViewFlags.PerformanceGraph) == DebugViewFlags.PerformanceGraph)
{
_primitiveBatch.Begin(ref _localProjection, ref _localView);
DrawPerformanceGraph();
_primitiveBatch.End();
}
// begin the sprite batch effect
_batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
// draw any strings we have (NORMAL)
for (int i = 0; i < _stringData.Count; i++)
{
if (_stringData[i].Args.Length > 0) //If they have variable arguments
{
_batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args),
new Vector2(_stringData[i].X + 1f, _stringData[i].Y + 1f), Color.Black);
_batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args),
new Vector2(_stringData[i].X, _stringData[i].Y), _stringData[i].Color);
}
else
{
_batch.DrawString(_font, _stringData[i].S,
new Vector2(_stringData[i].X + 1f, _stringData[i].Y + 1f), Color.Black);
_batch.DrawString(_font, _stringData[i].S,
new Vector2(_stringData[i].X, _stringData[i].Y), _stringData[i].Color);
}
}
// end the sprite batch effect
_batch.End();
_stringData.Clear();
//draw any strings that are in the (WORLD)
_batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, _camera.View);
for (int i = 0; i < _worldStringData.Count; i++)
{
if (_worldStringData[i].Args.Length > 0) //If they have variable arguments
{
_batch.DrawString(_font, string.Format(_worldStringData[i].S, _worldStringData[i].Args),
new Vector2(_worldStringData[i].X + 1f, _worldStringData[i].Y + 1f), Color.Black, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
_batch.DrawString(_font, string.Format(_worldStringData[i].S, _worldStringData[i].Args,0f,Vector2.Zero,1f,SpriteEffects.None,0f),
new Vector2(_worldStringData[i].X, _worldStringData[i].Y), _worldStringData[i].Color,0f,Vector2.Zero,1f,SpriteEffects.None,0f);
}
else
{
_batch.DrawString(_font, _worldStringData[i].S,
new Vector2(_worldStringData[i].X + 1f, _worldStringData[i].Y + 1f), Color.Black, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
_batch.DrawString(_font, _worldStringData[i].S,
new Vector2(_worldStringData[i].X, _worldStringData[i].Y), _worldStringData[i].Color, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
}
_worldStringData.RemoveAll(new Predicate<StringData>(x => x.S == _worldStringData[i].S));
i--;
}
_batch.End();
_worldStringData.Clear();
}
public void RenderDebugData(ref Matrix projection)
{
if (!Enabled)
{
return;
}
Matrix view = Matrix.Identity;
RenderDebugData(ref projection, ref view);
}
public void LoadContent(GraphicsDevice device, ContentManager content, params KeyValuePair<string, object>[] userData)
{
// Create a new SpriteBatch, which can be used to draw textures.
_device = device;
_batch = new SpriteBatch(_device);
_primitiveBatch = new PrimitiveBatch(_device, 1000);
_font = content.Load<SpriteFont>("Fonts/debugfont");
_stringData = new List<StringData>();
_worldStringData = new List<StringData>();
_localProjection = Matrix.CreateOrthographicOffCenter(0f, _device.Viewport.Width, _device.Viewport.Height,
0f, 0f, 1f);
_localView = Matrix.Identity;
if (userData != null && userData.Length > 0)
{
foreach (KeyValuePair<string, object> data in userData)
DebugPanelUserData.Add(data.Key, data.Value);
this.EnableOrDisableFlag(DebugViewFlags.PerformanceGraph);
this.EnableOrDisableFlag(DebugViewFlags.DebugPanel);
}
_graphTotalValues.Add(World.PhysicsUpdateTime + World.EntitySystemUpdateTime);
_graphEntitiesValues.Add(World.EntitySystemUpdateTime);
_graphPhysicsValues.Add(World.PhysicsUpdateTime);
}
#region Nested type: ContactPoint
private struct ContactPoint
{
public Vector2 Normal;
public Vector2 Position;
public PointState State;
}
#endregion
#region Nested type: StringData
private struct StringData
{
public object[] Args;
public Color Color;
public string S;
public int X, Y;
public StringData(int x, int y, string s, object[] args, Color color)
{
X = x;
Y = y;
S = s;
Args = args;
Color = color;
}
}
#endregion
}
}
| |
using PhotoNet.Common;
using RawNet.Decoder.Decompressor;
using RawNet.Format.Tiff;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace RawNet.Decoder
{
class RW2Decoder : TIFFDecoder
{
UInt32 load_flags;
ImageBinaryReader input_start;
IFD raw;
public override Thumbnail DecodeThumb()
{
var thumb = base.DecodeThumb();
if (thumb == null)
{
var jpegTag = ifd.GetEntryRecursive(TagType.MAKERNOTE_ALT);
if (jpegTag == null) return null;
reader.BaseStream.Position = jpegTag.dataOffset;
return new JPEGThumbnail(reader.ReadBytes((int)jpegTag.dataCount));
}
else return thumb;
}
internal RW2Decoder(Stream reader) : base(reader) { }
public override void DecodeRaw()
{
List<IFD> data = ifd.GetIFDsWithTag(TagType.PANASONIC_STRIPOFFSET);
bool isOldPanasonic = false;
if (data.Count == 0)
{
data = ifd.GetIFDsWithTag(TagType.STRIPOFFSETS);
if (data == null)
throw new RawDecoderException("No image data found");
isOldPanasonic = true;
}
raw = data[0];
uint height = raw.GetEntry((TagType)3).GetUInt(0);
uint width = raw.GetEntry((TagType)2).GetUInt(0);
if (isOldPanasonic)
{
Tag offsets = raw.GetEntry(TagType.STRIPOFFSETS);
if (offsets.dataCount != 1)
{
throw new RawDecoderException("Multiple Strips found:" + offsets.dataCount);
}
uint off = offsets.GetUInt(0);
if (!reader.IsValid(off))
throw new RawDecoderException("Invalid image data offset, cannot decode.");
rawImage.fullSize.dim = new Point2D(width, height);
rawImage.Init(false);
UInt32 size = (uint)(reader.BaseStream.Length - off);
input_start = new ImageBinaryReader(stream, off);
if (size >= width * height * 2)
{
// It's completely unpacked little-endian
RawDecompressor.Decode12BitRawUnpacked(input_start, new Point2D(width, height), new Point2D(), rawImage);
rawImage.fullSize.ColorDepth = 12;
}
else if (size >= width * height * 3 / 2)
{
// It's a packed format
RawDecompressor.Decode12BitRawWithControl(input_start, new Point2D(width, height), new Point2D(), rawImage);
rawImage.fullSize.ColorDepth = 12;
}
else
{
var colorTag = raw.GetEntry((TagType)5);
if (colorTag != null)
{
rawImage.fullSize.ColorDepth = colorTag.GetUShort(0);
}
else
{
//try to load with 12bits colordepth
}
// It's using the new .RW2 decoding method
load_flags = 0;
DecodeRw2();
}
}
else
{
rawImage.fullSize.dim = new Point2D(width, height);
rawImage.Init(false);
Tag offsets = raw.GetEntry(TagType.PANASONIC_STRIPOFFSET);
if (offsets.dataCount != 1)
{
throw new RawDecoderException("Multiple Strips found:" + offsets.dataCount);
}
load_flags = 0x2008;
uint off = offsets.GetUInt(0);
if (!reader.IsValid(off))
throw new RawDecoderException("Invalid image data offset, cannot decode.");
input_start = new ImageBinaryReader(stream, off);
DecodeRw2();
}
}
unsafe void DecodeRw2()
{
int i, j, sh = 0;
int[] pred = new int[2], nonz = new int[2];
uint w = rawImage.fullSize.dim.width / 14;
bool zero_is_bad = true;
PanaBitpump bits = new PanaBitpump(input_start, load_flags);
List<Int32> zero_pos = new List<int>();
for (int y = 0; y < rawImage.fullSize.dim.height; y++)
{
for (int x = 0, dest = 0; x < w; x++)
{
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
int u = 0;
for (i = 0; i < 14; i++)
{
// Even pixels
if (u == 2)
{
sh = 4 >> 3 - bits.GetBits(2);
u = -1;
}
if (nonz[0] != 0)
{
if (0 != (j = bits.GetBits(8)))
{
if ((pred[0] -= 0x80 << sh) < 0 || sh == 4)
pred[0] &= ~(-1 << sh);
pred[0] += j << sh;
}
}
else if ((nonz[0] = bits.GetBits(8)) != 0 || i > 11)
pred[0] = nonz[0] << 4 | bits.GetBits(4);
rawImage.fullSize.rawView[y * rawImage.fullSize.dim.width + (dest++)] = (ushort)pred[0];
if (zero_is_bad && 0 == pred[0])
zero_pos.Add((y << 16) | (x * 14 + i));
// Odd pixels
i++;
u++;
if (u == 2)
{
sh = 4 >> 3 - bits.GetBits(2);
u = -1;
}
if (nonz[1] != 0)
{
if ((j = bits.GetBits(8)) != 0)
{
if ((pred[1] -= 0x80 << sh) < 0 || sh == 4)
pred[1] &= ~(-1 << sh);
pred[1] += j << sh;
}
}
else if ((nonz[1] = bits.GetBits(8)) != 0 || i > 11)
pred[1] = nonz[1] << 4 | bits.GetBits(4);
rawImage.fullSize.rawView[y * rawImage.fullSize.dim.width + (dest++)] = (ushort)pred[1];
if (zero_is_bad && 0 == pred[1])
zero_pos.Add((y << 16) | (x * 14 + i));
u++;
}
}
}
}
public override void DecodeMetadata()
{
base.DecodeMetadata();
if (rawImage.metadata.Model == null)
throw new RawDecoderException("Model name not found");
if (rawImage.metadata.Make == null)
throw new RawDecoderException("Make name not found");
string mode = GuessMode();
SetMetadata(rawImage.metadata.Model);
rawImage.metadata.Mode = mode;
//in panasonic, exif are in ifd 0
if (rawImage.fullSize.ColorDepth == 16)
{
rawImage.fullSize.ColorDepth = 12;
}
//panasonic iso is in a special tag
if (rawImage.metadata.IsoSpeed == 0)
{
var t = raw.GetEntryRecursive(TagType.PANASONIC_ISO_SPEED);
if (t != null) rawImage.metadata.IsoSpeed = t.GetInt(0);
}
// Read blacklevels
var bias = raw.GetEntry((TagType)0x08).GetInt(0) + raw.GetEntry((TagType)0x09).GetInt(0) + raw.GetEntry((TagType)0x0a).GetInt(0);
var rTag = raw.GetEntry((TagType)0x1c);
var gTag = raw.GetEntry((TagType)0x1d);
var bTag = raw.GetEntry((TagType)0x1e);
if (rTag != null && gTag != null && bTag != null)
{
Debug.Assert(bTag.GetInt(0) + 15 == rTag.GetInt(0) + 15);
Debug.Assert(bTag.GetInt(0) + 15 == gTag.GetInt(0) + 15);
rawImage.black = rTag.GetInt(0) + bias;
/*
rawImage.blackLevelSeparate[0] = rTag.GetInt(0) + 15;
rawImage.blackLevelSeparate[1] = rawImage.blackLevelSeparate[2] = gTag.GetInt(0) + 15;
rawImage.blackLevelSeparate[3] = bTag.GetInt(0) + 15;*/
}
// Read WB levels
var rWBTag = raw.GetEntry((TagType)0x0024);
var gWBTag = raw.GetEntry((TagType)0x0025);
var bWBTag = raw.GetEntry((TagType)0x0026);
if (rWBTag != null && gWBTag != null && bWBTag != null)
{
rawImage.metadata.WbCoeffs = new WhiteBalance(bWBTag.GetShort(0), gWBTag.GetShort(0), rWBTag.GetShort(0), rawImage.fullSize.ColorDepth);
}
else
{
var wb1Tag = raw.GetEntry((TagType)0x0011);
var wb2Tag = raw.GetEntry((TagType)0x0012);
if (wb1Tag != null && wb2Tag != null)
{
rawImage.metadata.WbCoeffs = new WhiteBalance(wb1Tag.GetShort(0), 1, wb2Tag.GetShort(0));
}
}
}
private void SetMetadata(string model)
{
//find the color matrice
for (int i = 0; i < colorM.Length; i++)
{
if (colorM[i].name.Contains(rawImage.metadata.Model))
{
rawImage.convertionM = colorM[i].matrix;
if (colorM[i].black != 0) rawImage.black = colorM[i].black;
if (colorM[i].white != 0) rawImage.whitePoint = colorM[i].white;
break;
}
}
switch (model)
{
case "":
rawImage.metadata.Model = "";
break;
}
}
string GuessMode()
{
float ratio = 3.0f / 2.0f; // Default
if (rawImage.fullSize.rawView == null)
return "";
ratio = rawImage.fullSize.dim.width / (float)rawImage.fullSize.dim.height;
float min_diff = Math.Abs(ratio - 16.0f / 9.0f);
string closest_match = "16:9";
float t = Math.Abs(ratio - 3.0f / 2.0f);
if (t < min_diff)
{
closest_match = "3:2";
min_diff = t;
}
t = Math.Abs(ratio - 4.0f / 3.0f);
if (t < min_diff)
{
closest_match = "4:3";
min_diff = t;
}
t = Math.Abs(ratio - 1.0f);
if (t < min_diff)
{
closest_match = "1:1";
min_diff = t;
}
return closest_match;
}
private CamRGB[] colorM = {
new CamRGB("Panasonic DMC-CM1",15,0, new double[]{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } ),
new CamRGB("Panasonic DMC-FZ8", 0, 0xf7f, new double[] { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } ),
new CamRGB( "Panasonic DMC-FZ18", 0, 0, new double[] { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 }),
new CamRGB( "Panasonic DMC-FZ28", 15, 0xf96, new double[] { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 }),
new CamRGB("Panasonic DMC-FZ330", 15, 0, new double[] { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 }),
new CamRGB( "Panasonic DMC-FZ300", 15, 0, new double[] { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 }),
new CamRGB( "Panasonic DMC-FZ30", 0, 0xf94, new double[] { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 }),
new CamRGB( "Panasonic DMC-FZ3", 15, 0, new double[] { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 }),
new CamRGB( "Panasonic DMC-FZ4", 15, 0, new double[] { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 }),
new CamRGB( "Panasonic DMC-FZ50", 0, 0, new double[] { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 }),
new CamRGB( "Panasonic DMC-FZ7", 15, 0, new double[] { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 }),
new CamRGB( "Leica V-LUX1", 0, 0, new double[] { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 }),
new CamRGB( "Panasonic DMC-L10", 15, 0xf96, new double[] { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 }),
new CamRGB( "Panasonic DMC-L1", 0, 0xf7f, new double[] { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 }),
new CamRGB("Leica DIGILUX 3", 0, 0xf7f, new double[] { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 }),
new CamRGB("Panasonic DMC-LC1", 0, 0, new double[] { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 }),
new CamRGB("Leica DIGILUX 2", 0, 0, new double[] { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 }),
new CamRGB("Panasonic DMC-LX100", 15, 0, new double[] { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 }),
new CamRGB("Leica D-LUX (Typ 109)", 15, 0, new double[] { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 }),
new CamRGB("Panasonic DMC-LF1", 15, 0, new double[] { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 }),
new CamRGB("Leica C (Typ 112)", 15, 0, new double[] { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 }),
new CamRGB("Panasonic DMC-LX1", 0, 0xf7f, new double[] { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 }),
new CamRGB("Leica D-LUX2", 0, 0xf7f, new double[] { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 }),
new CamRGB("Panasonic DMC-LX2", 0, 0, new double[] { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 }),
new CamRGB("Leica D-LUX3", 0, 0, new double[] { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 }),
new CamRGB("Panasonic DMC-LX3", 15, 0, new double[] { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 }),
new CamRGB("Leica D-LUX 4", 15, 0, new double[] { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 }),
new CamRGB("Panasonic DMC-LX5", 15, 0, new double[] { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 }),
new CamRGB("Leica D-LUX 5", 15, 0, new double[] { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 }),
new CamRGB("Panasonic DMC-LX7", 15, 0, new double[] { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 }),
new CamRGB("Leica D-LUX 6", 15, 0, new double[] { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 }),
new CamRGB("Panasonic DMC-FZ1000", 15, 0, new double[] { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 }),
new CamRGB("Leica V-LUX (Typ 114)", 15, 0, new double[] { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 }),
new CamRGB("Panasonic DMC-FZ100", 15, 0xfff,new double[] { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 }),
new CamRGB("Leica V-LUX 2", 15, 0xfff,new double[] { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 }),
new CamRGB("Panasonic DMC-FZ150", 15, 0xfff,new double[] { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 }),
new CamRGB("Leica V-LUX 3", 15, 0xfff,new double[] { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 }),
new CamRGB("Panasonic DMC-FZ200", 15, 0xfff,new double[] { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 }),
new CamRGB("Leica V-LUX 4", 15, 0xfff,new double[] { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 }),
new CamRGB("Panasonic DMC-FX150", 15, 0xfff,new double[]{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 }),
new CamRGB("Panasonic DMC-G10", 0, 0,new double[]{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 }),
new CamRGB("Panasonic DMC-G1", 15, 0xf94,new double[] { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 }),
new CamRGB("Panasonic DMC-G2", 15, 0xf3c,new double[]{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 }),
new CamRGB("Panasonic DMC-G3", 15, 0xfff,new double[] { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 }),
new CamRGB("Panasonic DMC-G5", 15, 0xfff,new double[] { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 }),
new CamRGB("Panasonic DMC-G6", 15, 0xfff,new double[] { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 }),
new CamRGB("Panasonic DMC-G7", 15, 0xfff,new double[] { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 }),
new CamRGB("Panasonic DMC-GF1", 15, 0xf92,new double[] { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 }),
new CamRGB("Panasonic DMC-GF2", 15, 0xfff,new double[] { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 }),
new CamRGB("Panasonic DMC-GF3", 15, 0xfff,new double[] { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 }),
new CamRGB("Panasonic DMC-GF5", 15, 0xfff,new double[] { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 }),
new CamRGB("Panasonic DMC-GF6", 15, 0,new double[] { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 }),
new CamRGB("Panasonic DMC-GF7", 15, 0,new double[] { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 }),
new CamRGB("Panasonic DMC-GF8", 15, 0,new double[] { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 }),
new CamRGB("Panasonic DMC-GH1", 15, 0xf92,new double[] { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 }),
new CamRGB("Panasonic DMC-GH2", 15, 0xf95,new double[] { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 }),
new CamRGB("Panasonic DMC-GH3", 15, 0,new double[] { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 }),
new CamRGB("Panasonic DMC-GH4", 15, 0,new double[] { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 }),
new CamRGB("Panasonic DMC-GM1", 15, 0,new double[] { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 }),
new CamRGB("Panasonic DMC-GM5", 15, 0,new double[] { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 }),
new CamRGB("Panasonic DMC-GX1", 15, 0,new double[] { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 }),
new CamRGB("Panasonic DMC-GX7", 15, 0,new double[] { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 }),
new CamRGB("Panasonic DMC-GX8", 15, 0,new double[] { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 }),
new CamRGB("Panasonic DMC-TZ1", 15, 0,new double[] { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 }),
new CamRGB("Panasonic DMC-ZS1", 15, 0,new double[] { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 }),
new CamRGB("Panasonic DMC-TZ6", 15, 0,new double[] { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 }),
new CamRGB("Panasonic DMC-ZS4", 15, 0,new double[] { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 }),
new CamRGB("Panasonic DMC-TZ7", 15, 0,new double[] { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 }),
new CamRGB("Panasonic DMC-ZS5", 15, 0,new double[] { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 }),
new CamRGB("Panasonic DMC-TZ8", 15, 0,new double[] { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 }),
new CamRGB("Panasonic DMC-ZS6", 15, 0,new double[] { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 }),
new CamRGB("Leica S (Typ 007)", 0, 0,new double[] { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 }),
new CamRGB("Leica X", 0, 0, new double[] { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 }),
new CamRGB("Leica Q (Typ 116)", 0, 0,new double[] { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 }),
new CamRGB("Leica M (Typ 262)", 0, 0,new double[] { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 }),
new CamRGB("Leica SL (Typ 601)", 0, 0,new double[] { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} )};
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.InteropServices.PInvokeDiagnosticAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.InteropServices.PInvokeDiagnosticAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.InteropServices.UnitTests
{
public class PInvokeDiagnosticAnalyzerTests
{
#region Verifiers
private DiagnosticResult CSharpResult1401(int line, int column, params string[] arguments)
=> VerifyCS.Diagnostic(PInvokeDiagnosticAnalyzer.RuleCA1401)
.WithLocation(line, column)
.WithArguments(arguments);
private DiagnosticResult BasicResult1401(int line, int column, params string[] arguments)
=> VerifyVB.Diagnostic(PInvokeDiagnosticAnalyzer.RuleCA1401)
.WithLocation(line, column)
.WithArguments(arguments);
private DiagnosticResult CSharpResult2101(int line, int column, params string[] arguments)
=> VerifyCS.Diagnostic(PInvokeDiagnosticAnalyzer.RuleCA2101)
.WithLocation(line, column)
.WithArguments(arguments);
private DiagnosticResult BasicResult2101(int line, int column, params string[] arguments)
=> VerifyVB.Diagnostic(PInvokeDiagnosticAnalyzer.RuleCA2101)
.WithLocation(line, column)
.WithArguments(arguments);
#endregion
#region CA1401 tests
[Fact]
public async Task CA1401CSharpTest()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
public class C
{
[DllImport(""user32.dll"")]
public static extern void Method1(); // should not be public
[DllImport(""user32.dll"")]
protected static extern void Method2(); // should not be protected
[DllImport(""user32.dll"")]
private static extern void Method3(); // private is OK
[DllImport(""user32.dll"")]
static extern void Method4(); // implicitly private is OK
}
",
CSharpResult1401(7, 31, "Method1"),
CSharpResult1401(10, 34, "Method2"));
}
[Fact]
public async Task CA1401CSharpTestWithScope()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
public class C
{
[DllImport(""user32.dll"")]
public static extern void {|CA1401:Method1|}(); // should not be public
[DllImport(""user32.dll"")]
protected static extern void {|CA1401:Method2|}(); // should not be protected
[DllImport(""user32.dll"")]
private static extern void Method3(); // private is OK
[DllImport(""user32.dll"")]
static extern void Method4(); // implicitly private is OK
}
");
}
[Fact]
public async Task CA1401BasicSubTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Public Class C
<DllImport(""user32.dll"")>
Public Shared Sub Method1() ' should not be public
End Sub
<DllImport(""user32.dll"")>
Protected Shared Sub Method2() ' should not be protected
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method3() ' private is OK
End Sub
<DllImport(""user32.dll"")>
Shared Sub Method4() ' implicitly public is not OK
End Sub
End Class
",
BasicResult1401(6, 23, "Method1"),
BasicResult1401(10, 26, "Method2"),
BasicResult1401(18, 16, "Method4"));
}
[Fact]
public async Task CA1401BasicSubTestWithScope()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Public Class C
<DllImport(""user32.dll"")>
Public Shared Sub {|CA1401:Method1|}() ' should not be public
End Sub
<DllImport(""user32.dll"")>
Protected Shared Sub {|CA1401:Method2|}() ' should not be protected
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method3() ' private is OK
End Sub
<DllImport(""user32.dll"")>
Shared Sub {|CA1401:Method4|}() ' implicitly public is not OK
End Sub
End Class
");
}
[Fact]
public async Task CA1401BasicFunctionTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Public Class C
<DllImport(""user32.dll"")>
Public Shared Function Method1() As Integer ' should not be public
End Function
<DllImport(""user32.dll"")>
Protected Shared Function Method2() As Integer ' should not be protected
End Function
<DllImport(""user32.dll"")>
Private Shared Function Method3() As Integer ' private is OK
End Function
<DllImport(""user32.dll"")>
Shared Function Method4() As Integer ' implicitly public is not OK
End Function
End Class
",
BasicResult1401(6, 28, "Method1"),
BasicResult1401(10, 31, "Method2"),
BasicResult1401(18, 21, "Method4"));
}
[Fact]
public async Task CA1401BasicDeclareSubTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Public Class C
Public Declare Sub Method1 Lib ""user32.dll"" Alias ""Method1"" () ' should not be public
Protected Declare Sub Method2 Lib ""user32.dll"" Alias ""Method2"" () ' should not be protected
Private Declare Sub Method3 Lib ""user32.dll"" Alias ""Method3"" () ' private is OK
Declare Sub Method4 Lib ""user32.dll"" Alias ""Method4"" () ' implicitly public is not OK
End Class
",
BasicResult1401(5, 24, "Method1"),
BasicResult1401(7, 27, "Method2"),
BasicResult1401(11, 17, "Method4"));
}
[Fact]
public async Task CA1401BasicDeclareFunctionTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Public Class C
Public Declare Function Method1 Lib ""user32.dll"" Alias ""Method1"" () As Integer ' should not be public
Protected Declare Function Method2 Lib ""user32.dll"" Alias ""Method2"" () As Integer ' should not be protected
Private Declare Function Method3 Lib ""user32.dll"" Alias ""Method3"" () As Integer ' private is OK
Declare Function Method4 Lib ""user32.dll"" Alias ""Method4"" () As Integer ' implicitly public is not OK
End Class
",
BasicResult1401(5, 29, "Method1"),
BasicResult1401(7, 32, "Method2"),
BasicResult1401(11, 22, "Method4"));
}
[WorkItem(792, "https://github.com/dotnet/roslyn-analyzers/issues/792")]
[Fact]
public async Task CA1401CSharpNonPublic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Runtime.InteropServices;
public sealed class TimerFontContainer
{
private static class NativeMethods
{
[DllImport(""gdi32.dll"")]
public static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);
}
}
");
}
[WorkItem(792, "https://github.com/dotnet/roslyn-analyzers/issues/792")]
[Fact]
public async Task CA1401BasicNonPublic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public NotInheritable Class TimerFontContainer
Private Class NativeMethods
Public Declare Function AddFontMemResourceEx Lib ""gdi32.dll"" (pbFont As Integer, cbFont As Integer, pdv As Integer) As Integer
End Class
End Class
");
}
#endregion
#region CA2101 tests
[Fact]
public async Task CA2101SimpleCSharpTest()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern void Method1(string s); // one string parameter
[DllImport(""user32.dll"")]
private static extern void Method2(string s, string t); // two string parameters, should be only 1 diagnostic
[DllImport(""user32.dll"")]
private static extern void Method3(StringBuilder s); // one StringBuilder parameter
[DllImport(""user32.dll"")]
private static extern void Method4(StringBuilder s, StringBuilder t); // two StringBuilder parameters, should be only 1 diagnostic
}
",
CSharpResult2101(7, 6),
CSharpResult2101(10, 6),
CSharpResult2101(13, 6),
CSharpResult2101(16, 6));
}
[Fact]
public async Task CA2101SimpleCSharpTestWithScope()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[{|CA2101:DllImport(""user32.dll"")|}]
private static extern void Method1(string s); // one string parameter
[{|CA2101:DllImport(""user32.dll"")|}]
private static extern void Method2(string s, string t); // two string parameters, should be only 1 diagnostic
[{|CA2101:DllImport(""user32.dll"")|}]
private static extern void Method3(StringBuilder s); // one StringBuilder parameter
[{|CA2101:DllImport(""user32.dll"")|}]
private static extern void Method4(StringBuilder s, StringBuilder t); // two StringBuilder parameters, should be only 1 diagnostic
}
");
}
[Fact]
public async Task CA2101SimpleBasicTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Sub Method1(s As String) ' one string parameter
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method2(s As String, t As String) ' two string parameters, should be only 1 diagnostic
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method3(s As StringBuilder) ' one StringBuilder parameter
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method4(s As StringBuilder, t As StringBuilder) ' two StringBuilder parameters, should be only 1 diagnostic
End Sub
End Class
",
BasicResult2101(6, 6),
BasicResult2101(10, 6),
BasicResult2101(14, 6),
BasicResult2101(18, 6));
}
[Fact]
public async Task CA2101SimpleBasicTestWithScope()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<{|CA2101:DllImport(""user32.dll"")|}>
Private Shared Sub Method1(s As String) ' one string parameter
End Sub
<{|CA2101:DllImport(""user32.dll"")|}>
Private Shared Sub Method2(s As String, t As String) ' two string parameters, should be only 1 diagnostic
End Sub
<{|CA2101:DllImport(""user32.dll"")|}>
Private Shared Sub Method3(s As StringBuilder) ' one StringBuilder parameter
End Sub
<{|CA2101:DllImport(""user32.dll"")|}>
Private Shared Sub Method4(s As StringBuilder, t As StringBuilder) ' two StringBuilder parameters, should be only 1 diagnostic
End Sub
End Class
");
}
[Fact]
public async Task CA2101SimpleDeclareBasicTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Text
Class C
Private Declare Sub Method1 Lib ""user32.dll"" (s As String) ' one string parameter
Private Declare Sub Method2 Lib ""user32.dll"" (s As String, t As String) ' two string parameters, should be only 1 diagnostic
Private Declare Function Method3 Lib ""user32.dll"" (s As StringBuilder) As Integer ' one StringBuilder parameter
Private Declare Function Method4 Lib ""user32.dll"" (s As StringBuilder, t As StringBuilder) As Integer ' two StringBuilder parameters, should be only 1 diagnostic
End Class
",
BasicResult2101(5, 25),
BasicResult2101(7, 25),
BasicResult2101(9, 30),
BasicResult2101(11, 30));
}
[Fact]
public async Task CA2101ParameterMarshaledCSharpTest()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern void Method1([MarshalAs(UnmanagedType.LPWStr)] string s); // marshaling specified on parameter
[DllImport(""user32.dll"")]
private static extern void Method2([MarshalAs(UnmanagedType.LPWStr)] StringBuilder s);
[DllImport(""user32.dll"")]
private static extern void Method3([MarshalAs(UnmanagedType.LPWStr)] string s, [MarshalAs(UnmanagedType.LPWStr)] string t);
[DllImport(""user32.dll"")]
private static extern void Method4([MarshalAs(UnmanagedType.LPWStr)] StringBuilder s, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder t);
[DllImport(""user32.dll"")]
private static extern void Method5([MarshalAs(UnmanagedType.LPWStr)] string s, string t); // un-marshaled second parameter
[DllImport(""user32.dll"")]
private static extern void Method6([MarshalAs(UnmanagedType.LPWStr)] StringBuilder s, StringBuilder t);
[DllImport(""user32.dll"")]
private static extern void Method7([MarshalAs(UnmanagedType.LPStr)] string s); // marshaled, but as the wrong type
[DllImport(""user32.dll"")]
private static extern void Method8([MarshalAs(UnmanagedType.LPStr)] StringBuilder s);
[DllImport(""user32.dll"")]
private static extern void Method9([MarshalAs(UnmanagedType.LPStr)] string s, [MarshalAs(UnmanagedType.LPStr)] string t); // two parameters marshaled as the wrong type
[DllImport(""user32.dll"")]
private static extern void Method10([MarshalAs(UnmanagedType.LPStr)] StringBuilder s, [MarshalAs(UnmanagedType.LPStr)] StringBuilder t);
[DllImport(""user32.dll"")]
private static extern void Method11([MarshalAs((short)0)] string s);
}
",
CSharpResult2101(19, 6),
CSharpResult2101(22, 6),
CSharpResult2101(26, 41),
CSharpResult2101(29, 41),
CSharpResult2101(32, 41),
CSharpResult2101(32, 84),
CSharpResult2101(35, 42),
CSharpResult2101(35, 92),
CSharpResult2101(38, 42));
}
[Fact]
public async Task CA2101ParameterMarshaledBasicTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Sub Method1(<MarshalAs(UnmanagedType.LPWStr)> s As String) ' marshaling specified on parameter
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method2(<MarshalAs(UnmanagedType.LPWStr)> s As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method3(<MarshalAs(UnmanagedType.LPWStr)> s As String, <MarshalAs(UnmanagedType.LPWStr)> t As String)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method4(<MarshalAs(UnmanagedType.LPWStr)> s As StringBuilder, <MarshalAs(UnmanagedType.LPWStr)> t As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method5(<MarshalAs(UnmanagedType.LPWStr)> s As String, t As String) ' un-marshaled second parameter
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method6(<MarshalAs(UnmanagedType.LPWStr)> s As StringBuilder, t As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method7(<MarshalAs(UnmanagedType.LPStr)> s As String) ' marshaled, but as the wrong type
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method8(<MarshalAs(UnmanagedType.LPStr)> s As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method9(<MarshalAs(UnmanagedType.LPStr)> s As String, <MarshalAs(UnmanagedType.LPStr)> t As String) ' two parameters marshaled as the wrong type
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method10(<MarshalAs(UnmanagedType.LPStr)> s As StringBuilder, <MarshalAs(UnmanagedType.LPStr)> t As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Method11(<MarshalAs(CShort(0))> s As String)
End Sub
End Class
",
BasicResult2101(22, 6),
BasicResult2101(26, 6),
BasicResult2101(31, 33),
BasicResult2101(35, 33),
BasicResult2101(39, 33),
BasicResult2101(39, 79),
BasicResult2101(43, 34),
BasicResult2101(43, 87),
BasicResult2101(47, 34));
}
[Fact]
public async Task CA2101CharSetCSharpTest()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"", CharSet = CharSet.Auto)]
private static extern void Method1(string s); // wrong marshaling
[DllImport(""user32.dll"", CharSet = CharSet.Auto)]
private static extern void Method2(StringBuilder s);
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Method3(string s); // correct marshaling
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Method4(StringBuilder s);
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Method5([MarshalAs(UnmanagedType.LPStr)] string s); // correct marshaling on method, not on parameter
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Method6([MarshalAs(UnmanagedType.LPStr)] StringBuilder s);
}
",
CSharpResult2101(7, 6),
CSharpResult2101(10, 6),
CSharpResult2101(20, 41),
CSharpResult2101(23, 41));
}
[Fact]
public async Task CA2101CharSetBasicTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"", CharSet := CharSet.Auto)>
Private Shared Sub Method1(s As String) ' wrong marshaling
End Sub
<DllImport(""user32.dll"", CharSet := CharSet.Auto)>
Private Shared Sub Method2(s As StringBuilder)
End Sub
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Sub Method3(s As String) ' correct marshaling
End Sub
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Sub Method4(s As StringBuilder)
End Sub
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Sub Method5(<MarshalAs(UnmanagedType.LPStr)> s As String) ' correct marshaling on method, not on parameter
End Sub
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Sub Method6(<MarshalAs(UnmanagedType.LPStr)> s As StringBuilder)
End Sub
End Class
",
BasicResult2101(6, 6),
BasicResult2101(10, 6),
BasicResult2101(23, 33),
BasicResult2101(27, 33));
}
[Fact]
public async Task CA2101ReturnTypeCSharpTest()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern string Method1(); // wrong marshaling on return type
[DllImport(""user32.dll"")]
private static extern StringBuilder Method2();
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern string Method3(); // correct marshaling on return type
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern StringBuilder Method4();
}
",
CSharpResult2101(7, 6),
CSharpResult2101(10, 6));
}
[Fact]
public async Task CA2101ReturnTypeBasicTest()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Function Method1() As String ' wrong marshaling on return type
End Function
<DllImport(""user32.dll"")>
Private Shared Function Method2() As StringBuilder
End Function
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Function Method3() As String ' correct marshaling on return type
End Function
<DllImport(""user32.dll"", CharSet := CharSet.Unicode)>
Private Shared Function Method4() As StringBuilder
End Function
Private Declare Function Method5 Lib ""user32.dll"" () As String
End Class
",
BasicResult2101(6, 6),
BasicResult2101(10, 6),
BasicResult2101(22, 30));
}
#endregion
}
}
| |
/****************************************************************************
|
| Copyright (c) 2007 Novell, Inc.
| All Rights Reserved.
|
| This program is free software; you can redistribute it and/or
| modify it under the terms of version 2 of the GNU General Public License as
| published by the Free Software Foundation.
|
| 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, contact Novell, Inc.
|
| To contact Novell about this file by physical or electronic mail,
| you may find current contact information at www.novell.com
|
| Author: Russ Young
| Thanks to: Bruce Schneier / Counterpane Labs
| for the Blowfish encryption algorithm and
| reference implementation. http://www.schneier.com/blowfish.html
|***************************************************************************/
using System;
using System.IO;
using System.Security.Cryptography;
using GameRes.Utility;
namespace GameRes.Cryptography
{
/// <summary>
/// Class that provides blowfish encryption.
/// </summary>
public class Blowfish
{
const int N = 16;
const int KEYBYTES = 8;
static uint[] _P =
{
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
};
static uint[,] _S =
{
{
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
},
{
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
},
{
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
},
{
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
}
};
uint[] P;
uint[,] S;
/// <summary>
/// Constructs and initializes a blowfish instance with the supplied key.
/// </summary>
/// <param name="key">The key to cipher with.</param>
public Blowfish(byte[] key)
{
short i;
short j;
short k;
uint data;
uint datal;
uint datar;
P = _P.Clone() as uint[];
S = _S.Clone() as uint[,];
j = 0;
for (i = 0; i < N + 2; ++i)
{
data = 0x00000000;
for (k = 0; k < 4; ++k)
{
data = (data << 8) | key[j];
j++;
if (j >= key.Length)
{
j = 0;
}
}
P[i] = P[i] ^ data;
}
datal = 0x00000000;
datar = 0x00000000;
for (i = 0; i < N + 2; i += 2)
{
Encipher(ref datal, ref datar);
P[i] = datal;
P[i + 1] = datar;
}
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 256; j += 2)
{
Encipher(ref datal, ref datar);
S[i,j] = datal;
S[i,j + 1] = datar;
}
}
}
public ICryptoTransform CreateDecryptor ()
{
return new BlowfishDecryptor (this);
}
private uint F(uint x)
{
ushort a;
ushort b;
ushort c;
ushort d;
uint y;
d = (ushort)(x & 0x00FF);
x >>= 8;
c = (ushort)(x & 0x00FF);
x >>= 8;
b = (ushort)(x & 0x00FF);
x >>= 8;
a = (ushort)(x & 0x00FF);
//y = ((S[0][a] + S[1][b]) ^ S[2][c]) + S[3][d];
y = S[0,a] + S[1,b];
y = y ^ S[2,c];
y = y + S[3,d];
return y;
}
/// <summary>
/// Encrypts a byte array in place.
/// </summary>
/// <param name="data">The array to encrypt.</param>
/// <param name="length">The amount to encrypt.</param>
public void Encipher(byte[] data, int length)
{
uint xl, xr;
if ((length % 8) != 0)
throw new Exception("Invalid Length");
for (int i = 0; i < length; i+=8)
{
// Encode the data in 8 byte blocks.
xl = (uint)((data[i] << 24) | (data[i+1] << 16) | (data[i+2] << 8) | data[i+3]);
xr = (uint)((data[i+4] << 24) | (data[i+5] << 16) | (data[i+6] << 8) | data[i+7]);
Encipher(ref xl, ref xr);
// Now Replace the data.
data[i] = (byte)(xl >> 24);
data[i+1] = (byte)(xl >> 16);
data[i+2] = (byte)(xl >> 8);
data[i+3] = (byte)(xl);
data[i+4] = (byte)(xr >> 24);
data[i+5] = (byte)(xr >> 16);
data[i+6] = (byte)(xr >> 8);
data[i+7] = (byte)(xr);}
}
/// <summary>
/// Encrypts 8 bytes of data (1 block)
/// </summary>
/// <param name="xl">The left part of the 8 bytes.</param>
/// <param name="xr">The right part of the 8 bytes.</param>
private void Encipher(ref uint xl, ref uint xr)
{
uint Xl;
uint Xr;
uint temp;
short i;
Xl = xl;
Xr = xr;
for (i = 0; i < N; ++i)
{
Xl = Xl ^ P[i];
Xr = F(Xl) ^ Xr;
temp = Xl;
Xl = Xr;
Xr = temp;
}
temp = Xl;
Xl = Xr;
Xr = temp;
Xr = Xr ^ P[N];
Xl = Xl ^ P[N + 1];
xl = Xl;
xr = Xr;
}
/// <summary>
/// Decrypts a byte array in place.
/// </summary>
/// <param name="data">The array to decrypt.</param>
/// <param name="length">The amount to decrypt.</param>
public void Decipher(byte[] data, int length)
{
uint xl, xr;
if ((length % 8) != 0)
throw new Exception("Invalid Length");
for (int i = 0; i < length; i += 8)
{
// Encode the data in 8 byte blocks.
xl = (uint)(data[i] | (data[i+1] << 8) | (data[i+2] << 16) | (data[i+3] << 24));
xr = (uint)(data[i+4] | (data[i+5] << 8) | (data[i+6] << 16) | (data[i+7] << 24));
Decipher(ref xl, ref xr);
// Now Replace the data.
data[i] = (byte)(xl);
data[i+1] = (byte)(xl >> 8);
data[i+2] = (byte)(xl >> 16);
data[i+3] = (byte)(xl >> 24);
data[i+4] = (byte)(xr);
data[i+5] = (byte)(xr >> 8);
data[i+6] = (byte)(xr >> 16);
data[i+7] = (byte)(xr >> 24);
}
}
/// <summary>
/// Decrypts 8 bytes of data (1 block)
/// </summary>
/// <param name="xl">The left part of the 8 bytes.</param>
/// <param name="xr">The right part of the 8 bytes.</param>
public void Decipher(ref uint xl, ref uint xr)
{
uint Xl;
uint Xr;
uint temp;
short i;
Xl = xl;
Xr = xr;
for (i = N + 1; i > 1; --i)
{
Xl = Xl ^ P[i];
Xr = F(Xl) ^ Xr;
/* Exchange Xl and Xr */
temp = Xl;
Xl = Xr;
Xr = temp;
}
/* Exchange Xl and Xr */
temp = Xl;
Xl = Xr;
Xr = temp;
Xr = Xr ^ P[1];
Xl = Xl ^ P[0];
xl = Xl;
xr = Xr;
}
}
/// <summary>
/// ICryptoTransform implementation for use with CryptoStream.
/// </summary>
public sealed class BlowfishDecryptor : ICryptoTransform
{
Blowfish m_bf;
public const int BlockSize = 8;
public bool CanTransformMultipleBlocks { get { return true; } }
public bool CanReuseTransform { get { return true; } }
public int InputBlockSize { get { return BlockSize; } }
public int OutputBlockSize { get { return BlockSize; } }
public BlowfishDecryptor (Blowfish bf)
{
m_bf = bf;
}
public int TransformBlock (byte[] inBuffer, int offset, int count, byte[] outBuffer, int outOffset)
{
for (int i = 0; i < count; i += BlockSize)
{
uint xl = LittleEndian.ToUInt32 (inBuffer, offset+i);
uint xr = LittleEndian.ToUInt32 (inBuffer, offset+i+4);
m_bf.Decipher (ref xl, ref xr);
LittleEndian.Pack (xl, outBuffer, outOffset+i);
LittleEndian.Pack (xr, outBuffer, outOffset+i+4);
}
return count;
}
static readonly byte[] EmptyArray = new byte[0];
public byte[] TransformFinalBlock (byte[] inBuffer, int offset, int count)
{
if (0 == count)
return EmptyArray;
if (0 != count % BlockSize)
throw new InvalidDataException ("Non-padded block in Blowfish encrypted stream");
var output = new byte[count];
TransformBlock (inBuffer, offset, count, output, 0);
return output;
}
#region IDisposable implementation
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
_disposed = true;
}
GC.SuppressFinalize (this);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using Xunit;
namespace AsmResolver.DotNet.Tests.Builder
{
public class TokenMappingTest
{
[Fact]
public void NewTypeDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Create new type.
var type = new TypeDefinition("Namespace", "Name", TypeAttributes.Interface); ;
module.TopLevelTypes.Add(type);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[type];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the new type.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newType = (TypeDefinition) newModule.LookupMember(newToken);
Assert.Equal(type.Namespace, newType.Namespace);
Assert.Equal(type.Name, newType.Name);
}
[Fact]
public void NewFieldDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Create new field.
var field = new FieldDefinition(
"MyField",
FieldAttributes.Public | FieldAttributes.Static,
FieldSignature.CreateStatic(module.CorLibTypeFactory.Object));
module.GetOrCreateModuleType().Fields.Add(field);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[field];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the new field.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newField = (FieldDefinition) newModule.LookupMember(newToken);
Assert.Equal(field.Name, newField.Name);
}
[Fact]
public void NewMethodDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Create new method.
var method = new MethodDefinition(
"MyMethod",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
module.GetOrCreateModuleType().Methods.Add(method);
// Get existing main method.
var main = module.ManagedEntrypointMethod;
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid tokens for both methods.
var methodToken = result.TokenMapping[method];
var mainMethodToken = result.TokenMapping[main];
Assert.NotEqual(0u, methodToken.Rid);
Assert.NotEqual(0u, mainMethodToken.Rid);
// Assert tokens resolve to the same methods.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newMethod = (MethodDefinition) newModule.LookupMember(methodToken);
Assert.Equal(method.Name, newMethod.Name);
var newMain = (MethodDefinition) newModule.LookupMember(mainMethodToken);
Assert.Equal(main.Name, newMain.Name);
}
[Fact]
public void NewTypeReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Import arbitrary type as reference.
var importer = new ReferenceImporter(module);
var reference = importer.ImportType(typeof(MemoryStream));
// Ensure type ref is added to the module by adding a dummy field referencing it.
module.GetOrCreateModuleType().Fields.Add(new FieldDefinition(
"MyField",
FieldAttributes.Public | FieldAttributes.Static,
FieldSignature.CreateStatic(reference.ToTypeSignature())));
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same type reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newReference = (TypeReference) newModule.LookupMember(newToken);
Assert.Equal(reference.Namespace, newReference.Namespace);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewMemberReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Import arbitrary method.
var importer = new ReferenceImporter(module);
var reference = importer.ImportMethod(typeof(MemoryStream).GetConstructor(Type.EmptyTypes));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Newobj, reference);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newReference = (MemberReference) newModule.LookupMember(newToken);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewTypeSpecification()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Import arbitrary generic method.
var importer = new ReferenceImporter(module);
var specification = importer.ImportType(typeof(List<object>));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Ldtoken, specification);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[specification];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newReference = (TypeSpecification) newModule.LookupMember(newToken);
Assert.Equal(specification.Name, newReference.Name);
}
[Fact]
public void NewMethodSpecification()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Import arbitrary generic method.
var importer = new ReferenceImporter(module);
var reference = importer.ImportMethod(typeof(Array).GetMethod("Empty").MakeGenericMethod(typeof(object)));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Call, reference);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newReference = (MethodSpecification) newModule.LookupMember(newToken);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewStandaloneSignature()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
// Import arbitrary method signature.
var importer = new ReferenceImporter(module);
var signature = new StandAloneSignature(
importer.ImportMethodSignature(MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)));
// Ensure reference is added to the module by referencing it in main.
var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Ldnull);
instructions.Insert(0, CilOpCodes.Calli, signature);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[signature];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
var newSignature = (StandAloneSignature) newModule.LookupMember(newToken);
Assert.Equal((CallingConventionSignature) signature.Signature,
newSignature.Signature as CallingConventionSignature, new SignatureComparer());
}
}
}
| |
// Copyright 2019 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
//
// 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 Google.Api.Ads.Common.Util;
using Google.Api.Ads.AdManager.v202202;
using System;
using System.Collections.Generic;
using System.Text;
using DateTime = Google.Api.Ads.AdManager.v202202.DateTime;
namespace Google.Api.Ads.AdManager.Util.v202202
{
/// <summary>
/// A utility class that allows for statements to be constructed in parts.
/// Typical usage is:
/// <code>
/// StatementBuilder statementBuilder = new StatementBuilder()
/// .Where("lastModifiedTime > :yesterday AND type = :type")
/// .OrderBy("name DESC")
/// .Limit(200)
/// .Offset(20)
/// .AddValue("yesterday",
/// DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-1)))
/// .AddValue("type", "Type");
/// Statement statement = statementBuilder.ToStatement();
/// // ...
/// statementBuilder.increaseOffsetBy(20);
/// statement = statementBuilder.ToStatement();
/// </code>
/// </summary>
public class StatementBuilder
{
/// <summary>
/// The suggested default page size.
/// </summary>
public const int SUGGESTED_PAGE_LIMIT = 500;
private const string SELECT = "SELECT";
private const string FROM = "FROM";
private const string WHERE = "WHERE";
private const string LIMIT = "LIMIT";
private const string OFFSET = "OFFSET";
private const string ORDER_BY = "ORDER BY";
private string select;
private string from;
private string where;
private int? limit = null;
private int? offset = null;
private string orderBy;
/// <summary>
/// The list of query parameters.
/// </summary>
private List<String_ValueMapEntry> valueEntries;
/// <summary>
/// Constructs a statement builder for partial query building.
/// </summary>
public StatementBuilder()
{
valueEntries = new List<String_ValueMapEntry>();
}
/// <summary>
/// Removes a keyword from the start of a clause, if it exists.
/// </summary>
/// <param name="clause">The clause to remove the keyword from</param>
/// <param name="keyword">The keyword to remove</param>
/// <returns>The clause with the keyword removed</returns>
private static string RemoveKeyword(string clause, string keyword)
{
string formattedKeyword = keyword.Trim() + " ";
return clause.StartsWith(formattedKeyword, true, null)
? clause.Substring(formattedKeyword.Length)
: clause;
}
/// <summary>
/// Sets the statement SELECT clause in the form of "a,b".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "SELECT " keyword will be ignored.
/// </summary>
/// <param name="columns">
/// The statement serlect clause without "SELECT".
/// </param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Select(String columns)
{
PreconditionUtilities.CheckArgumentNotNull(columns, "columns");
this.select = RemoveKeyword(columns, SELECT);
return this;
}
/// <summary>
/// Sets the statement FROM clause in the form of "table".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "FROM " keyword will be ignored.
/// </summary>
/// <param name="table">The statement from clause without "FROM"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder From(String table)
{
PreconditionUtilities.CheckArgumentNotNull(table, "table");
this.from = RemoveKeyword(table, FROM);
return this;
}
/// <summary>
/// Sets the statement WHERE clause in the form of
/// <code>
/// "WHERE <condition> {[AND | OR] <condition> ...}"
/// </code>
/// e.g. "a = b OR b = c". The "WHERE " keyword will be ignored.
/// </summary>
/// <param name="conditions">The statement query without "WHERE"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Where(String conditions)
{
PreconditionUtilities.CheckArgumentNotNull(conditions, "conditions");
this.where = RemoveKeyword(conditions, WHERE);
return this;
}
/// <summary>
/// Sets the statement LIMIT clause in the form of
/// <code>"LIMIT <count>"</code>
/// </summary>
/// <param name="count">the statement limit</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Limit(Int32 count)
{
this.limit = count;
return this;
}
/// <summary>
/// Sets the statement OFFSET clause in the form of
/// <code>"OFFSET <count>"</code>
/// </summary>
/// <param name="count">the statement offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Offset(Int32 count)
{
this.offset = count;
return this;
}
/// <summary>
/// Increases the offset by the given amount.
/// </summary>
/// <param name="amount">the amount to increase the offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder IncreaseOffsetBy(Int32 amount)
{
if (this.offset == null)
{
this.offset = 0;
}
this.offset += amount;
return this;
}
/// <summary>
/// Gets the curent offset
/// </summary>
/// <returns>The current offset</returns>
public int? GetOffset()
{
return this.offset;
}
/// <summary>
/// Removes the limit and offset from the query.
/// </summary>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder RemoveLimitAndOffset()
{
this.offset = null;
this.limit = null;
return this;
}
/// <summary>
/// Sets the statement ORDER BY clause in the form of
/// <code>"ORDER BY <property> [ASC | DESC]"</code>
/// e.g. "type ASC, lastModifiedDateTime DESC".
/// The "ORDER BY " keyword will be ignored.
/// </summary>
/// <param name="orderBy">the statement order by without "ORDER BY"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder OrderBy(String orderBy)
{
PreconditionUtilities.CheckArgumentNotNull(orderBy, "orderBy");
this.orderBy = RemoveKeyword(orderBy, ORDER_BY);
return this;
}
/// <summary>
/// Adds a new string value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, string value)
{
TextValue queryValue = new TextValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new boolean value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, bool value)
{
BooleanValue queryValue = new BooleanValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new decimal value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, decimal value)
{
NumberValue queryValue = new NumberValue();
queryValue.value = value.ToString();
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new DateTime value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, DateTime value)
{
DateTimeValue queryValue = new DateTimeValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new Date value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, Date value)
{
DateValue queryValue = new DateValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
private StatementBuilder AddValue(string key, Value value)
{
String_ValueMapEntry queryValue = new String_ValueMapEntry();
queryValue.key = key;
queryValue.value = value;
valueEntries.Add(queryValue);
return this;
}
private void ValidateQuery()
{
if (limit == null && offset != null)
{
throw new InvalidOperationException(AdManagerErrorMessages.InvalidOffsetAndLimit);
}
}
private String BuildQuery()
{
ValidateQuery();
StringBuilder stringBuilder = new StringBuilder();
if (!String.IsNullOrEmpty(select))
{
stringBuilder = stringBuilder.Append(SELECT).Append(" ").Append(select).Append(" ");
}
if (!String.IsNullOrEmpty(from))
{
stringBuilder = stringBuilder.Append(FROM).Append(" ").Append(from).Append(" ");
}
if (!String.IsNullOrEmpty(where))
{
stringBuilder = stringBuilder.Append(WHERE).Append(" ").Append(where).Append(" ");
}
if (!String.IsNullOrEmpty(orderBy))
{
stringBuilder = stringBuilder.Append(ORDER_BY).Append(" ").Append(orderBy)
.Append(" ");
}
if (limit != null)
{
stringBuilder = stringBuilder.Append(LIMIT).Append(" ").Append(limit).Append(" ");
}
if (offset != null)
{
stringBuilder = stringBuilder.Append(OFFSET).Append(" ").Append(offset).Append(" ");
}
return stringBuilder.ToString().Trim();
}
/// <summary>
/// Gets the <see cref="Statement"/> representing the state of this
/// statement builder.
/// </summary>
/// <returns>The statement.</returns>
public Statement ToStatement()
{
Statement statement = new Statement();
statement.query = BuildQuery();
statement.values = valueEntries.ToArray();
return statement;
}
}
}
| |
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using FluentAssertions;
using Neo4j.Driver.Internal;
using Xunit;
using Xunit.Abstractions;
namespace Neo4j.Driver.IntegrationTests.Stress
{
[Collection(CCIntegrationCollection.CollectionName)]
public class CausalClusterStressTests : StressTest<CausalClusterStressTests.Context>
{
private readonly CausalClusterIntegrationTestFixture _cluster;
public CausalClusterStressTests(ITestOutputHelper output, CausalClusterIntegrationTestFixture cluster) :
base(output, cluster.Cluster.BoltRoutingUri, cluster.Cluster.AuthToken, cluster.Cluster.Configure)
{
_cluster = cluster;
}
protected override Context CreateContext()
{
return new Context();
}
protected override IEnumerable<IBlockingCommand<Context>> CreateTestSpecificBlockingCommands()
{
return new List<IBlockingCommand<Context>>
{
new BlockingWriteCommandUsingReadSessionTxFunc<Context>(_driver, false),
new BlockingWriteCommandUsingReadSessionTxFunc<Context>(_driver, true)
};
}
protected override IEnumerable<IAsyncCommand<Context>> CreateTestSpecificAsyncCommands()
{
return new List<IAsyncCommand<Context>>
{
new AsyncWriteCommandUsingReadSessionTxFunc<Context>(_driver, false),
new AsyncWriteCommandUsingReadSessionTxFunc<Context>(_driver, true)
};
}
protected override IEnumerable<IRxCommand<Context>> CreateTestSpecificRxCommands()
{
return Enumerable.Empty<IRxCommand<Context>>();
}
protected override void PrintStats(Context context)
{
_output.WriteLine("{0}", context);
}
protected override void VerifyReadQueryDistribution(Context context)
{
var clusterAddresses = DiscoverClusterAddresses();
VerifyServedReadQueries(context, clusterAddresses);
VerifyServedSimilarAmountOfReadQueries(context, clusterAddresses);
}
public override bool HandleWriteFailure(Exception error, Context context)
{
switch (error)
{
case SessionExpiredException _:
{
var isLeaderSwitch = error.Message.EndsWith("no longer accepts writes");
if (isLeaderSwitch)
{
context.LeaderSwitched();
return true;
}
break;
}
}
return false;
}
private ClusterAddresses DiscoverClusterAddresses()
{
var followers = new List<string>();
var readReplicas = new List<string>();
using (var session = _driver.Session())
{
var records = session.Run("CALL dbms.cluster.overview()").ToList();
foreach (var record in records)
{
var address = record["addresses"].As<IList<object>>().First().As<string>().Replace("bolt://", "");
// Pre 4.0
if (record.Keys.Contains("role"))
{
switch (record["role"].As<string>().ToLowerInvariant())
{
case "follower":
followers.Add(address);
break;
case "read_replica":
readReplicas.Add(address);
break;
}
}
// Post 4.0
if (record.Keys.Contains("databases"))
{
switch (record["databases"].As<IDictionary<string, object>>()["neo4j"].As<string>()
.ToLowerInvariant())
{
case "follower":
followers.Add(address);
break;
case "read_replica":
readReplicas.Add(address);
break;
}
}
}
}
return new ClusterAddresses(followers, readReplicas);
}
private static void VerifyServedReadQueries(Context context, ClusterAddresses clusterAddresses)
{
foreach (var address in clusterAddresses.Followers)
{
context.GetReadQueries(address).Should()
.BePositive("Follower {0} did not serve any read queries", address);
}
foreach (var address in clusterAddresses.ReadReplicas)
{
context.GetReadQueries(address).Should()
.BePositive("Read replica {0} did not serve any read queries", address);
}
}
private static void VerifyServedSimilarAmountOfReadQueries(Context context, ClusterAddresses clusterAddresses)
{
void Verify(string serverType, IEnumerable<string> addresses)
{
var expectedMagnitude = -1;
foreach (var address in addresses)
{
var queries = context.GetReadQueries(address);
var orderOfMagnitude = GetOrderOfMagnitude(queries);
if (expectedMagnitude == -1)
{
expectedMagnitude = orderOfMagnitude;
}
orderOfMagnitude.Should().BeInRange(expectedMagnitude - 1, expectedMagnitude + 1,
"{0} {1} is expected to server similar amount of queries. Context: {2}.", serverType, address,
context);
}
}
Verify("Follower", clusterAddresses.Followers);
Verify("Read-replica", clusterAddresses.ReadReplicas);
}
private static int GetOrderOfMagnitude(long number)
{
var result = 1;
while (number >= 10)
{
number /= 10;
result++;
}
return result;
}
public class Context : StressTestContext
{
private readonly ConcurrentDictionary<string, AtomicLong> _readQueriesByServer = new
ConcurrentDictionary<string, AtomicLong>();
private long _leaderSwitches;
protected override void ProcessSummary(IResultSummary summary)
{
if (summary == null)
{
return;
}
_readQueriesByServer.AddOrUpdate(summary.Server.Address, new AtomicLong(1),
(key, value) => value.Increment());
}
public long GetReadQueries(string address)
{
return _readQueriesByServer.TryGetValue(address, out var value) ? value.Value : 0;
}
public long LeaderSwitches => Interlocked.Read(ref _leaderSwitches);
public void LeaderSwitched()
{
Interlocked.Increment(ref _leaderSwitches);
}
public override string ToString()
{
return new StringBuilder()
.Append("CausalClusterContext{")
.AppendFormat("Bookmark={0}, ", Bookmark)
.AppendFormat("BookmarkFailures={0}, ", BookmarkFailures)
.AppendFormat("NodesCreated={0}, ", CreatedNodesCount)
.AppendFormat("NodesRead={0}, ", ReadNodesCount)
.AppendFormat("LeaderSwitches={0}, ", LeaderSwitches)
.AppendFormat("ReadsByServers={0}", _readQueriesByServer.ToContentString())
.Append("}")
.ToString();
}
}
public class AtomicLong
{
private long _value;
public AtomicLong(long value)
{
_value = value;
}
public long Value => Interlocked.Read(ref _value);
public AtomicLong Increment()
{
Interlocked.Increment(ref _value);
return this;
}
public AtomicLong Decrement()
{
Interlocked.Decrement(ref _value);
return this;
}
public override string ToString()
{
return Value.ToString();
}
}
private class ClusterAddresses
{
public ClusterAddresses(IEnumerable<string> followers, IEnumerable<string> readReplicas)
{
Followers = followers.ToHashSet();
ReadReplicas = readReplicas.ToHashSet();
}
public ISet<string> Followers { get; }
public ISet<string> ReadReplicas { get; }
public override string ToString()
{
return new StringBuilder()
.Append("ClusterAddresses{")
.AppendFormat("Followers={0}, ", Followers)
.AppendFormat("Read-Replicas={0}", ReadReplicas)
.Append("}")
.ToString();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalInt321()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt321
{
private struct TestStruct
{
public Vector256<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt321 testClass)
{
var result = Avx2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector256<Int32> _clsVar;
private Vector256<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt321();
var result = Avx2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] << 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] << 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<Int32>(Vector256<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
$TEP_BrushManager_SetHeight_Range_Min = 0;
$TEP_BrushManager_SetHeight_Range_Max = 200;
$TEP_BrushManager_BrushSize_Range_Min = 0;
$TEP_BrushManager_BrushSize_Range_Max = 200;
$TEP_BrushManager_Softness_Range_Min = 0;
$TEP_BrushManager_Softness_Range_Max = 200;
$TEP_BrushManager_Pressure_Range_Min = 0;
$TEP_BrushManager_Pressure_Range_Max = 200;
$TEP_BrushManager_SetHeight = 100;
$TEP_BrushManager_OptionFields = "heightRangeMin heightRangeMax";
$TEP_BrushManager_Types = "slopeMin slopeMax size pressure softness setheight";
function TEP_BrushManager::onWake( %this ) {
}
function TEP_BrushManager::init( %this ) {
foreach$(%type in $TEP_BrushManager_Types) {
%this.brushTypeCtrls[%type] = "";
%this.brushTypeSliders[%type] = "";
}
foreach$(%type in $TEP_BrushManager_Types) {
%edit = EWTerrainEditToolbar.findObjectByInternalName(%type,true);
%slider = EWTerrainEditToolbar.findObjectByInternalName(%type@"_slider",true);
if (isObject(%edit))
%this.brushTypeCtrls[%type] = strAddWord(%this.brushTypeSliders[%type],%edit.getId());
if (isObject(%slider))
%this.brushTypeSliders[%type] = strAddWord(%this.brushTypeSliders[%type],%slider.getId());
}
%this.setDefaultBrush();
}
//==============================================================================
// Set the size of the brush (in game unit)
function TEP_BrushManager::setDefaultBrush( %this ) {
foreach$(%type in $TEP_BrushManager_Types) {
%list = TEP_BrushManager.brushTypeCtrls[%type];
foreach$(%ctrl in %list) {
%cfg = "DefaultBrush"@%type;
%default = TerrainEditorPlugin.getCfg(%cfg);
%ctrl.setValue(%default);
%ctrl.updateFriends();
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Set Slope Angle Min. - Brush have no effect on terrain with lower angle
function TEP_BrushManager::updateSameCtrls( %this,%ctrl,%type,%value ) {
$TEP_BrushCtrlList_[%type] = strAddWord($TEP_BrushCtrlList_[%type],%ctrl.getId(),1);
%tmpList = $TEP_BrushCtrlList_[%type];
foreach$(%ctrlEx in $TEP_BrushCtrlList_[%type])
{
if (!isObject(%ctrlEx))
%tmpList = strRemoveWord(%tmpList,%ctrlEx);
if (%ctrlEx $= %ctrl.getId())
continue;
%ctrlEx.setValue( %formatVal);
}
$TEP_BrushCtrlList_[%type] = %tmpList;
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush Size update and validation
//==============================================================================
//==============================================================================
// Set the size of the brush (in game unit)
function TEP_BrushManager::updateBrushSize( %this,%ctrl ) {
%validValue = %this.validateBrushSize(%ctrl.getValue());
%maxBrushSize = getWord(ETerrainEditor.maxBrushSize, 0);
//Check the slider range and fix in case settings have changed
if(%ctrl.isMemberOfClass("GuiSliderCtrl")) {
%latestRange = "1" SPC %maxBrushSize;
if (%ctrl.range !$= %latestRange)
%ctrl.range = %latestRange;
}
%ctrl.setValue(%validValue);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"BrushSize",%formatVal);
Lab.currentEditor.setParam("BrushSize",%validValue);
}
//------------------------------------------------------------------------------
//==============================================================================
// Set the size of the brush (in game unit)
function TEP_BrushManager::validateBrushSize( %this,%value ) {
%minBrushSize = 1;
%maxBrushSize = getWord(ETerrainEditor.maxBrushSize, 0);
//Convert float to closest integer
%brushSize = mCeil(%value);
%brushSize = mClamp(%brushSize,%minBrushSize,%maxBrushSize);
ETerrainEditor.setBrushSize(%brushSize);
return %brushSize;
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush Pressure update and validation
//==============================================================================
//==============================================================================
// Set the pressure of the brush
function TEP_BrushManager::updateBrushPressure( %this,%ctrl ) {
//Convert float to closest integer
%brushPressure = %ctrl.getValue();
%validValue = %this.validateBrushPressure(%brushPressure);
Lab.currentEditor.setParam("BrushPressure",%validValue);
%ctrl.setValue(%validValue);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"BrushPressure",%formatVal);
}
//------------------------------------------------------------------------------
//==============================================================================
// Set the pressure of the brush
function TEP_BrushManager::validateBrushPressure( %this,%brushPressure ) {
//Convert float to closest integer
%convPressure = %brushPressure/100;
%clampPressure = mClamp(%convPressure,"0.0","1.0");
ETerrainEditor.setBrushPressure(%clampPressure);
%editorPressure = ETerrainEditor.getBrushPressure();
%newPressure = %editorPressure * 100;
%formatPressure = mFloatLength(%newPressure,1);
return %formatPressure;
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush Softness update and validation
//==============================================================================
//==============================================================================
// Set the softness of the brush - (Lower = Less effects)
function TEP_BrushManager::updateBrushSoftness( %this,%ctrl ) {
//Convert float to closest integer
%brushSoftness = %ctrl.getValue();
%validValue = %this.validateBrushSoftness(%brushSoftness);
Lab.currentEditor.setParam("BrushSoftness",%validValue);
logd("BrushSoftness",%validValue);
%ctrl.setValue(%validValue);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"BrushSoftness",%formatVal);
}
//------------------------------------------------------------------------------
//==============================================================================
// Set the softness of the brush - (Lower = Less effects)
function TEP_BrushManager::validateBrushSoftness( %this,%value ) {
//Convert float to closest integer
%brushSoftness = %value;
%convSoftness = %brushSoftness/100;
%clampSoftness = mClamp(%convSoftness,"0","1");
ETerrainEditor.setBrushSoftness(%clampSoftness);
%editorSoftness = ETerrainEditor.getBrushSoftness();
%newSoftness = %editorSoftness * 100;
%formatSoftness = mFloatLength(%newSoftness,1);
return %formatSoftness;
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush Softness update and validation
//==============================================================================
//==============================================================================
// Set the softness of the brush - (Lower = Less effects)
function TEP_BrushManager::updateSetHeightValue( %this,%ctrl ) {
//Convert float to closest integer
%validValue = %this.validateBrushSetHeight(%ctrl.getValue());
if (%validValue $= "")
return;
%ctrl.setValue(%validValue);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"BrushSetHeight",%formatVal);
Lab.currentEditor.setParam("BrushSetHeight",%validValue);
}
//------------------------------------------------------------------------------
//==============================================================================
// Set the softness of the brush - (Lower = Less effects)
function TEP_BrushManager::validateBrushSetHeight( %this,%value ) {
//Convert float to closest integer
if (!strIsNumeric(%value)) {
warnLog("Invalid non-numeric value specified:",%value);
return;
}
%value = mFloatLength(%value,2);
ETerrainEditor.setHeightVal = %value;
return %value;
foreach(%slider in $GuiGroup_TEP_SetHeightSlider) {
%slider.setValue(%value);
%slider.updateFriends();
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush SlopeMin update and validation
//==============================================================================
//==============================================================================
// Set Slope Angle Min. - Brush have no effect on terrain with lower angle
function TEP_BrushManager::setSlopeMin( %this,%ctrl ) {
%validValue = %this.validateBrushSlopeMin(%ctrl.getValue());
%plugin = Lab.currentEditor;
Lab.currentEditor.setParam("BrushSlopeMin",%validValue);
logd("TEP_BrushManager::setSlopeMin",%validValue);
%formatVal = mFloatLength(%validValue,1);
$TEP_BrushLastSlopeMin = %formatVal;
%ctrl.setValue(%formatVal);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"SlopeMin",%formatVal);
return;
$TEP_BrushCtrlList_SlopeMin = strAddWord($TEP_BrushCtrlList_SlopeMin,%ctrl.getId(),1);
%tmpList = $TEP_BrushCtrlList_SlopeMin;
foreach$(%ctrlEx in $TEP_BrushCtrlList_SlopeMin)
{
if (!isObject(%ctrlEx))
%tmpList = strRemoveWord(%tmpList,%ctrlEx);
if (%ctrlEx $= %ctrl.getId())
continue;
%ctrlEx.setValue( %formatVal);
}
$TEP_BrushCtrlList_SlopeMin = %tmpList;
}
//------------------------------------------------------------------------------
//==============================================================================
// Set Slope Angle Min. - Brush have no effect on terrain with lower angle
function TEP_BrushManager::validateBrushSlopeMin( %this,%value ) {
//Force the value into the TerrainEditor code and it will be returned validated
%val = ETerrainEditor.setSlopeLimitMinAngle(%value);
//Set precision to 1 for gui display
return %val;
}
//------------------------------------------------------------------------------
//==============================================================================
// Brush SlopeMax update and validation
//==============================================================================
//==============================================================================
// Set Slope Angle Min. - Brush have no effect on terrain with lower angle
function TEP_BrushManager::setSlopeMax( %this,%ctrl ) {
%validValue = %this.validateBrushSlopeMax(%ctrl.getValue());
Lab.currentEditor.setParam("BrushSlopeMax",%validValue);
%formatVal = mFloatLength(%validValue,1);
%ctrl.setValue(%formatVal);
%ctrl.updateFriends();
%this.updateSameCtrls(%ctrl,"SlopeMax",%formatVal);
}
//------------------------------------------------------------------------------
//==============================================================================
// Set Slope Angle Min. - Brush have no effect on terrain with lower angle
function TEP_BrushManager::validateBrushSlopeMax( %this,%value ) {
//Force the value into the TerrainEditor code and it will be returned validated
%val = ETerrainEditor.setSlopeLimitMaxAngle(%value);
//Set precision to 1 for gui display
%formatVal = mFloatLength(%val,1);
return %val;
//Set the validated value to control and update friends if there's any
foreach(%slider in $GuiGroup_TPP_Slider_SlopeMax) {
%slider.setValue(%formatVal);
%slider.updateFriends();
}
return %val;
}
//------------------------------------------------------------------------------
function PaintBrushSizeSliderCtrlContainer::onWake(%this) {
%this-->slider.range = "1" SPC getWord(ETerrainEditor.maxBrushSize, 0);
%this-->slider.setValue(PaintBrushSizeTextEditContainer-->textEdit.getValue());
}
function PaintBrushPressureSliderCtrlContainer::onWake(%this) {
%this-->slider.setValue(PaintBrushPressureTextEditContainer-->textEdit.getValue() / 100);
}
function PaintBrushSoftnessSliderCtrlContainer::onWake(%this) {
%this-->slider.setValue(PaintBrushSoftnessTextEditContainer-->textEdit.getValue() / 100);
}
//------------------------------------------------------------------------------------
function TerrainBrushSizeSliderCtrlContainer::onWake(%this) {
%this-->slider.range = "1" SPC getWord(ETerrainEditor.maxBrushSize, 0);
%this-->slider.setValue(TerrainBrushSizeTextEditContainer-->textEdit.getValue());
}
function TerrainBrushPressureSliderCtrlContainer::onWake(%this) {
%this-->slider.setValue(TerrainBrushPressureTextEditContainer-->textEdit.getValue() / 100.0);
}
function TerrainBrushSoftnessSliderCtrlContainer::onWake(%this) {
%this-->slider.setValue(TerrainBrushSoftnessTextEditContainer-->textEdit.getValue() / 100.0);
}
function TerrainSetHeightSliderCtrlContainer::onWake(%this) {
%this-->slider.setValue(TerrainSetHeightTextEditContainer-->textEdit.getValue());
}
| |
using UnityEngine;
using System.Collections;
public class VRCamera : MonoBehaviour {
[HideInInspector]
public Camera[] cameras;
public float mouseSensitivity=0.2f;
private Vector3 oldMousePosition;
#if !UNITY_EDITOR
private float rotationY=0f,oldRotationY;
#endif
private float FPSupdateInterval = 0.5F;
private float FPSaccum = 0; // FPS accumulated over the interval
private int FPSframes = 0; // Frames drawn over the interval
private float FPStimeleft; // Left time for current interval
[HideInInspector]
public float fps;
//public bool checkFPS=true;
//public float badFPSrate=30f;
public bool useAntiDrift=true;
public bool useCompassForAntiDrift=false;
//private float blackScreen=0,needBlackScreen=0;
//public Texture blackFadeTex;
private Transform vrCameraLocal;
[SerializeField] [HideInInspector]
private bool _useLensCorrection=true;
[HideInInspector]
public bool useLensCorrection
{
get{ return _useLensCorrection; }
set
{
_useLensCorrection = value;
Debug.Log("UseCorrection: " + _useLensCorrection);
NewLensCorrection[] nlc = GetComponentsInChildren<NewLensCorrection>();
for( int k=0; k<nlc.Length; k++ ) nlc[k].useDistortion = _useLensCorrection;
#if UNITY_EDITOR
//if( Application.isEditor ) UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
#endif
}
}
[SerializeField] [HideInInspector]
private float _distanceBetweenEyes=0.7f;
public float distanceBetweenEyes
{
get { return _distanceBetweenEyes; }
set
{
_distanceBetweenEyes = value;
if( _distanceBetweenEyes<0.0001f ) _distanceBetweenEyes = 0.0001f;
Camera[] _cameras = gameObject.GetComponentsInChildren<Camera>();
for( int k=0; k<_cameras.Length; k++ )
{
if( _cameras[k].transform.localPosition.x<0f ) _cameras[k].transform.localPosition = -Vector3.right*_distanceBetweenEyes*0.5f;
if( _cameras[k].transform.localPosition.x>0f ) _cameras[k].transform.localPosition = Vector3.right*_distanceBetweenEyes*0.5f;
}
}
}
public Transform vrCameraHeading
{
get
{
Init ();
return vrCameraLocal;
}
}
private Vector3 meanAcceleration;
#if UNITY_ANDROID && !UNITY_EDITOR
private float initCompassHeading=0f;
private float gyroYaccel;
private float gyroBiasPause;
private float oldDeltaRotation;
private float gyroBias;
void InitCompassHeading()
{
initCompassHeading = -rotationY+Input.compass.magneticHeading;
}
private int numInGyroBiasArray;
void AddToGyroBiasArray(float f)
{
gyroBiasArray[numInGyroBiasArray]=f;
numInGyroBiasArray++;
if( numInGyroBiasArray>=gyroBiasArray.Length ) numInGyroBiasArray=0;
}
private float[] gyroBiasArray;
private int numRecalculatesGyroBias=0;
void RecalculateGyroBias()
{
if( !FibrumController.useAntiDrift ) return;
float tempGyroBias=0;
int num=0;
for( int k=0; k<gyroBiasArray.Length; k++ )
{
tempGyroBias+=gyroBiasArray[k];
num++;
}
gyroBias = tempGyroBias/(float)num;
numRecalculatesGyroBias++;
}
public void EnableCompass(bool on)
{
if( on )
{
Input.compass.enabled = true;
CancelInvoke ("InitCompassHeading");
Invoke ("InitCompassHeading",0.1f);
}
else
{
Input.compass.enabled = false;
CancelInvoke ("InitCompassHeading");
}
}
#endif
bool noGyroscope=false;
Quaternion rotation;
#if UNITY_EDITOR
#elif UNITY_IPHONE
private float q0,q1,q2,q3;
Quaternion rot;
#elif UNITY_ANDROID
private float meanDeltaGyroY;
#elif UNITY_WP8 || UNITY_WP_8_1
private WindowsPhoneVRController.Controller c = null;
#endif
bool initialized=false;
public void Init()
{
if( initialized ) return;
NewLensCorrection[] nlc = GetComponentsInChildren<NewLensCorrection>();
cameras = new Camera[nlc.Length];
for( int k=0; k<cameras.Length; k++ ) cameras[k] = nlc[k].gameObject.GetComponent<Camera>();
FibrumController.useAntiDrift = useAntiDrift;
FibrumController.useCompassForAntiDrift = useCompassForAntiDrift;
FPStimeleft = FPSupdateInterval;
/*if( blackFadeTex==null ) checkFPS=false;
if( checkFPS )
{
blackScreen = 1f;
needBlackScreen = 1f;
Invoke ("CheckFPS",1.6f);
} */
if( transform.FindChild("VRCamera") ) vrCameraLocal = transform.FindChild("VRCamera").transform;
else vrCameraLocal = transform;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Screen.orientation = ScreenOrientation.LandscapeLeft;
#if !UNITY_STANDALONE && !UNITY_EDITOR
if( !SystemInfo.supportsGyroscope )
{
noGyroscope = true;
}
else
{
noGyroscope = false;
}
#endif
FibrumController.Init();
#if UNITY_ANDROID && !UNITY_EDITOR
gyroBiasArray = new float[128]; for( int k=0; k<gyroBiasArray.Length; k++) gyroBiasArray[k]=0f;
if( noGyroscope )
{
transform.Find("VRCamera/WarningPlane").gameObject.SetActive(true);
EnableCompass(true);
}
InvokeRepeating("RecalculateGyroBias",0.1f,0.2f);
if( FibrumController.useCompassForAntiDrift )
{
EnableCompass(true);
}
#endif
#if UNITY_IPHONE
//transform.localRotation = Quaternion.Euler(90, 0 ,0);
#elif (UNITY_WP8 || UNITY_WP_8_1) && !UNITY_EDITOR
Input.gyro.enabled = true;
//transform.localRotation = Quaternion.Euler(90, 0 ,0);
c = new WindowsPhoneVRController.Controller();
rotation = Quaternion.identity;
#endif
FibrumController.vrCamera = this;
bool noDummyUI=true;
Camera[] allCameras = GetComponentsInChildren<Camera>();
for( int k=0; k<allCameras.Length; k++ )
{
if( allCameras[k].rect.width<=0.5f )
{
if( allCameras[k].gameObject.GetComponent<ChangeCameraEye>()==null )
{
allCameras[k].gameObject.AddComponent<ChangeCameraEye>();
}
}
else if( allCameras[k].clearFlags==CameraClearFlags.Color && allCameras[k].depth==-100 ) noDummyUI=false;
}
if( noDummyUI )
{
GameObject dummyGO = GameObject.Instantiate((GameObject)Resources.Load("FibrumResources/VR_UI_dummyCamera",typeof(GameObject))) as GameObject;
dummyGO.transform.parent = vrCameraLocal;
dummyGO.transform.localPosition = Vector3.zero;
dummyGO.transform.localRotation = Quaternion.identity;
}
if( !noGyroscope ) Invoke("SensorCalibration", 0.1f);
FibrumInput.LoadJoystickPrefs();
meanAcceleration = Input.acceleration;
if( FibrumController.vrSetup == null )
{
GameObject _setup = GameObject.Instantiate((GameObject)Resources.Load("FibrumResources/VRSetup",typeof(GameObject))) as GameObject;
FibrumController.vrSetup = _setup;
}
useLensCorrection = useLensCorrection;
initialized = true;
}
void Start () {
Init ();
}
/*void CheckFPS()
{
needBlackScreen = 0f;
Invoke ("DisableBlackScreen",2f);
if( fps<badFPSrate )
{
for( int k=0; k<cameras.Length; k++ )
{
if( cameras[k] != null ) cameras[k].SendMessage("DisableLensCorrection");
else Debug.Log("VRCamera - cameras["+k+"] not assigned!");
}
}
} */
/*void DisableBlackScreen()
{
checkFPS = false;
} */
void SensorCalibration ()
{
#if UNITY_EDITOR
transform.localRotation = Quaternion.Euler(0f, -vrCameraLocal.localEulerAngles.y, 0f);
#elif UNITY_IPHONE
transform.localRotation = Quaternion.Euler(0f, -vrCameraLocal.localEulerAngles.y, 0f);
#elif UNITY_WP8 || UNITY_WP_8_1 && !UNITY_EDITOR
transform.localRotation = Quaternion.Euler(0f, -vrCameraLocal.localEulerAngles.y, 0f);
Vector3 gravity = Input.acceleration;
float fi = Mathf.Rad2Deg*Mathf.Atan(-gravity.z/(Mathf.Sign(gravity.y)*Mathf.Sqrt(gravity.y*gravity.y+gravity.x*gravity.x*0.01f)));
float teta = Mathf.Rad2Deg*Mathf.Atan(-gravity.x/(Mathf.Sqrt(gravity.z*gravity.z+gravity.y*gravity.y)));
rotation = Quaternion.Euler(-fi,0f,teta);
#elif !UNITY_IPHONE && !(UNITY_WP8 || UNITY_WP_8_1)
transform.localRotation = Quaternion.Euler(0f, -vrCameraLocal.localEulerAngles.y, 0f);
#else
transform.localRotation = Quaternion.Euler(0f, -vrCameraLocal.localEulerAngles.y, 0f);
#endif
}
void LateUpdate () {
float zoomSpeed = FibrumInput.FibAxis(FibrumInput.FibJoystick.Vertical) * Time.deltaTime * 10;
if (Input.GetAxis("Vertical") != 0)
{
zoomSpeed = Input.GetAxis("Vertical");
}
#if UNITY_EDITOR || UNITY_STANDALONE
Vector3 euler = rotation.eulerAngles;
//rotation = Quaternion.Euler(Mathf.Max (-89f,Mathf.Min (89f,Mathf.DeltaAngle(0,euler.x)+mouseSensitivity*(oldMousePosition.y-Input.mousePosition.y))),euler.y-mouseSensitivity*(oldMousePosition.x-Input.mousePosition.x),0f);
rotation = Quaternion.Euler(Mathf.Max(-89f, Mathf.Min(89f, Mathf.DeltaAngle(0, euler.x) - mouseSensitivity * Input.GetAxis("Mouse Y"))), euler.y + mouseSensitivity * Input.GetAxis("Mouse X"), 0f);
vrCameraLocal.localRotation = rotation;
oldMousePosition = Input.mousePosition;
#elif UNITY_ANDROID && !UNITY_EDITOR
if( !noGyroscope )
{
Matrix4x4 matrix = new Matrix4x4();
float[] M = FibrumController.vrs._ao.CallStatic<float[]>("getHeadMatrix");
matrix.SetColumn(0, new Vector4(M[0], M[4], -M[8], M[12]) );
matrix.SetColumn(1, new Vector4(M[1], M[5], -M[9], M[13]) );
matrix.SetColumn(2, new Vector4(-M[2], -M[6], M[10], M[14]) );
matrix.SetColumn(3, new Vector4(M[3], M[7], M[11], M[15]) );
TransformFromMatrix (matrix, vrCameraLocal);
float deltaRotation = vrCameraLocal.localRotation.eulerAngles.y-oldRotationY;
if (FibrumInput.FibButton(FibrumInput.FibJoystick.ButDown))
deltaRotation = 0;
while( deltaRotation>180f ) deltaRotation -= 360f;
while( deltaRotation<-180f ) deltaRotation += 360f;
gyroYaccel = Mathf.Lerp(gyroYaccel,(deltaRotation-oldDeltaRotation)/Time.deltaTime,Time.deltaTime);
oldDeltaRotation = deltaRotation;
oldRotationY = vrCameraLocal.localRotation.eulerAngles.y;
if( Mathf.Abs(gyroYaccel)>0.2f ) gyroBiasPause = Time.realtimeSinceStartup+1f;
if( Time.realtimeSinceStartup>gyroBiasPause )
{
meanDeltaGyroY = Mathf.Lerp(meanDeltaGyroY,deltaRotation/Time.deltaTime,Time.deltaTime*10f);
AddToGyroBiasArray(meanDeltaGyroY);
}
rotationY += deltaRotation - gyroBias*Time.deltaTime;
while( rotationY>180f ) rotationY -= 360f;
while( rotationY<-180f ) rotationY += 360f;
if( FibrumController.useCompassForAntiDrift )
{
float compassDeltaRotationY = rotationY-(Input.compass.magneticHeading-initCompassHeading);
while( compassDeltaRotationY>180f ) compassDeltaRotationY -= 360f;
while( compassDeltaRotationY<-180f ) compassDeltaRotationY += 360f;
if( Time.realtimeSinceStartup>gyroBiasPause-0.7f )
{
rotationY -= compassDeltaRotationY*Time.deltaTime*1.5f;
}
else
{
rotationY -= compassDeltaRotationY*Time.deltaTime*0.2f;
}
}
vrCameraLocal.localRotation = Quaternion.Euler(vrCameraLocal.localRotation.eulerAngles.x,rotationY,vrCameraLocal.localRotation.eulerAngles.z);
}
else
{
Vector3 gravity = Input.acceleration;
float fi = Mathf.Rad2Deg*Mathf.Atan(-gravity.z/(Mathf.Sign(gravity.y)*Mathf.Sqrt(gravity.y*gravity.y+gravity.x*gravity.x*0.01f)));
float teta = Mathf.Rad2Deg*Mathf.Atan(-gravity.x/(Mathf.Sqrt(gravity.z*gravity.z+gravity.y*gravity.y)));
rotation = Quaternion.Slerp(rotation,Quaternion.Euler(-fi,Input.compass.magneticHeading-initCompassHeading,teta),Time.deltaTime*4.0f);
vrCameraLocal.localRotation = rotation;
}
#elif UNITY_IPHONE
rot = ConvertRotation(Input.gyro.attitude);
float y = vrCameraLocal.eulerAngles.y;
vrCameraLocal.localRotation = Quaternion.Euler(90f,0f,0f)*rot;
if(Controller.IsCameraLocked)
{
free = false;
vrCameraLocal.eulerAngles = new Vector3(vrCameraLocal.eulerAngles.x, angle = y, vrCameraLocal.eulerAngles.z);
}
else
{
if(!free)
{
free = true;
angle = vrCameraLocal.eulerAngles.y - angle;
}
vrCameraLocal.eulerAngles = new Vector3(vrCameraLocal.eulerAngles.x, vrCameraLocal.eulerAngles.y - angle, vrCameraLocal.eulerAngles.z);
}
#elif UNITY_WP8 || UNITY_WP_8_1
//rot = ConvertRotation(Input.gyro.attitude);
//vrCameraLocal.localRotation = rot;
//print (vrCameraLocal.localRotation.eulerAngles);
float vertical_angle_delta = (float)c.AngularVelocityY * Time.deltaTime;
float horisontal_angle_delta = (float)c.AngularVelocityX * Time.deltaTime;
float z_angle_delta = (float)c.AngularVelocityZ * Time.deltaTime;
rotation = Quaternion.Euler(rotation.eulerAngles.x+vertical_angle_delta,rotation.eulerAngles.y-horisontal_angle_delta,rotation.eulerAngles.z+z_angle_delta);
Vector3 gravity = Input.acceleration;
float fi = Mathf.Rad2Deg*Mathf.Atan(-gravity.z/(Mathf.Sign(gravity.y)*Mathf.Sqrt(gravity.y*gravity.y+gravity.x*gravity.x*0.01f)));
float teta = Mathf.Rad2Deg*Mathf.Atan(-gravity.x/(Mathf.Sqrt(gravity.z*gravity.z+gravity.y*gravity.y)));
rotation = Quaternion.Slerp(rotation,Quaternion.Euler(-fi,rotation.eulerAngles.y,teta),Time.deltaTime*2f);
//vrCameraLocal.localRotation = Quaternion.Euler(90f,0f,0f)*rotation;
vrCameraLocal.localRotation = rotation;
//vrCameraLocal.localRotation = Quaternion.Euler(-fi,0f,teta);
#endif
meanAcceleration = Vector3.Lerp(meanAcceleration,Input.acceleration,Time.deltaTime*2.0f);
if( meanAcceleration.x>0.25f && Mathf.Abs (meanAcceleration.y)<0.1f && (meanAcceleration-Input.acceleration).magnitude<0.5f )
{
FibrumController.isHandOriented=true;
}
else
{
FibrumController.isHandOriented=false;
}
////////////////////////////////////////
// MEASURE FPS
////////////////////////////////////////
FPStimeleft -= Time.deltaTime;
FPSaccum += Time.timeScale/Time.deltaTime;
++FPSframes;
if( FPStimeleft <= 0.0 )
{
fps = FPSaccum/FPSframes;
FPStimeleft = FPSupdateInterval;
FPSaccum = 0.0F;
FPSframes = 0;
}
/*if( checkFPS )
{
blackScreen = Mathf.Lerp(blackScreen,needBlackScreen,Time.deltaTime*5f);
} */
}
float angle = 0;
bool free = true;
void OnGUI()
{
/*if( checkFPS )
{
if (Event.current.type.Equals(EventType.Repaint))
{
Graphics.DrawTexture (new Rect(0f,0f,Screen.width,Screen.height),blackFadeTex,new Rect(0f,0f,1f,1f),0,0,0,0,new Color(1f,1f,1f,blackScreen),null);
}
}*/
#if UNITY_ANDROID && !UNITY_EDITOR
//GUI.Box (new Rect(0f,0f,Screen.width,30f)," rotationY="+(int)rotationY+" deltaCompassHeading="+(int)(rotationY-(Input.compass.magneticHeading-initCompassHeading)));
//GUI.Box (new Rect(0f,0f,Screen.width,30f)," heading="+(int)Input.compass.magneticHeading+" initCompass="+(int)initCompassHeading);
#endif
//GUI.Box (new Rect (0f, 0f, Screen.width, 30f), "r=" + vrCameraLocal.localRotation.eulerAngles+" a="+Input.acceleration);
}
#if UNITY_IPHONE || UNITY_WP8
private static Quaternion ConvertRotation(Quaternion q)
{
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
#endif
#if UNITY_ANDROID
public static void TransformFromMatrix(Matrix4x4 matrix, Transform trans) {
trans.localRotation = QuaternionFromMatrix(matrix);
}
public static Quaternion QuaternionFromMatrix(Matrix4x4 m) {
Quaternion q = new Quaternion();
q.w = Mathf.Sqrt( Mathf.Max( 0, 1 + m[0,0] + m[1,1] + m[2,2] ) ) / 2;
q.x = Mathf.Sqrt( Mathf.Max( 0, 1 + m[0,0] - m[1,1] - m[2,2] ) ) / 2;
q.y = Mathf.Sqrt( Mathf.Max( 0, 1 - m[0,0] + m[1,1] - m[2,2] ) ) / 2;
q.z = Mathf.Sqrt( Mathf.Max( 0, 1 - m[0,0] - m[1,1] + m[2,2] ) ) / 2;
q.x *= Mathf.Sign( q.x * ( m[2,1] - m[1,2] ) );
q.y *= Mathf.Sign( q.y * ( m[0,2] - m[2,0] ) );
q.z *= Mathf.Sign( q.z * ( m[1,0] - m[0,1] ) );
return q;
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
public class TC_SchemaSet_Add_SchemaSet
{
private ITestOutputHelper _output;
public TC_SchemaSet_Add_SchemaSet(ITestOutputHelper output)
{
_output = output;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v1 - sc = null", Priority = 0)]
public void v1()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add((XmlSchemaSet)null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v2 - sc = empty SchemaSet", Priority = 0)]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add(scnew);
Assert.Equal(sc.Count, 0);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v3 - sc = non empty SchemaSet, add with duplicate schemas", Priority = 0)]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
scnew.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(scnew);
// adding schemaset with same schema should be ignored
Assert.Equal(sc.Count, 1);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v4 - sc = self", Priority = 0)]
public void v4()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(sc);
Assert.Equal(sc.Count, 1);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v5 - sc = scnew, scnew as some duplicate but some unique schemas")]
public void v5()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(null, TestData._XsdNoNs);
scnew.Add(null, TestData._XsdNoNs);
scnew.Add(null, TestData._FileXSD1);
sc.Add(scnew);
Assert.Equal(sc.Count, 3);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v6 - sc = add second set with all new schemas")]
public void v6()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(null, TestData._XsdNoNs);
scnew.Add(null, TestData._FileXSD1);
scnew.Add(null, TestData._FileXSD2);
sc.Add(scnew);
Assert.Equal(sc.Count, 4);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v7 - sc = add second set with a conflicting schema")]
public void v7()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(null, TestData._XsdNoNs);
scnew.Add(null, TestData._FileXSD1);
scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor
sc.Add(scnew);
Assert.Equal(sc.IsCompiled, false);
Assert.Equal(sc.Count, 4); //ok
try
{
sc.Compile(); // should fail
}
catch (XmlSchemaException)
{
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v8 - sc = add second set with a conflicting schema to compiled set")]
public void v8()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(null, TestData._XsdNoNs);
sc.Compile();
Assert.Equal(sc.IsCompiled, true);
scnew.Add(null, TestData._FileXSD1);
scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor
sc.Add(scnew);
Assert.Equal(sc.IsCompiled, false);
Assert.Equal(sc.Count, 4); //ok
try
{
sc.Compile(); // should fail
}
catch (XmlSchemaException)
{
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v9 - sc = add compiled second set with a conflicting schema to compiled set")]
public void v9()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchemaSet scnew = new XmlSchemaSet();
sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Add(null, TestData._XsdNoNs);
sc.Compile();
Assert.Equal(sc.IsCompiled, true);
scnew.Add(null, TestData._FileXSD1);
scnew.Add(null, TestData._XsdAuthorDup); // this conflicts with _XsdAuthor
scnew.Compile();
try
{
sc.Add(scnew);
}
catch (XmlSchemaException)
{
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v10 - set1 added to set2 with set1 containing an invalid schema")]
public void v10()
{
XmlSchemaSet schemaSet1 = new XmlSchemaSet();
XmlSchemaSet schemaSet2 = new XmlSchemaSet();
XmlSchema schema1 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdAuthor, FileMode.Open, FileAccess.Read)), null);
XmlSchema schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null);
schemaSet1.Add(schema1);
schemaSet1.Add(schema2); // added two schemas
//schemaSet1.Compile ();
XmlSchemaElement elem = new XmlSchemaElement();
schema1.Items.Add(elem); // make the first schema dirty
//the following throws an exception
try
{
schemaSet2.Add(schemaSet1);
// shound not reach here
}
catch (XmlSchemaException)
{
Assert.Equal(schemaSet2.Count, 0); // no schema should be added
Assert.Equal(schemaSet1.Count, 2); // no schema should be added
Assert.Equal(schemaSet2.IsCompiled, false); // no schema should be added
Assert.Equal(schemaSet1.IsCompiled, false); // no schema should be added
return;
}
Assert.Equal(schemaSet2.Count, 0); // no schema should be added
Assert.True(false);
}
[Fact]
//[Variation(Desc = "v11 - Add three XmlSchema to Set1 then add Set1 to uncompiled Set2")]
public void v11()
{
XmlSchemaSet schemaSet1 = new XmlSchemaSet();
XmlSchemaSet schemaSet2 = new XmlSchemaSet();
XmlSchema schema1 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdAuthor, FileMode.Open, FileAccess.Read)), null);
XmlSchema schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null);
XmlSchema schema3 = XmlSchema.Read(new StreamReader(new FileStream(TestData._FileXSD1, FileMode.Open, FileAccess.Read)), null);
schemaSet1.Add(schema1);
schemaSet1.Add(schema2); // added two schemas
schemaSet1.Add(schema3); // added third
schemaSet1.Compile();
//the following throws an exception
try
{
schemaSet2.Add(schemaSet1);
Assert.Equal(schemaSet1.Count, 3); // no schema should be added
Assert.Equal(schemaSet2.Count, 3); // no schema should be added
Assert.Equal(schemaSet1.IsCompiled, true); // no schema should be added
schemaSet2.Compile();
Assert.Equal(schemaSet2.IsCompiled, true); // no schema should be added
// shound not reach here
}
catch (XmlSchemaException)
{
Assert.True(false);
}
return;
}
}
}
| |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAdmin.XenSearch;
namespace XenAdmin.Controls.XenSearch
{
public partial class SearchFor : UserControl
{
public event Action QueryChanged;
private const ObjectTypes CUSTOM = ObjectTypes.None; // We use None as a special signal value for "Custom..."
private readonly Dictionary<ObjectTypes, String> typeNames = new Dictionary<ObjectTypes, String>();
private readonly Dictionary<ObjectTypes, Image> typeImages = new Dictionary<ObjectTypes, Image>();
private ObjectTypes customValue;
private ObjectTypes savedTypes;
private bool autoSelecting = false;
public SearchFor()
{
InitializeComponent();
InitializeDictionaries();
PopulateSearchForComboButton();
}
public void BlankSearch()
{
QueryScope = new QueryScope(ObjectTypes.None);
OnQueryChanged();
}
private void OnQueryChanged()
{
if (QueryChanged != null)
QueryChanged();
}
private void InitializeDictionaries()
{
// add all single types, names and images
Dictionary<String, ObjectTypes> dict = (Dictionary<String, ObjectTypes>)PropertyAccessors.Geti18nFor(PropertyNames.type);
ImageDelegate<ObjectTypes> images = (ImageDelegate<ObjectTypes>)PropertyAccessors.GetImagesFor(PropertyNames.type);
foreach (KeyValuePair<String, ObjectTypes> kvp in dict)
{
typeNames[kvp.Value] = kvp.Key;
typeImages[kvp.Value] = Images.GetImage16For(images(kvp.Value));
}
// add all combo types, mostly names only
typeNames[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Messages.ALL_SRS;
typeImages[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Images.GetImage16For(images(ObjectTypes.LocalSR | ObjectTypes.RemoteSR));
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM] = Messages.SERVERS_AND_VMS;
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_REMOTE_SRS;
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_ALL_SRS;
typeNames[ObjectTypes.AllExcFolders] = Messages.ALL_TYPES;
typeNames[ObjectTypes.AllIncFolders] = Messages.ALL_TYPES_AND_FOLDERS;
}
private void AddItemToSearchFor(ObjectTypes type)
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = typeNames[type];
item.Tag = type;
if (typeImages.ContainsKey(type))
item.Image = typeImages[type];
searchForComboButton.AddItem(item);
}
private void AddCustom()
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = Messages.CUSTOM;
item.Tag = CUSTOM;
searchForComboButton.AddItem(item);
}
private void AddSeparator()
{
searchForComboButton.AddItem(new ToolStripSeparator());
}
// The order here is not the same as the order in the Organization View,
// which is determined by the ObjectTypes enum (CA-28418).
private void PopulateSearchForComboButton()
{
AddItemToSearchFor(ObjectTypes.Pool);
AddItemToSearchFor(ObjectTypes.Server);
AddItemToSearchFor(ObjectTypes.DisconnectedServer);
AddItemToSearchFor(ObjectTypes.VM);
AddItemToSearchFor(ObjectTypes.Snapshot);
AddItemToSearchFor(ObjectTypes.UserTemplate);
AddItemToSearchFor(ObjectTypes.DefaultTemplate);
AddItemToSearchFor(ObjectTypes.RemoteSR);
AddItemToSearchFor(ObjectTypes.RemoteSR | ObjectTypes.LocalSR); // local SR on its own is pretty much useless
AddItemToSearchFor(ObjectTypes.VDI);
AddItemToSearchFor(ObjectTypes.Network);
AddItemToSearchFor(ObjectTypes.Folder);
AddSeparator();
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM);
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR);
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR);
AddSeparator();
AddItemToSearchFor(ObjectTypes.AllExcFolders);
AddItemToSearchFor(ObjectTypes.AllIncFolders);
AddSeparator();
AddCustom();
}
void searchForComboButton_BeforePopup(object sender, System.EventArgs e)
{
savedTypes = GetSelectedItemTag();
}
private void searchForComboButton_itemSelected(object sender, System.EventArgs e)
{
ObjectTypes types = GetSelectedItemTag();
if (types != CUSTOM)
return;
if (!autoSelecting)
{
// Launch custom dlg. Dependent on OK/Cancel, save result and continue, or quit
SearchForCustom sfc = new SearchForCustom(typeNames, customValue);
sfc.ShowDialog(Program.MainWindow);
if (sfc.DialogResult == DialogResult.Cancel)
{
autoSelecting = true;
SetFromScope(savedTypes); // reset combo button to value before Custom...
autoSelecting = false;
return;
}
customValue = sfc.Selected;
}
OnQueryChanged();
}
private void searchForComboButton_selChanged(object sender, EventArgs e)
{
ObjectTypes types = GetSelectedItemTag();
if (types == CUSTOM)
return; // CUSTOM is dealt with in searchForComboButton_itemSelected instead
OnQueryChanged();
}
public QueryScope QueryScope
{
get
{
return GetAsScope();
}
set
{
autoSelecting = true;
customValue = value.ObjectTypes;
SetFromScope(value);
autoSelecting = false;
}
}
private ObjectTypes GetSelectedItemTag()
{
return (searchForComboButton.SelectedItem == null ? ObjectTypes.None :
(ObjectTypes)searchForComboButton.SelectedItem.Tag);
}
private QueryScope GetAsScope()
{
ObjectTypes types = GetSelectedItemTag();
if (types == CUSTOM) // if we're on Custom..., look it up from the custom setting
return new QueryScope(customValue);
else // else just report what we're showing
return new QueryScope(types);
}
private void SetFromScope(QueryScope value)
{
// Can we represent it by one of the fixed types?
bool bDone = searchForComboButton.SelectItem<ObjectTypes>(
delegate(ObjectTypes types)
{
return (types == value.ObjectTypes);
}
);
// If not, set it to "Custom..."
if (!bDone)
bDone = searchForComboButton.SelectItem<ObjectTypes>(
delegate(ObjectTypes types)
{
return (types == CUSTOM);
}
);
}
private void SetFromScope(ObjectTypes types)
{
SetFromScope(new QueryScope(types));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace CartographerUtilities
{
/// <summary>
/// Class is responsible to manage MRU files list.
///
/// MruInfo passed to this instance should be read by client
/// from some persistent storage (like XML file).
///
/// Using: create this class and pass to its constructor
/// MruInfo class instance and Recent Files menu item.
/// Call class methods Add and Delete when necessary
/// (see notes in these functions).
/// Subscribe to FileSelected event and open file in
/// this event handler.
/// </summary>
public class MruManager
{
#region Class Members
MruInfo infoMru;
MenuItem menuItemMru;
int maxLength = 10;
public event EventHandler<MruFileOpenEventArgs> FileSelected;
#endregion Class Members
#region Constructor
public MruManager(MruInfo mruInfo, MenuItem mruMenuItem)
{
if (mruInfo == null)
{
throw new ArgumentNullException("mruInfo");
}
if (mruMenuItem == null)
{
throw new ArgumentNullException("mruMenuItem");
}
this.infoMru = mruInfo;
this.menuItemMru = mruMenuItem;
UpdateMenu();
}
#endregion Constructor
#region Properties
/// <summary>
/// Maximal number of entries in MRU list
/// </summary>
public int MaxLength
{
get
{
return maxLength;
}
set
{
if ( value > 0 )
{
maxLength = value;
}
}
}
#endregion Properties
#region Public Functions
/// <summary>
/// Add file name to MRU list.
/// Call this function after every successful Open operation
/// (including file selected from MRU list).
/// </summary>
public void Add(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
// If file exists, move it to the beginning.
// If not, add it to the beginning.
List<string> list = new List<string>();
list.Add(fileName);
if (infoMru.RecentFiles != null)
{
foreach (string s in infoMru.RecentFiles)
{
if (s != fileName)
{
list.Add(s);
}
}
}
MakeArrayFromList(list);
UpdateMenu();
}
/// <summary>
/// Delete file name from MRU list.
/// Call this function after every unsuccessful Open operation
/// (including file selected from MRU list).
/// </summary>
public void Delete(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
List<string> list = new List<string>();
if (infoMru.RecentFiles != null)
{
foreach (string s in infoMru.RecentFiles)
{
if (s != fileName)
{
list.Add(s);
}
}
}
MakeArrayFromList(list);
UpdateMenu();
}
#endregion Public Functions
#region Other Functions
/// <summary>
/// Fill MRU menu
/// </summary>
void UpdateMenu()
{
menuItemMru.Items.Clear();
if (infoMru.RecentFiles != null )
{
foreach (string fullName in infoMru.RecentFiles)
{
MenuItem item = new MenuItem();
string shortName = System.IO.Path.GetFileName(fullName);
ToolTip toolTip = new ToolTip();
toolTip.Content = fullName;
item.Header = shortName;
item.ToolTip = toolTip;
item.Tag = fullName;
item.Click += new RoutedEventHandler(item_Click);
menuItemMru.Items.Add(item);
}
}
menuItemMru.IsEnabled = (infoMru.RecentFiles.Length > 0);
}
/// <summary>
/// MRU item is selected - report to client.
/// </summary>
void item_Click(object sender, RoutedEventArgs e)
{
MenuItem item = (MenuItem)sender;
string fileName = (string)item.Tag;
if ( FileSelected != null )
{
FileSelected(this, new MruFileOpenEventArgs(fileName));
}
}
/// <summary>
/// Make string array from list and set it in MriInfo
/// </summary>
void MakeArrayFromList(List<string> list)
{
string[] files = new string[Math.Min(list.Count, maxLength)];
int index = 0;
foreach(string s in list)
{
files[index++] = s;
if ( index >= maxLength )
{
break;
}
}
infoMru.RecentFiles = files;
}
#endregion Other Functions
}
}
| |
using System;
using System.Threading.Tasks;
using NUnit.Framework;
[TestFixture]
public class RewritingMethods
{
private Type sampleClassType;
private Type classWithPrivateMethodType;
private Type specialClassType;
private Type classToExcludeType;
private Type classWithExplicitInterfaceType;
[SetUp]
public void SetUp()
{
sampleClassType = AssemblyWeaver.Assemblies[0].GetType("SimpleClass");
classWithPrivateMethodType = AssemblyWeaver.Assemblies[0].GetType("ClassWithPrivateMethod");
specialClassType = AssemblyWeaver.Assemblies[0].GetType("SpecialClass");
classToExcludeType = AssemblyWeaver.Assemblies[1].GetType("ClassToExclude");
classWithExplicitInterfaceType = AssemblyWeaver.Assemblies[0].GetType("ClassWithExplicitInterface");
AssemblyWeaver.TestListener.Reset();
}
[Test]
public void RequiresNonNullArgumentForExplicitInterface()
{
AssemblyWeaver.TestListener.Reset();
var sample = (IComparable<string>)Activator.CreateInstance(classWithExplicitInterfaceType);
var exception = Assert.Throws<ArgumentNullException>(() => sample.CompareTo(null));
Assert.AreEqual("other", exception.ParamName);
Assert.AreEqual("Fail: [NullGuard] other is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void RequiresNonNullArgument()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
var exception = Assert.Throws<ArgumentNullException>(() => sample.SomeMethod(null, ""));
Assert.AreEqual("nonNullArg", exception.ParamName);
Assert.AreEqual("Fail: [NullGuard] nonNullArg is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void AllowsNullWhenAttributeApplied()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
sample.SomeMethod("", null);
}
[Test]
public void RequiresNonNullMethodReturnValue()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
Assert.Throws<InvalidOperationException>(() => sample.MethodWithReturnValue(true));
Assert.AreEqual("Fail: [NullGuard] Return value of method 'System.String SimpleClass::MethodWithReturnValue(System.Boolean)' is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void RequiresNonNullGenericMethodReturnValue()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
Assert.Throws<InvalidOperationException>(() => sample.MethodWithGenericReturn<object>(true));
Assert.AreEqual("Fail: [NullGuard] Return value of method 'T SimpleClass::MethodWithGenericReturn(System.Boolean)' is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void AllowsNullReturnValueWhenAttributeApplied()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
sample.MethodAllowsNullReturnValue();
}
[Test]
public void RequiresNonNullOutValue()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
string value;
Assert.Throws<InvalidOperationException>(() => sample.MethodWithOutValue(out value));
Assert.AreEqual("Fail: [NullGuard] Out parameter 'nonNullOutArg' is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void DoesNotRequireNonNullForNonPublicMethod()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
sample.PublicWrapperOfPrivateMethod();
}
[Test]
public void DoesNotRequireNonNullForOptionalParameter()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
sample.MethodWithOptionalParameter(optional: null);
}
[Test]
public void RequiresNonNullForOptionalParameterWithNonNullDefaultValue()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
var exception = Assert.Throws<ArgumentNullException>(() => sample.MethodWithOptionalParameterWithNonNullDefaultValue(optional: null));
Assert.AreEqual("optional", exception.ParamName);
Assert.AreEqual("Fail: [NullGuard] optional is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void DoesNotRequireNonNullForOptionalParameterWithNonNullDefaultValueButAllowNullAttribute()
{
var sample = (dynamic)Activator.CreateInstance(sampleClassType);
sample.MethodWithOptionalParameterWithNonNullDefaultValueButAllowNullAttribute(optional: null);
}
[Test]
public void RequiresNonNullForNonPublicMethodWhenAttributeSpecifiesNonPublic()
{
var sample = (dynamic)Activator.CreateInstance(classWithPrivateMethodType);
Assert.Throws<ArgumentNullException>(() => sample.PublicWrapperOfPrivateMethod());
Assert.AreEqual("Fail: [NullGuard] x is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void ReturnGuardDoesNotInterfereWithIteratorMethod()
{
var sample = (dynamic)Activator.CreateInstance(specialClassType);
Assert.That(new[] { 0, 1, 2, 3, 4 }, Is.EquivalentTo(sample.CountTo(5)));
}
#if (DEBUG)
[Test]
public void RequiresNonNullArgumentAsync()
{
var sample = (dynamic)Activator.CreateInstance(specialClassType);
var exception = Assert.Throws<ArgumentNullException>(() => sample.SomeMethodAsync(null, ""));
Assert.AreEqual("nonNullArg", exception.ParamName);
Assert.AreEqual("Fail: [NullGuard] nonNullArg is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void AllowsNullWhenAttributeAppliedAsync()
{
var sample = (dynamic)Activator.CreateInstance(specialClassType);
sample.SomeMethodAsync("", null);
}
[Test]
public void RequiresNonNullMethodReturnValueAsync()
{
var sample = (dynamic)Activator.CreateInstance(specialClassType);
Exception ex = null;
((Task<string>)sample.MethodWithReturnValueAsync(true))
.ContinueWith(t =>
{
if (t.IsFaulted)
ex = t.Exception.Flatten().InnerException;
})
.Wait();
Assert.NotNull(ex);
Assert.IsInstanceOf<InvalidOperationException>(ex);
Assert.AreEqual("[NullGuard] Return value of method 'System.Threading.Tasks.Task`1<System.String> SpecialClass::MethodWithReturnValueAsync(System.Boolean)' is null.", ex.Message);
Assert.AreEqual("Fail: [NullGuard] Return value of method 'System.Threading.Tasks.Task`1<System.String> SpecialClass::MethodWithReturnValueAsync(System.Boolean)' is null.", AssemblyWeaver.TestListener.Message);
}
[Test]
public void AllowsNullReturnValueWhenAttributeAppliedAsync()
{
var sample = (dynamic)Activator.CreateInstance(specialClassType);
Exception ex = null;
((Task<string>)sample.MethodAllowsNullReturnValueAsync())
.ContinueWith(t =>
{
if (t.IsFaulted)
ex = t.Exception.Flatten().InnerException;
})
.Wait();
Assert.Null(ex);
}
[Test]
public void NoAwaitWillCompile()
{
var instance = (dynamic)Activator.CreateInstance(specialClassType);
Assert.AreEqual(42, instance.NoAwaitCode().Result);
}
#endif
[Test]
public void AllowsNullWhenClassMatchExcludeRegex()
{
var ClassToExclude = (dynamic)Activator.CreateInstance(classToExcludeType, "");
ClassToExclude.Test(null);
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using i16 = System.Int16;
using u8 = System.Byte;
using u16 = System.UInt16;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2005 May 23
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the encoding enc of name zName, length nName.
*/
static void callCollNeeded( sqlite3 db, int enc, string zName )
{
Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null );
if ( db.xCollNeeded != null )
{
string zExternal = zName;// sqlite3DbStrDup(db, zName);
if ( zExternal == null ) return;
db.xCollNeeded( db.pCollNeededArg, db, enc, zExternal );
sqlite3DbFree( db, ref zExternal );
}
#if !SQLITE_OMIT_UTF16
if( db.xCollNeeded16!=null ){
string zExternal;
sqlite3_value pTmp = sqlite3ValueNew(db);
sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
if( zExternal!="" ){
db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal);
}
sqlite3ValueFree(ref pTmp);
}
#endif
}
/*
** This routine is called if the collation factory fails to deliver a
** collation function in the best encoding but there may be other versions
** of this collation function (for other text encodings) available. Use one
** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
** possible.
*/
static int synthCollSeq( sqlite3 db, CollSeq pColl )
{
CollSeq pColl2;
string z = pColl.zName;
int i;
byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
for ( i = 0; i < 3; i++ )
{
pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 );
if ( pColl2.xCmp != null )
{
pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
pColl.xDel = null; /* Do not copy the destructor */
return SQLITE_OK;
}
}
return SQLITE_ERROR;
}
/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**
** If it is not NULL, then pColl must point to the database native encoding
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
static CollSeq sqlite3GetCollSeq(
sqlite3 db, /* The database connection */
u8 enc, /* The desired encoding for the collating sequence */
CollSeq pColl, /* Collating sequence with native encoding, or NULL */
string zName /* Collating sequence name */
)
{
CollSeq p;
p = pColl;
if ( p == null )
{
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p == null || p.xCmp == null )
{
/* No collation sequence of this type for this encoding is registered.
** Call the collation factory to see if it can supply us with one.
*/
callCollNeeded( db, enc, zName );
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 )
{
p = null;
}
Debug.Assert( p == null || p.xCmp != null );
return p;
}
/*
** This routine is called on a collation sequence before it is used to
** check that it is defined. An undefined collation sequence exists when
** a database is loaded that contains references to collation sequences
** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work,
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl )
{
if ( pColl != null )
{
string zName = pColl.zName;
sqlite3 db = pParse.db;
CollSeq p = sqlite3GetCollSeq( db, ENC( db ), pColl, zName );
if ( null == p )
{
sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
pParse.nErr++;
return SQLITE_ERROR;
}
//
//Debug.Assert(p == pColl);
if ( p != pColl ) // Had to lookup appropriate sequence
{
pColl.enc = p.enc;
pColl.pUser = p.pUser;
pColl.type = p.type;
pColl.xCmp = p.xCmp;
pColl.xDel = p.xDel;
}
}
return SQLITE_OK;
}
/*
** Locate and return an entry from the db.aCollSeq hash table. If the entry
** specified by zName and nName is not found and parameter 'create' is
** true, then create a new entry. Otherwise return NULL.
**
** Each pointer stored in the sqlite3.aCollSeq hash table contains an
** array of three CollSeq structures. The first is the collation sequence
** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
**
** Stored immediately after the three collation sequences is a copy of
** the collation sequence name. A pointer to this string is stored in
** each collation sequence structure.
*/
static CollSeq[] findCollSeqEntry(
sqlite3 db, /* Database connection */
string zName, /* Name of the collating sequence */
int create /* Create a new entry if true */
)
{
CollSeq[] pColl;
int nName = sqlite3Strlen30( zName );
pColl = (CollSeq[])sqlite3HashFind( db.aCollSeq, zName, nName );
if ( ( null == pColl ) && create != 0 )
{
pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
if ( pColl != null )
{
CollSeq pDel = null;
pColl[0] = new CollSeq();
pColl[0].zName = zName;
pColl[0].enc = SQLITE_UTF8;
pColl[1] = new CollSeq();
pColl[1].zName = zName;
pColl[1].enc = SQLITE_UTF16LE;
pColl[2] = new CollSeq();
pColl[2].zName = zName;
pColl[2].enc = SQLITE_UTF16BE;
//memcpy(pColl[0].zName, zName, nName);
//pColl[0].zName[nName] = 0;
pDel = (CollSeq)sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl );
/* If a malloc() failure occurred in sqlite3HashInsert(), it will
** return the pColl pointer to be deleted (because it wasn't added
** to the hash table).
*/
Debug.Assert( pDel == null || pDel == pColl[0] );
if ( pDel != null )
{
//// db.mallocFailed = 1;
pDel = null; //was sqlite3DbFree(db,ref pDel);
pColl = null;
}
}
}
return pColl;
}
/*
** Parameter zName points to a UTF-8 encoded string nName bytes long.
** Return the CollSeq* pointer for the collation sequence named zName
** for the encoding 'enc' from the database 'db'.
**
** If the entry specified is not found and 'create' is true, then create a
** new entry. Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine. sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
*/
static CollSeq sqlite3FindCollSeq(
sqlite3 db,
u8 enc,
string zName,
u8 create
)
{
CollSeq[] pColl;
if ( zName != null )
{
pColl = findCollSeqEntry( db, zName, create );
}
else
{
pColl = new CollSeq[enc];
pColl[enc - 1] = db.pDfltColl;
}
Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 );
Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE );
if ( pColl != null )
{
enc -= 1; // if (pColl != null) pColl += enc - 1;
return pColl[enc];
}
else return null;
}
/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
** encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
** requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality( FuncDef p, int nArg, int enc )
{
int match = 0;
if ( p.nArg == -1 || p.nArg == nArg
|| ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) )
)
{
match = 1;
if ( p.nArg == nArg || nArg == -1 )
{
match = 4;
}
if ( enc == p.iPrefEnc )
{
match += 2;
}
else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) ||
( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) )
{
match += 1;
}
}
return match;
}
/*
** Search a FuncDefHash for a function with the given name. Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef functionSearch(
FuncDefHash pHash, /* Hash table to search */
int h, /* Hash of the name */
string zFunc, /* Name of function */
int nFunc /* Number of bytes in zFunc */
)
{
FuncDef p;
for ( p = pHash.a[h]; p != null; p = p.pHash )
{
if ( sqlite3StrNICmp( p.zName, zFunc, nFunc ) == 0 && p.zName.Length == nFunc )
{
return p;
}
}
return null;
}
/*
** Insert a new FuncDef into a FuncDefHash hash table.
*/
static void sqlite3FuncDefInsert(
FuncDefHash pHash, /* The hash table into which to insert */
FuncDef pDef /* The function definition to insert */
)
{
FuncDef pOther;
int nName = sqlite3Strlen30( pDef.zName );
u8 c1 = (u8)pDef.zName[0];
int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a );
pOther = functionSearch( pHash, h, pDef.zName, nName );
if ( pOther != null )
{
Debug.Assert( pOther != pDef && pOther.pNext != pDef );
pDef.pNext = pOther.pNext;
pOther.pNext = pDef;
}
else
{
pDef.pNext = null;
pDef.pHash = pHash.a[h];
pHash.a[h] = pDef;
}
}
/*
** Locate a user function given a name, a number of arguments and a flag
** indicating whether the function prefers UTF-16 over UTF-8. Return a
** pointer to the FuncDef structure that defines that function, or return
** NULL if the function does not exist.
**
** If the createFlag argument is true, then a new (blank) FuncDef
** structure is created and liked into the "db" structure if a
** no matching function previously existed. When createFlag is true
** and the nArg parameter is -1, then only a function that accepts
** any number of arguments will be returned.
**
** If createFlag is false and nArg is -1, then the first valid
** function found is returned. A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
static FuncDef sqlite3FindFunction(
sqlite3 db, /* An open database */
string zName, /* Name of the function. Not null-terminated */
int nName, /* Number of characters in the name */
int nArg, /* Number of arguments. -1 means any number */
u8 enc, /* Preferred text encoding */
u8 createFlag /* Create new entry if true and does not otherwise exist */
)
{
FuncDef p; /* Iterator variable */
FuncDef pBest = null; /* Best match found so far */
int bestScore = 0;
int h; /* Hash value */
Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE );
h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a );
/* First search for a match amongst the application-defined functions.
*/
p = functionSearch( db.aFunc, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
/* If no match is found, search the built-in functions.
**
** Except, if createFlag is true, that means that we are trying to
** install a new function. Whatever FuncDef structure is returned will
** have fields overwritten with new information appropriate for the
** new function. But the FuncDefs for built-in functions are read-only.
** So we must not search for built-ins when creating a new function.
*/
if ( 0 == createFlag && pBest == null )
{
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
#else
FuncDefHash pHash = sqlite3GlobalFunctions;
#endif
p = functionSearch( pHash, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
}
/* If the createFlag parameter is true and the search did not reveal an
** exact match for the name, number of arguments and encoding, then add a
** new entry to the hash table and return it.
*/
if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) &&
( pBest = new FuncDef() ) != null )
{ //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
//pBest.zName = (char *)&pBest[1];
pBest.nArg = (i16)nArg;
pBest.iPrefEnc = enc;
pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
//pBest.zName[nName] = 0;
sqlite3FuncDefInsert( db.aFunc, pBest );
}
if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) )
{
return pBest;
}
return null;
}
/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
** pointer itself, it just cleans up subsiduary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
static void sqlite3SchemaFree( Schema p )
{
Hash temp1;
Hash temp2;
HashElem pElem;
Schema pSchema = p;
temp1 = pSchema.tblHash;
temp2 = pSchema.trigHash;
sqlite3HashInit( pSchema.trigHash );
sqlite3HashClear( pSchema.idxHash );
for ( pElem = sqliteHashFirst( temp2 ); pElem != null; pElem = sqliteHashNext( pElem ) )
{
Trigger pTrigger = (Trigger)sqliteHashData( pElem );
sqlite3DeleteTrigger( null, ref pTrigger );
}
sqlite3HashClear( temp2 );
sqlite3HashInit( pSchema.trigHash );
for ( pElem = temp1.first; pElem != null; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
{
Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
Debug.Assert( pTab.dbMem == null );
sqlite3DeleteTable( ref pTab );
}
sqlite3HashClear( temp1 );
sqlite3HashClear( pSchema.fkeyHash );
pSchema.pSeqTab = null;
pSchema.flags = (u16)( pSchema.flags & ~DB_SchemaLoaded );
}
/*
** Find and return the schema associated with a BTree. Create
** a new one if necessary.
*/
static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt )
{
Schema p;
if ( pBt != null )
{
p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaFree );//Schema.Length, sqlite3SchemaFree);
}
else
{
p = new Schema(); // (Schema*)sqlite3MallocZero(Schema).Length;
}
if ( p == null )
{
//// db.mallocFailed = 1;
}
else if ( 0 == p.file_format )
{
sqlite3HashInit( p.tblHash );
sqlite3HashInit( p.idxHash );
sqlite3HashInit( p.trigHash );
sqlite3HashInit( p.fkeyHash );
p.enc = SQLITE_UTF8;
}
return p;
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (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.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Advanced;
namespace PdfSharp.Drawing
{
/// <summary>
/// Specifies details about how the font is used in PDF creation.
/// </summary>
public class XPdfFontOptions
{
internal XPdfFontOptions() { }
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
public XPdfFontOptions(PdfFontEncoding encoding, PdfFontEmbedding embedding)
{
this.fontEncoding = encoding;
this.fontEmbedding = embedding;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
public XPdfFontOptions(PdfFontEncoding encoding)
{
this.fontEncoding = encoding;
this.fontEmbedding = PdfFontEmbedding.None;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
public XPdfFontOptions(PdfFontEmbedding embedding)
{
this.fontEncoding = PdfFontEncoding.WinAnsi;
this.fontEmbedding = embedding;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="embed">If set to <c>true</c> the font is embedded.</param>
/// <param name="unicode">If set to <c>true</c> Unicode encoding is used.</param>
/// <param name="baseFont">Not yet implemented. Should be "".</param>
/// <param name="fontFile">Not yet implemented. Should be "".</param>
[Obsolete("Use other constructor")]
XPdfFontOptions(bool embed, bool unicode, string baseFont, string fontFile)
{
this.fontEmbedding = embed ? PdfFontEmbedding.Always : PdfFontEmbedding.None;
this.fontEncoding = unicode ? PdfFontEncoding.Unicode : PdfFontEncoding.WinAnsi;
//this.baseFont = baseFont == null ? "" : baseFont;
//this.fontFile = fontFile == null ? "" : fontFile;
this.fontEmbedding = PdfFontEmbedding.Default;
this.fontEncoding = PdfFontEncoding.WinAnsi;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="unicode">If set to <c>true</c> Unicode encoding is used.</param>
/// <param name="fontData">User supplied font data.</param>
[Obsolete("Use other constructor")]
public XPdfFontOptions(bool unicode, byte[] fontData)
{
this.fontEmbedding = PdfFontEmbedding.None;
this.fontEncoding = unicode ? PdfFontEncoding.Unicode : PdfFontEncoding.WinAnsi;
//this.baseFont = "";
//this.fontFile = "";
//this.fontData = fontData;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="embed">If set to <c>true</c> the font is embedded.</param>
/// <param name="baseFont">Not yet implemented. Should be "".</param>
[Obsolete("Use other constructor")]
public XPdfFontOptions(bool embed, string baseFont)
: this(embed, false, baseFont, "")
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="embed">If set to <c>true</c> the font is embedded.</param>
/// <param name="unicode">If set to <c>true</c> Unicode encoding is used.</param>
[Obsolete("Use other constructor")]
public XPdfFontOptions(bool embed, bool unicode)
: this(embed, unicode, "", "")
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="embed">If set to <c>true</c> the font is embedded.</param>
[Obsolete("Use other constructor")]
public XPdfFontOptions(bool embed)
: this(embed, false, "", "")
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XPdfFontOptions"/> class.
/// </summary>
/// <param name="fontEmbedding">Indicates how font is embedded.</param>
/// <param name="unicode">If set to <c>true</c> Unicode encoding is used.</param>
[Obsolete("Use other constructor")]
public XPdfFontOptions(PdfFontEmbedding fontEmbedding, bool unicode)
: this(fontEmbedding == PdfFontEmbedding.Always || fontEmbedding == PdfFontEmbedding.Automatic,
unicode, "", "")
{ }
/// <summary>
/// Gets a value indicating whether the gets embedded in the PDF file.
/// </summary>
[Obsolete("Use FontEmbedding")]
public bool Embed
{
get { return this.fontEmbedding != PdfFontEmbedding.None; }
}
//bool embed;
/// <summary>
/// Gets a value indicating the font embedding.
/// </summary>
public PdfFontEmbedding FontEmbedding
{
get { return this.fontEmbedding; }
}
PdfFontEmbedding fontEmbedding;
//public bool Subset
//{
// get {return this.subset;}
//}
//bool subset;
/// <summary>
/// Gets a value indicating whether the font is encoded as Unicode.
/// </summary>
[Obsolete("Use FontEncoding")]
public bool Unicode
{
get { return this.fontEncoding == PdfFontEncoding.Unicode; }
}
//bool unicode;
/// <summary>
/// Gets a value indicating how the font is encoded.
/// </summary>
public PdfFontEncoding FontEncoding
{
get { return this.fontEncoding; }
}
PdfFontEncoding fontEncoding;
/// <summary>
/// Not yet implemented.
/// </summary>
[Obsolete("Not yet implemented")]
public string BaseFont
{
//get { return this.baseFont; }
get { return ""; }
}
//string baseFont = "";
/// <summary>
/// Not yet implemented.
/// </summary>
[Obsolete("Not yet implemented")]
public string FontFile
{
//get { return this.fontFile; }
get { return ""; }
}
//string fontFile = "";
/// <summary>
/// Gets the font image.
/// </summary>
[Obsolete("Not yet implemented")]
public byte[] FontData
{
//get { return this.fontData; }
get { return null; }
}
//byte[] fontData;
// this is part of XGraphics
// public double CharacterSpacing;
// public double WordSpacing;
// public double HorizontalScaling;
// public double Leading;
// public double TextRise;
// Kerning
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: base.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Messages {
/// <summary>Holder for reflection information generated from base.proto</summary>
public static partial class BaseReflection {
#region Descriptor
/// <summary>File descriptor for base.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static BaseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgpiYXNlLnByb3RvEghtZXNzYWdlcyI4Cg1SZXF1ZXN0VGFyZ2V0EhcKD1Rh",
"cmdldEFjdG9yTmFtZRgBIAEoCRIOCgZyZXBlYXQYAiABKAgiDgoMSGVsbG9S",
"ZXF1ZXN0IiAKDUhlbGxvUmVzcG9uc2USDwoHTWVzc2FnZRgBIAEoCUILqgII",
"TWVzc2FnZXNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.RequestTarget), global::Messages.RequestTarget.Parser, new[]{ "TargetActorName", "Repeat" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.HelloRequest), global::Messages.HelloRequest.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Messages.HelloResponse), global::Messages.HelloResponse.Parser, new[]{ "Message" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class RequestTarget : pb::IMessage<RequestTarget> {
private static readonly pb::MessageParser<RequestTarget> _parser = new pb::MessageParser<RequestTarget>(() => new RequestTarget());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RequestTarget> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.BaseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RequestTarget() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RequestTarget(RequestTarget other) : this() {
targetActorName_ = other.targetActorName_;
repeat_ = other.repeat_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RequestTarget Clone() {
return new RequestTarget(this);
}
/// <summary>Field number for the "TargetActorName" field.</summary>
public const int TargetActorNameFieldNumber = 1;
private string targetActorName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TargetActorName {
get { return targetActorName_; }
set {
targetActorName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "repeat" field.</summary>
public const int RepeatFieldNumber = 2;
private bool repeat_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Repeat {
get { return repeat_; }
set {
repeat_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RequestTarget);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RequestTarget other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (TargetActorName != other.TargetActorName) return false;
if (Repeat != other.Repeat) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (TargetActorName.Length != 0) hash ^= TargetActorName.GetHashCode();
if (Repeat != false) hash ^= Repeat.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (TargetActorName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(TargetActorName);
}
if (Repeat != false) {
output.WriteRawTag(16);
output.WriteBool(Repeat);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (TargetActorName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TargetActorName);
}
if (Repeat != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RequestTarget other) {
if (other == null) {
return;
}
if (other.TargetActorName.Length != 0) {
TargetActorName = other.TargetActorName;
}
if (other.Repeat != false) {
Repeat = other.Repeat;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
TargetActorName = input.ReadString();
break;
}
case 16: {
Repeat = input.ReadBool();
break;
}
}
}
}
}
public sealed partial class HelloRequest : pb::IMessage<HelloRequest> {
private static readonly pb::MessageParser<HelloRequest> _parser = new pb::MessageParser<HelloRequest>(() => new HelloRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HelloRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.BaseReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest(HelloRequest other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest Clone() {
return new HelloRequest(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HelloRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HelloRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HelloRequest other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
public sealed partial class HelloResponse : pb::IMessage<HelloResponse> {
private static readonly pb::MessageParser<HelloResponse> _parser = new pb::MessageParser<HelloResponse>(() => new HelloResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HelloResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Messages.BaseReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloResponse(HelloResponse other) : this() {
message_ = other.message_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloResponse Clone() {
return new HelloResponse(this);
}
/// <summary>Field number for the "Message" field.</summary>
public const int MessageFieldNumber = 1;
private string message_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HelloResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HelloResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Message != other.Message) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Message.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Message);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HelloResponse other) {
if (other == null) {
return;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Message = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* Anarres C Preprocessor
* Copyright (c) 2007-2008, Shevek
*
* 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 boolean = System.Boolean;
namespace CppNet
{
/**
* An input to the Preprocessor.
*
* Inputs may come from Files, Strings or other sources. The
* preprocessor maintains a stack of Sources. Operations such as
* file inclusion or token pasting will push a new source onto
* the Preprocessor stack. Sources pop from the stack when they
* are exhausted; this may be transparent or explicit.
*
* BUG: Error messages are not handled properly.
*/
public abstract class Source : Iterable<Token>, Closeable
{
private Source parent;
private boolean autopop;
private PreprocessorListener listener;
private boolean active;
private boolean werror;
/* LineNumberReader */
/*
// We can't do this, since we would lose the LexerException
private class Itr implements Iterator {
private Token next = null;
private void advance() {
try {
if (next != null)
next = token();
}
catch (IOException e) {
throw new UnsupportedOperationException(
"Failed to advance token iterator: " +
e.getMessage()
);
}
}
public boolean hasNext() {
return next.getType() != EOF;
}
public Token next() {
advance();
Token t = next;
next = null;
return t;
}
public void remove() {
throw new UnsupportedOperationException(
"Cannot remove tokens from a Source."
);
}
}
*/
public Source()
{
this.parent = null;
this.autopop = false;
this.listener = null;
this.active = true;
this.werror = false;
}
/**
* Sets the parent source of this source.
*
* Sources form a singly linked list.
*/
internal void setParent(Source parent, boolean autopop)
{
this.parent = parent;
this.autopop = autopop;
}
/**
* Returns the parent source of this source.
*
* Sources form a singly linked list.
*/
internal Source getParent()
{
return parent;
}
// @OverrideMustInvoke
internal virtual void init(Preprocessor pp)
{
setListener(pp.getListener());
this.werror = pp.getWarnings().HasFlag(Warning.ERROR);
}
/**
* Sets the listener for this Source.
*
* Normally this is set by the Preprocessor when a Source is
* used, but if you are using a Source as a standalone object,
* you may wish to call this.
*/
public void setListener(PreprocessorListener pl)
{
this.listener = pl;
}
/**
* Returns the File currently being lexed.
*
* If this Source is not a {@link FileLexerSource}, then
* it will ask the parent Source, and so forth recursively.
* If no Source on the stack is a FileLexerSource, returns null.
*/
internal virtual String getPath()
{
Source parent = getParent();
if(parent != null)
return parent.getPath();
return null;
}
/**
* Returns the human-readable name of the current Source.
*/
internal virtual String getName()
{
Source parent = getParent();
if(parent != null)
return parent.getName();
return null;
}
/**
* Returns the current line number within this Source.
*/
public virtual int getLine()
{
Source parent = getParent();
if(parent == null)
return 0;
return parent.getLine();
}
/**
* Returns the current column number within this Source.
*/
public virtual int getColumn()
{
Source parent = getParent();
if(parent == null)
return 0;
return parent.getColumn();
}
/**
* Returns true if this Source is expanding the given macro.
*
* This is used to prevent macro recursion.
*/
internal virtual boolean isExpanding(Macro m)
{
Source parent = getParent();
if(parent != null)
return parent.isExpanding(m);
return false;
}
/**
* Returns true if this Source should be transparently popped
* from the input stack.
*
* Examples of such sources are macro expansions.
*/
internal boolean isAutopop()
{
return autopop;
}
/**
* Returns true if this source has line numbers.
*/
internal virtual boolean isNumbered()
{
return false;
}
/* This is an incredibly lazy way of disabling warnings when
* the source is not active. */
internal void setActive(boolean b)
{
this.active = b;
}
internal boolean isActive()
{
return active;
}
/**
* Returns the next Token parsed from this input stream.
*
* @see Token
*/
public abstract Token token();
/**
* Returns a token iterator for this Source.
*/
public Iterator<Token> iterator()
{
return new SourceIterator(this);
}
/**
* Skips tokens until the end of line.
*
* @param white true if only whitespace is permitted on the
* remainder of the line.
* @return the NL token.
*/
public Token skipline(boolean white)
{
for(; ; ) {
Token tok = token();
switch(tok.getType()) {
case Token.EOF:
/* There ought to be a newline before EOF.
* At least, in any skipline context. */
/* XXX Are we sure about this? */
warning(tok.getLine(), tok.getColumn(),
"No newline before end of file");
return new Token(Token.NL,
tok.getLine(), tok.getColumn(),
"\n");
// return tok;
case Token.NL:
/* This may contain one or more newlines. */
return tok;
case Token.CCOMMENT:
case Token.CPPCOMMENT:
case Token.WHITESPACE:
break;
default:
/* XXX Check white, if required. */
if(white)
warning(tok.getLine(), tok.getColumn(),
"Unexpected nonwhite token");
break;
}
}
}
protected void error(int line, int column, String msg)
{
if(listener != null)
listener.handleError(this, line, column, msg);
else
throw new LexerException("Error at " + line + ":" + column + ": " + msg);
}
protected void warning(int line, int column, String msg)
{
if(werror)
error(line, column, msg);
else if(listener != null)
listener.handleWarning(this, line, column, msg);
else
throw new LexerException("Warning at " + line + ":" + column + ": " + msg);
}
public virtual void close()
{
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Collections
{
/// <summary>
/// A dropdown to select the <see cref="CollectionFilterMenuItem"/> to filter beatmaps using.
/// </summary>
public class CollectionFilterDropdown : OsuDropdown<CollectionFilterMenuItem>
{
/// <summary>
/// Whether to show the "manage collections..." menu item in the dropdown.
/// </summary>
protected virtual bool ShowManageCollectionsItem => true;
private readonly BindableWithCurrent<CollectionFilterMenuItem> current = new BindableWithCurrent<CollectionFilterMenuItem>();
public new Bindable<CollectionFilterMenuItem> Current
{
get => current.Current;
set => current.Current = value;
}
private readonly IBindableList<BeatmapCollection> collections = new BindableList<BeatmapCollection>();
private readonly IBindableList<BeatmapInfo> beatmaps = new BindableList<BeatmapInfo>();
private readonly BindableList<CollectionFilterMenuItem> filters = new BindableList<CollectionFilterMenuItem>();
[Resolved(CanBeNull = true)]
private ManageCollectionsDialog manageCollectionsDialog { get; set; }
[Resolved(CanBeNull = true)]
private CollectionManager collectionManager { get; set; }
public CollectionFilterDropdown()
{
ItemSource = filters;
Current.Value = new AllBeatmapsCollectionFilterMenuItem();
}
protected override void LoadComplete()
{
base.LoadComplete();
if (collectionManager != null)
collections.BindTo(collectionManager.Collections);
// Dropdown has logic which triggers a change on the bindable with every change to the contained items.
// This is not desirable here, as it leads to multiple filter operations running even though nothing has changed.
// An extra bindable is enough to subvert this behaviour.
base.Current = Current;
collections.BindCollectionChanged((_, __) => collectionsChanged(), true);
Current.BindValueChanged(filterChanged, true);
}
/// <summary>
/// Occurs when a collection has been added or removed.
/// </summary>
private void collectionsChanged()
{
var selectedItem = SelectedItem?.Value?.Collection;
filters.Clear();
filters.Add(new AllBeatmapsCollectionFilterMenuItem());
filters.AddRange(collections.Select(c => new CollectionFilterMenuItem(c)));
if (ShowManageCollectionsItem)
filters.Add(new ManageCollectionsFilterMenuItem());
Current.Value = filters.SingleOrDefault(f => f.Collection != null && f.Collection == selectedItem) ?? filters[0];
}
/// <summary>
/// Occurs when the <see cref="CollectionFilterMenuItem"/> selection has changed.
/// </summary>
private void filterChanged(ValueChangedEvent<CollectionFilterMenuItem> filter)
{
// Binding the beatmaps will trigger a collection change event, which results in an infinite-loop. This is rebound later, when it's safe to do so.
beatmaps.CollectionChanged -= filterBeatmapsChanged;
if (filter.OldValue?.Collection != null)
beatmaps.UnbindFrom(filter.OldValue.Collection.Beatmaps);
if (filter.NewValue?.Collection != null)
beatmaps.BindTo(filter.NewValue.Collection.Beatmaps);
beatmaps.CollectionChanged += filterBeatmapsChanged;
// Never select the manage collection filter - rollback to the previous filter.
// This is done after the above since it is important that bindable is unbound from OldValue, which is lost after forcing it back to the old value.
if (filter.NewValue is ManageCollectionsFilterMenuItem)
{
Current.Value = filter.OldValue;
manageCollectionsDialog?.Show();
}
}
/// <summary>
/// Occurs when the beatmaps contained by a <see cref="BeatmapCollection"/> have changed.
/// </summary>
private void filterBeatmapsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// The filtered beatmaps have changed, without the filter having changed itself. So a change in filter must be notified.
// Note that this does NOT propagate to bound bindables, so the FilterControl must bind directly to the value change event of this bindable.
Current.TriggerChange();
}
protected override LocalisableString GenerateItemText(CollectionFilterMenuItem item) => item.CollectionName.Value;
protected sealed override DropdownHeader CreateHeader() => CreateCollectionHeader().With(d =>
{
d.SelectedItem.BindTarget = Current;
});
protected sealed override DropdownMenu CreateMenu() => CreateCollectionMenu();
protected virtual CollectionDropdownHeader CreateCollectionHeader() => new CollectionDropdownHeader();
protected virtual CollectionDropdownMenu CreateCollectionMenu() => new CollectionDropdownMenu();
public class CollectionDropdownHeader : OsuDropdownHeader
{
public readonly Bindable<CollectionFilterMenuItem> SelectedItem = new Bindable<CollectionFilterMenuItem>();
private readonly Bindable<string> collectionName = new Bindable<string>();
protected override LocalisableString Label
{
get => base.Label;
set { } // See updateText().
}
public CollectionDropdownHeader()
{
Height = 25;
Icon.Size = new Vector2(16);
Foreground.Padding = new MarginPadding { Top = 4, Bottom = 4, Left = 8, Right = 4 };
}
protected override void LoadComplete()
{
base.LoadComplete();
SelectedItem.BindValueChanged(_ => updateBindable(), true);
}
private void updateBindable()
{
collectionName.UnbindAll();
if (SelectedItem.Value != null)
collectionName.BindTo(SelectedItem.Value.CollectionName);
collectionName.BindValueChanged(_ => updateText(), true);
}
// Dropdowns don't bind to value changes, so the real name is copied directly from the selected item here.
private void updateText() => base.Label = collectionName.Value;
}
protected class CollectionDropdownMenu : OsuDropdownMenu
{
public CollectionDropdownMenu()
{
MaxHeight = 200;
}
protected override DrawableDropdownMenuItem CreateDrawableDropdownMenuItem(MenuItem item) => new CollectionDropdownMenuItem(item)
{
BackgroundColourHover = HoverColour,
BackgroundColourSelected = SelectionColour
};
}
protected class CollectionDropdownMenuItem : OsuDropdownMenu.DrawableOsuDropdownMenuItem
{
[NotNull]
protected new CollectionFilterMenuItem Item => ((DropdownMenuItem<CollectionFilterMenuItem>)base.Item).Value;
[Resolved]
private IBindable<WorkingBeatmap> beatmap { get; set; }
[CanBeNull]
private readonly BindableList<BeatmapInfo> collectionBeatmaps;
[NotNull]
private readonly Bindable<string> collectionName;
private IconButton addOrRemoveButton;
private Content content;
private bool beatmapInCollection;
public CollectionDropdownMenuItem(MenuItem item)
: base(item)
{
collectionBeatmaps = Item.Collection?.Beatmaps.GetBoundCopy();
collectionName = Item.CollectionName.GetBoundCopy();
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(addOrRemoveButton = new IconButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
X = -OsuScrollContainer.SCROLL_BAR_HEIGHT,
Scale = new Vector2(0.65f),
Action = addOrRemove,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
if (collectionBeatmaps != null)
{
collectionBeatmaps.CollectionChanged += (_, __) => collectionChanged();
beatmap.BindValueChanged(_ => collectionChanged(), true);
}
// Although the DrawableMenuItem binds to value changes of the item's text, the item is an internal implementation detail of Dropdown that has no knowledge
// of the underlying CollectionFilter value and its accompanying name, so the real name has to be copied here. Without this, the collection name wouldn't update when changed.
collectionName.BindValueChanged(name => content.Text = name.NewValue, true);
updateButtonVisibility();
}
protected override bool OnHover(HoverEvent e)
{
updateButtonVisibility();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateButtonVisibility();
base.OnHoverLost(e);
}
private void collectionChanged()
{
Debug.Assert(collectionBeatmaps != null);
beatmapInCollection = collectionBeatmaps.Contains(beatmap.Value.BeatmapInfo);
addOrRemoveButton.Enabled.Value = !beatmap.IsDefault;
addOrRemoveButton.Icon = beatmapInCollection ? FontAwesome.Solid.MinusSquare : FontAwesome.Solid.PlusSquare;
addOrRemoveButton.TooltipText = beatmapInCollection ? "Remove selected beatmap" : "Add selected beatmap";
updateButtonVisibility();
}
protected override void OnSelectChange()
{
base.OnSelectChange();
updateButtonVisibility();
}
private void updateButtonVisibility()
{
if (collectionBeatmaps == null)
addOrRemoveButton.Alpha = 0;
else
addOrRemoveButton.Alpha = IsHovered || IsPreSelected || beatmapInCollection ? 1 : 0;
}
private void addOrRemove()
{
Debug.Assert(collectionBeatmaps != null);
if (!collectionBeatmaps.Remove(beatmap.Value.BeatmapInfo))
collectionBeatmaps.Add(beatmap.Value.BeatmapInfo);
}
protected override Drawable CreateContent() => content = (Content)base.CreateContent();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.